From 6c65e064e65b0adef4cd427c705c103d2dc15df5 Mon Sep 17 00:00:00 2001 From: Vritra4 Date: Mon, 29 Jul 2024 16:27:42 +0900 Subject: [PATCH 1/7] add polyfill --- src/util/index.ts | 1 + src/util/polyfill.spec.ts | 41 ++++++++++++++++++++++++++++ src/util/polyfill.ts | 57 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+) create mode 100644 src/util/polyfill.spec.ts create mode 100644 src/util/polyfill.ts diff --git a/src/util/index.ts b/src/util/index.ts index b80c2da..613891f 100644 --- a/src/util/index.ts +++ b/src/util/index.ts @@ -1,3 +1,4 @@ export * from './bcs'; export * from './hash'; export * from './json'; +export * from './polyfill'; diff --git a/src/util/polyfill.spec.ts b/src/util/polyfill.spec.ts new file mode 100644 index 0000000..389961d --- /dev/null +++ b/src/util/polyfill.spec.ts @@ -0,0 +1,41 @@ +import { bytesFromBase64, base64FromBytes } from './polyfill'; + +describe('bytesFromBase64', () => { + const b64Data = 'SGVsbG8gd29ybGQ='; + const arrData = new Uint8Array([ + 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, + ]); + + it('should convert base64 string to Uint8Array', () => { + const result = bytesFromBase64(b64Data); + + expect(result).toEqual(arrData); + }); + + // Handles empty base64 strings + it('should return an empty Uint8Array when given an empty base64 string', () => { + const b64 = ''; + const expected = new Uint8Array(0); + + const result = bytesFromBase64(b64); + + expect(result).toEqual(expected); + }); + + // Converts a base64 string to a Uint8Array using Buffer when available + it('should convert Uint8Array to base64 string', () => { + const result = base64FromBytes(arrData); + + expect(result).toEqual(b64Data); + }); + + // Handles empty base64 strings + it('should return an empty string when given an empty Uint8Array', () => { + const emptyArr = new Uint8Array(0); + const expected = ''; + + const result = base64FromBytes(emptyArr); + + expect(result).toEqual(expected); + }); +}); diff --git a/src/util/polyfill.ts b/src/util/polyfill.ts new file mode 100644 index 0000000..553be6d --- /dev/null +++ b/src/util/polyfill.ts @@ -0,0 +1,57 @@ +declare const self: any | undefined; +declare const window: any | undefined; +declare const global: any | undefined; + +const gt: any = (() => { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw 'Unable to locate global object'; +})(); + +/** + * Converts a base64 string to Uint8Array. + * + * @param b64 - The base64 string to convert. + * @returns The Uint8Array representation of the base64 string. + */ +export function bytesFromBase64(b64: string): Uint8Array { + if ((gt as any).Buffer) { + return Uint8Array.from(gt.Buffer.from(b64, 'base64')); + } else { + const bin = gt.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} + +/** + * Converts a Uint8Array to a base64 encoded string. + * Uses 'Buffer' if available in the global object, otherwise performs the conversion manually. + * + * @param arr - The Uint8Array to be converted to base64. + * @returns The base64 encoded string representation of the input Uint8Array. + */ +export function base64FromBytes(arr: Uint8Array): string { + if ((gt as any).Buffer) { + return gt.Buffer.from(arr).toString('base64'); + } else { + const bin: string[] = []; + arr.forEach(byte => { + bin.push(gt.String.fromCharCode(byte)); + }); + return gt.btoa(bin.join('')); + } +} From 7742c2feea8f7552d34d1aec730abc2eac762c45 Mon Sep 17 00:00:00 2001 From: joon9823 Date: Fri, 13 Sep 2024 13:56:43 +0900 Subject: [PATCH 2/7] Apply lint and remove semicolon --- README.md | 54 +++++++------- src/client/WebSocketClient.ts | 18 ++--- src/client/lcd/LCDClient.ts | 4 +- src/client/lcd/api/FeeGrantAPI.spec.ts | 44 ++++++------ src/client/lcd/api/GovAPI.spec.ts | 44 ++++++------ src/client/lcd/api/IbcAPI.spec.ts | 72 +++++++++---------- src/client/lcd/api/IbcTransferAPI.spec.ts | 8 +-- src/core/bank/msgs/MsgMultiSend.ts | 8 +-- .../proposals/ParameterChangeProposal.ts | 6 +- src/key/MnemonicKey.ts | 10 +-- src/key/ledger/app.ts | 2 +- src/util/polyfill.spec.ts | 40 +++++------ src/util/polyfill.ts | 45 ++++++------ 13 files changed, 178 insertions(+), 177 deletions(-) diff --git a/README.md b/README.md index a3f7a99..ce7fe45 100644 --- a/README.md +++ b/README.md @@ -24,13 +24,13 @@ The usage section of this document provides detailed explanations and code examp **LCD**(Light Client Daemon) class facilitates interaction with the Initia blockchain. ```typescript -import { LCDClient } from '@initia/initia.js'; +import { LCDClient } from '@initia/initia.js' const lcd = new LCDClient('https://lcd.mahalo-1.initia.xyz', { chainId: 'mahalo-1', gasPrices: '0.15uinit', // default gas prices gasAdjustment: '1.75', // default gas adjustment for fee estimation -}); +}) ``` @@ -42,14 +42,14 @@ const lcd = new LCDClient('https://lcd.mahalo-1.initia.xyz', { An abstract key interface that enables transaction signing and provides Bech32 address and public key derivation from a public key. ```typescript -import { MnemonicKey } from '@initia/initia.js'; +import { MnemonicKey } from '@initia/initia.js' const key = new MnemonicKey({ mnemonic: 'bird upset ... evil cigar', // (optional) if null, generate a new Mnemonic key account: 0, // (optional) BIP44 account number. default = 0 index: 0, // (optional) BIP44 index number. defualt = 0 coinType: 118, // (optional) BIP44 coinType. default = 118 -}); +}) ``` ### BCS @@ -57,28 +57,28 @@ const key = new MnemonicKey({ **BCS**(Binary Canonical Serialization) is the binary encoding for Move resources and other non-module values published on-chain. ```typescript -import { bcs } from '@initia/initia.js'; +import { bcs } from '@initia/initia.js' // serialize, serialize value to BCS and encode it to base64 const serializedU64 = bcs .u64() // type .serialize(1234) // value - .toBase64(); + .toBase64() // deserialize const deserializedU64 = bcs .u64() // type - .parse(Uint8Array.from(Buffer.from(serializedU64, 'base64'))); + .parse(Uint8Array.from(Buffer.from(serializedU64, 'base64'))) // vector const serializedVector = bcs .vector(bcs.u64()) .serialize([123, 456, 789]) - .toBase64(); + .toBase64() // option -const serializedSome = bcs.option(bcs.u64()).serialize(123); -const serializedNone = bcs.option(bcs.u64()).serialize(null); +const serializedSome = bcs.option(bcs.u64()).serialize(123) +const serializedNone = bcs.option(bcs.u64()).serialize(null) ``` **Support types for BCS** @@ -94,13 +94,13 @@ Msgs are object whose end-goal is to trigger state-transitions. They are wrapped Send coins to others. ```typescript -import { MsgSend } from '@initia/initia.js'; +import { MsgSend } from '@initia/initia.js' const msg = new MsgSend( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address 'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np', // recipient address '1000uinit', // send amount -); +) ``` * `MsgDelegate()` @@ -108,13 +108,13 @@ const msg = new MsgSend( Delegate governance coin to validators (staking). ```typescript -import { MsgDelegate } from '@initia/initia.js'; +import { MsgDelegate } from '@initia/initia.js' const msg = new MsgDelegate( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // delegator address 'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np', // validator's operator addres '100000uinit', // delegate amount -); +) ``` * `MsgUndelegate()` @@ -122,13 +122,13 @@ const msg = new MsgDelegate( Undelegate governance coin from validators (unstaking). ```typescript -import { MsgUndelegate } from '@initia/initia.js'; +import { MsgUndelegate } from '@initia/initia.js' const msg = new MsgUndelegate( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // delegator address 'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np', // validator's operator addres '100000uinit', // undelegate amount -); +) ``` * `MsgExecute()` @@ -136,7 +136,7 @@ const msg = new MsgUndelegate( Execute move contract function. ```typescript -import { MsgExecute } from '@initia/initia.js'; +import { MsgExecute } from '@initia/initia.js' const msg = new MsgExecute( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address @@ -149,7 +149,7 @@ const msg = new MsgExecute( bcs.address().serialize('0x3').toBase64(), // arguments, BCS-encoded bcs.u64().serialize(10000).toBase64() // arguments, BCS-encoded ] -); +) ``` ### Tx broadcasting @@ -159,31 +159,31 @@ const msg = new MsgExecute( Create a wallet and sign transaction. ```typescript -import { Wallet, LCDClient, MnemonicKey } from '@initia/initia.js'; +import { Wallet, LCDClient, MnemonicKey } from '@initia/initia.js' const key = new MnemonicKey({ mnemonic: 'moral wise tape glance grit gentle movie doll omit you pet soon enter year funny gauge digital supply cereal city ring egg repair coyote', -}); +}) const lcd = new LCDClient('https://lcd.mahalo-1.initia.xyz', { chainId: 'mahalo-1', gasPrices: '0.15uinit', // default gas prices gasAdjustment: '1.75', // default gas adjustment for fee estimation -}); +}) -const wallet = new Wallet(lcd, key); +const wallet = new Wallet(lcd, key) const sendMsg = new MsgSend( 'init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu', // sender address 'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np', // recipient address '1000uinit', // send amount -); +) const signedTx = await wallet.createAndSignTx({ msgs: [sendMsg], memo: 'sample memo', -}); +}) ``` When sending coins with `MsgSend`, sender address should be same with wallet address. @@ -193,7 +193,7 @@ When sending coins with `MsgSend`, sender address should be same with wallet add `broadcast()` is the action that sends your transaction to the blockchain code. ```typescript -const broadcastResult = await lcd.tx.broadcast(signedTx); +const broadcastResult = await lcd.tx.broadcast(signedTx) ``` ### Queries @@ -203,7 +203,7 @@ const broadcastResult = await lcd.tx.broadcast(signedTx); Query the balance of the account. ```typescript -const balances = await lcd.bank.balance('init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu'); +const balances = await lcd.bank.balance('init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu') ``` * `viewfunction()` @@ -221,5 +221,5 @@ const res = await lcd.move.viewFunction( bcs.address().serialize('0x3').toBase64(), // arguments, BCS-encoded bcs.u64().serialize(10000).toBase64() // arguments, BCS-encoded ] -); +) ``` diff --git a/src/client/WebSocketClient.ts b/src/client/WebSocketClient.ts index a1c4b5c..3b101c2 100644 --- a/src/client/WebSocketClient.ts +++ b/src/client/WebSocketClient.ts @@ -98,15 +98,15 @@ function makeQueryParams(query: TendermintQuery): string { * ### Example * * ```ts - * import { WebSocketClient } from '@initia/initia.js'; + * import { WebSocketClient } from '@initia/initia.js' * - * const wsclient = new WebSocketClient("ws://localhost:26657/websocket"); + * const wsclient = new WebSocketClient("ws://localhost:26657/websocket") * * wsclient.subscribe('NewBlock', {}, (data) => { - * console.log(data.value); + * console.log(data.value) * * // close after receiving one block. - * wsclient.destroy(); + * wsclient.destroy() * }) * * wsclient.subscribe( @@ -116,13 +116,13 @@ function makeQueryParams(query: TendermintQuery): string { * 'message.sender': ['CONTAINS', 'init1...'], * }, * (data) => { - * console.log(data.value); + * console.log(data.value) * * // close after receiving one send Tx - * wsclient.destroy(); - * }); + * wsclient.destroy() + * }) * - * wsclient.start(); + * wsclient.start() * ``` */ export class WebSocketClient extends EventEmitter { @@ -205,7 +205,7 @@ export class WebSocketClient extends EventEmitter { parsedData.result && // eslint-disable-line @typescript-eslint/no-unsafe-member-access parsedData.result.query === this.queryParams // eslint-disable-line @typescript-eslint/no-unsafe-member-access ) { - // this.emit('message', parsedData.result.data); + // this.emit('message', parsedData.result.data) this.callback(parsedData.result.data) // eslint-disable-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access } } catch (err) { diff --git a/src/client/lcd/LCDClient.ts b/src/client/lcd/LCDClient.ts index 76a400f..5c67c75 100644 --- a/src/client/lcd/LCDClient.ts +++ b/src/client/lcd/LCDClient.ts @@ -69,11 +69,11 @@ const DEFAULT_GAS_PRICES_BY_CHAIN_ID: Record = { * ### Example * * ```ts - * import { LCDClient } from 'initia.js'; + * import { LCDClient } from 'initia.js' * * const initia = new LCDClient("https://lcd.devnet.initia.xyz", { * chainId: "testnet" - * }); + * }) * ``` */ diff --git a/src/client/lcd/api/FeeGrantAPI.spec.ts b/src/client/lcd/api/FeeGrantAPI.spec.ts index 4970cb9..7c4fea1 100644 --- a/src/client/lcd/api/FeeGrantAPI.spec.ts +++ b/src/client/lcd/api/FeeGrantAPI.spec.ts @@ -1,21 +1,21 @@ -// import { APIRequester } from '../APIRequester'; -// import { FeeGrantAPI } from './FeeGrantAPI'; +// import { APIRequester } from '../APIRequester' +// import { FeeGrantAPI } from './FeeGrantAPI' -// const c = new APIRequester('https://lcd.devnet.initia.xyz/'); -// const feeGrant = new FeeGrantAPI(c); +// const c = new APIRequester('https://lcd.devnet.initia.xyz/') +// const feeGrant = new FeeGrantAPI(c) describe('FeeGrantAPI', () => { it('allowances', async () => { // const res = await feeGrant.allowances( // 'init1p204wtykwke52hcyt6vdh630725rdayczyzcvz' - // ); + // ) // expect(res.allowances[0]).toMatchObject({ // granter: expect.any(String), // grantee: expect.any(String), - // }); - // const allowanceData = res.allowances[0].allowance.toData(); - // expect(allowanceData['@type']).toMatch(/cosmos.feegrant.v1beta1/g); - // expect(res.pagination).not.toBeUndefined(); + // }) + // const allowanceData = res.allowances[0].allowance.toData() + // expect(allowanceData['@type']).toMatch(/cosmos.feegrant.v1beta1/g) + // expect(res.pagination).not.toBeUndefined() }) // describe('allowance', () => { @@ -23,11 +23,11 @@ describe('FeeGrantAPI', () => { // const res = await feeGrant.allowance( // 'init13ggppncs97f4cl90fvxqelflg0upedd0n7rnd3', // 'init1p204wtykwke52hcyt6vdh630725rdayczyzcvz' - // ); + // ) - // const allowanceData = res.toData(); - // expect(allowanceData['@type']).toMatch(/cosmos.feegrant.v1beta1/g); - // }); + // const allowanceData = res.toData() + // expect(allowanceData['@type']).toMatch(/cosmos.feegrant.v1beta1/g) + // }) // it('allowance not exist', async () => { // expect( @@ -35,20 +35,20 @@ describe('FeeGrantAPI', () => { // 'init1p204wtykwke52hcyt6vdh630725rdayczyzcvz', // 'init13ggppncs97f4cl90fvxqelflg0upedd0n7rnd3' // ) - // ).rejects.toThrow(); - // }); - // }); + // ).rejects.toThrow() + // }) + // }) // it('allowancesByGranter', async () => { // const res = await feeGrant.allowancesByGranter( // 'init1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v' - // ); + // ) // expect(res.allowances[0]).toMatchObject({ // granter: expect.any(String), // grantee: expect.any(String), - // }); - // const allowanceData = res.allowances[0].allowance.toData(); - // expect(allowanceData['@type']).toMatch(/cosmos.feegrant.v1beta1/g); - // expect(res.pagination).not.toBeUndefined(); - // }); + // }) + // const allowanceData = res.allowances[0].allowance.toData() + // expect(allowanceData['@type']).toMatch(/cosmos.feegrant.v1beta1/g) + // expect(res.pagination).not.toBeUndefined() + // }) }) diff --git a/src/client/lcd/api/GovAPI.spec.ts b/src/client/lcd/api/GovAPI.spec.ts index 5ff4293..11a35ef 100644 --- a/src/client/lcd/api/GovAPI.spec.ts +++ b/src/client/lcd/api/GovAPI.spec.ts @@ -36,38 +36,38 @@ describe('GovAPI', () => { // abstain: expect.any(String), // no: expect.any(String), // no_with_veto: expect.any(String), - // }); - // }); + // }) + // }) // it('proposals', async () => { - // const proposals = await gov.proposals().then(v => v[0]); - // expect(proposals).toContainEqual(expect.any(Proposal)); - // }); + // const proposals = await gov.proposals().then(v => v[0]) + // expect(proposals).toContainEqual(expect.any(Proposal)) + // }) // it('proposal', async () => { - // const proposalId = await gov.proposals().then(v => v[0][0].id); - // const proposal = await gov.proposal(proposalId); - // expect(proposal).toEqual(expect.any(Proposal)); - // }); + // const proposalId = await gov.proposals().then(v => v[0][0].id) + // const proposal = await gov.proposal(proposalId) + // expect(proposal).toEqual(expect.any(Proposal)) + // }) // it('proposer', async () => { - // const proposalId = await gov.proposals().then(v => v[0][0].id); - // const proposer = await gov.proposer(proposalId); - // expect(proposer).toEqual(expect.any(String)); - // }); + // const proposalId = await gov.proposals().then(v => v[0][0].id) + // const proposer = await gov.proposer(proposalId) + // expect(proposer).toEqual(expect.any(String)) + // }) // it('initialDeposit', async () => { - // const proposalId = await gov.proposals().then(v => v[0][0].id); - // const initialDeposit = await gov.initialDeposit(proposalId); - // expect(initialDeposit).toEqual(expect.any(Coins)); - // }); + // const proposalId = await gov.proposals().then(v => v[0][0].id) + // const initialDeposit = await gov.initialDeposit(proposalId) + // expect(initialDeposit).toEqual(expect.any(Coins)) + // }) // it('deposits', async () => { - // const proposals = await gov.proposals().then(v => v[0]); - // const proposalId = proposals[0].id; - // const deposits = await gov.deposits(proposalId).then(v => v[0][0]); + // const proposals = await gov.proposals().then(v => v[0]) + // const proposalId = proposals[0].id + // const deposits = await gov.deposits(proposalId).then(v => v[0][0]) // if (deposits !== undefined) { - // expect(deposits).toEqual(expect.any(Deposit)); + // expect(deposits).toEqual(expect.any(Deposit)) // } - // }); + // }) }) diff --git a/src/client/lcd/api/IbcAPI.spec.ts b/src/client/lcd/api/IbcAPI.spec.ts index 0f3bcfd..f521b98 100644 --- a/src/client/lcd/api/IbcAPI.spec.ts +++ b/src/client/lcd/api/IbcAPI.spec.ts @@ -18,16 +18,16 @@ describe('IbcClientAPI', () => { }) // it('client_state', async () => { - // const res = await ibc.clientState('07-tendermint-0'); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // }); + // const res = await ibc.clientState('07-tendermint-0') + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // }) // it('client_status', async () => { - // const res = await ibc.clientStatus('07-tendermint-0'); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // }); + // const res = await ibc.clientStatus('07-tendermint-0') + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // }) it('consensus_states', async () => { const res = await ibc.consensusStates('07-tendermint-0') @@ -36,40 +36,40 @@ describe('IbcClientAPI', () => { }) // it('channels', async () => { - // const [res, _] = await ibc.channels(); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // expect(res.length).toBeGreaterThan(0); - // }); + // const [res, _] = await ibc.channels() + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // expect(res.length).toBeGreaterThan(0) + // }) // it('channels for a connection', async () => { - // const [res, height, _] = await ibc.connectionChannels('connection-3'); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // expect(height).not.toBeNull(); - // expect(height).toBeInstanceOf(Height); - // expect(res.length).toBeGreaterThan(0); - // }); + // const [res, height, _] = await ibc.connectionChannels('connection-3') + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // expect(height).not.toBeNull() + // expect(height).toBeInstanceOf(Height) + // expect(res.length).toBeGreaterThan(0) + // }) // it('port', async () => { - // const res = await ibc.port('channel-0', 'transfer'); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // expect(res).toHaveProperty('channel'); - // expect(res).toHaveProperty('proof'); - // expect(res).toHaveProperty('proof_height'); - // }); + // const res = await ibc.port('channel-0', 'transfer') + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // expect(res).toHaveProperty('channel') + // expect(res).toHaveProperty('proof') + // expect(res).toHaveProperty('proof_height') + // }) // it('connections', async () => { - // const [res, _] = await ibc.connections(); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // expect(res.length).toBeGreaterThan(0); - // }); + // const [res, _] = await ibc.connections() + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // expect(res.length).toBeGreaterThan(0) + // }) // it('a connection', async () => { - // const res = await ibc.connection('connection-0'); - // expect(res).not.toBeNull(); - // expect(res).not.toBeUndefined(); - // }); + // const res = await ibc.connection('connection-0') + // expect(res).not.toBeNull() + // expect(res).not.toBeUndefined() + // }) }) diff --git a/src/client/lcd/api/IbcTransferAPI.spec.ts b/src/client/lcd/api/IbcTransferAPI.spec.ts index 41eaae0..00460fa 100644 --- a/src/client/lcd/api/IbcTransferAPI.spec.ts +++ b/src/client/lcd/api/IbcTransferAPI.spec.ts @@ -17,10 +17,10 @@ describe('IbcTransferAPI', () => { // it('denomTrace', async () => { // const denomTrace = await ibctx.denomTrace( // '6DD0D40C3A5FE38336FC5EF017CC248E11C15E28C76F95C83A8FFE61E1566063' - // ); - // expect(denomTrace.path).toEqual('transfer/channel-7'); - // expect(denomTrace.base_denom).toEqual('ukuji'); - // }); + // ) + // expect(denomTrace.path).toEqual('transfer/channel-7') + // expect(denomTrace.base_denom).toEqual('ukuji') + // }) it('params', async () => { const param = await ibctx.parameters() diff --git a/src/core/bank/msgs/MsgMultiSend.ts b/src/core/bank/msgs/MsgMultiSend.ts index 2a2569c..3e06ea8 100644 --- a/src/core/bank/msgs/MsgMultiSend.ts +++ b/src/core/bank/msgs/MsgMultiSend.ts @@ -19,7 +19,7 @@ import { * Example: * * ```ts - * import { MsgMultiSend } from "@initia/initia.js"; + * import { MsgMultiSend } from "@initia/initia.js" * * const inputs: MsgMultiSend.Input[] = [ * new MsgMultiSend.Input( @@ -31,7 +31,7 @@ import { * new MsgMultiSend.Input('init105rz2q5a4w7nv7239tl9c4px5cjy7axx3axfad', [ * new Coin('uinit', 123123), * ]), - * ]; + * ] * const outputs: MsgMultiSend.Output[] = [ * new MsgMultiSend.Output( * 'init105rz2q5a4w7nv7239tl9c4px5cjy7axx3axfad', @@ -44,8 +44,8 @@ import { * uinit: 123123, * } * ), - * ]; - * const multisend = new MsgMultiSend(inputs, outputs); + * ] + * const multisend = new MsgMultiSend(inputs, outputs) * ``` */ export class MsgMultiSend extends JSONSerializable< diff --git a/src/core/params/proposals/ParameterChangeProposal.ts b/src/core/params/proposals/ParameterChangeProposal.ts index 12e03e3..a259364 100644 --- a/src/core/params/proposals/ParameterChangeProposal.ts +++ b/src/core/params/proposals/ParameterChangeProposal.ts @@ -15,15 +15,15 @@ import { ParameterChangeProposal as ParameterChangeProposal_pb } from '@initia/i * Dec, * MsgSubmitProposal, * ParameterChangeProposal - * } from "@initia/initia.js"; + * } from "@initia/initia.js" * * const proposal = new ParameterChangeProposal("title", "description", { * mstaking: { * UnbondingTime: 15000000 * } - * }); + * }) * - * const msg = new MsgSubmitProposal(); + * const msg = new MsgSubmitProposal() * ``` */ export class ParameterChangeProposal extends JSONSerializable< diff --git a/src/key/MnemonicKey.ts b/src/key/MnemonicKey.ts index 437e538..c5369dc 100644 --- a/src/key/MnemonicKey.ts +++ b/src/key/MnemonicKey.ts @@ -50,17 +50,17 @@ export class MnemonicKey extends RawKey { * ### Providing a mnemonic * * ```ts - * import { MnemonicKey } from 'initia.js'; + * import { MnemonicKey } from 'initia.js' * - * const mk = new MnemonicKey({ mnemonic: '...' }); - * console.log(mk.accAddress); + * const mk = new MnemonicKey({ mnemonic: '...' }) + * console.log(mk.accAddress) * ``` * * ### Generating a random mnemonic * * ```ts - * const mk2 = new MnemonicKey(); - * console.log(mk2.mnemonic); + * const mk2 = new MnemonicKey() + * console.log(mk2.mnemonic) * ``` * * @param options diff --git a/src/key/ledger/app.ts b/src/key/ledger/app.ts index 97d1769..d7dbb41 100644 --- a/src/key/ledger/app.ts +++ b/src/key/ledger/app.ts @@ -2,7 +2,7 @@ * (c) 2019 ZondaX GmbH * (c) 2016-2017 Ledger * - * Licensed under the Apache License, Version 2.0 (the 'License'); + * Licensed under the Apache License, Version 2.0 (the 'License') * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * diff --git a/src/util/polyfill.spec.ts b/src/util/polyfill.spec.ts index 389961d..7c1c2ee 100644 --- a/src/util/polyfill.spec.ts +++ b/src/util/polyfill.spec.ts @@ -1,41 +1,41 @@ -import { bytesFromBase64, base64FromBytes } from './polyfill'; +import { bytesFromBase64, base64FromBytes } from './polyfill' describe('bytesFromBase64', () => { - const b64Data = 'SGVsbG8gd29ybGQ='; + const b64Data = 'SGVsbG8gd29ybGQ=' const arrData = new Uint8Array([ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, - ]); + ]) it('should convert base64 string to Uint8Array', () => { - const result = bytesFromBase64(b64Data); + const result = bytesFromBase64(b64Data) - expect(result).toEqual(arrData); - }); + expect(result).toEqual(arrData) + }) // Handles empty base64 strings it('should return an empty Uint8Array when given an empty base64 string', () => { - const b64 = ''; - const expected = new Uint8Array(0); + const b64 = '' + const expected = new Uint8Array(0) - const result = bytesFromBase64(b64); + const result = bytesFromBase64(b64) - expect(result).toEqual(expected); - }); + expect(result).toEqual(expected) + }) // Converts a base64 string to a Uint8Array using Buffer when available it('should convert Uint8Array to base64 string', () => { - const result = base64FromBytes(arrData); + const result = base64FromBytes(arrData) - expect(result).toEqual(b64Data); - }); + expect(result).toEqual(b64Data) + }) // Handles empty base64 strings it('should return an empty string when given an empty Uint8Array', () => { - const emptyArr = new Uint8Array(0); - const expected = ''; + const emptyArr = new Uint8Array(0) + const expected = '' - const result = base64FromBytes(emptyArr); + const result = base64FromBytes(emptyArr) - expect(result).toEqual(expected); - }); -}); + expect(result).toEqual(expected) + }) +}) diff --git a/src/util/polyfill.ts b/src/util/polyfill.ts index 553be6d..5f018d0 100644 --- a/src/util/polyfill.ts +++ b/src/util/polyfill.ts @@ -1,22 +1,23 @@ -declare const self: any | undefined; -declare const window: any | undefined; -declare const global: any | undefined; +/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-redundant-type-constituents */ +declare const self: any | undefined +declare const window: any | undefined +declare const global: any | undefined const gt: any = (() => { if (typeof globalThis !== 'undefined') { - return globalThis; + return globalThis } if (typeof self !== 'undefined') { - return self; + return self } if (typeof window !== 'undefined') { - return window; + return window } if (typeof global !== 'undefined') { - return global; + return global } - throw 'Unable to locate global object'; -})(); + throw 'Unable to locate global object' +})() /** * Converts a base64 string to Uint8Array. @@ -25,15 +26,15 @@ const gt: any = (() => { * @returns The Uint8Array representation of the base64 string. */ export function bytesFromBase64(b64: string): Uint8Array { - if ((gt as any).Buffer) { - return Uint8Array.from(gt.Buffer.from(b64, 'base64')); + if (gt.Buffer) { + return Uint8Array.from(gt.Buffer.from(b64, 'base64')) } else { - const bin = gt.atob(b64); - const arr = new Uint8Array(bin.length); + const bin = gt.atob(b64) + const arr = new Uint8Array(bin.length) for (let i = 0; i < bin.length; ++i) { - arr[i] = bin.charCodeAt(i); + arr[i] = bin.charCodeAt(i) } - return arr; + return arr } } @@ -45,13 +46,13 @@ export function bytesFromBase64(b64: string): Uint8Array { * @returns The base64 encoded string representation of the input Uint8Array. */ export function base64FromBytes(arr: Uint8Array): string { - if ((gt as any).Buffer) { - return gt.Buffer.from(arr).toString('base64'); + if (gt.Buffer) { + return gt.Buffer.from(arr).toString('base64') } else { - const bin: string[] = []; - arr.forEach(byte => { - bin.push(gt.String.fromCharCode(byte)); - }); - return gt.btoa(bin.join('')); + const bin: string[] = [] + arr.forEach((byte) => { + bin.push(gt.String.fromCharCode(byte)) + }) + return gt.btoa(bin.join('')) } } From a0de75119788abc1aeeb86bc81725bc6b7be7e55 Mon Sep 17 00:00:00 2001 From: joon9823 Date: Fri, 13 Sep 2024 14:06:42 +0900 Subject: [PATCH 3/7] Change to Number.parseInt for sense of unity --- src/client/lcd/api/ForwardingAPI.ts | 4 ++-- src/client/lcd/api/OpchildAPI.ts | 4 ++-- src/client/lcd/api/OphostAPI.ts | 2 +- src/core/ibc/core/client/Height.ts | 4 ++-- src/core/ibc/core/client/msgs/tendermint/types.ts | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/client/lcd/api/ForwardingAPI.ts b/src/client/lcd/api/ForwardingAPI.ts index a4c0620..5825e84 100644 --- a/src/client/lcd/api/ForwardingAPI.ts +++ b/src/client/lcd/api/ForwardingAPI.ts @@ -39,8 +39,8 @@ export class ForwardingAPI extends BaseAPI { params ) .then((d) => ({ - num_of_accounts: parseInt(d.num_of_accounts), - num_of_forwards: parseInt(d.num_of_forwards), + num_of_accounts: Number.parseInt(d.num_of_accounts), + num_of_forwards: Number.parseInt(d.num_of_forwards), total_forwarded: Coin.fromData(d.total_forwarded), })) } diff --git a/src/client/lcd/api/OpchildAPI.ts b/src/client/lcd/api/OpchildAPI.ts index 461b072..caa621d 100644 --- a/src/client/lcd/api/OpchildAPI.ts +++ b/src/client/lcd/api/OpchildAPI.ts @@ -43,7 +43,7 @@ export class OpchildAPI extends BaseAPI { .get<{ next_l1_sequence: string }>(`/opinit/opchild/v1/next_l1_sequence`, params) - .then((d) => parseInt(d.next_l1_sequence)) + .then((d) => Number.parseInt(d.next_l1_sequence)) } public async nextL2Sequence(params: APIParams = {}): Promise { @@ -51,7 +51,7 @@ export class OpchildAPI extends BaseAPI { .get<{ next_l2_sequence: string }>(`/opinit/opchild/v1/next_l2_sequence`, params) - .then((d) => parseInt(d.next_l2_sequence)) + .then((d) => Number.parseInt(d.next_l2_sequence)) } public async baseDenom( diff --git a/src/client/lcd/api/OphostAPI.ts b/src/client/lcd/api/OphostAPI.ts index 3d87779..1605b3b 100644 --- a/src/client/lcd/api/OphostAPI.ts +++ b/src/client/lcd/api/OphostAPI.ts @@ -163,7 +163,7 @@ export class OphostAPI extends BaseAPI { .get<{ next_l1_sequence: string }>(`/opinit/ophost/v1/bridges/${bridgeId}/next_l1_sequence`, params) - .then((d) => parseInt(d.next_l1_sequence)) + .then((d) => Number.parseInt(d.next_l1_sequence)) } public async batchInfos( diff --git a/src/core/ibc/core/client/Height.ts b/src/core/ibc/core/client/Height.ts index b57bf52..aaf121e 100644 --- a/src/core/ibc/core/client/Height.ts +++ b/src/core/ibc/core/client/Height.ts @@ -33,8 +33,8 @@ export class Height extends JSONSerializable< public static fromAmino(data: Height.Amino): Height { const { revision_number, revision_height } = data return new Height( - parseInt(revision_number ?? '0'), - parseInt(revision_height ?? '0') + Number.parseInt(revision_number ?? '0'), + Number.parseInt(revision_height ?? '0') ) } diff --git a/src/core/ibc/core/client/msgs/tendermint/types.ts b/src/core/ibc/core/client/msgs/tendermint/types.ts index 38dbdb3..0431800 100644 --- a/src/core/ibc/core/client/msgs/tendermint/types.ts +++ b/src/core/ibc/core/client/msgs/tendermint/types.ts @@ -380,7 +380,7 @@ export class PartSetHeader extends JSONSerializable< public static fromData(data: PartSetHeader.Data): PartSetHeader { const { total, hash } = data - return new PartSetHeader(parseInt(total), hash) + return new PartSetHeader(Number.parseInt(total), hash) } public toData(): PartSetHeader.Data { From cd4b5eebe27ad6bc29aca9ba934010f4f3245eff Mon Sep 17 00:00:00 2001 From: joon9823 Date: Tue, 8 Oct 2024 16:12:02 +0900 Subject: [PATCH 4/7] Replace Buffer with Uint8Array --- src/client/WebSocketClient.ts | 2 +- src/client/lcd/api/OphostAPI.ts | 3 +- src/client/lcd/api/TendermintAPI.spec.ts | 3 +- src/client/lcd/api/TxAPI.ts | 7 +- src/core/PublicKey.ts | 47 ++- src/core/auction/AuctionParams.ts | 5 +- src/core/auction/msgs/MsgAuctionBid.ts | 5 +- src/core/bech32.spec.ts | 9 +- src/core/bech32.ts | 11 +- src/core/celestia/Blob.ts | 9 +- src/core/celestia/BlobTx.ts | 2 +- src/core/celestia/msgs/MsgPayForBlobs.ts | 17 +- src/core/ibc/core/channel/Packet.ts | 9 +- .../channel/msgs/MsgChannelCloseConfirm.ts | 5 +- .../core/channel/msgs/MsgChannelOpenAck.ts | 5 +- .../channel/msgs/MsgChannelOpenConfirm.ts | 5 +- .../core/channel/msgs/MsgChannelOpenTry.ts | 5 +- .../channel/msgs/MsgRecvAcknowledgement.ts | 9 +- .../ibc/core/channel/msgs/MsgRecvPacket.ts | 5 +- src/core/ibc/core/channel/msgs/MsgTimeout.ts | 5 +- .../ibc/core/channel/msgs/MsgTimeoutClose.ts | 9 +- .../ibc/core/client/msgs/MsgUpgradeClient.ts | 12 +- .../ibc/core/client/msgs/tendermint/crypto.ts | 34 +- .../ibc/core/client/msgs/tendermint/types.ts | 304 +++++++++--------- src/core/ibc/core/commitment/MerklePrefix.ts | 5 +- src/core/ibc/core/commitment/MerkleRoot.ts | 5 +- .../connection/msgs/MsgConnectionOpenAck.ts | 13 +- .../msgs/MsgConnectionOpenConfirm.ts | 5 +- .../connection/msgs/MsgConnectionOpenTry.ts | 19 +- src/core/move/msgs/MsgExecute.ts | 5 +- src/core/move/msgs/MsgGovExecute.ts | 5 +- src/core/move/msgs/MsgGovPublish.ts | 5 +- src/core/move/msgs/MsgGovScript.ts | 9 +- src/core/move/msgs/MsgGovScriptJSON.ts | 5 +- src/core/move/msgs/MsgPublish.ts | 5 +- src/core/move/msgs/MsgScript.ts | 9 +- src/core/move/msgs/MsgScriptJSON.ts | 5 +- .../opchild/msgs/MsgFinalizeTokenDeposit.ts | 7 +- src/core/opchild/msgs/MsgUpdateOracle.ts | 5 +- src/core/ophost/BridgeConfig.ts | 5 +- src/core/ophost/Output.ts | 5 +- .../ophost/msgs/MsgFinalizeTokenWithdrawal.ts | 21 +- .../ophost/msgs/MsgInitiateTokenDeposit.ts | 7 +- src/core/ophost/msgs/MsgProposeOutput.ts | 5 +- src/core/ophost/msgs/MsgRecordBatch.ts | 5 +- src/core/ophost/msgs/MsgUpdateMetadata.ts | 5 +- src/core/slashing/SlashingParams.ts | 13 +- src/core/tx/CompactBitArray.ts | 13 +- src/core/tx/SignDoc.ts | 5 +- src/core/tx/SignatureV2.ts | 3 +- src/core/tx/Tx.ts | 9 +- .../authorizations/AcceptedMessagesFilter.ts | 7 +- src/core/wasm/authorizations/CodeGrant.ts | 5 +- src/core/wasm/msgs/MsgExecuteContract.ts | 5 +- src/core/wasm/msgs/MsgInstantiateContract.ts | 5 +- .../wasm/msgs/MsgInstantiateContractV2.ts | 9 +- src/core/wasm/msgs/MsgMigrateContract.ts | 5 +- .../msgs/MsgStoreAndInstantiateContract.ts | 13 +- .../wasm/msgs/MsgStoreAndMigrateContract.ts | 9 +- src/core/wasm/msgs/MsgStoreCode.ts | 5 +- src/core/wasm/msgs/MsgSudoContract.ts | 5 +- src/key/Key.ts | 21 +- src/key/MnemonicKey.ts | 2 +- src/key/RawKey.ts | 38 +-- src/util/bcs.ts | 5 +- src/util/hash.ts | 5 - src/util/polyfill.spec.ts | 84 ++++- src/util/polyfill.ts | 49 +++ 68 files changed, 571 insertions(+), 431 deletions(-) diff --git a/src/client/WebSocketClient.ts b/src/client/WebSocketClient.ts index 3b101c2..c51da4b 100644 --- a/src/client/WebSocketClient.ts +++ b/src/client/WebSocketClient.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'events' import WebSocket from 'ws' -import { hashToHex } from '../util' +import { hashToHex } from '../util/hash' type Callback = (data: TendermintSubscriptionResponse) => void diff --git a/src/client/lcd/api/OphostAPI.ts b/src/client/lcd/api/OphostAPI.ts index 1605b3b..2bde9e7 100644 --- a/src/client/lcd/api/OphostAPI.ts +++ b/src/client/lcd/api/OphostAPI.ts @@ -6,6 +6,7 @@ import { BridgeInfo, BatchInfoWithOutput, } from '../../../core' +import { bytesFromHex, base64FromBytes } from '../../../util/polyfill' export interface TokenPair { l1_denom: string @@ -150,7 +151,7 @@ export class OphostAPI extends BaseAPI { claimed: boolean }>(`/opinit/ophost/v1/bridges/${bridgeId}/withdrawals/claimed/by_hash`, { ...params, - withdrawal_hash: Buffer.from(withdrawalHash, 'hex').toString('base64'), + withdrawal_hash: base64FromBytes(bytesFromHex(withdrawalHash)), }) .then((d) => d.claimed) } diff --git a/src/client/lcd/api/TendermintAPI.spec.ts b/src/client/lcd/api/TendermintAPI.spec.ts index 65b7aec..4f017bc 100644 --- a/src/client/lcd/api/TendermintAPI.spec.ts +++ b/src/client/lcd/api/TendermintAPI.spec.ts @@ -1,6 +1,7 @@ import { APIRequester } from '../APIRequester' import { TendermintAPI } from './TendermintAPI' import { Tx } from '../../../core' +import { bytesFromBase64 } from '../../../util/polyfill' import { Tx as Tx_pb } from '@initia/initia.proto/cosmos/tx/v1beta1/tx' const c = new APIRequester('https://lcd.devnet.initia.xyz/') @@ -11,7 +12,7 @@ describe('TendermintAPI', () => { const blockInfo = await tendermint.blockInfo(1) if (blockInfo.block.data.txs != null) { blockInfo.block.data.txs.every((txBytes) => { - const txProto = Tx_pb.decode(Buffer.from(txBytes, 'base64')) + const txProto = Tx_pb.decode(bytesFromBase64(txBytes)) expect(Tx.fromProto(txProto)).toBeDefined() }) } diff --git a/src/client/lcd/api/TxAPI.ts b/src/client/lcd/api/TxAPI.ts index 7933ef3..1cb5e98 100644 --- a/src/client/lcd/api/TxAPI.ts +++ b/src/client/lcd/api/TxAPI.ts @@ -12,7 +12,8 @@ import { TxLog, Event, } from '../../../core' -import { hashToHex } from '../../../util' +import { hashToHex } from '../../../util/hash' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { LCDClient } from '../LCDClient' import { APIParams, Pagination, PaginationOptions } from '../APIRequester' import { BroadcastMode } from '@initia/initia.proto/cosmos/tx/v1beta1/service' @@ -372,7 +373,7 @@ export class TxAPI extends BaseAPI { * @param tx transaction to encode */ public static encode(tx: Tx): string { - return Buffer.from(tx.toBytes()).toString('base64') + return base64FromBytes(tx.toBytes()) } /** @@ -380,7 +381,7 @@ export class TxAPI extends BaseAPI { * @param tx transaction string to decode */ public static decode(encodedTx: string): Tx { - return Tx.fromBuffer(Buffer.from(encodedTx, 'base64')) + return Tx.fromBytes(bytesFromBase64(encodedTx)) } /** diff --git a/src/core/PublicKey.ts b/src/core/PublicKey.ts index 4133d39..151e3d3 100644 --- a/src/core/PublicKey.ts +++ b/src/core/PublicKey.ts @@ -1,27 +1,24 @@ -import { JSONSerializable } from '../util/json' +import { bech32 } from 'bech32' import { sha256, ripemd160 } from '../util/hash' +import { JSONSerializable } from '../util/json' +import { + bytesFromBase64, + bytesFromHex, + base64FromBytes, + concatBytes, +} from '../util/polyfill' import { LegacyAminoPubKey as LegacyAminoPubKey_pb } from '@initia/initia.proto/cosmos/crypto/multisig/keys' import { Any } from '@initia/initia.proto/google/protobuf/any' import { PubKey as PubKey_pb } from '@initia/initia.proto/cosmos/crypto/secp256k1/keys' import { PubKey as ValConsPubKey_pb } from '@initia/initia.proto/cosmos/crypto/ed25519/keys' -import { bech32 } from 'bech32' // As discussed in https://github.com/binance-chain/javascript-sdk/issues/163 // Prefixes listed here: https://github.com/tendermint/tendermint/blob/d419fffe18531317c28c29a292ad7d253f6cafdf/docs/spec/blockchain/encoding.md#public-key-cryptography // Last bytes is varint-encoded length prefix -const pubkeyAminoPrefixSecp256k1 = Buffer.from( - 'eb5ae987' + '21' /* fixed length */, - 'hex' -) -const pubkeyAminoPrefixEd25519 = Buffer.from( - '1624de64' + '20' /* fixed length */, - 'hex' -) +const pubkeyAminoPrefixSecp256k1 = bytesFromHex('eb5ae987' + '21') // fixed length +const pubkeyAminoPrefixEd25519 = bytesFromHex('1624de64' + '20') // fixed length /** See https://github.com/tendermint/tendermint/commit/38b401657e4ad7a7eeb3c30a3cbf512037df3740 */ -const pubkeyAminoPrefixMultisigThreshold = Buffer.from( - '22c1f7e2' /* variable length not included */, - 'hex' -) +const pubkeyAminoPrefixMultisigThreshold = bytesFromHex('22c1f7e2') // variable length not included const encodeUvarint = (value: number | string): number[] => { const checked = Number.parseInt(value.toString()) @@ -117,12 +114,12 @@ export class SimplePublicKey extends JSONSerializable< } public static fromProto(pubkeyProto: SimplePublicKey.Proto): SimplePublicKey { - return new SimplePublicKey(Buffer.from(pubkeyProto.key).toString('base64')) + return new SimplePublicKey(base64FromBytes(pubkeyProto.key)) } public toProto(): SimplePublicKey.Proto { return PubKey_pb.fromPartial({ - key: Buffer.from(this.key, 'base64'), + key: bytesFromBase64(this.key), }) } @@ -138,14 +135,11 @@ export class SimplePublicKey extends JSONSerializable< } public encodeAminoPubkey(): Uint8Array { - return Buffer.concat([ - pubkeyAminoPrefixSecp256k1, - Buffer.from(this.key, 'base64'), - ]) + return concatBytes([pubkeyAminoPrefixSecp256k1, bytesFromBase64(this.key)]) } public rawAddress(): Uint8Array { - const pubkeyData = Buffer.from(this.key, 'base64') + const pubkeyData = bytesFromBase64(this.key) return ripemd160(sha256(pubkeyData)) } @@ -328,12 +322,12 @@ export class ValConsPublicKey extends JSONSerializable< public static fromProto( pubkeyProto: ValConsPublicKey.Proto ): ValConsPublicKey { - return new ValConsPublicKey(Buffer.from(pubkeyProto.key).toString('base64')) + return new ValConsPublicKey(base64FromBytes(pubkeyProto.key)) } public toProto(): ValConsPublicKey.Proto { return ValConsPubKey_pb.fromPartial({ - key: Buffer.from(this.key, 'base64'), + key: bytesFromBase64(this.key), }) } @@ -349,14 +343,11 @@ export class ValConsPublicKey extends JSONSerializable< } public encodeAminoPubkey(): Uint8Array { - return Buffer.concat([ - pubkeyAminoPrefixEd25519, - Buffer.from(this.key, 'base64'), - ]) + return concatBytes([pubkeyAminoPrefixEd25519, bytesFromBase64(this.key)]) } public rawAddress(): Uint8Array { - const pubkeyData = Buffer.from(this.key, 'base64') + const pubkeyData = bytesFromBase64(this.key) return sha256(pubkeyData).slice(0, 20) } diff --git a/src/core/auction/AuctionParams.ts b/src/core/auction/AuctionParams.ts index a3f6a64..f00a5a5 100644 --- a/src/core/auction/AuctionParams.ts +++ b/src/core/auction/AuctionParams.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../util/polyfill' import { Coin } from '../Coin' import { Params as Params_pb } from '@initia/initia.proto/sdk/auction/v1/genesis' @@ -115,7 +116,7 @@ export class AuctionParams extends JSONSerializable< public static fromProto(data: AuctionParams.Proto): AuctionParams { return new AuctionParams( data.maxBundleSize, - Buffer.from(data.escrowAccountAddress).toString('base64'), + base64FromBytes(data.escrowAccountAddress), Coin.fromProto(data.reserveFee as Coin), Coin.fromProto(data.minBidIncrement as Coin), data.frontRunningProtection, @@ -135,7 +136,7 @@ export class AuctionParams extends JSONSerializable< return Params_pb.fromPartial({ maxBundleSize: max_bundle_size, - escrowAccountAddress: Buffer.from(escrow_account_address, 'base64'), + escrowAccountAddress: bytesFromBase64(escrow_account_address), reserveFee: reserve_fee.toProto(), minBidIncrement: min_bid_increment.toProto(), frontRunningProtection: front_running_protection, diff --git a/src/core/auction/msgs/MsgAuctionBid.ts b/src/core/auction/msgs/MsgAuctionBid.ts index 06b82d0..25f5f35 100644 --- a/src/core/auction/msgs/MsgAuctionBid.ts +++ b/src/core/auction/msgs/MsgAuctionBid.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Coin } from '../../Coin' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -60,7 +61,7 @@ export class MsgAuctionBid extends JSONSerializable< return new MsgAuctionBid( data.bidder, Coin.fromProto(data.bid as Coin), - data.transactions.map((tx) => Buffer.from(tx).toString('base64')) + data.transactions.map(base64FromBytes) ) } @@ -69,7 +70,7 @@ export class MsgAuctionBid extends JSONSerializable< return MsgAuctionBid_pb.fromPartial({ bidder, bid: bid.toProto(), - transactions: transactions.map((tx) => Buffer.from(tx, 'base64')), + transactions: transactions.map(bytesFromBase64), }) } diff --git a/src/core/bech32.spec.ts b/src/core/bech32.spec.ts index beb82ad..eb611ab 100644 --- a/src/core/bech32.spec.ts +++ b/src/core/bech32.spec.ts @@ -5,6 +5,7 @@ import { ValPubKey, ValConsAddress, } from './bech32' +import { bytesFromUtf8 } from '../util/polyfill' import { bech32 } from 'bech32' describe('AccAddress', () => { @@ -21,7 +22,7 @@ describe('AccAddress', () => { AccAddress.validate('cosmos176m2p8l3fps3dal7h8gf9jvrv98tu3rqfdht86') ).toBe(false) - const words = bech32.toWords(Buffer.from('foobar', 'utf8')) + const words = bech32.toWords(bytesFromUtf8('foobar')) const badAddress = bech32.encode('init', words) expect(AccAddress.validate(badAddress)).toBe(false) @@ -41,7 +42,7 @@ describe('AccAddress', () => { describe('ValAddress', () => { it('validates validator address', () => { - const words = bech32.toWords(Buffer.from('foobar', 'utf8')) + const words = bech32.toWords(bytesFromUtf8('foobar')) const badAddress = bech32.encode('initvaloper', words) expect(ValAddress.validate(badAddress)).toBe(false) @@ -66,7 +67,7 @@ describe('AccPubKey', () => { ) ).toBe(false) - const words = bech32.toWords(Buffer.from('foobar', 'utf8')) + const words = bech32.toWords(bytesFromUtf8('foobar')) const badPubKey = bech32.encode('initpub', words) expect(AccPubKey.validate(badPubKey)).toBe(false) @@ -90,7 +91,7 @@ describe('ValPubKey', () => { ) ).toBe(true) - const words = bech32.toWords(Buffer.from('foobar', 'utf8')) + const words = bech32.toWords(bytesFromUtf8('foobar')) const badPubKey = bech32.encode('initpub', words) expect(ValPubKey.validate(badPubKey)).toBe(false) diff --git a/src/core/bech32.ts b/src/core/bech32.ts index bbb5be1..5bb5657 100644 --- a/src/core/bech32.ts +++ b/src/core/bech32.ts @@ -1,4 +1,5 @@ import { bech32 } from 'bech32' +import { bytesFromHex, hexFromBytes } from '../util/polyfill' /** `init-` prefixed account address */ export type AccAddress = string @@ -58,7 +59,7 @@ export namespace AccAddress { */ export function toHex(address: AccAddress): string { const vals = bech32.decode(address) - return '0x' + Buffer.from(bech32.fromWords(vals.words)).toString('hex') + return '0x' + hexFromBytes(new Uint8Array(bech32.fromWords(vals.words))) } /** @@ -72,19 +73,19 @@ export namespace AccAddress { if (hex.length <= 40) { return bech32.encode( 'init', - bech32.toWords(Buffer.from(hex.padStart(40, '0'), 'hex')) + bech32.toWords(bytesFromHex(hex.padStart(40, '0'))) ) } else { return bech32.encode( 'init', - bech32.toWords(Buffer.from(hex.padStart(64, '0'), 'hex')) + bech32.toWords(bytesFromHex(hex.padStart(64, '0'))) ) } } - export function toBuffer(address: AccAddress): Buffer { + export function toBytes(address: AccAddress): Uint8Array { const vals = bech32.decode(address) - return Buffer.from(bech32.fromWords(vals.words)) + return new Uint8Array(bech32.fromWords(vals.words)) } } diff --git a/src/core/celestia/Blob.ts b/src/core/celestia/Blob.ts index d4926a7..3f2cd1e 100644 --- a/src/core/celestia/Blob.ts +++ b/src/core/celestia/Blob.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../util/polyfill' import { Blob as Blob_pb } from '@initia/initia.proto/celestia/blob/v1/blob' export class Blob extends JSONSerializable { @@ -47,8 +48,8 @@ export class Blob extends JSONSerializable { public static fromProto(data: Blob.Proto): Blob { return new Blob( - Buffer.from(data.namespaceId).toString('base64'), - Buffer.from(data.data).toString('base64'), + base64FromBytes(data.namespaceId), + base64FromBytes(data.data), data.shareVersion, data.namespaceVersion ) @@ -57,8 +58,8 @@ export class Blob extends JSONSerializable { public toProto(): Blob.Proto { const { namespace_id, data, share_version, namespace_version } = this return Blob_pb.fromPartial({ - namespaceId: Buffer.from(namespace_id, 'base64'), - data: Buffer.from(data, 'base64'), + namespaceId: bytesFromBase64(namespace_id), + data: bytesFromBase64(data), shareVersion: share_version, namespaceVersion: namespace_version, }) diff --git a/src/core/celestia/BlobTx.ts b/src/core/celestia/BlobTx.ts index 2e43646..1111736 100644 --- a/src/core/celestia/BlobTx.ts +++ b/src/core/celestia/BlobTx.ts @@ -42,7 +42,7 @@ export class BlobTx extends JSONSerializable { public static fromProto(data: BlobTx.Proto): BlobTx { return new BlobTx( - Tx.fromBuffer(Buffer.from(data.tx)), + Tx.fromBytes(data.tx), data.blobs.map(Blob.fromProto), data.typeId ) diff --git a/src/core/celestia/msgs/MsgPayForBlobs.ts b/src/core/celestia/msgs/MsgPayForBlobs.ts index 3ec59c6..5843309 100644 --- a/src/core/celestia/msgs/MsgPayForBlobs.ts +++ b/src/core/celestia/msgs/MsgPayForBlobs.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgPayForBlobs as MsgPayForBlobs_pb } from '@initia/initia.proto/celestia/blob/v1/tx' @@ -72,13 +73,9 @@ export class MsgPayForBlobs extends JSONSerializable< public static fromProto(data: MsgPayForBlobs.Proto): MsgPayForBlobs { return new MsgPayForBlobs( data.signer, - data.namespaces.map((namespace) => - Buffer.from(namespace).toString('base64') - ), + data.namespaces.map(base64FromBytes), data.blobSizes, - data.shareCommitments.map((commitment) => - Buffer.from(commitment).toString('base64') - ), + data.shareCommitments.map(base64FromBytes), data.shareVersions ) } @@ -93,13 +90,9 @@ export class MsgPayForBlobs extends JSONSerializable< } = this return MsgPayForBlobs_pb.fromPartial({ signer, - namespaces: namespaces.map((namespace) => - Buffer.from(namespace, 'base64') - ), + namespaces: namespaces.map(bytesFromBase64), blobSizes: blob_sizes, - shareCommitments: share_commitments.map((commitment) => - Buffer.from(commitment, 'base64') - ), + shareCommitments: share_commitments.map(bytesFromBase64), shareVersions: share_versions, }) } diff --git a/src/core/ibc/core/channel/Packet.ts b/src/core/ibc/core/channel/Packet.ts index 52c1a5f..fc57a64 100644 --- a/src/core/ibc/core/channel/Packet.ts +++ b/src/core/ibc/core/channel/Packet.ts @@ -1,7 +1,8 @@ -import { Packet as Packet_pb } from '@initia/initia.proto/ibc/core/channel/v1/channel' -import Long from 'long' import { JSONSerializable } from '../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../util/polyfill' import { Height } from '../client/Height' +import { Packet as Packet_pb } from '@initia/initia.proto/ibc/core/channel/v1/channel' +import Long from 'long' /** Packet defines a type that carries data across different chains through IBC */ export class Packet extends JSONSerializable< @@ -127,7 +128,7 @@ export class Packet extends JSONSerializable< proto.sourceChannel, proto.destinationPort, proto.destinationChannel, - Buffer.from(proto.data).toString('base64'), + base64FromBytes(proto.data), proto.timeoutHeight ? Height.fromProto(proto.timeoutHeight) : undefined, proto.timeoutTimestamp.toString() ) @@ -150,7 +151,7 @@ export class Packet extends JSONSerializable< sourceChannel: source_channel, destinationPort: destination_port, destinationChannel: destination_channel, - data: Buffer.from(data, 'base64'), + data: bytesFromBase64(data), timeoutHeight: timeout_height?.toProto(), timeoutTimestamp: Long.fromString(timeout_timestamp), }) diff --git a/src/core/ibc/core/channel/msgs/MsgChannelCloseConfirm.ts b/src/core/ibc/core/channel/msgs/MsgChannelCloseConfirm.ts index 39cb064..26a8f79 100644 --- a/src/core/ibc/core/channel/msgs/MsgChannelCloseConfirm.ts +++ b/src/core/ibc/core/channel/msgs/MsgChannelCloseConfirm.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgChannelCloseConfirm as MsgChannelCloseConfirm_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -69,7 +70,7 @@ export class MsgChannelCloseConfirm extends JSONSerializable< return new MsgChannelCloseConfirm( proto.portId, proto.channelId, - Buffer.from(proto.proofInit).toString('base64'), + base64FromBytes(proto.proofInit), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -80,7 +81,7 @@ export class MsgChannelCloseConfirm extends JSONSerializable< return MsgChannelCloseConfirm_pb.fromPartial({ portId: port_id, channelId: channel_id, - proofInit: Buffer.from(proof_init, 'base64'), + proofInit: bytesFromBase64(proof_init), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/channel/msgs/MsgChannelOpenAck.ts b/src/core/ibc/core/channel/msgs/MsgChannelOpenAck.ts index a9ac232..aaa55b2 100644 --- a/src/core/ibc/core/channel/msgs/MsgChannelOpenAck.ts +++ b/src/core/ibc/core/channel/msgs/MsgChannelOpenAck.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgChannelOpenAck as MsgChannelOpenAck_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -91,7 +92,7 @@ export class MsgChannelOpenAck extends JSONSerializable< proto.channelId, proto.counterpartyChannelId, proto.counterpartyVersion, - Buffer.from(proto.proofTry).toString('base64'), + base64FromBytes(proto.proofTry), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -112,7 +113,7 @@ export class MsgChannelOpenAck extends JSONSerializable< channelId: channel_id, counterpartyChannelId: counterparty_channel_id, counterpartyVersion: counterparty_version, - proofTry: Buffer.from(proof_try, 'base64'), + proofTry: bytesFromBase64(proof_try), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/channel/msgs/MsgChannelOpenConfirm.ts b/src/core/ibc/core/channel/msgs/MsgChannelOpenConfirm.ts index 13b0cf2..a2ff166 100644 --- a/src/core/ibc/core/channel/msgs/MsgChannelOpenConfirm.ts +++ b/src/core/ibc/core/channel/msgs/MsgChannelOpenConfirm.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgChannelOpenConfirm as MsgChannelOpenConfirm_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -69,7 +70,7 @@ export class MsgChannelOpenConfirm extends JSONSerializable< return new MsgChannelOpenConfirm( proto.portId, proto.channelId, - Buffer.from(proto.proofAck).toString('base64'), + base64FromBytes(proto.proofAck), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -80,7 +81,7 @@ export class MsgChannelOpenConfirm extends JSONSerializable< return MsgChannelOpenConfirm_pb.fromPartial({ portId: port_id, channelId: channel_id, - proofAck: Buffer.from(proof_ack, 'base64'), + proofAck: bytesFromBase64(proof_ack), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/channel/msgs/MsgChannelOpenTry.ts b/src/core/ibc/core/channel/msgs/MsgChannelOpenTry.ts index 3788ba4..451499e 100644 --- a/src/core/ibc/core/channel/msgs/MsgChannelOpenTry.ts +++ b/src/core/ibc/core/channel/msgs/MsgChannelOpenTry.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgChannelOpenTry as MsgChannelOpenTry_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -91,7 +92,7 @@ export class MsgChannelOpenTry extends JSONSerializable< proto.previousChannelId, proto.channel ? Channel.fromProto(proto.channel) : undefined, proto.counterpartyVersion, - Buffer.from(proto.proofInit).toString('base64'), + base64FromBytes(proto.proofInit), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -112,7 +113,7 @@ export class MsgChannelOpenTry extends JSONSerializable< previousChannelId: previous_channel_id, channel: channel?.toProto(), counterpartyVersion: counterparty_version, - proofInit: Buffer.from(proof_init, 'base64'), + proofInit: bytesFromBase64(proof_init), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/channel/msgs/MsgRecvAcknowledgement.ts b/src/core/ibc/core/channel/msgs/MsgRecvAcknowledgement.ts index 16415b3..0ffdc1b 100644 --- a/src/core/ibc/core/channel/msgs/MsgRecvAcknowledgement.ts +++ b/src/core/ibc/core/channel/msgs/MsgRecvAcknowledgement.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgAcknowledgement as MsgAcknowledgement_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -64,8 +65,8 @@ export class MsgAcknowledgement extends JSONSerializable< public static fromProto(proto: MsgAcknowledgement.Proto): MsgAcknowledgement { return new MsgAcknowledgement( proto.packet ? Packet.fromProto(proto.packet) : undefined, - Buffer.from(proto.acknowledgement).toString('base64'), - Buffer.from(proto.proofAcked).toString('base64'), + base64FromBytes(proto.acknowledgement), + base64FromBytes(proto.proofAcked), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -75,8 +76,8 @@ export class MsgAcknowledgement extends JSONSerializable< const { packet, acknowledgement, proof_acked, proof_height, signer } = this return MsgAcknowledgement_pb.fromPartial({ packet: packet?.toProto(), - acknowledgement: Buffer.from(acknowledgement, 'base64'), - proofAcked: Buffer.from(proof_acked, 'base64'), + acknowledgement: bytesFromBase64(acknowledgement), + proofAcked: bytesFromBase64(proof_acked), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/channel/msgs/MsgRecvPacket.ts b/src/core/ibc/core/channel/msgs/MsgRecvPacket.ts index 602035a..f284a73 100644 --- a/src/core/ibc/core/channel/msgs/MsgRecvPacket.ts +++ b/src/core/ibc/core/channel/msgs/MsgRecvPacket.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgRecvPacket as MsgRecvPacket_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -60,7 +61,7 @@ export class MsgRecvPacket extends JSONSerializable< public static fromProto(proto: MsgRecvPacket.Proto): MsgRecvPacket { return new MsgRecvPacket( proto.packet ? Packet.fromProto(proto.packet) : undefined, - Buffer.from(proto.proofCommitment).toString('base64'), + base64FromBytes(proto.proofCommitment), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -70,7 +71,7 @@ export class MsgRecvPacket extends JSONSerializable< const { packet, proof_commitment, proof_height, signer } = this return MsgRecvPacket_pb.fromPartial({ packet: packet?.toProto(), - proofCommitment: Buffer.from(proof_commitment, 'base64'), + proofCommitment: bytesFromBase64(proof_commitment), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/channel/msgs/MsgTimeout.ts b/src/core/ibc/core/channel/msgs/MsgTimeout.ts index 5b5e04d..bedddad 100644 --- a/src/core/ibc/core/channel/msgs/MsgTimeout.ts +++ b/src/core/ibc/core/channel/msgs/MsgTimeout.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgTimeout as MsgTimeout_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -77,7 +78,7 @@ export class MsgTimeout extends JSONSerializable< public static fromProto(proto: MsgTimeout.Proto): MsgTimeout { return new MsgTimeout( proto.packet ? Packet.fromProto(proto.packet) : undefined, - Buffer.from(proto.proofUnreceived).toString('base64'), + base64FromBytes(proto.proofUnreceived), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.nextSequenceRecv.toNumber(), proto.signer @@ -94,7 +95,7 @@ export class MsgTimeout extends JSONSerializable< } = this return MsgTimeout_pb.fromPartial({ packet: packet?.toProto(), - proofUnreceived: Buffer.from(proof_unreceived, 'base64'), + proofUnreceived: bytesFromBase64(proof_unreceived), proofHeight: proof_height?.toProto(), nextSequenceRecv: Long.fromNumber(next_sequence_recv), signer, diff --git a/src/core/ibc/core/channel/msgs/MsgTimeoutClose.ts b/src/core/ibc/core/channel/msgs/MsgTimeoutClose.ts index 69846ae..0d87f8f 100644 --- a/src/core/ibc/core/channel/msgs/MsgTimeoutClose.ts +++ b/src/core/ibc/core/channel/msgs/MsgTimeoutClose.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgTimeoutOnClose as MsgTimeoutOnClose_pb } from '@initia/initia.proto/ibc/core/channel/v1/tx' @@ -83,8 +84,8 @@ export class MsgTimeoutOnClose extends JSONSerializable< public static fromProto(proto: MsgTimeoutOnClose.Proto): MsgTimeoutOnClose { return new MsgTimeoutOnClose( proto.packet ? Packet.fromProto(proto.packet) : undefined, - Buffer.from(proto.proofUnreceived).toString('base64'), - Buffer.from(proto.proofClose).toString('base64'), + base64FromBytes(proto.proofUnreceived), + base64FromBytes(proto.proofClose), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.nextSequenceRecv.toNumber(), proto.signer @@ -102,8 +103,8 @@ export class MsgTimeoutOnClose extends JSONSerializable< } = this return MsgTimeoutOnClose_pb.fromPartial({ packet: packet?.toProto(), - proofUnreceived: Buffer.from(proof_unreceived, 'base64'), - proofClose: Buffer.from(proof_close, 'base64'), + proofUnreceived: bytesFromBase64(proof_unreceived), + proofClose: bytesFromBase64(proof_close), proofHeight: proof_height?.toProto(), nextSequenceRecv: Long.fromNumber(next_sequence_recv), signer, diff --git a/src/core/ibc/core/client/msgs/MsgUpgradeClient.ts b/src/core/ibc/core/client/msgs/MsgUpgradeClient.ts index 3209942..a378062 100644 --- a/src/core/ibc/core/client/msgs/MsgUpgradeClient.ts +++ b/src/core/ibc/core/client/msgs/MsgUpgradeClient.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgUpgradeClient as MsgUpgradeClient_pb } from '@initia/initia.proto/ibc/core/client/v1/tx' @@ -83,8 +84,8 @@ export class MsgUpgradeClient extends JSONSerializable< proto.clientId, proto.clientState, proto.consensusState, - Buffer.from(proto.proofUpgradeClient).toString('base64'), - Buffer.from(proto.proofUpgradeConsensusState).toString('base64'), + base64FromBytes(proto.proofUpgradeClient), + base64FromBytes(proto.proofUpgradeConsensusState), proto.signer ) } @@ -102,10 +103,9 @@ export class MsgUpgradeClient extends JSONSerializable< clientId: client_id, clientState: client_state, consensusState: consensus_state, - proofUpgradeClient: Buffer.from(proof_upgrade_client, 'base64'), - proofUpgradeConsensusState: Buffer.from( - proof_upgrade_consensus_state, - 'base64' + proofUpgradeClient: bytesFromBase64(proof_upgrade_client), + proofUpgradeConsensusState: bytesFromBase64( + proof_upgrade_consensus_state ), signer: signer, }) diff --git a/src/core/ibc/core/client/msgs/tendermint/crypto.ts b/src/core/ibc/core/client/msgs/tendermint/crypto.ts index 51d1e1d..9993bb9 100644 --- a/src/core/ibc/core/client/msgs/tendermint/crypto.ts +++ b/src/core/ibc/core/client/msgs/tendermint/crypto.ts @@ -1,4 +1,8 @@ import { JSONSerializable } from '../../../../../../util/json' +import { + base64FromBytes, + bytesFromBase64, +} from '../../../../../../util/polyfill' import { Proof as Proof_pb } from '@initia/initia.proto/tendermint/crypto/proof' import { PublicKey as PublicKey_pb } from '@initia/initia.proto/tendermint/crypto/keys' import Long from 'long' @@ -7,13 +11,13 @@ export class Proof extends JSONSerializable { /** * @param total * @param index - * @param leafHash + * @param leaf_hash * @param aunts */ constructor( public total: number, public index: number, - public leafHash: string, + public leaf_hash: string, public aunts: string[] ) { super() @@ -29,21 +33,21 @@ export class Proof extends JSONSerializable { } public static fromData(data: Proof.Data): Proof { - const { total, index, leaf_hash: leafHash, aunts } = data + const { total, index, leaf_hash, aunts } = data return new Proof( Number.parseInt(total), Number.parseInt(index), - leafHash, + leaf_hash, aunts ) } public toData(): Proof.Data { - const { total, index, leafHash, aunts } = this + const { total, index, leaf_hash, aunts } = this const res: Proof.Data = { total: total.toFixed(), index: index.toFixed(), - leaf_hash: leafHash, + leaf_hash, aunts, } return res @@ -53,18 +57,18 @@ export class Proof extends JSONSerializable { return new Proof( proto.total.toNumber(), proto.index.toNumber(), - Buffer.from(proto.leafHash).toString('base64'), - proto.aunts.map((aunt) => Buffer.from(aunt).toString('base64')) + base64FromBytes(proto.leafHash), + proto.aunts.map(base64FromBytes) ) } public toProto(): Proof.Proto { - const { total, index, leafHash, aunts } = this + const { total, index, leaf_hash, aunts } = this return Proof_pb.fromPartial({ total: Long.fromNumber(total), index: Long.fromNumber(index), - leafHash: Buffer.from(leafHash, 'base64'), - aunts: aunts.map((aunt) => Buffer.from(aunt, 'base64')), + leafHash: bytesFromBase64(leaf_hash), + aunts: aunts.map(bytesFromBase64), }) } } @@ -123,16 +127,16 @@ export class PublicKey extends JSONSerializable< public static fromProto(proto: PublicKey.Proto): PublicKey { const { ed25519, secp256k1 } = proto return new PublicKey( - ed25519 ? Buffer.from(ed25519).toString('base64') : undefined, - secp256k1 ? Buffer.from(secp256k1).toString('base64') : undefined + ed25519 ? base64FromBytes(ed25519) : undefined, + secp256k1 ? base64FromBytes(secp256k1) : undefined ) } public toProto(): PublicKey.Proto { const { ed25519, secp256k1 } = this return PublicKey_pb.fromPartial({ - ed25519: ed25519 ? Buffer.from(ed25519, 'base64') : undefined, - secp256k1: secp256k1 ? Buffer.from(secp256k1, 'base64') : undefined, + ed25519: ed25519 ? bytesFromBase64(ed25519) : undefined, + secp256k1: secp256k1 ? bytesFromBase64(secp256k1) : undefined, }) } } diff --git a/src/core/ibc/core/client/msgs/tendermint/types.ts b/src/core/ibc/core/client/msgs/tendermint/types.ts index 0431800..a88ade8 100644 --- a/src/core/ibc/core/client/msgs/tendermint/types.ts +++ b/src/core/ibc/core/client/msgs/tendermint/types.ts @@ -1,4 +1,8 @@ import { JSONSerializable } from '../../../../../../util/json' +import { + base64FromBytes, + bytesFromBase64, +} from '../../../../../../util/polyfill' import { Header as Header_pb, SignedHeader as SignedHeader_pb, @@ -26,19 +30,19 @@ export class Header extends JSONSerializable { */ constructor( public version: Consensus | undefined, - public chainId: string, + public chain_id: string, public height: string, public time: Date | undefined, - public lastBlockId: BlockID | undefined, - public lastCommitHash: string, - public dataHash: string, - public validatorsHash: string, - public nextValidatorsHash: string, - public consensusHash: string, - public appHash: string, - public lastResultsHash: string, - public evidenceHash: string, - public proposerAddress: string + public last_block_id: BlockID | undefined, + public last_commit_hash: string, + public data_hash: string, + public validators_hash: string, + public next_validators_hash: string, + public consensus_hash: string, + public app_hash: string, + public last_results_hash: string, + public evidence_hash: string, + public proposer_address: string ) { super() } @@ -55,70 +59,70 @@ export class Header extends JSONSerializable { public static fromData(data: Header.Data): Header { const { version, - chain_id: chainId, + chain_id, height, time, - last_block_id: lastBlockId, - last_commit_hash: lastCommitHash, - data_hash: dataHash, - validators_hash: validatorsHash, - next_validators_hash: nextValidatorsHash, - consensus_hash: consensusHash, - app_hash: appHash, - last_results_hash: lastResultsHash, - evidence_hash: evidenceHash, - proposer_address: proposerAddress, + last_block_id, + last_commit_hash, + data_hash, + validators_hash, + next_validators_hash, + consensus_hash, + app_hash, + last_results_hash, + evidence_hash, + proposer_address, } = data return new Header( version ? Consensus.fromData(version) : undefined, - chainId, + chain_id, height, time ? new Date(time) : undefined, - lastBlockId ? BlockID.fromData(lastBlockId) : undefined, - lastCommitHash, - dataHash, - validatorsHash, - nextValidatorsHash, - consensusHash, - appHash, - lastResultsHash, - evidenceHash, - proposerAddress + last_block_id ? BlockID.fromData(last_block_id) : undefined, + last_commit_hash, + data_hash, + validators_hash, + next_validators_hash, + consensus_hash, + app_hash, + last_results_hash, + evidence_hash, + proposer_address ) } public toData(): Header.Data { const { version, - chainId, + chain_id, height, time, - lastBlockId, - lastCommitHash, - dataHash, - validatorsHash, - nextValidatorsHash, - consensusHash, - appHash, - lastResultsHash, - evidenceHash, - proposerAddress, + last_block_id, + last_commit_hash, + data_hash, + validators_hash, + next_validators_hash, + consensus_hash, + app_hash, + last_results_hash, + evidence_hash, + proposer_address, } = this const res: Header.Data = { version: version?.toData(), - chain_id: chainId, + chain_id, height, time: time?.toISOString().replace(/\.000Z$/, 'Z'), - last_block_id: lastBlockId?.toData(), - last_commit_hash: lastCommitHash, - data_hash: dataHash, - validators_hash: validatorsHash, - next_validators_hash: nextValidatorsHash, - consensus_hash: consensusHash, - app_hash: appHash, - last_results_hash: lastResultsHash, - evidence_hash: evidenceHash, - proposer_address: proposerAddress, + last_block_id: last_block_id?.toData(), + last_commit_hash, + data_hash, + validators_hash, + next_validators_hash, + consensus_hash, + app_hash, + last_results_hash, + evidence_hash, + proposer_address, } return res } @@ -146,50 +150,50 @@ export class Header extends JSONSerializable { height.toString(), time, lastBlockId ? BlockID.fromProto(lastBlockId) : undefined, - Buffer.from(lastCommitHash).toString('base64'), - Buffer.from(dataHash).toString('base64'), - Buffer.from(validatorsHash).toString('base64'), - Buffer.from(nextValidatorsHash).toString('base64'), - Buffer.from(consensusHash).toString('base64'), - Buffer.from(appHash).toString('base64'), - Buffer.from(lastResultsHash).toString('base64'), - Buffer.from(evidenceHash).toString('base64'), - Buffer.from(proposerAddress).toString('base64') + base64FromBytes(lastCommitHash), + base64FromBytes(dataHash), + base64FromBytes(validatorsHash), + base64FromBytes(nextValidatorsHash), + base64FromBytes(consensusHash), + base64FromBytes(appHash), + base64FromBytes(lastResultsHash), + base64FromBytes(evidenceHash), + base64FromBytes(proposerAddress) ) } public toProto(): Header.Proto { const { version, - chainId, + chain_id, height, time, - lastBlockId, - lastCommitHash, - dataHash, - validatorsHash, - nextValidatorsHash, - consensusHash, - appHash, - lastResultsHash, - evidenceHash, - proposerAddress, + last_block_id, + last_commit_hash, + data_hash, + validators_hash, + next_validators_hash, + consensus_hash, + app_hash, + last_results_hash, + evidence_hash, + proposer_address, } = this return Header_pb.fromPartial({ version: version?.toProto(), - chainId, + chainId: chain_id, height: Long.fromString(height), time, - lastBlockId: lastBlockId?.toProto(), - lastCommitHash: Buffer.from(lastCommitHash, 'base64'), - dataHash: Buffer.from(dataHash, 'base64'), - validatorsHash: Buffer.from(validatorsHash, 'base64'), - nextValidatorsHash: Buffer.from(nextValidatorsHash, 'base64'), - consensusHash: Buffer.from(consensusHash, 'base64'), - appHash: Buffer.from(appHash, 'base64'), - lastResultsHash: Buffer.from(lastResultsHash, 'base64'), - evidenceHash: Buffer.from(evidenceHash, 'base64'), - proposerAddress: Buffer.from(proposerAddress, 'base64'), + lastBlockId: last_block_id?.toProto(), + lastCommitHash: bytesFromBase64(last_commit_hash), + dataHash: bytesFromBase64(data_hash), + validatorsHash: bytesFromBase64(validators_hash), + nextValidatorsHash: bytesFromBase64(next_validators_hash), + consensusHash: bytesFromBase64(consensus_hash), + appHash: bytesFromBase64(app_hash), + lastResultsHash: bytesFromBase64(last_results_hash), + evidenceHash: bytesFromBase64(evidence_hash), + proposerAddress: bytesFromBase64(proposer_address), }) } } @@ -290,11 +294,11 @@ export class BlockID extends JSONSerializable< > { /** * @param hash - * @param partSetHeader + * @param part_set_header */ constructor( public hash: string, - public partSetHeader?: PartSetHeader + public part_set_header?: PartSetHeader ) { super() } @@ -309,25 +313,25 @@ export class BlockID extends JSONSerializable< } public static fromData(data: BlockID.Data): BlockID { - const { hash, part_set_header: partSetHeader } = data + const { hash, part_set_header } = data return new BlockID( hash, - partSetHeader ? PartSetHeader.fromData(partSetHeader) : undefined + part_set_header ? PartSetHeader.fromData(part_set_header) : undefined ) } public toData(): BlockID.Data { - const { hash, partSetHeader } = this + const { hash, part_set_header } = this const res: BlockID.Data = { hash, - part_set_header: partSetHeader?.toData(), + part_set_header: part_set_header?.toData(), } return res } public static fromProto(proto: BlockID.Proto): BlockID { return new BlockID( - Buffer.from(proto.hash).toString('base64'), + base64FromBytes(proto.hash), proto.partSetHeader ? PartSetHeader.fromProto(proto.partSetHeader) : undefined @@ -335,10 +339,10 @@ export class BlockID extends JSONSerializable< } public toProto(): BlockID.Proto { - const { hash, partSetHeader } = this + const { hash, part_set_header } = this return BlockID_pb.fromPartial({ - hash: Buffer.from(hash, 'base64'), - partSetHeader: partSetHeader?.toProto(), + hash: bytesFromBase64(hash), + partSetHeader: part_set_header?.toProto(), }) } } @@ -393,17 +397,14 @@ export class PartSetHeader extends JSONSerializable< } public static fromProto(proto: PartSetHeader.Proto): PartSetHeader { - return new PartSetHeader( - proto.total, - Buffer.from(proto.hash).toString('base64') - ) + return new PartSetHeader(proto.total, base64FromBytes(proto.hash)) } public toProto(): PartSetHeader.Proto { const { total, hash } = this return PartSetHeader_pb.fromPartial({ total: total, - hash: Buffer.from(hash, 'base64'), + hash: bytesFromBase64(hash), }) } } @@ -422,13 +423,13 @@ export class Commit extends JSONSerializable { /** * @param height * @param round - * @param blockId + * @param block_id * @param signatures */ constructor( public height: Long, public round: number, - public blockId: BlockID | undefined, + public block_id: BlockID | undefined, public signatures: CommitSig[] ) { super() @@ -444,21 +445,21 @@ export class Commit extends JSONSerializable { } public static fromData(data: Commit.Data): Commit { - const { height, round, block_id: blockId, signatures } = data + const { height, round, block_id, signatures } = data return new Commit( Long.fromString(height), Number.parseInt(round), - blockId ? BlockID.fromData(blockId) : undefined, + block_id ? BlockID.fromData(block_id) : undefined, signatures.map((sig) => CommitSig.fromData(sig)) ) } public toData(): Commit.Data { - const { height, round, blockId, signatures } = this + const { height, round, block_id, signatures } = this const res: Commit.Data = { height: height.toString(), round: round.toFixed(), - block_id: blockId?.toData(), + block_id: block_id?.toData(), signatures: signatures.map((sig) => sig.toData()), } return res @@ -475,11 +476,11 @@ export class Commit extends JSONSerializable { } public toProto(): Commit.Proto { - const { height, round, blockId, signatures } = this + const { height, round, block_id, signatures } = this return Commit_pb.fromPartial({ height, round, - blockId: blockId?.toProto(), + blockId: block_id?.toProto(), signatures: signatures.map((sig) => sig.toProto()), }) } @@ -503,14 +504,14 @@ export class CommitSig extends JSONSerializable< CommitSig.Proto > { /** - * @param blockIdFlag - * @param validatorAddress + * @param block_id_flag + * @param validator_address * @param timestamp * @param signature */ constructor( - public blockIdFlag: BlockIDFlag, - public validatorAddress?: string, + public block_id_flag: BlockIDFlag, + public validator_address?: string, public timestamp?: Date, public signature?: string ) { @@ -537,10 +538,10 @@ export class CommitSig extends JSONSerializable< } public toData(): CommitSig.Data { - const { blockIdFlag, validatorAddress, timestamp, signature } = this + const { block_id_flag, validator_address, timestamp, signature } = this const res: CommitSig.Data = { - block_id_flag: blockIDFlagToJSON(blockIdFlag), - validator_address: validatorAddress ?? '', + block_id_flag: blockIDFlagToJSON(block_id_flag), + validator_address: validator_address ?? '', timestamp: timestamp?.toISOString().replace(/\.000Z$/, 'Z'), signature: signature ?? '', } @@ -551,21 +552,21 @@ export class CommitSig extends JSONSerializable< const { blockIdFlag, validatorAddress, timestamp, signature } = proto return new CommitSig( blockIdFlag, - Buffer.from(validatorAddress).toString('base64'), + base64FromBytes(validatorAddress), timestamp, - Buffer.from(signature).toString('base64') + base64FromBytes(signature) ) } public toProto(): CommitSig.Proto { - const { blockIdFlag, validatorAddress, timestamp, signature } = this + const { block_id_flag, validator_address, timestamp, signature } = this return CommitSig_pb.fromPartial({ - blockIdFlag, - validatorAddress: validatorAddress - ? Buffer.from(validatorAddress, 'base64') + blockIdFlag: block_id_flag, + validatorAddress: validator_address + ? bytesFromBase64(validator_address) : undefined, timestamp, - signature: signature ? Buffer.from(signature, 'base64') : undefined, + signature: signature ? bytesFromBase64(signature) : undefined, }) } } @@ -589,12 +590,12 @@ export class ValidatorSet extends JSONSerializable< /** * @param validators * @param proposer - * @param totalVotingPower + * @param total_voting_power */ constructor( public validators: Validator[], public proposer: Validator | undefined, - public totalVotingPower: Long + public total_voting_power: Long ) { super() } @@ -618,11 +619,11 @@ export class ValidatorSet extends JSONSerializable< } public toData(): ValidatorSet.Data { - const { validators, proposer, totalVotingPower } = this + const { validators, proposer, total_voting_power } = this const res: ValidatorSet.Data = { validators: validators.map((val) => val.toData()), proposer: proposer?.toData(), - total_voting_power: totalVotingPower.toString(), + total_voting_power: total_voting_power.toString(), } return res } @@ -637,11 +638,11 @@ export class ValidatorSet extends JSONSerializable< } public toProto(): ValidatorSet.Proto { - const { validators, proposer, totalVotingPower } = this + const { validators, proposer, total_voting_power } = this return ValidatorSet_pb.fromPartial({ validators: validators.map((val) => val.toProto()), proposer: proposer?.toProto(), - totalVotingPower, + totalVotingPower: total_voting_power, }) } } @@ -663,15 +664,15 @@ export class Validator extends JSONSerializable< > { /** * @param address - * @param pubKey - * @param votingPower - * @param proposerPriority + * @param pub_key + * @param voting_power + * @param proposer_priority */ constructor( public address: string, // not AccAddress in case of opposite chain is not cosmos-sdk based - public pubKey: PublicKey | undefined, - public votingPower: Long, - public proposerPriority: Long + public pub_key: PublicKey | undefined, + public voting_power: Long, + public proposer_priority: Long ) { super() } @@ -686,27 +687,22 @@ export class Validator extends JSONSerializable< } public static fromData(data: Validator.Data): Validator { - const { - address, - pub_key: pubKey, - voting_power: votingPower, - proposer_priority: proposerPriority, - } = data + const { address, pub_key, voting_power, proposer_priority } = data return new Validator( address, - pubKey ? PublicKey.fromData(pubKey) : undefined, - Long.fromString(votingPower), - Long.fromString(proposerPriority) + pub_key ? PublicKey.fromData(pub_key) : undefined, + Long.fromString(voting_power), + Long.fromString(proposer_priority) ) } public toData(): Validator.Data { - const { address, pubKey, votingPower, proposerPriority } = this + const { address, pub_key, voting_power, proposer_priority } = this const res: Validator.Data = { address, - pub_key: pubKey?.toData(), - voting_power: votingPower.toString(), - proposer_priority: proposerPriority.toString(), + pub_key: pub_key?.toData(), + voting_power: voting_power.toString(), + proposer_priority: proposer_priority.toString(), } return res } @@ -714,7 +710,7 @@ export class Validator extends JSONSerializable< public static fromProto(proto: Validator.Proto): Validator { const { address, pubKey, votingPower, proposerPriority } = proto return new Validator( - Buffer.from(address).toString('base64'), + base64FromBytes(address), pubKey ? PublicKey.fromProto(pubKey) : undefined, votingPower, proposerPriority @@ -722,12 +718,12 @@ export class Validator extends JSONSerializable< } public toProto(): Validator.Proto { - const { address, pubKey, votingPower, proposerPriority } = this + const { address, pub_key, voting_power, proposer_priority } = this return Validator_pb.fromPartial({ - address: Buffer.from(address, 'base64'), - pubKey: pubKey?.toProto(), - votingPower, - proposerPriority, + address: bytesFromBase64(address), + pubKey: pub_key?.toProto(), + votingPower: voting_power, + proposerPriority: proposer_priority, }) } } diff --git a/src/core/ibc/core/commitment/MerklePrefix.ts b/src/core/ibc/core/commitment/MerklePrefix.ts index 7f7ff7f..ce13bfe 100644 --- a/src/core/ibc/core/commitment/MerklePrefix.ts +++ b/src/core/ibc/core/commitment/MerklePrefix.ts @@ -1,5 +1,6 @@ import { MerklePrefix as MerklePrefix_pb } from '@initia/initia.proto/ibc/core/commitment/v1/commitment' import { JSONSerializable } from '../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../util/polyfill' /* * MerklePrefix is merkle path prefixed to the key. @@ -45,13 +46,13 @@ export class MerklePrefix extends JSONSerializable< } public static fromProto(proto: MerklePrefix.Proto): MerklePrefix { - return new MerklePrefix(Buffer.from(proto.keyPrefix).toString('base64')) + return new MerklePrefix(base64FromBytes(proto.keyPrefix)) } public toProto(): MerklePrefix.Proto { const { key_prefix } = this return MerklePrefix_pb.fromPartial({ - keyPrefix: Buffer.from(key_prefix, 'base64'), + keyPrefix: bytesFromBase64(key_prefix), }) } } diff --git a/src/core/ibc/core/commitment/MerkleRoot.ts b/src/core/ibc/core/commitment/MerkleRoot.ts index 916ec2d..0c00182 100644 --- a/src/core/ibc/core/commitment/MerkleRoot.ts +++ b/src/core/ibc/core/commitment/MerkleRoot.ts @@ -1,5 +1,6 @@ import { MerkleRoot as MerkleRoot_pb } from '@initia/initia.proto/ibc/core/commitment/v1/commitment' import { JSONSerializable } from '../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../util/polyfill' // MerkleRoot defines a merkle root hash. // In the Cosmos SDK, the AppHash of a block header becomes the root. @@ -36,12 +37,12 @@ export class MerkleRoot extends JSONSerializable< } public static fromProto(proto: MerkleRoot.Proto): MerkleRoot { - return new MerkleRoot(Buffer.from(proto.hash).toString('base64')) + return new MerkleRoot(base64FromBytes(proto.hash)) } public toProto(): MerkleRoot.Proto { return MerkleRoot_pb.fromPartial({ - hash: Buffer.from(this.hash, 'base64'), + hash: bytesFromBase64(this.hash), }) } } diff --git a/src/core/ibc/core/connection/msgs/MsgConnectionOpenAck.ts b/src/core/ibc/core/connection/msgs/MsgConnectionOpenAck.ts index e38bad8..6537e87 100644 --- a/src/core/ibc/core/connection/msgs/MsgConnectionOpenAck.ts +++ b/src/core/ibc/core/connection/msgs/MsgConnectionOpenAck.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgConnectionOpenAck as MsgConnectionOpenAck_pb } from '@initia/initia.proto/ibc/core/connection/v1/tx' @@ -115,9 +116,9 @@ export class MsgConnectionOpenAck extends JSONSerializable< proto.version ? IbcVersion.fromProto(proto.version) : undefined, proto.clientState, proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, - Buffer.from(proto.proofTry).toString('base64'), - Buffer.from(proto.proofClient).toString('base64'), - Buffer.from(proto.proofConsensus).toString('base64'), + base64FromBytes(proto.proofTry), + base64FromBytes(proto.proofClient), + base64FromBytes(proto.proofConsensus), proto.consensusHeight ? Height.fromProto(proto.consensusHeight) : undefined, @@ -144,9 +145,9 @@ export class MsgConnectionOpenAck extends JSONSerializable< version: version?.toProto(), clientState: client_state, proofHeight: proof_height?.toProto(), - proofTry: Buffer.from(proof_try, 'base64'), - proofClient: Buffer.from(proof_client, 'base64'), - proofConsensus: Buffer.from(proof_consensus, 'base64'), + proofTry: bytesFromBase64(proof_try), + proofClient: bytesFromBase64(proof_client), + proofConsensus: bytesFromBase64(proof_consensus), consensusHeight: consensus_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/connection/msgs/MsgConnectionOpenConfirm.ts b/src/core/ibc/core/connection/msgs/MsgConnectionOpenConfirm.ts index 31c7c11..25b379f 100644 --- a/src/core/ibc/core/connection/msgs/MsgConnectionOpenConfirm.ts +++ b/src/core/ibc/core/connection/msgs/MsgConnectionOpenConfirm.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgConnectionOpenConfirm as MsgConnectionOpenConfirm_pb } from '@initia/initia.proto/ibc/core/connection/v1/tx' @@ -65,7 +66,7 @@ export class MsgConnectionOpenConfirm extends JSONSerializable< ): MsgConnectionOpenConfirm { return new MsgConnectionOpenConfirm( proto.connectionId, - Buffer.from(proto.proofAck).toString('base64'), + base64FromBytes(proto.proofAck), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, proto.signer ) @@ -75,7 +76,7 @@ export class MsgConnectionOpenConfirm extends JSONSerializable< const { connection_id, proof_ack, proof_height, signer } = this return MsgConnectionOpenConfirm_pb.fromPartial({ connectionId: connection_id, - proofAck: Buffer.from(proof_ack, 'base64'), + proofAck: bytesFromBase64(proof_ack), proofHeight: proof_height?.toProto(), signer, }) diff --git a/src/core/ibc/core/connection/msgs/MsgConnectionOpenTry.ts b/src/core/ibc/core/connection/msgs/MsgConnectionOpenTry.ts index fd6f3f4..75c9833 100644 --- a/src/core/ibc/core/connection/msgs/MsgConnectionOpenTry.ts +++ b/src/core/ibc/core/connection/msgs/MsgConnectionOpenTry.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../../../util/polyfill' import { AccAddress } from '../../../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgConnectionOpenTry as MsgConnectionOpenTry_pb } from '@initia/initia.proto/ibc/core/connection/v1/tx' @@ -76,9 +77,9 @@ export class MsgConnectionOpenTry extends JSONSerializable< Number.parseInt(delay_period), counterparty_versions.map((cv) => IbcVersion.fromData(cv)), proof_height ? Height.fromData(proof_height) : undefined, - Buffer.from(proof_init).toString('base64'), - Buffer.from(proof_client).toString('base64'), - Buffer.from(proof_consensus).toString('base64'), + proof_init, + proof_client, + proof_consensus, consensus_height ? Height.fromData(consensus_height) : undefined, signer ) @@ -126,9 +127,9 @@ export class MsgConnectionOpenTry extends JSONSerializable< proto.delayPeriod.toNumber(), proto.counterpartyVersions.map((cv) => IbcVersion.fromProto(cv)), proto.proofHeight ? Height.fromProto(proto.proofHeight) : undefined, - Buffer.from(proto.proofInit).toString('base64'), - Buffer.from(proto.proofClient).toString('base64'), - Buffer.from(proto.proofConsensus).toString('base64'), + base64FromBytes(proto.proofInit), + base64FromBytes(proto.proofClient), + base64FromBytes(proto.proofConsensus), proto.consensusHeight ? Height.fromProto(proto.consensusHeight) : undefined, @@ -157,9 +158,9 @@ export class MsgConnectionOpenTry extends JSONSerializable< delayPeriod: Long.fromNumber(delay_period), counterpartyVersions: counterparty_versions.map((cv) => cv.toProto()), proofHeight: proof_height?.toProto(), - proofInit: Buffer.from(proof_init, 'base64'), - proofClient: Buffer.from(proof_client, 'base64'), - proofConsensus: Buffer.from(proof_consensus, 'base64'), + proofInit: bytesFromBase64(proof_init), + proofClient: bytesFromBase64(proof_client), + proofConsensus: bytesFromBase64(proof_consensus), consensusHeight: consensus_height?.toProto(), signer, }) diff --git a/src/core/move/msgs/MsgExecute.ts b/src/core/move/msgs/MsgExecute.ts index 574122a..78393bc 100644 --- a/src/core/move/msgs/MsgExecute.ts +++ b/src/core/move/msgs/MsgExecute.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgExecute as MsgExecute_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -83,7 +84,7 @@ export class MsgExecute extends JSONSerializable< data.moduleName, data.functionName, data.typeArgs, - data.args.map((arg) => Buffer.from(arg).toString('base64')) + data.args.map(base64FromBytes) ) } @@ -102,7 +103,7 @@ export class MsgExecute extends JSONSerializable< moduleName: module_name, functionName: function_name, typeArgs: type_args, - args: args.map((arg) => Buffer.from(arg, 'base64')), + args: args.map(bytesFromBase64), }) } diff --git a/src/core/move/msgs/MsgGovExecute.ts b/src/core/move/msgs/MsgGovExecute.ts index 6cc440b..1e88a8d 100644 --- a/src/core/move/msgs/MsgGovExecute.ts +++ b/src/core/move/msgs/MsgGovExecute.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgGovExecute as MsgGovExecute_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -136,7 +137,7 @@ export class MsgGovExecute extends JSONSerializable< data.moduleName, data.functionName, data.typeArgs, - data.args.map((arg) => Buffer.from(arg).toString('base64')) + data.args.map(base64FromBytes) ) } @@ -158,7 +159,7 @@ export class MsgGovExecute extends JSONSerializable< moduleName: module_name, functionName: function_name, typeArgs: type_args, - args: args.map((arg) => Buffer.from(arg, 'base64')), + args: args.map(bytesFromBase64), }) } diff --git a/src/core/move/msgs/MsgGovPublish.ts b/src/core/move/msgs/MsgGovPublish.ts index d4c20ef..374d86f 100644 --- a/src/core/move/msgs/MsgGovPublish.ts +++ b/src/core/move/msgs/MsgGovPublish.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgGovPublish as MsgGovPublish_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -73,7 +74,7 @@ export class MsgGovPublish extends JSONSerializable< return new MsgGovPublish( proto.authority, proto.sender, - proto.codeBytes.map((code) => Buffer.from(code).toString('base64')), + proto.codeBytes.map(base64FromBytes), proto.upgradePolicy ) } @@ -83,7 +84,7 @@ export class MsgGovPublish extends JSONSerializable< return MsgGovPublish_pb.fromPartial({ authority, sender, - codeBytes: code_bytes.map((code) => Buffer.from(code, 'base64')), + codeBytes: code_bytes.map(bytesFromBase64), upgradePolicy: upgrade_policy, }) } diff --git a/src/core/move/msgs/MsgGovScript.ts b/src/core/move/msgs/MsgGovScript.ts index 7642ae0..0ee70ef 100644 --- a/src/core/move/msgs/MsgGovScript.ts +++ b/src/core/move/msgs/MsgGovScript.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgGovScript as MsgGovScript_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -79,9 +80,9 @@ export class MsgGovScript extends JSONSerializable< return new MsgGovScript( data.authority, data.sender, - Buffer.from(data.codeBytes).toString('base64'), + base64FromBytes(data.codeBytes), data.typeArgs, - data.args.map((arg) => Buffer.from(arg).toString('base64')) + data.args.map(base64FromBytes) ) } @@ -90,9 +91,9 @@ export class MsgGovScript extends JSONSerializable< return MsgGovScript_pb.fromPartial({ authority, sender, - codeBytes: Buffer.from(code_bytes, 'base64'), + codeBytes: bytesFromBase64(code_bytes), typeArgs: type_args, - args: args.map((arg) => Buffer.from(arg, 'base64')), + args: args.map(bytesFromBase64), }) } diff --git a/src/core/move/msgs/MsgGovScriptJSON.ts b/src/core/move/msgs/MsgGovScriptJSON.ts index 92fd1c2..ccd7222 100644 --- a/src/core/move/msgs/MsgGovScriptJSON.ts +++ b/src/core/move/msgs/MsgGovScriptJSON.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgGovScriptJSON as MsgGovScriptJSON_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -79,7 +80,7 @@ export class MsgGovScriptJSON extends JSONSerializable< return new MsgGovScriptJSON( data.authority, data.sender, - Buffer.from(data.codeBytes).toString('base64'), + base64FromBytes(data.codeBytes), data.typeArgs, data.args ) @@ -90,7 +91,7 @@ export class MsgGovScriptJSON extends JSONSerializable< return MsgGovScriptJSON_pb.fromPartial({ authority, sender, - codeBytes: Buffer.from(code_bytes, 'base64'), + codeBytes: bytesFromBase64(code_bytes), typeArgs: type_args, args, }) diff --git a/src/core/move/msgs/MsgPublish.ts b/src/core/move/msgs/MsgPublish.ts index 1cd6f55..2c1a496 100644 --- a/src/core/move/msgs/MsgPublish.ts +++ b/src/core/move/msgs/MsgPublish.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgPublish as MsgPublish_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -51,7 +52,7 @@ export class MsgPublish extends JSONSerializable< public static fromProto(proto: MsgPublish.Proto): MsgPublish { return new MsgPublish( proto.sender, - proto.codeBytes.map((code) => Buffer.from(code).toString('base64')), + proto.codeBytes.map(base64FromBytes), proto.upgradePolicy ) } @@ -60,7 +61,7 @@ export class MsgPublish extends JSONSerializable< const { sender, code_bytes, upgrade_policy } = this return MsgPublish_pb.fromPartial({ sender, - codeBytes: code_bytes.map((code) => Buffer.from(code, 'base64')), + codeBytes: code_bytes.map(bytesFromBase64), upgradePolicy: upgrade_policy, }) } diff --git a/src/core/move/msgs/MsgScript.ts b/src/core/move/msgs/MsgScript.ts index c17ac59..00afc55 100644 --- a/src/core/move/msgs/MsgScript.ts +++ b/src/core/move/msgs/MsgScript.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgScript as MsgScript_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -52,9 +53,9 @@ export class MsgScript extends JSONSerializable< public static fromProto(data: MsgScript.Proto): MsgScript { return new MsgScript( data.sender, - Buffer.from(data.codeBytes).toString('base64'), + base64FromBytes(data.codeBytes), data.typeArgs, - data.args.map((arg) => Buffer.from(arg).toString('base64')) + data.args.map(base64FromBytes) ) } @@ -62,9 +63,9 @@ export class MsgScript extends JSONSerializable< const { sender, code_bytes, type_args, args } = this return MsgScript_pb.fromPartial({ sender, - codeBytes: Buffer.from(code_bytes, 'base64'), + codeBytes: bytesFromBase64(code_bytes), typeArgs: type_args, - args: args.map((arg) => Buffer.from(arg, 'base64')), + args: args.map(bytesFromBase64), }) } diff --git a/src/core/move/msgs/MsgScriptJSON.ts b/src/core/move/msgs/MsgScriptJSON.ts index 614447a..3511d22 100644 --- a/src/core/move/msgs/MsgScriptJSON.ts +++ b/src/core/move/msgs/MsgScriptJSON.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgScriptJSON as MsgScriptJSON_pb } from '@initia/initia.proto/initia/move/v1/tx' @@ -68,7 +69,7 @@ export class MsgScriptJSON extends JSONSerializable< public static fromProto(data: MsgScriptJSON.Proto): MsgScriptJSON { return new MsgScriptJSON( data.sender, - Buffer.from(data.codeBytes).toString('base64'), + base64FromBytes(data.codeBytes), data.typeArgs, data.args ) @@ -78,7 +79,7 @@ export class MsgScriptJSON extends JSONSerializable< const { sender, code_bytes, type_args, args } = this return MsgScriptJSON_pb.fromPartial({ sender, - codeBytes: Buffer.from(code_bytes, 'base64'), + codeBytes: bytesFromBase64(code_bytes), typeArgs: type_args, args, }) diff --git a/src/core/opchild/msgs/MsgFinalizeTokenDeposit.ts b/src/core/opchild/msgs/MsgFinalizeTokenDeposit.ts index a05aa2c..56e9e27 100644 --- a/src/core/opchild/msgs/MsgFinalizeTokenDeposit.ts +++ b/src/core/opchild/msgs/MsgFinalizeTokenDeposit.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Coin } from '../../Coin' import { Denom } from '../../Denom' @@ -114,9 +115,7 @@ export class MsgFinalizeTokenDeposit extends JSONSerializable< msgProto.sequence.toNumber(), msgProto.height.toNumber(), msgProto.baseDenom, - msgProto.data.length - ? Buffer.from(msgProto.data).toString('base64') - : undefined + msgProto.data.length ? base64FromBytes(msgProto.data) : undefined ) } @@ -131,7 +130,7 @@ export class MsgFinalizeTokenDeposit extends JSONSerializable< sequence: Long.fromNumber(sequence), height: Long.fromNumber(height), baseDenom: base_denom, - data: data ? Buffer.from(data, 'base64') : undefined, + data: data ? bytesFromBase64(data) : undefined, }) } diff --git a/src/core/opchild/msgs/MsgUpdateOracle.ts b/src/core/opchild/msgs/MsgUpdateOracle.ts index 275eaf9..63d702c 100644 --- a/src/core/opchild/msgs/MsgUpdateOracle.ts +++ b/src/core/opchild/msgs/MsgUpdateOracle.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { MsgUpdateOracle as MsgUpdateOracle_pb } from '@initia/opinit.proto/opinit/opchild/v1/tx' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -64,7 +65,7 @@ export class MsgUpdateOracle extends JSONSerializable< return new MsgUpdateOracle( data.sender, data.height.toNumber(), - Buffer.from(data.data).toString('base64') + base64FromBytes(data.data) ) } @@ -73,7 +74,7 @@ export class MsgUpdateOracle extends JSONSerializable< return MsgUpdateOracle_pb.fromPartial({ sender, height: Long.fromNumber(height), - data: Buffer.from(data, 'base64'), + data: bytesFromBase64(data), }) } diff --git a/src/core/ophost/BridgeConfig.ts b/src/core/ophost/BridgeConfig.ts index 7a1c238..4b8921a 100644 --- a/src/core/ophost/BridgeConfig.ts +++ b/src/core/ophost/BridgeConfig.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../util/polyfill' import { AccAddress } from '../bech32' import { Duration } from '../Duration' import { BridgeConfig as BridgeConfig_pb } from '@initia/opinit.proto/opinit/ophost/v1/types' @@ -138,7 +139,7 @@ export class BridgeConfig extends JSONSerializable< Duration.fromProto(data.finalizationPeriod as Duration.Proto), data.submissionStartHeight.toNumber(), data.oracleEnabled, - Buffer.from(data.metadata).toString('base64') + base64FromBytes(data.metadata) ) } @@ -162,7 +163,7 @@ export class BridgeConfig extends JSONSerializable< finalizationPeriod: finalization_period.toProto(), submissionStartHeight: Long.fromNumber(submission_start_height), oracleEnabled: oracle_enabled, - metadata: metadata ? Buffer.from(metadata, 'base64') : undefined, + metadata: metadata ? bytesFromBase64(metadata) : undefined, }) } } diff --git a/src/core/ophost/Output.ts b/src/core/ophost/Output.ts index 708649e..1f6adcb 100644 --- a/src/core/ophost/Output.ts +++ b/src/core/ophost/Output.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../util/polyfill' import { Output as Output_pb } from '@initia/opinit.proto/opinit/ophost/v1/types' import Long from 'long' @@ -68,7 +69,7 @@ export class Output extends JSONSerializable< public static fromProto(data: Output.Proto): Output { return new Output( - Buffer.from(data.outputRoot).toString('base64'), + base64FromBytes(data.outputRoot), data.l1BlockNumber.toNumber(), data.l1BlockTime as Date, data.l2BlockNumber.toNumber() @@ -79,7 +80,7 @@ export class Output extends JSONSerializable< const { output_root, l1_block_number, l1_block_time, l2_block_number } = this return Output_pb.fromPartial({ - outputRoot: Buffer.from(output_root, 'base64'), + outputRoot: bytesFromBase64(output_root), l1BlockNumber: Long.fromNumber(l1_block_number), l1BlockTime: l1_block_time, l2BlockNumber: Long.fromNumber(l2_block_number), diff --git a/src/core/ophost/msgs/MsgFinalizeTokenWithdrawal.ts b/src/core/ophost/msgs/MsgFinalizeTokenWithdrawal.ts index bc6572c..b15f857 100644 --- a/src/core/ophost/msgs/MsgFinalizeTokenWithdrawal.ts +++ b/src/core/ophost/msgs/MsgFinalizeTokenWithdrawal.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Coin } from '../../Coin' import { MsgFinalizeTokenWithdrawal as MsgFinalizeTokenWithdrawal_pb } from '@initia/opinit.proto/opinit/ophost/v1/tx' @@ -176,16 +177,14 @@ export class MsgFinalizeTokenWithdrawal extends JSONSerializable< data.sender, data.bridgeId.toNumber(), data.outputIndex.toNumber(), - data.withdrawalProofs.map((proof) => - Buffer.from(proof).toString('base64') - ), + data.withdrawalProofs.map(base64FromBytes), data.from, data.to, data.sequence.toNumber(), Coin.fromProto(data.amount as Coin), - Buffer.from(data.version).toString('base64'), - Buffer.from(data.storageRoot).toString('base64'), - Buffer.from(data.lastBlockHash).toString('base64') + base64FromBytes(data.version), + base64FromBytes(data.storageRoot), + base64FromBytes(data.lastBlockHash) ) } @@ -208,16 +207,14 @@ export class MsgFinalizeTokenWithdrawal extends JSONSerializable< sender, bridgeId: Long.fromNumber(bridge_id), outputIndex: Long.fromNumber(output_index), - withdrawalProofs: withdrawal_proofs.map((proof) => - Buffer.from(proof, 'base64') - ), + withdrawalProofs: withdrawal_proofs.map(bytesFromBase64), from, to, sequence: Long.fromNumber(sequence), amount: amount.toProto(), - version: Buffer.from(version, 'base64'), - storageRoot: Buffer.from(storage_root, 'base64'), - lastBlockHash: Buffer.from(last_block_hash, 'base64'), + version: bytesFromBase64(version), + storageRoot: bytesFromBase64(storage_root), + lastBlockHash: bytesFromBase64(last_block_hash), }) } diff --git a/src/core/ophost/msgs/MsgInitiateTokenDeposit.ts b/src/core/ophost/msgs/MsgInitiateTokenDeposit.ts index fa2d444..51f2543 100644 --- a/src/core/ophost/msgs/MsgInitiateTokenDeposit.ts +++ b/src/core/ophost/msgs/MsgInitiateTokenDeposit.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Coin } from '../../Coin' import { MsgInitiateTokenDeposit as MsgInitiateTokenDeposit_pb } from '@initia/opinit.proto/opinit/ophost/v1/tx' @@ -89,9 +90,7 @@ export class MsgInitiateTokenDeposit extends JSONSerializable< msgProto.bridgeId.toNumber(), msgProto.to, Coin.fromProto(msgProto.amount as Coin), - msgProto.data.length - ? Buffer.from(msgProto.data).toString('base64') - : undefined + msgProto.data.length ? base64FromBytes(msgProto.data) : undefined ) } @@ -102,7 +101,7 @@ export class MsgInitiateTokenDeposit extends JSONSerializable< bridgeId: Long.fromNumber(bridge_id), to, amount: amount.toProto(), - data: data ? Buffer.from(data, 'base64') : undefined, + data: data ? bytesFromBase64(data) : undefined, }) } diff --git a/src/core/ophost/msgs/MsgProposeOutput.ts b/src/core/ophost/msgs/MsgProposeOutput.ts index 4e462e7..e72fdd2 100644 --- a/src/core/ophost/msgs/MsgProposeOutput.ts +++ b/src/core/ophost/msgs/MsgProposeOutput.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { MsgProposeOutput as MsgProposeOutput_pb } from '@initia/opinit.proto/opinit/ophost/v1/tx' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -91,7 +92,7 @@ export class MsgProposeOutput extends JSONSerializable< data.bridgeId.toNumber(), data.outputIndex.toNumber(), data.l2BlockNumber.toNumber(), - Buffer.from(data.outputRoot).toString('base64') + base64FromBytes(data.outputRoot) ) } @@ -103,7 +104,7 @@ export class MsgProposeOutput extends JSONSerializable< bridgeId: Long.fromNumber(bridge_id), outputIndex: Long.fromNumber(output_index), l2BlockNumber: Long.fromNumber(l2_block_number), - outputRoot: output_root ? Buffer.from(output_root, 'base64') : undefined, + outputRoot: output_root ? bytesFromBase64(output_root) : undefined, }) } diff --git a/src/core/ophost/msgs/MsgRecordBatch.ts b/src/core/ophost/msgs/MsgRecordBatch.ts index 09f62eb..8df7caa 100644 --- a/src/core/ophost/msgs/MsgRecordBatch.ts +++ b/src/core/ophost/msgs/MsgRecordBatch.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { MsgRecordBatch as MsgRecordBatch_pb } from '@initia/opinit.proto/opinit/ophost/v1/tx' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -68,7 +69,7 @@ export class MsgRecordBatch extends JSONSerializable< return new MsgRecordBatch( data.submitter, data.bridgeId.toNumber(), - Buffer.from(data.batchBytes).toString('base64') + base64FromBytes(data.batchBytes) ) } @@ -77,7 +78,7 @@ export class MsgRecordBatch extends JSONSerializable< return MsgRecordBatch_pb.fromPartial({ submitter, bridgeId: Long.fromNumber(bridge_id), - batchBytes: batch_bytes ? Buffer.from(batch_bytes, 'base64') : undefined, + batchBytes: batch_bytes ? bytesFromBase64(batch_bytes) : undefined, }) } diff --git a/src/core/ophost/msgs/MsgUpdateMetadata.ts b/src/core/ophost/msgs/MsgUpdateMetadata.ts index 95e8294..9e4aebb 100644 --- a/src/core/ophost/msgs/MsgUpdateMetadata.ts +++ b/src/core/ophost/msgs/MsgUpdateMetadata.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { MsgUpdateMetadata as MsgUpdateMetadata_pb } from '@initia/opinit.proto/opinit/ophost/v1/tx' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -69,7 +70,7 @@ export class MsgUpdateMetadata extends JSONSerializable< return new MsgUpdateMetadata( data.authority, data.bridgeId.toNumber(), - Buffer.from(data.metadata).toString('base64') + base64FromBytes(data.metadata) ) } @@ -78,7 +79,7 @@ export class MsgUpdateMetadata extends JSONSerializable< return MsgUpdateMetadata_pb.fromPartial({ authority, bridgeId: Long.fromNumber(bridge_id), - metadata: Buffer.from(metadata, 'base64'), + metadata: bytesFromBase64(metadata), }) } diff --git a/src/core/slashing/SlashingParams.ts b/src/core/slashing/SlashingParams.ts index 0ec42b2..03be162 100644 --- a/src/core/slashing/SlashingParams.ts +++ b/src/core/slashing/SlashingParams.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../util/json' +import { utf8FromBytes, bytesFromUtf8 } from '../../util/polyfill' import { Duration } from '../Duration' import { Params as Params_pb } from '@initia/initia.proto/cosmos/slashing/v1beta1/slashing' import Long from 'long' @@ -106,10 +107,10 @@ export class SlashingParams extends JSONSerializable< public static fromProto(data: SlashingParams.Proto): SlashingParams { return new SlashingParams( data.signedBlocksWindow.toNumber(), - Number.parseFloat(data.minSignedPerWindow.toString()), + Number.parseFloat(utf8FromBytes(data.minSignedPerWindow)), Duration.fromProto(data.downtimeJailDuration as Duration.Proto), - Number.parseFloat(data.slashFractionDoubleSign.toString()), - Number.parseFloat(data.slashFractionDowntime.toString()) + Number.parseFloat(utf8FromBytes(data.slashFractionDoubleSign)), + Number.parseFloat(utf8FromBytes(data.slashFractionDowntime)) ) } @@ -124,12 +125,12 @@ export class SlashingParams extends JSONSerializable< return Params_pb.fromPartial({ signedBlocksWindow: Long.fromNumber(signed_blocks_window), - minSignedPerWindow: Buffer.from(min_signed_per_window.toString()), + minSignedPerWindow: bytesFromUtf8(min_signed_per_window.toString()), downtimeJailDuration: downtime_jail_duration.toProto(), - slashFractionDoubleSign: Buffer.from( + slashFractionDoubleSign: bytesFromUtf8( slash_fraction_double_sign.toString() ), - slashFractionDowntime: Buffer.from(slash_fraction_downtime.toString()), + slashFractionDowntime: bytesFromUtf8(slash_fraction_downtime.toString()), }) } } diff --git a/src/core/tx/CompactBitArray.ts b/src/core/tx/CompactBitArray.ts index f21f2f3..f745a96 100644 --- a/src/core/tx/CompactBitArray.ts +++ b/src/core/tx/CompactBitArray.ts @@ -1,9 +1,10 @@ import { CompactBitArray as CompactBitArray_pb } from '@initia/initia.proto/cosmos/crypto/multisig/v1beta1/multisig' +import { base64FromBytes, bytesFromBase64 } from '../../util/polyfill' export class CompactBitArray { constructor( public extra_bits_stored: number, - public elems: Buffer + public elems: Uint8Array ) {} public static fromBits(bits: number): CompactBitArray { @@ -19,7 +20,7 @@ export class CompactBitArray { throw new Error('CompactBitArray overflow') } - return new CompactBitArray(bits % 8, Buffer.alloc(num_elems)) + return new CompactBitArray(bits % 8, new Uint8Array(num_elems)) } // returns the number of bits in the bitarray @@ -38,7 +39,7 @@ export class CompactBitArray { return false } - return (this.elems.readUInt8(i >> 3) & (1 << (7 - (i % 8)))) > 0 + return (this.elems[i >> 3] & (1 << (7 - (i % 8)))) > 0 } // sets the bit at index i within the bit array. Returns true if and only if the @@ -82,19 +83,19 @@ export class CompactBitArray { public static fromData(data: CompactBitArray.Data): CompactBitArray { return new CompactBitArray( data.extra_bits_stored, - Buffer.from(data.elems, 'base64') + bytesFromBase64(data.elems) ) } public toData(): CompactBitArray.Data { return { - elems: this.elems.toString('base64'), + elems: base64FromBytes(this.elems), extra_bits_stored: this.extra_bits_stored, } } public static fromProto(proto: CompactBitArray.Proto): CompactBitArray { - return new CompactBitArray(proto.extraBitsStored, Buffer.from(proto.elems)) + return new CompactBitArray(proto.extraBitsStored, proto.elems) } public toProto(): CompactBitArray.Proto { diff --git a/src/core/tx/SignDoc.ts b/src/core/tx/SignDoc.ts index 2c1a612..b2181f8 100644 --- a/src/core/tx/SignDoc.ts +++ b/src/core/tx/SignDoc.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../util/json' +import { base64FromBytes } from '../../util/polyfill' import { Fee } from './Fee' import { Msg } from '../Msg' import Long from 'long' @@ -63,8 +64,8 @@ export class SignDoc extends JSONSerializable< public toData(): SignDoc.Data { const { account_number, chain_id, tx_body, auth_info } = this return { - body_bytes: Buffer.from(tx_body.toBytes()).toString('base64'), - auth_info_bytes: Buffer.from(auth_info.toBytes()).toString('base64'), + body_bytes: base64FromBytes(tx_body.toBytes()), + auth_info_bytes: base64FromBytes(auth_info.toBytes()), account_number: account_number.toFixed(), chain_id, } diff --git a/src/core/tx/SignatureV2.ts b/src/core/tx/SignatureV2.ts index bdf8adc..bd9af7f 100644 --- a/src/core/tx/SignatureV2.ts +++ b/src/core/tx/SignatureV2.ts @@ -1,3 +1,4 @@ +import { bytesFromBase64 } from '../../util/polyfill' import { PublicKey } from '../PublicKey' import { ModeInfo } from './Tx' import { CompactBitArray } from './CompactBitArray' @@ -102,7 +103,7 @@ export namespace SignatureV2 { const sigData = this.single return [ new ModeInfo(new ModeInfo.Single(sigData.mode)), - Buffer.from(sigData.signature, 'base64'), + bytesFromBase64(sigData.signature), ] } diff --git a/src/core/tx/Tx.ts b/src/core/tx/Tx.ts index 298facb..36d61bc 100644 --- a/src/core/tx/Tx.ts +++ b/src/core/tx/Tx.ts @@ -1,3 +1,4 @@ +import { base64FromBytes, bytesFromBase64 } from '../../util/polyfill' import { PublicKey, SimplePublicKey, @@ -72,7 +73,7 @@ export class Tx { return new Tx( TxBody.fromProto(proto.body as TxBody_pb), AuthInfo.fromProto(proto.authInfo as AuthInfo_pb), - proto.signatures.map((sig) => Buffer.from(sig).toString('base64')) + proto.signatures.map(base64FromBytes) ) } @@ -80,7 +81,7 @@ export class Tx { return Tx_pb.fromPartial({ body: this.body.toProto(), authInfo: this.auth_info.toProto(), - signatures: this.signatures.map((s) => Buffer.from(s, 'base64')), + signatures: this.signatures.map(bytesFromBase64), }) } @@ -88,7 +89,7 @@ export class Tx { return Tx_pb.encode(this.toProto()).finish() } - public static fromBuffer(buf: Buffer): Tx { + public static fromBytes(buf: Uint8Array): Tx { return Tx.fromProto(Tx_pb.decode(buf)) } @@ -138,7 +139,7 @@ export class Tx { for (const signature of signatures) { const [modeInfo, sigBytes] = signature.data.toModeInfoAndSignature() - this.signatures.push(Buffer.from(sigBytes).toString('base64')) + this.signatures.push(base64FromBytes(sigBytes)) this.auth_info.signer_infos.push( new SignerInfo(signature.public_key, signature.sequence, modeInfo) ) diff --git a/src/core/wasm/authorizations/AcceptedMessagesFilter.ts b/src/core/wasm/authorizations/AcceptedMessagesFilter.ts index f0ebd2c..36dfb03 100644 --- a/src/core/wasm/authorizations/AcceptedMessagesFilter.ts +++ b/src/core/wasm/authorizations/AcceptedMessagesFilter.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AcceptedMessagesFilter as AcceptedMessagesFilter_pb } from '@initia/initia.proto/cosmwasm/wasm/v1/authz' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -40,14 +41,12 @@ export class AcceptedMessagesFilter extends JSONSerializable< public static fromProto( data: AcceptedMessagesFilter.Proto ): AcceptedMessagesFilter { - return new AcceptedMessagesFilter( - data.messages.map((msg) => Buffer.from(msg).toString('base64')) - ) + return new AcceptedMessagesFilter(data.messages.map(base64FromBytes)) } public toProto(): AcceptedMessagesFilter.Proto { return AcceptedMessagesFilter_pb.fromPartial({ - messages: this.messages.map((msg) => Buffer.from(msg, 'base64')), + messages: this.messages.map(bytesFromBase64), }) } diff --git a/src/core/wasm/authorizations/CodeGrant.ts b/src/core/wasm/authorizations/CodeGrant.ts index 310572c..7ebbdd2 100644 --- a/src/core/wasm/authorizations/CodeGrant.ts +++ b/src/core/wasm/authorizations/CodeGrant.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { CodeGrant as CodeGrant_pb } from '@initia/initia.proto/cosmwasm/wasm/v1/authz' import { AccessConfig } from '../AccessConfig' @@ -52,7 +53,7 @@ export class CodeGrant extends JSONSerializable< public static fromProto(data: CodeGrant.Proto): CodeGrant { return new CodeGrant( - Buffer.from(data.codeHash).toString('base64'), + base64FromBytes(data.codeHash), data.instantiatePermission ? AccessConfig.fromProto(data.instantiatePermission) : undefined @@ -62,7 +63,7 @@ export class CodeGrant extends JSONSerializable< public toProto(): CodeGrant.Proto { const { code_hash, instantiate_permission } = this return CodeGrant_pb.fromPartial({ - codeHash: Buffer.from(code_hash, 'base64'), + codeHash: bytesFromBase64(code_hash), instantiatePermission: instantiate_permission?.toProto(), }) } diff --git a/src/core/wasm/msgs/MsgExecuteContract.ts b/src/core/wasm/msgs/MsgExecuteContract.ts index 653c2eb..d1df3e6 100644 --- a/src/core/wasm/msgs/MsgExecuteContract.ts +++ b/src/core/wasm/msgs/MsgExecuteContract.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { Coins } from '../../Coins' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -67,7 +68,7 @@ export class MsgExecuteContract extends JSONSerializable< return new MsgExecuteContract( data.sender, data.contract, - Buffer.from(data.msg).toString('base64'), + base64FromBytes(data.msg), Coins.fromProto(data.funds) ) } @@ -77,7 +78,7 @@ export class MsgExecuteContract extends JSONSerializable< return MsgExecuteContract_pb.fromPartial({ sender, contract, - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), funds: funds.toProto(), }) } diff --git a/src/core/wasm/msgs/MsgInstantiateContract.ts b/src/core/wasm/msgs/MsgInstantiateContract.ts index 53c5322..b60db48 100644 --- a/src/core/wasm/msgs/MsgInstantiateContract.ts +++ b/src/core/wasm/msgs/MsgInstantiateContract.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { Coins } from '../../Coins' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -98,7 +99,7 @@ export class MsgInstantiateContract extends JSONSerializable< data.admin, data.codeId.toNumber(), data.label, - Buffer.from(data.msg).toString('base64'), + base64FromBytes(data.msg), Coins.fromProto(data.funds) ) } @@ -110,7 +111,7 @@ export class MsgInstantiateContract extends JSONSerializable< admin, codeId: Long.fromNumber(code_id), label, - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), funds: funds.toProto(), }) } diff --git a/src/core/wasm/msgs/MsgInstantiateContractV2.ts b/src/core/wasm/msgs/MsgInstantiateContractV2.ts index 002d831..1f66ac5 100644 --- a/src/core/wasm/msgs/MsgInstantiateContractV2.ts +++ b/src/core/wasm/msgs/MsgInstantiateContractV2.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { Coins } from '../../Coins' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -110,9 +111,9 @@ export class MsgInstantiateContractV2 extends JSONSerializable< data.admin, data.codeId.toNumber(), data.label, - Buffer.from(data.msg).toString('base64'), + base64FromBytes(data.msg), Coins.fromProto(data.funds), - Buffer.from(data.salt).toString('base64'), + base64FromBytes(data.salt), data.fixMsg ) } @@ -124,9 +125,9 @@ export class MsgInstantiateContractV2 extends JSONSerializable< admin, codeId: Long.fromNumber(code_id), label, - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), funds: funds.toProto(), - salt: Buffer.from(salt, 'base64'), + salt: bytesFromBase64(salt), fixMsg: fix_msg, }) } diff --git a/src/core/wasm/msgs/MsgMigrateContract.ts b/src/core/wasm/msgs/MsgMigrateContract.ts index 3523e69..a8efb03 100644 --- a/src/core/wasm/msgs/MsgMigrateContract.ts +++ b/src/core/wasm/msgs/MsgMigrateContract.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgMigrateContract as MsgMigrateContract_pb } from '@initia/initia.proto/cosmwasm/wasm/v1/tx' @@ -76,7 +77,7 @@ export class MsgMigrateContract extends JSONSerializable< data.sender, data.contract, data.codeId.toNumber(), - Buffer.from(data.msg).toString('base64') + base64FromBytes(data.msg) ) } @@ -86,7 +87,7 @@ export class MsgMigrateContract extends JSONSerializable< sender, contract, codeId: Long.fromNumber(code_id), - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), }) } diff --git a/src/core/wasm/msgs/MsgStoreAndInstantiateContract.ts b/src/core/wasm/msgs/MsgStoreAndInstantiateContract.ts index f8913dc..e0d3505 100644 --- a/src/core/wasm/msgs/MsgStoreAndInstantiateContract.ts +++ b/src/core/wasm/msgs/MsgStoreAndInstantiateContract.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { Coins } from '../../Coins' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' @@ -180,18 +181,18 @@ export class MsgStoreAndInstantiateContract extends JSONSerializable< ): MsgStoreAndInstantiateContract { return new MsgStoreAndInstantiateContract( data.authority, - Buffer.from(data.wasmByteCode).toString('base64'), + base64FromBytes(data.wasmByteCode), data.instantiatePermission ? AccessConfig.fromProto(data.instantiatePermission) : undefined, data.unpinCode, data.admin, data.label, - Buffer.from(data.msg).toString('base64'), + base64FromBytes(data.msg), Coins.fromProto(data.funds), data.source, data.builder, - Buffer.from(data.codeHash).toString('base64') + base64FromBytes(data.codeHash) ) } @@ -212,16 +213,16 @@ export class MsgStoreAndInstantiateContract extends JSONSerializable< return MsgStoreAndInstantiateContract_pb.fromPartial({ authority, - wasmByteCode: Buffer.from(wasm_byte_code, 'base64'), + wasmByteCode: bytesFromBase64(wasm_byte_code), instantiatePermission: instantiate_permission?.toProto(), unpinCode: unpin_code, admin, label, - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), funds: funds.toProto(), source, builder, - codeHash: Buffer.from(code_hash, 'base64'), + codeHash: bytesFromBase64(code_hash), }) } diff --git a/src/core/wasm/msgs/MsgStoreAndMigrateContract.ts b/src/core/wasm/msgs/MsgStoreAndMigrateContract.ts index 6cf7d12..d2ba55a 100644 --- a/src/core/wasm/msgs/MsgStoreAndMigrateContract.ts +++ b/src/core/wasm/msgs/MsgStoreAndMigrateContract.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgStoreAndMigrateContract as MsgStoreAndMigrateContract_pb } from '@initia/initia.proto/cosmwasm/wasm/v1/tx' @@ -102,12 +103,12 @@ export class MsgStoreAndMigrateContract extends JSONSerializable< ): MsgStoreAndMigrateContract { return new MsgStoreAndMigrateContract( data.authority, - Buffer.from(data.wasmByteCode).toString('base64'), + base64FromBytes(data.wasmByteCode), data.instantiatePermission ? AccessConfig.fromProto(data.instantiatePermission) : undefined, data.contract, - Buffer.from(data.msg).toString('base64') + base64FromBytes(data.msg) ) } @@ -117,10 +118,10 @@ export class MsgStoreAndMigrateContract extends JSONSerializable< return MsgStoreAndMigrateContract_pb.fromPartial({ authority, - wasmByteCode: Buffer.from(wasm_byte_code, 'base64'), + wasmByteCode: bytesFromBase64(wasm_byte_code), instantiatePermission: instantiate_permission?.toProto(), contract, - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), }) } diff --git a/src/core/wasm/msgs/MsgStoreCode.ts b/src/core/wasm/msgs/MsgStoreCode.ts index 5532a57..31c46cb 100644 --- a/src/core/wasm/msgs/MsgStoreCode.ts +++ b/src/core/wasm/msgs/MsgStoreCode.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgStoreCode as MsgStoreCode_pb } from '@initia/initia.proto/cosmwasm/wasm/v1/tx' @@ -71,7 +72,7 @@ export class MsgStoreCode extends JSONSerializable< public static fromProto(data: MsgStoreCode.Proto): MsgStoreCode { return new MsgStoreCode( data.sender, - Buffer.from(data.wasmByteCode).toString('base64'), + base64FromBytes(data.wasmByteCode), data.instantiatePermission ? AccessConfig.fromProto(data.instantiatePermission) : undefined @@ -82,7 +83,7 @@ export class MsgStoreCode extends JSONSerializable< const { sender, wasm_byte_code, instantiate_permission } = this return MsgStoreCode_pb.fromPartial({ sender, - wasmByteCode: Buffer.from(wasm_byte_code, 'base64'), + wasmByteCode: bytesFromBase64(wasm_byte_code), instantiatePermission: instantiate_permission?.toProto(), }) } diff --git a/src/core/wasm/msgs/MsgSudoContract.ts b/src/core/wasm/msgs/MsgSudoContract.ts index 8320d54..8594252 100644 --- a/src/core/wasm/msgs/MsgSudoContract.ts +++ b/src/core/wasm/msgs/MsgSudoContract.ts @@ -1,4 +1,5 @@ import { JSONSerializable } from '../../../util/json' +import { base64FromBytes, bytesFromBase64 } from '../../../util/polyfill' import { AccAddress } from '../../bech32' import { Any } from '@initia/initia.proto/google/protobuf/any' import { MsgSudoContract as MsgSudoContract_pb } from '@initia/initia.proto/cosmwasm/wasm/v1/tx' @@ -59,7 +60,7 @@ export class MsgSudoContract extends JSONSerializable< return new MsgSudoContract( data.authority, data.contract, - Buffer.from(data.msg).toString('base64') + base64FromBytes(data.msg) ) } @@ -68,7 +69,7 @@ export class MsgSudoContract extends JSONSerializable< return MsgSudoContract_pb.fromPartial({ authority, contract, - msg: Buffer.from(msg, 'base64'), + msg: bytesFromBase64(msg), }) } diff --git a/src/key/Key.ts b/src/key/Key.ts index 6442094..edb0ecd 100644 --- a/src/key/Key.ts +++ b/src/key/Key.ts @@ -11,6 +11,7 @@ import { SignatureV2, } from '../core' import { SignMode } from '@initia/initia.proto/cosmos/tx/signing/v1beta1/signing' +import { base64FromBytes, bytesFromUtf8, concatBytes } from '../util/polyfill' /** * Abstract key interface that provides transaction signing features and Bech32 address @@ -26,7 +27,7 @@ export abstract class Key { * * @param payload the data to be signed */ - public abstract sign(payload: Buffer): Promise // needs to be async for ledger key signing + public abstract sign(payload: Uint8Array): Promise // needs to be async for ledger key signing /** * You will need to supply `signWithKeccak256`, which produces a signature for an arbitrary bytes payload @@ -34,7 +35,7 @@ export abstract class Key { * * @param payload the data to be signed */ - public abstract signWithKeccak256(payload: Buffer): Promise // needs to be async for ledger key signing + public abstract signWithKeccak256(payload: Uint8Array): Promise // needs to be async for ledger key signing /** * Initia account address. `init-` prefixed. @@ -87,7 +88,7 @@ export abstract class Key { new SignatureV2.Descriptor( new SignatureV2.Descriptor.Single( SignMode.SIGN_MODE_LEGACY_AMINO_JSON, - (await this.sign(Buffer.from(tx.toAminoJSON()))).toString('base64') + base64FromBytes(await this.sign(bytesFromUtf8(tx.toAminoJSON()))) ) ), tx.sequence @@ -116,9 +117,7 @@ export abstract class Key { ), ] - const sigBytes = (await this.sign(Buffer.from(signDoc.toBytes()))).toString( - 'base64' - ) + const sigBytes = base64FromBytes(await this.sign(signDoc.toBytes())) // restore signDoc to origin signDoc.auth_info.signer_infos = signerInfos @@ -145,11 +144,11 @@ export abstract class Key { ) } - const message = Buffer.from(tx.toAminoJSON()) + const message = bytesFromUtf8(tx.toAminoJSON()) const EIP191MessagePrefix = '\x19Ethereum Signed Message:\n' - const signBytes = Buffer.concat([ - Buffer.from(EIP191MessagePrefix), - Buffer.from(message.length.toString()), + const signBytes = concatBytes([ + bytesFromUtf8(EIP191MessagePrefix), + bytesFromUtf8(message.length.toString()), message, ]) @@ -158,7 +157,7 @@ export abstract class Key { new SignatureV2.Descriptor( new SignatureV2.Descriptor.Single( SignMode.SIGN_MODE_EIP_191, - (await this.signWithKeccak256(signBytes)).toString('base64') + base64FromBytes(await this.signWithKeccak256(signBytes)) ) ), tx.sequence diff --git a/src/key/MnemonicKey.ts b/src/key/MnemonicKey.ts index c5369dc..1d6bd6c 100644 --- a/src/key/MnemonicKey.ts +++ b/src/key/MnemonicKey.ts @@ -84,7 +84,7 @@ export class MnemonicKey extends RawKey { throw new Error('Failed to derive key pair') } - super(privateKey) + super(Uint8Array.from(privateKey)) this.mnemonic = mnemonic } } diff --git a/src/key/RawKey.ts b/src/key/RawKey.ts index 5b57a7a..9cf4316 100644 --- a/src/key/RawKey.ts +++ b/src/key/RawKey.ts @@ -2,6 +2,7 @@ import { SHA256, Word32Array } from 'jscrypto' import * as secp256k1 from 'secp256k1' import { Key } from './Key' import { SimplePublicKey } from '../core' +import { base64FromBytes, bytesFromHex } from '../util' import keccak256 from 'keccak256' /** @@ -11,47 +12,34 @@ export class RawKey extends Key { /** * Raw private key, in bytes. */ - public privateKey: Buffer + public privateKey: Uint8Array - constructor(privateKey: Buffer) { - const publicKey = secp256k1.publicKeyCreate( - new Uint8Array(privateKey), - true - ) - super(new SimplePublicKey(Buffer.from(publicKey).toString('base64'))) + constructor(privateKey: Uint8Array) { + const publicKey = secp256k1.publicKeyCreate(privateKey, true) + super(new SimplePublicKey(base64FromBytes(publicKey))) this.privateKey = privateKey } public static fromHex(key: string): RawKey { const hex = key.startsWith('0x') ? key.slice(2) : key if (hex.length !== 64) throw new Error('Invalid private key length') - return new RawKey(Buffer.from(hex, 'hex')) + return new RawKey(bytesFromHex(hex)) } // eslint-disable-next-line @typescript-eslint/require-await - public async sign(payload: Buffer): Promise { - const hash = Buffer.from( - SHA256.hash(new Word32Array(payload)).toString(), - 'hex' - ) - - const { signature } = secp256k1.ecdsaSign( - Uint8Array.from(hash), - Uint8Array.from(this.privateKey) - ) - - return Buffer.from(signature) + public async sign(payload: Uint8Array): Promise { + const hash = bytesFromHex(SHA256.hash(new Word32Array(payload)).toString()) + const { signature } = secp256k1.ecdsaSign(hash, this.privateKey) + return signature } // eslint-disable-next-line @typescript-eslint/require-await - public async signWithKeccak256(payload: Buffer): Promise { + public async signWithKeccak256(payload: Uint8Array): Promise { const hash = keccak256(payload) - const { signature } = secp256k1.ecdsaSign( Uint8Array.from(hash), - Uint8Array.from(this.privateKey) + this.privateKey ) - - return Buffer.from(signature) + return signature } } diff --git a/src/util/bcs.ts b/src/util/bcs.ts index 6a9baeb..db2e904 100644 --- a/src/util/bcs.ts +++ b/src/util/bcs.ts @@ -1,5 +1,6 @@ import { BcsTypeOptions, bcs as mystenBcs } from '@mysten/bcs' import { AccAddress, BigNumber, num } from '../core' +import { hexFromBytes, bytesFromHex } from './polyfill' const initiaAddress = ( options?: BcsTypeOptions> @@ -18,9 +19,9 @@ const initiaAddress = ( throw new Error('invalid address') } - return Buffer.from(val, 'hex') + return bytesFromHex(val) }, - output: (val) => `0x${Buffer.from(val).toString('hex')}`, + output: (val) => `0x${hexFromBytes(val)}`, }) // initia specific types diff --git a/src/util/hash.ts b/src/util/hash.ts index b14a8b8..ba67ad9 100644 --- a/src/util/hash.ts +++ b/src/util/hash.ts @@ -2,7 +2,6 @@ import { SHA256 } from 'jscrypto/SHA256' import { RIPEMD160 } from 'jscrypto/RIPEMD160' import { Base64 } from 'jscrypto/Base64' import { Word32Array } from 'jscrypto' -import KECCAK256 from 'keccak256' /* DEPRECATED (was used by crypto-js) @@ -30,10 +29,6 @@ export function sha256(data: Uint8Array): Uint8Array { return SHA256.hash(new Word32Array(data)).toUint8Array() } -export function keccak256(data: Uint8Array): Uint8Array { - return KECCAK256(Buffer.from(data)) -} - export function ripemd160(data: Uint8Array): Uint8Array { return RIPEMD160.hash(new Word32Array(data)).toUint8Array() } diff --git a/src/util/polyfill.spec.ts b/src/util/polyfill.spec.ts index 7c1c2ee..92f7ea6 100644 --- a/src/util/polyfill.spec.ts +++ b/src/util/polyfill.spec.ts @@ -1,6 +1,6 @@ -import { bytesFromBase64, base64FromBytes } from './polyfill' +import { bytesFromBase64, base64FromBytes, bytesFromHex, hexFromBytes, bytesFromUtf8, utf8FromBytes } from './polyfill' -describe('bytesFromBase64', () => { +describe('base64', () => { const b64Data = 'SGVsbG8gd29ybGQ=' const arrData = new Uint8Array([ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, @@ -39,3 +39,83 @@ describe('bytesFromBase64', () => { expect(result).toEqual(expected) }) }) + +describe('hex', () => { + const hexData = '48656c6c6f20776f726c64' + const arrData = new Uint8Array([ + 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, + ]) + + it('should convert hex string to Uint8Array', () => { + const result = bytesFromHex(hexData) + + expect(result).toEqual(arrData) + }) + + // Handles empty hex strings + it('should return an empty Uint8Array when given an empty hex string', () => { + const hex = '' + const expected = new Uint8Array(0) + + const result = bytesFromHex(hex) + + expect(result).toEqual(expected) + }) + + // Converts a hex string to a Uint8Array using Buffer when available + it('should convert Uint8Array to hex string', () => { + const result = hexFromBytes(arrData) + + expect(result).toEqual(hexData) + }) + + // Handles empty hex strings + it('should return an empty string when given an empty Uint8Array', () => { + const emptyArr = new Uint8Array(0) + const expected = '' + + const result = hexFromBytes(emptyArr) + + expect(result).toEqual(expected) + }) +}) + +describe('utf8', () => { + const utf8Data = 'hello world' + const arrData = new Uint8Array([ + 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 + ]) + + it('should convert utf8 string to Uint8Array', () => { + const result = bytesFromUtf8(utf8Data) + + expect(result).toEqual(arrData) + }) + + // Handles empty utf8 strings + it('should return an empty Uint8Array when given an empty utf8 string', () => { + const utf8 = '' + const expected = new Uint8Array(0) + + const result = bytesFromUtf8(utf8) + + expect(result).toEqual(expected) + }) + + // Converts a utf8 string to a Uint8Array using Buffer when available + it('should convert Uint8Array to utf8 string', () => { + const result = utf8FromBytes(arrData) + + expect(result).toEqual(utf8Data) + }) + + // Handles empty utf8 strings + it('should return an empty string when given an empty Uint8Array', () => { + const emptyArr = new Uint8Array(0) + const expected = '' + + const result = utf8FromBytes(emptyArr) + + expect(result).toEqual(expected) + }) +}) diff --git a/src/util/polyfill.ts b/src/util/polyfill.ts index 5f018d0..eafe2ef 100644 --- a/src/util/polyfill.ts +++ b/src/util/polyfill.ts @@ -56,3 +56,52 @@ export function base64FromBytes(arr: Uint8Array): string { return gt.btoa(bin.join('')) } } + +export function bytesFromHex(hex: string): Uint8Array { + if (gt.Buffer) { + return Uint8Array.from(gt.Buffer.from(hex, 'hex')) + } else { + return new Uint8Array( + (hex.match(/.{1,2}/g) ?? []).map((byte) => parseInt(byte, 16)) + ) + } +} + +export function hexFromBytes(arr: Uint8Array): string { + if (gt.Buffer) { + return gt.Buffer.from(arr).toString('hex') + } else { + return Array.from(arr, (byte) => byte.toString(16).padStart(2, '0')).join( + '' + ) + } +} + +export function bytesFromUtf8(utf8: string): Uint8Array { + if (gt.Buffer) { + return Uint8Array.from(gt.Buffer.from(utf8)) + } else { + return new Uint8Array(new TextEncoder().encode(utf8)) + } +} + +export function utf8FromBytes(arr: Uint8Array): string { + if (gt.Buffer) { + return gt.Buffer.from(arr).toString() + } else { + return new TextDecoder().decode(arr) + } +} + +export function concatBytes(arrs: Uint8Array[]): Uint8Array { + if (gt.Buffer) { + return gt.Buffer.concat(arrs) + } else { + return arrs.reduce((acc, arr) => { + const combined = new Uint8Array(acc.length + arr.length) + combined.set(acc) + combined.set(arr, acc.length) + return combined + }, new Uint8Array()) + } +} From ee54c82eab25757c6ede710a293eefe0a43504e6 Mon Sep 17 00:00:00 2001 From: joon9823 Date: Tue, 8 Oct 2024 16:17:45 +0900 Subject: [PATCH 5/7] Remove webpack --- package-lock.json | 835 +--------------------------------------------- package.json | 7 +- webpack.config.js | 71 ---- 3 files changed, 13 insertions(+), 900 deletions(-) delete mode 100644 webpack.config.js diff --git a/package-lock.json b/package-lock.json index bdd3222..50f3c9b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -52,16 +52,11 @@ "process": "^0.11.10", "stream-browserify": "^3.0.0", "ts-jest": "^29.2.5", - "ts-loader": "^9.4.1", "ts-node": "^10.9.2", - "tsconfig-paths-webpack-plugin": "^4.0.0", "typescript": "^5.4.5", "typescript-eslint": "^7.13.1", "vite": "^5.4.8", - "vite-plugin-dts": "^4.2.3", - "webpack": "^5.94.0", - "webpack-bundle-analyzer": "^4.6.1", - "webpack-cli": "^4.10.0" + "vite-plugin-dts": "^4.2.3" }, "engines": { "node": ">=20" @@ -780,15 +775,6 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/@discoveryjs/json-ext": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz", - "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==", - "dev": true, - "engines": { - "node": ">=10.0.0" - } - }, "node_modules/@esbuild/aix-ppc64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", @@ -1726,6 +1712,8 @@ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz", "integrity": "sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "@jridgewell/gen-mapping": "^0.3.0", "@jridgewell/trace-mapping": "^0.3.9" @@ -1736,6 +1724,8 @@ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "@jridgewell/set-array": "^1.0.1", "@jridgewell/sourcemap-codec": "^1.4.10", @@ -2023,12 +2013,6 @@ "url": "https://opencollective.com/unts" } }, - "node_modules/@polka/url": { - "version": "1.0.0-next.21", - "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz", - "integrity": "sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g==", - "dev": true - }, "node_modules/@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", @@ -3059,217 +3043,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@webassemblyjs/ast": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.12.1.tgz", - "integrity": "sha512-EKfMUOPRRUTy5UII4qJDGPpqfwjOmZ5jeGFwid9mnoqIFK+e0vqoi1qH56JpmZSzEL53jKnNzScdmftJyG5xWg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/helper-numbers": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6" - } - }, - "node_modules/@webassemblyjs/floating-point-hex-parser": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz", - "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-api-error": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz", - "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-buffer": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.12.1.tgz", - "integrity": "sha512-nzJwQw99DNDKr9BVCOZcLuJJUlqkJh+kVzVl6Fmq/tI5ZtEyWT1KZMyOXltXLZJmDtvLCDgwsyrkohEtopTXCw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-numbers": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz", - "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/floating-point-hex-parser": "1.11.6", - "@webassemblyjs/helper-api-error": "1.11.6", - "@xtuc/long": "4.2.2" - } - }, - "node_modules/@webassemblyjs/helper-wasm-bytecode": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz", - "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-wasm-section": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.12.1.tgz", - "integrity": "sha512-Jif4vfB6FJlUlSbgEMHUyk1j234GTNG9dBJ4XJdOySoj518Xj0oGsNi59cUQF4RRMS9ouBUxDDdyBVfPTypa5g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.12.1", - "@webassemblyjs/helper-buffer": "1.12.1", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/wasm-gen": "1.12.1" - } - }, - "node_modules/@webassemblyjs/ieee754": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz", - "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@xtuc/ieee754": "^1.2.0" - } - }, - "node_modules/@webassemblyjs/leb128": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz", - "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@xtuc/long": "4.2.2" - } - }, - "node_modules/@webassemblyjs/utf8": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz", - "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/wasm-edit": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.12.1.tgz", - "integrity": "sha512-1DuwbVvADvS5mGnXbE+c9NfA8QRcZ6iKquqjjmR10k6o+zzsRVesil54DKexiowcFCPdr/Q0qaMgB01+SQ1u6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.12.1", - "@webassemblyjs/helper-buffer": "1.12.1", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/helper-wasm-section": "1.12.1", - "@webassemblyjs/wasm-gen": "1.12.1", - "@webassemblyjs/wasm-opt": "1.12.1", - "@webassemblyjs/wasm-parser": "1.12.1", - "@webassemblyjs/wast-printer": "1.12.1" - } - }, - "node_modules/@webassemblyjs/wasm-gen": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.12.1.tgz", - "integrity": "sha512-TDq4Ojh9fcohAw6OIMXqiIcTq5KUXTGRkVxbSo1hQnSy6lAM5GSdfwWeSxpAo0YzgsgF182E/U0mDNhuA0tW7w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.12.1", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/ieee754": "1.11.6", - "@webassemblyjs/leb128": "1.11.6", - "@webassemblyjs/utf8": "1.11.6" - } - }, - "node_modules/@webassemblyjs/wasm-opt": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.12.1.tgz", - "integrity": "sha512-Jg99j/2gG2iaz3hijw857AVYekZe2SAskcqlWIZXjji5WStnOpVoat3gQfT/Q5tb2djnCjBtMocY/Su1GfxPBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.12.1", - "@webassemblyjs/helper-buffer": "1.12.1", - "@webassemblyjs/wasm-gen": "1.12.1", - "@webassemblyjs/wasm-parser": "1.12.1" - } - }, - "node_modules/@webassemblyjs/wasm-parser": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.12.1.tgz", - "integrity": "sha512-xikIi7c2FHXysxXe3COrVUPSheuBtpcfhbpFj4gmu7KRLYOzANztwUU0IbsqvMqzuNK2+glRGWCEqZo1WCLyAQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.12.1", - "@webassemblyjs/helper-api-error": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/ieee754": "1.11.6", - "@webassemblyjs/leb128": "1.11.6", - "@webassemblyjs/utf8": "1.11.6" - } - }, - "node_modules/@webassemblyjs/wast-printer": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.12.1.tgz", - "integrity": "sha512-+X4WAlOisVWQMikjbcvY2e0rwPsKQ9F688lksZhBcPycBBuii3O7m8FACbDMWDojpAqvjIncrG8J0XHKyQfVeA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.12.1", - "@xtuc/long": "4.2.2" - } - }, - "node_modules/@webpack-cli/configtest": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.2.0.tgz", - "integrity": "sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg==", - "dev": true, - "peerDependencies": { - "webpack": "4.x.x || 5.x.x", - "webpack-cli": "4.x.x" - } - }, - "node_modules/@webpack-cli/info": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.5.0.tgz", - "integrity": "sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==", - "dev": true, - "dependencies": { - "envinfo": "^7.7.3" - }, - "peerDependencies": { - "webpack-cli": "4.x.x" - } - }, - "node_modules/@webpack-cli/serve": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.7.0.tgz", - "integrity": "sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==", - "dev": true, - "peerDependencies": { - "webpack-cli": "4.x.x" - }, - "peerDependenciesMeta": { - "webpack-dev-server": { - "optional": true - } - } - }, - "node_modules/@xtuc/ieee754": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", - "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/@xtuc/long": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", - "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/acorn": { "version": "8.12.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", @@ -3282,16 +3055,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-attributes": { - "version": "1.9.5", - "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", - "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^8" - } - }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -3368,16 +3131,6 @@ "dev": true, "license": "MIT" }, - "node_modules/ajv-keywords": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", - "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "ajv": "^6.9.1" - } - }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -4144,15 +3897,6 @@ "node": ">=10" } }, - "node_modules/chrome-trace-event": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", - "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", - "dev": true, - "engines": { - "node": ">=6.0" - } - }, "node_modules/ci-info": { "version": "3.5.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.5.0.tgz", @@ -4248,20 +3992,6 @@ "node": ">=8" } }, - "node_modules/clone-deep": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", - "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", - "dev": true, - "dependencies": { - "is-plain-object": "^2.0.4", - "kind-of": "^6.0.2", - "shallow-clone": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", @@ -4654,12 +4384,6 @@ "node": ">=6.0.0" } }, - "node_modules/duplexer": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz", - "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==", - "dev": true - }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -4725,20 +4449,6 @@ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "dev": true }, - "node_modules/enhanced-resolve": { - "version": "5.17.1", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz", - "integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "tapable": "^2.2.0" - }, - "engines": { - "node": ">=10.13.0" - } - }, "node_modules/entities": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", @@ -4752,18 +4462,6 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, - "node_modules/envinfo": { - "version": "7.8.1", - "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.8.1.tgz", - "integrity": "sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==", - "dev": true, - "bin": { - "envinfo": "dist/cli.js" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", @@ -4854,12 +4552,6 @@ "node": ">= 0.4" } }, - "node_modules/es-module-lexer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.2.1.tgz", - "integrity": "sha512-9978wrXM50Y4rTMmW5kXIC09ZdXQZqkE4mxhwkd8VbzsGkXGPgV4zWuqQJgCEzYngdo2dYDa0l8xhX4fkSwJSg==", - "dev": true - }, "node_modules/es-object-atoms": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", @@ -5210,19 +4902,6 @@ } } }, - "node_modules/eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", - "dev": true, - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - }, - "engines": { - "node": ">=8.0.0" - } - }, "node_modules/eslint-visitor-keys": { "version": "3.4.3", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", @@ -5341,15 +5020,6 @@ "node": ">=4.0" } }, - "node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", @@ -5497,15 +5167,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fastest-levenshtein": { - "version": "1.0.16", - "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", - "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", - "dev": true, - "engines": { - "node": ">= 4.9.1" - } - }, "node_modules/fastq": { "version": "1.17.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", @@ -5841,13 +5502,6 @@ "node": ">=10.13.0" } }, - "node_modules/glob-to-regexp": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", - "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", - "dev": true, - "license": "BSD-2-Clause" - }, "node_modules/globals": { "version": "13.24.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", @@ -5929,21 +5583,6 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, - "node_modules/gzip-size": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-6.0.0.tgz", - "integrity": "sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==", - "dev": true, - "dependencies": { - "duplexer": "^0.1.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/has-bigints": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", @@ -6227,15 +5866,6 @@ "node": ">= 0.4" } }, - "node_modules/interpret": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz", - "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==", - "dev": true, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/is-array-buffer": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", @@ -6431,18 +6061,6 @@ "node": ">=8" } }, - "node_modules/is-plain-object": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", - "dev": true, - "dependencies": { - "isobject": "^3.0.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/is-regex": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", @@ -6555,15 +6173,6 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "dev": true }, - "node_modules/isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/istanbul-lib-coverage": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", @@ -7339,15 +6948,6 @@ "json-buffer": "3.0.1" } }, - "node_modules/kind-of": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", - "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/kleur": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", @@ -7631,15 +7231,6 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/loader-runner": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", - "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", - "dev": true, - "engines": { - "node": ">=6.11.5" - } - }, "node_modules/local-pkg": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.0.tgz", @@ -7995,15 +7586,6 @@ "ufo": "^1.5.3" } }, - "node_modules/mrmime": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-1.0.1.tgz", - "integrity": "sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==", - "dev": true, - "engines": { - "node": ">=10" - } - }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -8047,12 +7629,6 @@ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true }, - "node_modules/neo-async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", - "dev": true - }, "node_modules/node-addon-api": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-2.0.2.tgz", @@ -8214,15 +7790,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/opener": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", - "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", - "dev": true, - "bin": { - "opener": "bin/opener-bin.js" - } - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -8746,18 +8313,6 @@ "node": ">= 6" } }, - "node_modules/rechoir": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz", - "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", - "dev": true, - "dependencies": { - "resolve": "^1.9.0" - }, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/regexp.prototype.flags": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz", @@ -9012,25 +8567,6 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, - "node_modules/schema-utils": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", - "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/json-schema": "^7.0.8", - "ajv": "^6.12.5", - "ajv-keywords": "^3.5.2" - }, - "engines": { - "node": ">= 10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, "node_modules/secp256k1": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/secp256k1/-/secp256k1-5.0.0.tgz", @@ -9062,16 +8598,6 @@ "node": ">=10" } }, - "node_modules/serialize-javascript": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", - "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "randombytes": "^2.1.0" - } - }, "node_modules/set-function-length": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", @@ -9116,18 +8642,6 @@ "sha.js": "bin.js" } }, - "node_modules/shallow-clone": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", - "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", - "dev": true, - "dependencies": { - "kind-of": "^6.0.2" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -9173,20 +8687,6 @@ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, - "node_modules/sirv": { - "version": "1.0.19", - "resolved": "https://registry.npmjs.org/sirv/-/sirv-1.0.19.tgz", - "integrity": "sha512-JuLThK3TnZG1TAKDwNIqNq6QA2afLOCcm+iE8D1Kj3GA40pSPsxQjjJl0J8X3tsR7T+CP1GavpzLwYkgVLWrZQ==", - "dev": true, - "dependencies": { - "@polka/url": "^1.0.0-next.20", - "mrmime": "^1.0.0", - "totalist": "^1.0.0" - }, - "engines": { - "node": ">= 10" - } - }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", @@ -9520,21 +9020,14 @@ "url": "https://opencollective.com/unts" } }, - "node_modules/tapable": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", - "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/terser": { "version": "5.34.1", "resolved": "https://registry.npmjs.org/terser/-/terser-5.34.1.tgz", "integrity": "sha512-FsJZ7iZLd/BXkz+4xrRTGJ26o/6VTjQytUk8b8OxkwcD2I+79VPJlz7qss1+zE7h8GNIScFqXcDyJ/KqBYZFVA==", "dev": true, "license": "BSD-2-Clause", + "optional": true, + "peer": true, "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.8.2", @@ -9548,83 +9041,21 @@ "node": ">=10" } }, - "node_modules/terser-webpack-plugin": { - "version": "5.3.10", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.10.tgz", - "integrity": "sha512-BKFPWlPDndPs+NGGCr1U59t0XScL5317Y0UReNrHaw9/FwhPENlq6bfgs+4yPfyP51vqC1bQ4rp1EfXW5ZSH9w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.20", - "jest-worker": "^27.4.5", - "schema-utils": "^3.1.1", - "serialize-javascript": "^6.0.1", - "terser": "^5.26.0" - }, - "engines": { - "node": ">= 10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - }, - "peerDependencies": { - "webpack": "^5.1.0" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "uglify-js": { - "optional": true - } - } - }, - "node_modules/terser-webpack-plugin/node_modules/jest-worker": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", - "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": ">= 10.13.0" - } - }, - "node_modules/terser-webpack-plugin/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, "node_modules/terser/node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true + "dev": true, + "optional": true, + "peer": true }, "node_modules/terser/node_modules/source-map-support": { "version": "0.5.21", "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" @@ -9699,15 +9130,6 @@ "node": ">=8.0" } }, - "node_modules/totalist": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/totalist/-/totalist-1.1.0.tgz", - "integrity": "sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/ts-api-utils": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", @@ -9768,25 +9190,6 @@ } } }, - "node_modules/ts-loader": { - "version": "9.4.1", - "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-9.4.1.tgz", - "integrity": "sha512-384TYAqGs70rn9F0VBnh6BPTfhga7yFNdC5gXbQpDrBj9/KsT4iRkGqKXhziofHOlE2j6YEaiTYVGKKvPhGWvw==", - "dev": true, - "dependencies": { - "chalk": "^4.1.0", - "enhanced-resolve": "^5.0.0", - "micromatch": "^4.0.0", - "semver": "^7.3.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "typescript": "*", - "webpack": "^5.0.0" - } - }, "node_modules/ts-node": { "version": "10.9.2", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", @@ -9830,43 +9233,6 @@ } } }, - "node_modules/tsconfig-paths": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-4.1.0.tgz", - "integrity": "sha512-AHx4Euop/dXFC+Vx589alFba8QItjF+8hf8LtmuiCwHyI4rHXQtOOENaM8kvYf5fR0dRChy3wzWIZ9WbB7FWow==", - "dev": true, - "dependencies": { - "json5": "^2.2.1", - "minimist": "^1.2.6", - "strip-bom": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/tsconfig-paths-webpack-plugin": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tsconfig-paths-webpack-plugin/-/tsconfig-paths-webpack-plugin-4.0.0.tgz", - "integrity": "sha512-fw/7265mIWukrSHd0i+wSwx64kYUSAKPfxRDksjKIYTxSAp9W9/xcZVBF4Kl0eqQd5eBpAQ/oQrc5RyM/0c1GQ==", - "dev": true, - "dependencies": { - "chalk": "^4.1.0", - "enhanced-resolve": "^5.7.0", - "tsconfig-paths": "^4.0.0" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/tsconfig-paths/node_modules/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/tslib": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", @@ -10271,177 +9637,6 @@ "makeerror": "1.0.12" } }, - "node_modules/watchpack": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.2.tgz", - "integrity": "sha512-TnbFSbcOCcDgjZ4piURLCbJ3nJhznVh9kw6F6iokjiFPl8ONxe9A6nMDVXDiNbrSfLILs6vB07F7wLBrwPYzJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "glob-to-regexp": "^0.4.1", - "graceful-fs": "^4.1.2" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/webpack": { - "version": "5.95.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.95.0.tgz", - "integrity": "sha512-2t3XstrKULz41MNMBF+cJ97TyHdyQ8HCt//pqErqDvNjU9YQBnZxIHa11VXsi7F3mb5/aO2tuDxdeTPdU7xu9Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.5", - "@webassemblyjs/ast": "^1.12.1", - "@webassemblyjs/wasm-edit": "^1.12.1", - "@webassemblyjs/wasm-parser": "^1.12.1", - "acorn": "^8.7.1", - "acorn-import-attributes": "^1.9.5", - "browserslist": "^4.21.10", - "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.17.1", - "es-module-lexer": "^1.2.1", - "eslint-scope": "5.1.1", - "events": "^3.2.0", - "glob-to-regexp": "^0.4.1", - "graceful-fs": "^4.2.11", - "json-parse-even-better-errors": "^2.3.1", - "loader-runner": "^4.2.0", - "mime-types": "^2.1.27", - "neo-async": "^2.6.2", - "schema-utils": "^3.2.0", - "tapable": "^2.1.1", - "terser-webpack-plugin": "^5.3.10", - "watchpack": "^2.4.1", - "webpack-sources": "^3.2.3" - }, - "bin": { - "webpack": "bin/webpack.js" - }, - "engines": { - "node": ">=10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - }, - "peerDependenciesMeta": { - "webpack-cli": { - "optional": true - } - } - }, - "node_modules/webpack-bundle-analyzer": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/webpack-bundle-analyzer/-/webpack-bundle-analyzer-4.7.0.tgz", - "integrity": "sha512-j9b8ynpJS4K+zfO5GGwsAcQX4ZHpWV+yRiHDiL+bE0XHJ8NiPYLTNVQdlFYWxtpg9lfAQNlwJg16J9AJtFSXRg==", - "dev": true, - "dependencies": { - "acorn": "^8.0.4", - "acorn-walk": "^8.0.0", - "chalk": "^4.1.0", - "commander": "^7.2.0", - "gzip-size": "^6.0.0", - "lodash": "^4.17.20", - "opener": "^1.5.2", - "sirv": "^1.0.7", - "ws": "^7.3.1" - }, - "bin": { - "webpack-bundle-analyzer": "lib/bin/analyzer.js" - }, - "engines": { - "node": ">= 10.13.0" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", - "dev": true, - "engines": { - "node": ">= 10" - } - }, - "node_modules/webpack-cli": { - "version": "4.10.0", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.10.0.tgz", - "integrity": "sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w==", - "dev": true, - "dependencies": { - "@discoveryjs/json-ext": "^0.5.0", - "@webpack-cli/configtest": "^1.2.0", - "@webpack-cli/info": "^1.5.0", - "@webpack-cli/serve": "^1.7.0", - "colorette": "^2.0.14", - "commander": "^7.0.0", - "cross-spawn": "^7.0.3", - "fastest-levenshtein": "^1.0.12", - "import-local": "^3.0.2", - "interpret": "^2.2.0", - "rechoir": "^0.7.0", - "webpack-merge": "^5.7.3" - }, - "bin": { - "webpack-cli": "bin/cli.js" - }, - "engines": { - "node": ">=10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - }, - "peerDependencies": { - "webpack": "4.x.x || 5.x.x" - }, - "peerDependenciesMeta": { - "@webpack-cli/generators": { - "optional": true - }, - "@webpack-cli/migrate": { - "optional": true - }, - "webpack-bundle-analyzer": { - "optional": true - }, - "webpack-dev-server": { - "optional": true - } - } - }, - "node_modules/webpack-cli/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", - "dev": true, - "engines": { - "node": ">= 10" - } - }, - "node_modules/webpack-merge": { - "version": "5.8.0", - "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz", - "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==", - "dev": true, - "dependencies": { - "clone-deep": "^4.0.1", - "wildcard": "^2.0.0" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/webpack-sources": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", - "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", - "dev": true, - "engines": { - "node": ">=10.13.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -10500,12 +9695,6 @@ "bs58check": "<3.0.0" } }, - "node_modules/wildcard": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.0.tgz", - "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==", - "dev": true - }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/package.json b/package.json index 8e06a8c..60c213f 100644 --- a/package.json +++ b/package.json @@ -52,16 +52,11 @@ "process": "^0.11.10", "stream-browserify": "^3.0.0", "ts-jest": "^29.2.5", - "ts-loader": "^9.4.1", "ts-node": "^10.9.2", - "tsconfig-paths-webpack-plugin": "^4.0.0", "typescript": "^5.4.5", "typescript-eslint": "^7.13.1", "vite": "^5.4.8", - "vite-plugin-dts": "^4.2.3", - "webpack": "^5.94.0", - "webpack-bundle-analyzer": "^4.6.1", - "webpack-cli": "^4.10.0" + "vite-plugin-dts": "^4.2.3" }, "dependencies": { "@initia/initia.proto": "^0.2.3", diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index f8d5252..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,71 +0,0 @@ -const webpack = require('webpack'); -const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); -// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; - -const commonConfig = { - mode: 'production', - entry: './src/index.ts', - devtool: 'source-map', - module: { - rules: [ - { - test: /\.tsx?$/, - use: 'ts-loader', - exclude: /node_modules/, - }, - ], - }, - resolve: { - extensions: ['.tsx', '.ts', '.js'], - plugins: [new TsconfigPathsPlugin()], - }, - plugins: [ - new webpack.IgnorePlugin({ - resourceRegExp: /wordlists\/(french|spanish|italian|korean|chinese_simplified|chinese_traditional|japanese|czech|portuguese)\.json$/, - }), - new webpack.IgnorePlugin({ - checkResource(resource) { - return resource === './CLIKey' - } - }), - ], -}; - -const webConfig = { - ...commonConfig, - target: 'web', - output: { - filename: 'bundle.js', - libraryTarget: 'umd', - library: 'Initia', - }, - resolve: { - ...commonConfig.resolve, - fallback: { - stream: require.resolve('stream-browserify'), - buffer: require.resolve('buffer'), - crypto: require.resolve('crypto-browserify'), - }, - }, - plugins: [ - ...commonConfig.plugins, - new webpack.ProvidePlugin({ - Buffer: ['buffer', 'Buffer'], - }), - new webpack.ProvidePlugin({ - process: 'process/browser', - }), - // new BundleAnalyzerPlugin(), - ], -}; - -const nodeConfig = { - ...commonConfig, - target: 'node', - output: { - libraryTarget: 'commonjs', - filename: 'bundle.node.js', - }, -}; - -module.exports = [webConfig, nodeConfig]; From 4733e0a82e345a6d9516a5d56fc655ffdc860300 Mon Sep 17 00:00:00 2001 From: joon9823 Date: Tue, 8 Oct 2024 16:35:03 +0900 Subject: [PATCH 6/7] Remove Buffer from mnemonic key --- src/key/MnemonicKey.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/key/MnemonicKey.ts b/src/key/MnemonicKey.ts index 1d6bd6c..72a2680 100644 --- a/src/key/MnemonicKey.ts +++ b/src/key/MnemonicKey.ts @@ -74,8 +74,7 @@ export class MnemonicKey extends RawKey { if (mnemonic === undefined) { mnemonic = bip39.generateMnemonic(256) } - const seed: Buffer = bip39.mnemonicToSeedSync(mnemonic) - const masterKey = bip32.fromSeed(seed) + const masterKey = bip32.fromSeed(bip39.mnemonicToSeedSync(mnemonic)) const hdPathInitia = `m/44'/${coinType}'/${account}'/0/${index}` const initiaHD = masterKey.derivePath(hdPathInitia) const privateKey = initiaHD.privateKey From f593173c5def1fbb71c335adde3e3fc520024be5 Mon Sep 17 00:00:00 2001 From: joon9823 Date: Fri, 11 Oct 2024 17:49:32 +0900 Subject: [PATCH 7/7] Remove ledger key and unused packages --- package-lock.json | 421 ++-------------------------------- package.json | 7 +- src/client/WebSocketClient.ts | 2 +- src/key/index.ts | 1 - src/key/ledger/LedgerKey.ts | 313 ------------------------- src/key/ledger/app.ts | 151 ------------ src/key/ledger/constants.ts | 51 ---- src/key/ledger/device.ts | 398 -------------------------------- src/key/ledger/index.ts | 6 - src/key/ledger/types.ts | 51 ---- vite.config.ts | 1 - 11 files changed, 23 insertions(+), 1379 deletions(-) delete mode 100644 src/key/ledger/LedgerKey.ts delete mode 100644 src/key/ledger/app.ts delete mode 100644 src/key/ledger/constants.ts delete mode 100644 src/key/ledger/device.ts delete mode 100644 src/key/ledger/index.ts delete mode 100644 src/key/ledger/types.ts diff --git a/package-lock.json b/package-lock.json index 50f3c9b..e0f5946 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,9 +11,6 @@ "dependencies": { "@initia/initia.proto": "^0.2.3", "@initia/opinit.proto": "^0.0.10", - "@ledgerhq/hw-transport": "^6.27.12", - "@ledgerhq/hw-transport-webhid": "^6.27.12", - "@ledgerhq/hw-transport-webusb": "^6.27.12", "@mysten/bcs": "^1.0.2", "axios": "^1.7.4", "bech32": "^2.0.0", @@ -40,17 +37,15 @@ "@types/ws": "^7.4.7", "@typescript-eslint/eslint-plugin": "^7", "@typescript-eslint/parser": "^7", - "crypto-browserify": "^3.12.0", "eslint": "^8.57.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-import": "^2.29.0", "eslint-plugin-prettier": "^5.1.3", + "eventemitter3": "^5.0.1", "husky": "^9.0.11", "jest": "^29.1.1", "lint-staged": "^13.3.0", "prettier": "^3.1.1", - "process": "^0.11.10", - "stream-browserify": "^3.0.0", "ts-jest": "^29.2.5", "ts-node": "^10.9.2", "typescript": "^5.4.5", @@ -1752,75 +1747,6 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@ledgerhq/devices": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@ledgerhq/devices/-/devices-8.0.0.tgz", - "integrity": "sha512-gSnRT0KPca+LIpaC6D/WZQjOAlSI5uCvK1dmxXtKhODLAj735rX5Z3SnGnLUavRCHNbUi44FzgvloF5BKTkh7A==", - "dependencies": { - "@ledgerhq/errors": "^6.12.3", - "@ledgerhq/logs": "^6.10.1", - "rxjs": "6", - "semver": "^7.3.5" - } - }, - "node_modules/@ledgerhq/devices/node_modules/rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", - "dependencies": { - "tslib": "^1.9.0" - }, - "engines": { - "npm": ">=2.0.0" - } - }, - "node_modules/@ledgerhq/devices/node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" - }, - "node_modules/@ledgerhq/errors": { - "version": "6.12.3", - "resolved": "https://registry.npmjs.org/@ledgerhq/errors/-/errors-6.12.3.tgz", - "integrity": "sha512-djiMSgB/7hnK3aLR/c5ZMMivxjcI7o2+y3VKcsZZpydPoVf9+FXqeJPRfOwmJ0JxbQ//LinUfWpIfHew8LkaVw==" - }, - "node_modules/@ledgerhq/hw-transport": { - "version": "6.28.1", - "resolved": "https://registry.npmjs.org/@ledgerhq/hw-transport/-/hw-transport-6.28.1.tgz", - "integrity": "sha512-RaZe+abn0zBIz82cE9tp7Y7aZkHWWbEaE2yJpfxT8AhFz3fx+BU0kLYzuRN9fmA7vKueNJ1MTVUCY+Ex9/CHSQ==", - "dependencies": { - "@ledgerhq/devices": "^8.0.0", - "@ledgerhq/errors": "^6.12.3", - "events": "^3.3.0" - } - }, - "node_modules/@ledgerhq/hw-transport-webhid": { - "version": "6.27.12", - "resolved": "https://registry.npmjs.org/@ledgerhq/hw-transport-webhid/-/hw-transport-webhid-6.27.12.tgz", - "integrity": "sha512-Yhy5dOKeJIU24Dh9xQjrStc++NviPjRSGHsbc1PeyEjgPEGc8q8wtvm7WFBDzmymBwMhIA5eoNj3fGLk/voXQQ==", - "dependencies": { - "@ledgerhq/devices": "^8.0.0", - "@ledgerhq/errors": "^6.12.3", - "@ledgerhq/hw-transport": "^6.28.1", - "@ledgerhq/logs": "^6.10.1" - } - }, - "node_modules/@ledgerhq/hw-transport-webusb": { - "version": "6.27.12", - "resolved": "https://registry.npmjs.org/@ledgerhq/hw-transport-webusb/-/hw-transport-webusb-6.27.12.tgz", - "integrity": "sha512-U96UWLZIurD9ifHlm77PAgBbvDCe99DAJk64O2SdR41WRF3WaRq/pjrzCq2UvvammdCd1p7nS4zbhlse0wZplg==", - "dependencies": { - "@ledgerhq/devices": "^8.0.0", - "@ledgerhq/errors": "^6.12.3", - "@ledgerhq/hw-transport": "^6.28.1", - "@ledgerhq/logs": "^6.10.1" - } - }, - "node_modules/@ledgerhq/logs": { - "version": "6.10.1", - "resolved": "https://registry.npmjs.org/@ledgerhq/logs/-/logs-6.10.1.tgz", - "integrity": "sha512-z+ILK8Q3y+nfUl43ctCPuR4Y2bIxk/ooCQFwZxhtci1EhAtMDzMAx2W25qx8G1PPL9UUOdnUax19+F0OjXoj4w==" - }, "node_modules/@microsoft/api-extractor": { "version": "7.47.7", "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.47.7.tgz", @@ -3330,24 +3256,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "dev": true, - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } - }, - "node_modules/asn1.js/node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "dev": true - }, "node_modules/async": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", @@ -3606,93 +3514,6 @@ "resolved": "https://registry.npmjs.org/browser-headers/-/browser-headers-0.4.1.tgz", "integrity": "sha512-CA9hsySZVo9371qEHjHZtYxV2cFtVj5Wj/ZHi8ooEsrtm4vOnl9Y9HmyYWk9q+05d7K3rdoAE0j3MVEFVvtQtg==" }, - "node_modules/browserify-aes": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", - "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", - "dev": true, - "dependencies": { - "buffer-xor": "^1.0.3", - "cipher-base": "^1.0.0", - "create-hash": "^1.1.0", - "evp_bytestokey": "^1.0.3", - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/browserify-cipher": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", - "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", - "dev": true, - "dependencies": { - "browserify-aes": "^1.0.4", - "browserify-des": "^1.0.0", - "evp_bytestokey": "^1.0.0" - } - }, - "node_modules/browserify-des": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", - "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", - "dev": true, - "dependencies": { - "cipher-base": "^1.0.1", - "des.js": "^1.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "node_modules/browserify-rsa": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.1.0.tgz", - "integrity": "sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog==", - "dev": true, - "dependencies": { - "bn.js": "^5.0.0", - "randombytes": "^2.0.1" - } - }, - "node_modules/browserify-sign": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.2.tgz", - "integrity": "sha512-1rudGyeYY42Dk6texmv7c4VcQ0EsvVbLwZkA+AQB7SxvXxmcD93jcHie8bzecJ+ChDlmAm2Qyu0+Ccg5uhZXCg==", - "dev": true, - "dependencies": { - "bn.js": "^5.2.1", - "browserify-rsa": "^4.1.0", - "create-hash": "^1.2.0", - "create-hmac": "^1.1.7", - "elliptic": "^6.5.4", - "inherits": "^2.0.4", - "parse-asn1": "^5.1.6", - "readable-stream": "^3.6.2", - "safe-buffer": "^5.2.1" - }, - "engines": { - "node": ">= 4" - } - }, - "node_modules/browserify-sign/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/browserslist": { "version": "4.24.0", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.0.tgz", @@ -3794,12 +3615,6 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, - "node_modules/buffer-xor": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", - "integrity": "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ==", - "dev": true - }, "node_modules/bufferutil": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.7.tgz", @@ -4085,22 +3900,6 @@ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true }, - "node_modules/create-ecdh": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", - "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", - "dev": true, - "dependencies": { - "bn.js": "^4.1.0", - "elliptic": "^6.5.3" - } - }, - "node_modules/create-ecdh/node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "dev": true - }, "node_modules/create-hash": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", @@ -4146,28 +3945,6 @@ "node": ">= 8" } }, - "node_modules/crypto-browserify": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", - "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", - "dev": true, - "dependencies": { - "browserify-cipher": "^1.0.0", - "browserify-sign": "^4.0.0", - "create-ecdh": "^4.0.0", - "create-hash": "^1.1.0", - "create-hmac": "^1.1.0", - "diffie-hellman": "^5.0.0", - "inherits": "^2.0.1", - "pbkdf2": "^3.0.3", - "public-encrypt": "^4.0.0", - "randombytes": "^2.0.0", - "randomfill": "^1.0.3" - }, - "engines": { - "node": "*" - } - }, "node_modules/data-view-buffer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", @@ -4306,16 +4083,6 @@ "node": ">=0.4.0" } }, - "node_modules/des.js": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", - "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", - "dev": true, - "dependencies": { - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0" - } - }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -4343,23 +4110,6 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, - "node_modules/diffie-hellman": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", - "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", - "dev": true, - "dependencies": { - "bn.js": "^4.1.0", - "miller-rabin": "^4.0.0", - "randombytes": "^2.0.0" - } - }, - "node_modules/diffie-hellman/node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "dev": true - }, "node_modules/dir-glob": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", @@ -4413,9 +4163,9 @@ "license": "ISC" }, "node_modules/elliptic": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", - "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", + "version": "6.5.7", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.7.tgz", + "integrity": "sha512-ESVCtTwiA+XhY3wyh24QqRGBoP3rEdDUl3EDUUo9tft074fi19IrdpH7hLCMMP3CIj7jb3W96rn8lt/BqIlt5Q==", "dependencies": { "bn.js": "^4.11.9", "brorand": "^1.1.0", @@ -5042,24 +4792,6 @@ "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", "dev": true }, - "node_modules/events": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", - "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", - "engines": { - "node": ">=0.8.x" - } - }, - "node_modules/evp_bytestokey": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", - "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", - "dev": true, - "dependencies": { - "md5.js": "^1.3.4", - "safe-buffer": "^5.1.1" - } - }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -5665,25 +5397,6 @@ "node": ">=4" } }, - "node_modules/hash-base/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/hash.js": { "version": "1.1.7", "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", @@ -7495,25 +7208,6 @@ "node": ">=8.6" } }, - "node_modules/miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", - "dev": true, - "dependencies": { - "bn.js": "^4.0.0", - "brorand": "^1.0.1" - }, - "bin": { - "miller-rabin": "bin/miller-rabin" - } - }, - "node_modules/miller-rabin/node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "dev": true - }, "node_modules/mime-db": { "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", @@ -7858,19 +7552,6 @@ "node": ">=6" } }, - "node_modules/parse-asn1": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", - "integrity": "sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw==", - "dev": true, - "dependencies": { - "asn1.js": "^5.2.0", - "browserify-aes": "^1.0.0", - "evp_bytestokey": "^1.0.0", - "pbkdf2": "^3.0.3", - "safe-buffer": "^5.1.1" - } - }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -8176,15 +7857,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/process": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", - "dev": true, - "engines": { - "node": ">= 0.6.0" - } - }, "node_modules/prompts": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", @@ -8227,26 +7899,6 @@ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" }, - "node_modules/public-encrypt": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", - "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", - "dev": true, - "dependencies": { - "bn.js": "^4.1.0", - "browserify-rsa": "^4.0.0", - "create-hash": "^1.1.0", - "parse-asn1": "^5.0.0", - "randombytes": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "node_modules/public-encrypt/node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "dev": true - }, "node_modules/punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", @@ -8284,16 +7936,6 @@ "safe-buffer": "^5.1.0" } }, - "node_modules/randomfill": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", - "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", - "dev": true, - "dependencies": { - "randombytes": "^2.0.5", - "safe-buffer": "^5.1.0" - } - }, "node_modules/react-is": { "version": "18.2.0", "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", @@ -8540,9 +8182,23 @@ } }, "node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, "node_modules/safe-regex-test": { "version": "1.0.3", @@ -8561,12 +8217,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true - }, "node_modules/secp256k1": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/secp256k1/-/secp256k1-5.0.0.tgz", @@ -8786,16 +8436,6 @@ "node": ">=8" } }, - "node_modules/stream-browserify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-3.0.0.tgz", - "integrity": "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==", - "dev": true, - "dependencies": { - "inherits": "~2.0.4", - "readable-stream": "^3.5.0" - } - }, "node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -8804,25 +8444,6 @@ "safe-buffer": "~5.2.0" } }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/string-argv": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", diff --git a/package.json b/package.json index 60c213f..d5f42d9 100644 --- a/package.json +++ b/package.json @@ -40,17 +40,15 @@ "@types/ws": "^7.4.7", "@typescript-eslint/eslint-plugin": "^7", "@typescript-eslint/parser": "^7", - "crypto-browserify": "^3.12.0", "eslint": "^8.57.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-import": "^2.29.0", "eslint-plugin-prettier": "^5.1.3", + "eventemitter3": "^5.0.1", "husky": "^9.0.11", "jest": "^29.1.1", "lint-staged": "^13.3.0", "prettier": "^3.1.1", - "process": "^0.11.10", - "stream-browserify": "^3.0.0", "ts-jest": "^29.2.5", "ts-node": "^10.9.2", "typescript": "^5.4.5", @@ -61,9 +59,6 @@ "dependencies": { "@initia/initia.proto": "^0.2.3", "@initia/opinit.proto": "^0.0.10", - "@ledgerhq/hw-transport": "^6.27.12", - "@ledgerhq/hw-transport-webhid": "^6.27.12", - "@ledgerhq/hw-transport-webusb": "^6.27.12", "@mysten/bcs": "^1.0.2", "axios": "^1.7.4", "bech32": "^2.0.0", diff --git a/src/client/WebSocketClient.ts b/src/client/WebSocketClient.ts index c51da4b..bc8eb8c 100644 --- a/src/client/WebSocketClient.ts +++ b/src/client/WebSocketClient.ts @@ -1,4 +1,4 @@ -import { EventEmitter } from 'events' +import { EventEmitter } from 'eventemitter3' import WebSocket from 'ws' import { hashToHex } from '../util/hash' diff --git a/src/key/index.ts b/src/key/index.ts index c9b95e3..a4f6dc7 100644 --- a/src/key/index.ts +++ b/src/key/index.ts @@ -1,4 +1,3 @@ -export * from './ledger' export * from './Key' export * from './MnemonicKey' export * from './RawKey' diff --git a/src/key/ledger/LedgerKey.ts b/src/key/ledger/LedgerKey.ts deleted file mode 100644 index 7a48cc3..0000000 --- a/src/key/ledger/LedgerKey.ts +++ /dev/null @@ -1,313 +0,0 @@ -import * as semver from 'semver' -import Transport from '@ledgerhq/hw-transport' -import InitiaApp from './app' -import { AccAddress, SimplePublicKey, SignatureV2, SignDoc } from '../..' -import { Key } from '../Key' -import { INIT_COIN_TYPE } from '../MnemonicKey' -import { signatureImport } from 'secp256k1' -import { - AppInfoResponse, - CommonResponse, - DeviceInfoResponse, - PublicKeyResponse, - VersionResponse, -} from './types' - -const INTERACTION_TIMEOUT = 120 -const REQUIRED_APP_VERSION = '1.0.0' - -declare global { - interface Window { - google: any - } - interface Navigator { - hid: any - } -} - -export class LedgerError extends Error { - constructor(message: string) { - super(message) - this.name = 'LedgerError' - } -} - -/** - * Key implementation that uses Ledger to sign transactions. Keys should be registered - * in Ledger device - */ -export class LedgerKey extends Key { - private app: InitiaApp - private path: number[] = [44, INIT_COIN_TYPE, 0, 0, 0] - - /** - * - * @param transport transporter for LedgerKey - */ - constructor(private transport?: Transport) { - super() - this.app = new InitiaApp(this.transport) - } - - /** - * Initia account address. `init-` prefixed. - */ - public get accAddress(): AccAddress { - if (!this.publicKey) { - throw new Error('Ledger is unintialized. Initialize it first.') - } - - return this.publicKey.address() - } - - /** - * create and return initialized ledger key - */ - public static async create( - transport?: Transport, - index?: number - ): Promise { - if (!transport) { - transport = await createTransport() - } - - const key = new LedgerKey(transport) - - if (index != undefined) { - key.path[4] = index - } - - if (transport && typeof transport.on === 'function') { - transport.on('disconnect', () => { - key.transport = undefined - }) - } - - await key.initialize().catch(handleConnectError) - return key - } - - /** - * initialize LedgerKey. - * it loads accAddress and publicKey from connected Ledger - */ - private async initialize() { - const res = await this.app.initialize() - - const { app_name: appName } = this.app.getInfo() - if (appName !== 'Initia') { - throw new LedgerError('Open the Initia app in the Ledger') - } - - const { major, minor, patch } = this.app.getVersion() - const version = `${major}.${minor}.${patch}` - if (appName === 'Initia' && semver.lt(version, REQUIRED_APP_VERSION)) { - throw new LedgerError( - 'Outdated version: Update Ledger Initia App to the latest version' - ) - } - checkLedgerErrors(res) - await this.loadAccountDetails() - } - - /** - * get Address and Pubkey from Ledger - */ - public async loadAccountDetails(): Promise { - const res = await this.app.getAddressAndPubKey(this.path, 'init') - checkLedgerErrors(res) - - this.publicKey = new SimplePublicKey( - Buffer.from(res.compressed_pk.data).toString('base64') - ) - return this - } - - // eslint-disable-next-line @typescript-eslint/require-await - public async sign(message: Buffer): Promise { - if (!this.publicKey) { - await this.loadAccountDetails() - } - const res = await this.app.sign(this.path, message) - checkLedgerErrors(res) - - return Buffer.from(signatureImport(Buffer.from(res.signature as any))) // eslint-disable-line @typescript-eslint/no-unsafe-argument - } - - // eslint-disable-next-line @typescript-eslint/require-await - public async signWithKeccak256(): Promise { - throw new Error('LedgerKey does not support signWithKeccak256()') - } - - // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/require-await - public async createSignature(_tx: SignDoc): Promise { - throw new Error('direct sign mode is not supported') - } - - public async getAppAddressAndPubKey(): Promise { - return this.app.getAddressAndPubKey(this.path, 'init') - } - - public getAppInfo(): AppInfoResponse { - return this.app.getInfo() - } - - public async getAppDeviceInfo(): Promise { - return this.app.getDeviceInfo() - } - - public async getAppPublicKey(): Promise { - return this.app.getPublicKey(this.path) - } - - public getAppVersion(): VersionResponse { - return this.app.getVersion() - } - - public async showAddressAndPubKey(): Promise { - return this.app.showAddressAndPubKey(this.path, 'init') - } -} - -const handleConnectError = (err: Error) => { - const message = err.message.trim() - - if (message.startsWith('The device is already open')) { - // ignore this error - return //transport - } - - if (err.name === 'TransportOpenUserCancelled') { - throw new LedgerError( - "Couldn't find the Ledger. Check the Ledger is plugged in and unlocked." - ) - } - - /* istanbul ignore next: specific error rewrite */ - if (message.startsWith('No WebUSB interface found for the Ledger device')) { - throw new LedgerError( - `Couldn't connect to a Ledger device. Use Ledger Live to upgrade the Ledger firmware to version ${REQUIRED_APP_VERSION} or later.` - ) - } - - /* istanbul ignore next: specific error rewrite */ - if (message.startsWith('Unable to claim interface')) { - // apparently can't use it in several tabs in parallel - throw new LedgerError( - "Couldn't access Ledger device. Is it being used in another tab?" - ) - } - - /* istanbul ignore next: specific error rewrite */ - if (message.startsWith('Transport not defined')) { - // apparently can't use it in several tabs in parallel - throw new LedgerError( - "Couldn't access Ledger device. Is it being used in another tab?" - ) - } - - /* istanbul ignore next: specific error rewrite */ - if (message.startsWith('Not supported')) { - throw new LedgerError( - "This browser doesn't support WebUSB yet. Update it to the latest version." - ) - } - - /* istanbul ignore next: specific error rewrite */ - if (message.startsWith('No device selected')) { - throw new LedgerError( - "Couldn't find the Ledger. Check the Ledger is plugged in and unlocked." - ) - } - - // throw unknown error - throw err -} - -const checkLedgerErrors = (response?: CommonResponse) => { - if (!response) { - return - } - - const { error_message, device_locked } = response - - if (device_locked) { - throw new LedgerError("Ledger's screensaver mode is on") - } - - if (error_message.startsWith('TransportRaceCondition')) { - throw new LedgerError('Finish previous action in Ledger') - } else if (error_message.startsWith('DisconnectedDeviceDuringOperation')) { - throw new LedgerError('Open the Initia app in the Ledger') - } - - switch (error_message) { - case 'U2F: Timeout': - throw new LedgerError( - "Couldn't find a connected and unlocked Ledger device" - ) - - case 'App does not seem to be open': - throw new LedgerError('Open the Initia app in the Ledger') - - case 'Command not allowed': - throw new LedgerError('Transaction rejected') - - case 'Transaction rejected': - throw new LedgerError('User rejected the transaction') - - case 'Unknown Status Code: 26628': - throw new LedgerError("Ledger's screensaver mode is on") - - case 'Instruction not supported': - throw new LedgerError( - 'Check the Ledger is running latest version of Initia' - ) - - case 'No errors': - break - - default: - throw new LedgerError(error_message) - } -} - -const isWindows = (platform: string) => platform.indexOf('Win') > -1 -const checkBrowser = (userAgent: string): string => { - const ua = userAgent.toLowerCase() - const isChrome = /chrome|crios/.test(ua) && !/edge|opr\//.test(ua) - const isBrave = isChrome && !window.google - - if (!isChrome && !isBrave) { - throw new LedgerError("This browser doesn't support Ledger devices") - } - - return isChrome ? 'chrome' : 'brave' -} - -async function createTransport(): Promise { - let transport: Transport - - checkBrowser(navigator.userAgent) - - if (isWindows(navigator.platform)) { - // For Windows - if (!navigator.hid) { - throw new LedgerError( - "This browser doesn't have HID enabled. Enable this feature by visiting: chrome://flags/#enable-experimental-web-platform-features" - ) - } - - const { default: TransportWebHid } = await import( - '@ledgerhq/hw-transport-webhid' - ) - transport = await TransportWebHid.create(INTERACTION_TIMEOUT * 1000) - } else { - // For other than Windows - const { default: TransportWebUsb } = await import( - '@ledgerhq/hw-transport-webusb' - ) - transport = await TransportWebUsb.create(INTERACTION_TIMEOUT * 1000) - } - return transport -} diff --git a/src/key/ledger/app.ts b/src/key/ledger/app.ts deleted file mode 100644 index d7dbb41..0000000 --- a/src/key/ledger/app.ts +++ /dev/null @@ -1,151 +0,0 @@ -/** ****************************************************************************** - * (c) 2019 ZondaX GmbH - * (c) 2016-2017 Ledger - * - * Licensed under the Apache License, Version 2.0 (the 'License') - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ******************************************************************************* */ - -import * as crypto from 'crypto' -import Ripemd160 from 'ripemd160' -import Transport from '@ledgerhq/hw-transport' -import { bech32 } from 'bech32' -import { - publicKey, - serializePath, - sign, - getVersion, - getAppInfo, - getDeviceInfo, - getAddressAndPubKey, - showAddressAndPubKey, -} from './device' -import { - CommonResponse, - AppInfoResponse, - VersionResponse, - PublicKeyResponse, - DeviceInfoResponse, - SignResponse, -} from './types' - -const APP_NAME_INITIA = 'Initia' -const APP_NAME_COSMOS = 'Cosmos' - -export default class InitiaApp { - private transport: Transport - private info!: AppInfoResponse - private version!: VersionResponse - - constructor(transport?: Transport) { - if (!transport) { - throw new Error('Transport has not been defined') - } - - this.transport = transport - } - - static serializeHRP(hrp: string): Buffer { - if (!hrp?.length || hrp.length < 3 || hrp.length > 83) { - throw new Error('Invalid HRP') - } - const buf = Buffer.alloc(1 + hrp.length) - buf.writeUInt8(hrp.length, 0) - buf.write(hrp, 1) - return buf - } - - static getBech32FromPK(hrp: string, pk: Buffer): string { - if (pk.length !== 33) { - throw new Error('expected compressed public key [31 bytes]') - } - const hashSha256 = crypto.createHash('sha256').update(pk).digest() - const hashRip = new Ripemd160().update(hashSha256).digest() - return bech32.encode(hrp, bech32.toWords(hashRip)) - } - - private validateCompatibility(): CommonResponse | undefined { - if (this.info && this.version) { - if (this.info.return_code !== 0x9000) { - return this.info - } - - if (this.version.return_code !== 0x9000) { - return this.version - } - - if ( - (this.info.app_name === APP_NAME_INITIA && this.version.major === 1) || - (this.info.app_name === APP_NAME_COSMOS && this.version.major === 2) - ) { - return - } - } - - return { - return_code: 0x6400, - error_message: 'App Version is not supported', - } - } - - /** - * @returns CommonResponse returns CommonResponse if app is not compatible - */ - async initialize(): Promise { - return getAppInfo(this.transport) - .then((appInfo) => { - this.info = appInfo - return getVersion(this.transport) - }) - .then((version) => { - this.version = version - return this.validateCompatibility() - }) - } - - getInfo(): AppInfoResponse { - return this.info - } - - getVersion(): VersionResponse { - return this.version - } - - getDeviceInfo(): Promise { - return getDeviceInfo(this.transport) - } - - getPublicKey(path: number[]): Promise { - const result = serializePath(path) - const data = Buffer.concat([InitiaApp.serializeHRP('init'), result]) - return publicKey(this.transport, data) - } - - getAddressAndPubKey(path: number[], hrp: string): Promise { - const result = serializePath(path) - const data = Buffer.concat([InitiaApp.serializeHRP(hrp), result]) - return getAddressAndPubKey(this.transport, data) - } - - showAddressAndPubKey( - path: number[], - hrp: string - ): Promise { - const result = serializePath(path) - const data = Buffer.concat([InitiaApp.serializeHRP(hrp), result]) - return showAddressAndPubKey(this.transport, data) - } - - sign(path: number[], message: Buffer): Promise { - return sign(this.transport, path, message) - } -} diff --git a/src/key/ledger/constants.ts b/src/key/ledger/constants.ts deleted file mode 100644 index 3c3a65c..0000000 --- a/src/key/ledger/constants.ts +++ /dev/null @@ -1,51 +0,0 @@ -export const CLA = 0x55 -export const CHUNK_SIZE = 250 -export const APP_KEY = 'CSM' - -export const INS = { - GET_VERSION: 0x00, - INS_PUBLIC_KEY_SECP256K1: 0x01, // Obsolete - SIGN_SECP256K1: 0x02, - GET_ADDR_SECP256K1: 0x04, -} - -export const PAYLOAD_TYPE = { - INIT: 0x00, - ADD: 0x01, - LAST: 0x02, -} - -export const P1_VALUES = { - ONLY_RETRIEVE: 0x00, - SHOW_ADDRESS_IN_DEVICE: 0x01, -} - -export const ERROR_CODE = { - NoError: 0x9000, -} - -export const ERROR_DESCRIPTION: Record = { - 1: 'U2F: Unknown', - 2: 'U2F: Bad request', - 3: 'U2F: Configuration unsupported', - 4: 'U2F: Device Ineligible', - 5: 'U2F: Timeout', - 14: 'Timeout', - 0x9000: 'No errors', - 0x9001: 'Device is busy', - 0x6802: 'Error deriving keys', - 0x6400: 'Execution Error', - 0x6700: 'Wrong Length', - 0x6982: 'Empty Buffer', - 0x6983: 'Output buffer too small', - 0x6984: 'Data is invalid', - 0x6985: 'Conditions not satisfied', - 0x6986: 'Transaction rejected', - 0x6a80: 'Bad key handle', - 0x6b00: 'Invalid P1/P2', - 0x6b0c: 'Ledger is locked', - 0x6d00: 'Instruction not supported', - 0x6e00: 'App does not seem to be open', - 0x6f00: 'Unknown error', - 0x6f01: 'Sign/verify error', -} diff --git a/src/key/ledger/device.ts b/src/key/ledger/device.ts deleted file mode 100644 index 58c5cac..0000000 --- a/src/key/ledger/device.ts +++ /dev/null @@ -1,398 +0,0 @@ -import Transport from '@ledgerhq/hw-transport' -import { - CLA, - ERROR_CODE, - P1_VALUES, - INS, - PAYLOAD_TYPE, - CHUNK_SIZE, - ERROR_DESCRIPTION, -} from './constants' -import { - AppInfoResponse, - VersionResponse, - DeviceInfoResponse, - PublicKeyResponse, - SignResponse, -} from './types' - -function errorCodeToString(statusCode: number): string { - if (statusCode in ERROR_DESCRIPTION) { - return ERROR_DESCRIPTION[statusCode] - } - - return `Unknown Status Code: ${statusCode}` -} - -function isDict(v: any): boolean { - return ( - typeof v === 'object' && - v !== null && - !(v instanceof Array) && - !(v instanceof Date) - ) -} - -function processErrorResponse(response: any) { - if (response) { - if (isDict(response)) { - if (Object.prototype.hasOwnProperty.call(response, 'statusCode')) { - return { - return_code: response.statusCode, // eslint-disable-line @typescript-eslint/no-unsafe-member-access - error_message: errorCodeToString(response.statusCode as number), // eslint-disable-line @typescript-eslint/no-unsafe-member-access - } - } - - if ( - Object.prototype.hasOwnProperty.call(response, 'return_code') && - Object.prototype.hasOwnProperty.call(response, 'error_message') - ) { - return response - } - } - - return { - return_code: 0xffff, - error_message: response.toString(), // eslint-disable-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access - } - } - - return { - return_code: 0xffff, - error_message: response.toString(), // eslint-disable-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access - } -} - -export function serializePath(path: number[]): Buffer { - if (path?.length !== 5) { - throw new TypeError('Invalid path.') - } - - const buf = Buffer.alloc(20) - - buf.writeUInt32LE(0x80000000 + path[0], 0) - buf.writeUInt32LE(0x80000000 + path[1], 4) - buf.writeUInt32LE(0x80000000 + path[2], 8) - buf.writeUInt32LE(path[3], 12) - buf.writeUInt32LE(path[4], 16) - return buf -} - -export async function getVersion( - transport: Transport -): Promise { - return transport - .send(CLA, INS.GET_VERSION, 0, 0) - .then((response) => { - const errorCodeData = response.slice(-2) - const return_code = errorCodeData[0] * 256 + errorCodeData[1] - - let targetId = 0 - if (response.length >= 9) { - /* eslint-disable no-bitwise */ - targetId = - (response[5] << 24) + - (response[6] << 16) + - (response[7] << 8) + - (response[8] << 0) - /* eslint-enable no-bitwise */ - } - - return { - return_code: return_code, - error_message: errorCodeToString(return_code), - // /// - test_mode: response[0] !== 0, - major: response[1], - minor: response[2], - patch: response[3], - device_locked: response[4] === 1, - target_id: targetId.toString(16), - } - }) - .catch(processErrorResponse) -} - -export async function getAppInfo( - transport: Transport -): Promise { - return transport - .send(0xb0, 0x01, 0, 0) - .then((response) => { - const errorCodeData = response.slice(-2) - let return_code: number = errorCodeData[0] * 256 + errorCodeData[1] - let error_message: string - - let app_name = 'err' - let app_version = 'err' - let flag_len = 0 - let flags_value = 0 - - if (response[0] !== 1) { - // Ledger responds with format ID 1. There is no spec for any format != 1 - error_message = 'response format ID not recognized' - return_code = 0x9001 - } else { - error_message = 'No errors' - const appNameLen = response[1] - app_name = response.slice(2, 2 + appNameLen).toString('ascii') - let idx = 2 + appNameLen - const appVersionLen = response[idx] - idx += 1 - app_version = response.slice(idx, idx + appVersionLen).toString('ascii') - idx += appVersionLen - const appFlagsLen = response[idx] - idx += 1 - flag_len = appFlagsLen - flags_value = response[idx] - } - - return { - return_code, - error_message, - // // - app_name, - app_version, - flag_len, - flags_value, - // eslint-disable-next-line no-bitwise - flag_recovery: (flags_value & 1) !== 0, - // eslint-disable-next-line no-bitwise - flag_signed_mcu_code: (flags_value & 2) !== 0, - // eslint-disable-next-line no-bitwise - flag_onboarded: (flags_value & 4) !== 0, - // eslint-disable-next-line no-bitwise - flag_pin_validated: (flags_value & 128) !== 0, - } - }) - .catch(processErrorResponse) -} - -export async function getDeviceInfo( - transport: Transport -): Promise { - return transport - .send(0xe0, 0x01, 0, 0, Buffer.from([]), [ERROR_CODE.NoError, 0x6e00]) - .then((response) => { - const errorCodeData = response.slice(-2) - const returnCode = errorCodeData[0] * 256 + errorCodeData[1] - - if (returnCode === 0x6e00) { - return { - return_code: returnCode, - error_message: 'This command is only available in the Dashboard', - } - } - - const target_id = response.slice(0, 4).toString('hex') - - let pos = 4 - const secureElementVersionLen = response[pos] - pos += 1 - const se_version = response - .slice(pos, pos + secureElementVersionLen) - .toString() - pos += secureElementVersionLen - - const flagsLen = response[pos] - pos += 1 - const flag = response.slice(pos, pos + flagsLen).toString('hex') - pos += flagsLen - - const mcuVersionLen = response[pos] - pos += 1 - // Patch issue in mcu version - let tmp = response.slice(pos, pos + mcuVersionLen) - if (tmp[mcuVersionLen - 1] === 0) { - tmp = response.slice(pos, pos + mcuVersionLen - 1) - } - const mcu_version = tmp.toString() - - return { - return_code: returnCode, - error_message: errorCodeToString(returnCode), - // // - target_id, - se_version, - flag, - mcu_version, - } - }) - .catch(processErrorResponse) -} - -export async function publicKey( - transport: Transport, - data: Buffer -): Promise { - return transport - .send(CLA, INS.GET_ADDR_SECP256K1, 0, 0, data, [ERROR_CODE.NoError]) - .then((response) => { - const errorCodeData = response.slice(-2) - const returnCode: number = errorCodeData[0] * 256 + errorCodeData[1] - const compressedPk = response ? Buffer.from(response.slice(0, 33)) : null - - return { - pk: 'OBSOLETE PROPERTY', - compressed_pk: compressedPk ? compressedPk.toJSON() : compressedPk, - return_code: returnCode, - error_message: errorCodeToString(returnCode), - } - }) - .catch(processErrorResponse) -} - -export async function getAddressAndPubKey( - transport: Transport, - data: Buffer -): Promise { - return transport - .send(CLA, INS.GET_ADDR_SECP256K1, P1_VALUES.ONLY_RETRIEVE, 0, data, [ - ERROR_CODE.NoError, - ]) - .then((response) => { - const errorCodeData = response.slice(-2) - const returnCode = errorCodeData[0] * 256 + errorCodeData[1] - - const compressedPk = Buffer.from(response.slice(0, 33)) - const bech32Address = Buffer.from(response.slice(33, -2)).toString() - - return { - bech32_address: bech32Address, - compressed_pk: compressedPk.toJSON(), - return_code: returnCode, - error_message: errorCodeToString(returnCode), - } - }) - .catch(processErrorResponse) -} - -export async function showAddressAndPubKey( - transport: Transport, - data: Buffer -): Promise { - return transport - .send( - CLA, - INS.GET_ADDR_SECP256K1, - P1_VALUES.SHOW_ADDRESS_IN_DEVICE, - 0, - data, - [ERROR_CODE.NoError] - ) - .then((response) => { - const errorCodeData = response.slice(-2) - const returnCode = errorCodeData[0] * 256 + errorCodeData[1] - - const compressedPk = Buffer.from(response.slice(0, 33)) - const bech32Address = Buffer.from(response.slice(33, -2)).toString() - - return { - bech32_address: bech32Address, - compressed_pk: compressedPk.toJSON(), - return_code: returnCode, - error_message: errorCodeToString(returnCode), - } - }) - .catch(processErrorResponse) -} - -function signGetChunks(path: number[], message: Buffer): Buffer[] { - const result = serializePath(path) - const chunks: Buffer[] = [] - - if (result instanceof Buffer) { - chunks.push(result) - const buffer = Buffer.from(message) - - for (let i = 0; i < buffer.length; i += CHUNK_SIZE) { - let end = i + CHUNK_SIZE - if (i > buffer.length) { - end = buffer.length - } - chunks.push(buffer.slice(i, end)) - } - } - - return chunks -} - -async function signSendChunk( - transport: Transport, - chunkIdx: number, - chunkNum: number, - chunk: Buffer -): Promise { - let payloadType = PAYLOAD_TYPE.ADD - - if (chunkIdx === 1) { - payloadType = PAYLOAD_TYPE.INIT - } - - if (chunkIdx === chunkNum) { - payloadType = PAYLOAD_TYPE.LAST - } - - return transport - .send(CLA, INS.SIGN_SECP256K1, payloadType, 0, chunk, [ - ERROR_CODE.NoError, - 0x6984, - 0x6a80, - ]) - .then((response) => { - const errorCodeData = response.slice(-2) - const returnCode = errorCodeData[0] * 256 + errorCodeData[1] - let errorMessage = errorCodeToString(returnCode) - - if (returnCode === 0x6a80 || returnCode === 0x6984) { - errorMessage = `${errorMessage} : ${response - .slice(0, response.length - 2) - .toString('ascii')}` - } - - let signature: Buffer = Buffer.from([]) - - if (response.length > 2) { - signature = response.slice(0, response.length - 2) - } - - return { - signature: signature.toJSON(), - return_code: returnCode, - error_message: errorMessage, - } - }) - .catch(processErrorResponse) -} - -export async function sign( - transport: Transport, - path: number[], - message: Buffer -): Promise { - const chunks = signGetChunks(path, message) - - return signSendChunk(transport, 1, chunks.length, chunks[0]) - .then(async (response) => { - let result: SignResponse = { - return_code: response.return_code, - error_message: response.error_message, - signature: { type: 'Buffer', data: [] }, - } - - for (let i = 1; i < chunks.length; i += 1) { - result = await signSendChunk(transport, 1 + i, chunks.length, chunks[i]) - - if (result.return_code !== ERROR_CODE.NoError) { - break - } - } - - return { - return_code: result.return_code, - error_message: result.error_message, - signature: result.signature, - } - }) - .catch(processErrorResponse) -} diff --git a/src/key/ledger/index.ts b/src/key/ledger/index.ts deleted file mode 100644 index 2458882..0000000 --- a/src/key/ledger/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -import InitiaApp from './app' -export * from './types' -export * from './constants' -export * from './LedgerKey' - -export default InitiaApp diff --git a/src/key/ledger/types.ts b/src/key/ledger/types.ts deleted file mode 100644 index 70cf585..0000000 --- a/src/key/ledger/types.ts +++ /dev/null @@ -1,51 +0,0 @@ -export interface JSONBuffer { - type: 'Buffer' - data: number[] -} - -export interface CommonResponse { - return_code: number - error_message: string - device_locked?: boolean -} - -export interface PublicKeyResponse extends CommonResponse { - bech32_address: string - pk: 'OBSOLETE PROPERTY' - compressed_pk: JSONBuffer -} - -export interface AddressResponse extends CommonResponse { - bech32_address: string - compressed_pk: JSONBuffer -} - -export interface SignResponse extends CommonResponse { - signature: JSONBuffer -} - -export interface AppInfoResponse extends CommonResponse { - app_name: string - app_version: string - flag_len: number - flags_value: number - flag_recovery: boolean - flag_signed_mcu_code: boolean - flag_onboarded: boolean - flag_pin_validated: boolean -} - -export interface VersionResponse extends CommonResponse { - test_mode: boolean - major: number - minor: number - patch: number - target_id: string -} - -export interface DeviceInfoResponse extends CommonResponse { - target_id: string // '31100004', - se_version: string // '1.6.0', - flag: string // 'a6000000', - mcu_version: string // '1.11' -} diff --git a/vite.config.ts b/vite.config.ts index 2336171..0c45ed3 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -14,7 +14,6 @@ export default defineConfig({ external: [ new RegExp('^@initia/.*'), new RegExp('^jscrypto.*'), - '@ledgerhq/hw-transport', '@mysten/bcs', 'axios', 'bech32',