@aeternity/aepp-sdk 13.3.2 → 13.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.mjs","names":["BigNumber","genSalt","hash","decode","encode","Encoding","toBytes","concatBuffers","NAME_BID_RANGES","NAME_BID_TIMEOUT_BLOCKS","NAME_FEE_BID_INCREMENT","NAME_MAX_LENGTH_FEE","ceil","ArgumentError","IllegalBidFeeError","buildContractId","ownerId","nonce","ownerIdAndNonce","_Buffer","from","b2bHash","ContractAddress","oracleQueryId","senderId","oracleId","_int32","val","nonceBE","alloc","length","OracleQueryId","AENS_SUFFIX","nameToPunycode","maybeName","name","suffix","other","split","slice","test","punycode","u","URL","username","password","port","search","pathname","host","error","TypeError","message","includes","produceNameId","Name","commitmentHash","salt","toString","padStart","Commitment","readInt","buf","ensureName","isNameValid","encodingToPointerKey","AccountAddress","OracleAddress","Channel","getDefaultPointerKey","identifier","_encodingToPointerKey","encoding","substring","result","find","e","map","join","getMinimumNameFee","nameLength","Math","min","computeBidFee","startFee","increment","Number","times","plus","computeAuctionEndBlock","claimHeight","_ref","_ref2","_ref3","h","isAuctionName"],"sources":["../../../src/tx/builder/helpers.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { genSalt, hash } from '../../utils/crypto';\nimport {\n decode, encode, Encoded, Encoding,\n} from '../../utils/encoder';\nimport { toBytes } from '../../utils/bytes';\nimport { concatBuffers } from '../../utils/other';\nimport {\n AensName,\n NAME_BID_RANGES,\n NAME_BID_TIMEOUT_BLOCKS,\n NAME_FEE_BID_INCREMENT,\n NAME_MAX_LENGTH_FEE,\n} from './constants';\nimport { ceil } from '../../utils/bignumber';\nimport { ArgumentError, IllegalBidFeeError } from '../../utils/errors';\n\n/**\n * JavaScript-based Transaction builder helper function's\n */\n\n/**\n * Build a contract public key\n * @category contract\n * @param ownerId - The public key of the owner account\n * @param nonce - the nonce of the transaction\n * @returns Contract public key\n */\nexport function buildContractId(\n ownerId: Encoded.AccountAddress,\n nonce: number | BigNumber,\n): Encoded.ContractAddress {\n const ownerIdAndNonce = Buffer.from([...decode(ownerId), ...toBytes(nonce)]);\n const b2bHash = hash(ownerIdAndNonce);\n return encode(b2bHash, Encoding.ContractAddress);\n}\n\n/**\n * Build a oracle query id\n * @category oracle\n * @param senderId - The public key of the sender account\n * @param nonce - the nonce of the transaction\n * @param oracleId - The oracle public key\n * @returns Contract public key\n */\nexport function oracleQueryId(\n senderId: Encoded.AccountAddress,\n nonce: number | BigNumber | string,\n oracleId: Encoded.OracleAddress,\n): Encoded.OracleQueryId {\n function _int32(val: number | string | BigNumber): Buffer {\n const nonceBE = toBytes(val, true);\n return concatBuffers([Buffer.alloc(32 - nonceBE.length), nonceBE]);\n }\n\n const b2bHash = hash(\n Buffer.from([...decode(senderId), ..._int32(nonce), ...decode(oracleId)]),\n );\n return encode(b2bHash, Encoding.OracleQueryId);\n}\n\nconst AENS_SUFFIX = '.chain';\n\nexport function nameToPunycode(maybeName: string): AensName {\n const [name, suffix, ...other] = maybeName.split('.');\n if (other.length !== 0) throw new ArgumentError('aens name', 'including only one dot', maybeName);\n if (suffix !== AENS_SUFFIX.slice(1)) {\n throw new ArgumentError('aens name', `suffixed with ${AENS_SUFFIX}`, maybeName);\n }\n if (/\\p{Emoji_Presentation}/u.test(name)) {\n throw new ArgumentError('aens name', 'not containing emoji', maybeName);\n }\n let punycode;\n try {\n const u = new URL(`http://${name}.${suffix}`);\n if (u.username + u.password + u.port + u.search + u.hash !== '' || u.pathname !== '/') {\n throw new ArgumentError('aens name', 'valid', maybeName);\n }\n punycode = u.host;\n } catch (error) {\n if (error instanceof TypeError && error.message.includes('Invalid URL')) {\n throw new ArgumentError('aens name', 'valid', maybeName);\n }\n throw error;\n }\n if (!/^[a-z0-9.-]+$/i.test(punycode)) {\n throw new ArgumentError('aens name', 'without illegal chars', maybeName);\n }\n if (punycode.length > 63 + AENS_SUFFIX.length) {\n throw new ArgumentError('aens name', 'not too long', maybeName);\n }\n return punycode as AensName;\n}\n\n/**\n * Encode an AENS name\n * @category AENS\n * @param name - Name to encode\n * @returns `nm_` prefixed encoded AENS name\n */\nexport function produceNameId(name: AensName): Encoded.Name {\n return encode(hash(nameToPunycode(name)), Encoding.Name);\n}\n\n/**\n * Generate the commitment hash by hashing the salt and\n * name, base 58 encoding the result and prepending 'cm_'\n * @category transaction builder\n * @param name - Name to be registered\n * @param salt - Random number\n * @returns Commitment hash\n */\nexport function commitmentHash(\n name: AensName,\n salt: number = genSalt(),\n): Encoded.Commitment {\n return encode(\n hash(concatBuffers([\n Buffer.from(nameToPunycode(name)),\n Buffer.from(salt.toString(16).padStart(64, '0'), 'hex'),\n ])),\n Encoding.Commitment,\n );\n}\n\n/**\n * Utility function to convert bytes to int\n * @category transaction builder\n * @param buf - Value\n * @returns Buffer Buffer from number(BigEndian)\n */\nexport function readInt(buf: Buffer = Buffer.from([])): string {\n return new BigNumber(Buffer.from(buf).toString('hex'), 16).toString(10);\n}\n\n/**\n * Ensure that name is valid AENS name, would throw an exception otherwise\n * @category AENS\n * @param maybeName - AENS name\n */\nexport function ensureName(maybeName: string): asserts maybeName is AensName {\n nameToPunycode(maybeName);\n}\n\n/**\n * Is AENS name valid\n * @category AENS\n * @param maybeName - AENS name\n */\n// TODO: consider renaming to isName\nexport function isNameValid(maybeName: string): maybeName is AensName {\n try {\n ensureName(maybeName);\n return true;\n } catch (error) {\n return false;\n }\n}\n\nconst encodingToPointerKey = [\n [Encoding.AccountAddress, 'account_pubkey'],\n [Encoding.OracleAddress, 'oracle_pubkey'],\n [Encoding.ContractAddress, 'contract_pubkey'],\n [Encoding.Channel, 'channel'],\n] as const;\n\n/**\n * @category AENS\n * @param identifier - account/oracle/contract address, or channel\n * @returns default AENS pointer key\n */\nexport function getDefaultPointerKey(\n identifier: Encoded.Generic<typeof encodingToPointerKey[number][0]>,\n): typeof encodingToPointerKey[number][1] {\n decode(identifier);\n const encoding = identifier.substring(0, 2);\n const result = encodingToPointerKey.find(([e]) => e === encoding)?.[1];\n if (result != null) return result;\n throw new ArgumentError(\n 'identifier',\n `prefixed with one of ${encodingToPointerKey.map(([e]) => `${e}_`).join(', ')}`,\n identifier,\n );\n}\n\n/**\n * Get the minimum AENS name fee\n * @category AENS\n * @param name - the AENS name to get the fee for\n * @returns the minimum fee for the AENS name auction\n */\nexport function getMinimumNameFee(name: AensName): BigNumber {\n const nameLength = nameToPunycode(name).length - AENS_SUFFIX.length;\n return NAME_BID_RANGES[Math.min(nameLength, NAME_MAX_LENGTH_FEE)];\n}\n\n/**\n * Compute bid fee for AENS auction\n * @category AENS\n * @param name - the AENS name to get the fee for\n * @param options - Options\n * @param options.startFee - Auction start fee\n * @param options.increment - Bid multiplier(In percentage, must be between 0 and 1)\n * @returns Bid fee\n */\nexport function computeBidFee(\n name: AensName,\n { startFee, increment = NAME_FEE_BID_INCREMENT }:\n { startFee?: number | string | BigNumber; increment?: number } = {},\n): BigNumber {\n if (!(Number(increment) === increment && increment % 1 !== 0)) throw new IllegalBidFeeError(`Increment must be float. Current increment ${increment}`);\n if (increment < NAME_FEE_BID_INCREMENT) throw new IllegalBidFeeError(`minimum increment percentage is ${NAME_FEE_BID_INCREMENT}`);\n // FIXME: increment should be used somehow here\n return ceil(\n new BigNumber(startFee ?? getMinimumNameFee(name))\n .times(new BigNumber(NAME_FEE_BID_INCREMENT).plus(1)),\n );\n}\n\n/**\n * Compute auction end height\n * @category AENS\n * @param name - Name to compute auction end for\n * @param claimHeight - Auction starting height\n * @see {@link https://github.com/aeternity/aeternity/blob/72e440b8731422e335f879a31ecbbee7ac23a1cf/apps/aecore/src/aec_governance.erl#L273}\n * @returns Auction end height\n */\nexport function computeAuctionEndBlock(name: AensName, claimHeight: number): number {\n const length = nameToPunycode(name).length - AENS_SUFFIX.length;\n const h = (length <= 4 ? 62 * NAME_BID_TIMEOUT_BLOCKS : null)\n ?? (length <= 8 ? 31 * NAME_BID_TIMEOUT_BLOCKS : null)\n ?? (length <= 12 ? NAME_BID_TIMEOUT_BLOCKS : null)\n ?? 0;\n return h + claimHeight;\n}\n\n/**\n * Is name accept going to auction\n * @category AENS\n */\nexport function isAuctionName(name: AensName): boolean {\n return nameToPunycode(name).length < 13 + AENS_SUFFIX.length;\n}\n"],"mappings":";;;;AAAA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC5BC,OAAO,EAAEC,IAAI;AAAA,SAEpBC,MAAM,EAAEC,MAAM,EAAWC,QAAQ;AAAA,SAE1BC,OAAO;AAAA,SACPC,aAAa;AAAA,SAGpBC,eAAe,EACfC,uBAAuB,EACvBC,sBAAsB,EACtBC,mBAAmB;AAAA,SAEZC,IAAI;AAAA,SACJC,aAAa,EAAEC,kBAAkB;AAE1C;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAC7BC,OAA+B,EAC/BC,KAAyB,EACA;EACzB,MAAMC,eAAe,GAAGC,OAAA,CAAOC,IAAI,CAAC,CAAC,GAAGjB,MAAM,CAACa,OAAO,CAAC,EAAE,GAAGV,OAAO,CAACW,KAAK,CAAC,CAAC,CAAC;EAC5E,MAAMI,OAAO,GAAGnB,IAAI,CAACgB,eAAe,CAAC;EACrC,OAAOd,MAAM,CAACiB,OAAO,EAAEhB,QAAQ,CAACiB,eAAe,CAAC;AAClD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAC3BC,QAAgC,EAChCP,KAAkC,EAClCQ,QAA+B,EACR;EACvB,SAASC,MAAMA,CAACC,GAAgC,EAAU;IACxD,MAAMC,OAAO,GAAGtB,OAAO,CAACqB,GAAG,EAAE,IAAI,CAAC;IAClC,OAAOpB,aAAa,CAAC,CAACY,OAAA,CAAOU,KAAK,CAAC,EAAE,GAAGD,OAAO,CAACE,MAAM,CAAC,EAAEF,OAAO,CAAC,CAAC;EACpE;EAEA,MAAMP,OAAO,GAAGnB,IAAI,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AEuD,WAAmB,EAAU;EAAA,IAAAC,IAAA,EAAAC,KAAA,EAAAC,KAAA;EAClF,MAAM/D,MAAM,GAAGG,cAAc,CAACE,IAAI,CAAC,CAACL,MAAM,GAAGE,WAAW,CAACF,MAAM;EAC/D,MAAMgE,CAAC,IAAAH,IAAA,IAAAC,KAAA,IAAAC,KAAA,GAAI/D,MAAM,IAAI,CAAC,GAAG,EAAE,GAAGrB,uBAAuB,GAAG,IAAI,cAAAoF,KAAA,cAAAA,KAAA,GACtD/D,MAAM,IAAI,CAAC,GAAG,EAAE,GAAGrB,uBAAuB,GAAG,IAAI,cAAAmF,KAAA,cAAAA,KAAA,GACjD9D,MAAM,IAAI,EAAE,GAAGrB,uBAAuB,GAAG,IAAI,cAAAkF,IAAA,cAAAA,IAAA,GAC9C,CAAC;EACN,OAAOG,CAAC,GAAGJ,WAAW;AACxB;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASK,aAAaA,CAAC5D,IAAc,EAAW;EACrD,OAAOF,cAAc,CAACE,IAAI,CAAC,CAACL,MAAM,GAAG,EAAE,GAAGE,WAAW,CAACF,MAAM;AAC9D"}
1
+ {"version":3,"file":"helpers.mjs","names":["BigNumber","genSalt","hash","decode","encode","Encoding","toBytes","concatBuffers","NAME_BID_RANGES","NAME_BID_TIMEOUT_BLOCKS","NAME_FEE_BID_INCREMENT","NAME_MAX_LENGTH_FEE","ceil","ArgumentError","IllegalBidFeeError","buildContractId","ownerId","nonce","ownerIdAndNonce","_Buffer","from","b2bHash","ContractAddress","oracleQueryId","senderId","oracleId","_int32","val","nonceBE","alloc","length","OracleQueryId","AENS_SUFFIX","nameToPunycode","maybeName","name","suffix","other","split","slice","test","at","punycode","u","URL","username","password","port","search","pathname","host","error","TypeError","message","includes","produceNameId","Name","commitmentHash","salt","toString","padStart","Commitment","readInt","buf","ensureName","isNameValid","encodingToPointerKey","AccountAddress","OracleAddress","Channel","getDefaultPointerKey","identifier","_encodingToPointerKey","encoding","substring","result","find","e","map","join","getMinimumNameFee","nameLength","Math","min","computeBidFee","startFee","increment","Number","times","plus","computeAuctionEndBlock","claimHeight","_ref","_ref2","_ref3","h","isAuctionName"],"sources":["../../../src/tx/builder/helpers.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { genSalt, hash } from '../../utils/crypto';\nimport {\n decode, encode, Encoded, Encoding,\n} from '../../utils/encoder';\nimport { toBytes } from '../../utils/bytes';\nimport { concatBuffers } from '../../utils/other';\nimport {\n AensName,\n NAME_BID_RANGES,\n NAME_BID_TIMEOUT_BLOCKS,\n NAME_FEE_BID_INCREMENT,\n NAME_MAX_LENGTH_FEE,\n} from './constants';\nimport { ceil } from '../../utils/bignumber';\nimport { ArgumentError, IllegalBidFeeError } from '../../utils/errors';\n\n/**\n * JavaScript-based Transaction builder helper function's\n */\n\n/**\n * Build a contract public key\n * @category contract\n * @param ownerId - The public key of the owner account\n * @param nonce - the nonce of the transaction\n * @returns Contract public key\n */\nexport function buildContractId(\n ownerId: Encoded.AccountAddress,\n nonce: number | BigNumber,\n): Encoded.ContractAddress {\n const ownerIdAndNonce = Buffer.from([...decode(ownerId), ...toBytes(nonce)]);\n const b2bHash = hash(ownerIdAndNonce);\n return encode(b2bHash, Encoding.ContractAddress);\n}\n\n/**\n * Build a oracle query id\n * @category oracle\n * @param senderId - The public key of the sender account\n * @param nonce - the nonce of the transaction\n * @param oracleId - The oracle public key\n * @returns Contract public key\n */\nexport function oracleQueryId(\n senderId: Encoded.AccountAddress,\n nonce: number | BigNumber | string,\n oracleId: Encoded.OracleAddress,\n): Encoded.OracleQueryId {\n function _int32(val: number | string | BigNumber): Buffer {\n const nonceBE = toBytes(val, true);\n return concatBuffers([Buffer.alloc(32 - nonceBE.length), nonceBE]);\n }\n\n const b2bHash = hash(\n Buffer.from([...decode(senderId), ..._int32(nonce), ...decode(oracleId)]),\n );\n return encode(b2bHash, Encoding.OracleQueryId);\n}\n\nconst AENS_SUFFIX = '.chain';\n\nexport function nameToPunycode(maybeName: string): AensName {\n const [name, suffix, ...other] = maybeName.split('.');\n if (other.length !== 0) throw new ArgumentError('aens name', 'including only one dot', maybeName);\n if (suffix !== AENS_SUFFIX.slice(1)) {\n throw new ArgumentError('aens name', `suffixed with ${AENS_SUFFIX}`, maybeName);\n }\n if (/\\p{Emoji_Presentation}/u.test(name)) {\n throw new ArgumentError('aens name', 'not containing emoji', maybeName);\n }\n if (name[2] === '-' && name[3] === '-') {\n throw new ArgumentError('aens name', 'without \"-\" char in both the third and fourth positions', maybeName);\n }\n if (name[0] === '-') {\n throw new ArgumentError('aens name', 'starting with no \"-\" char', maybeName);\n }\n if (name.at(-1) === '-') {\n throw new ArgumentError('aens name', 'ending with no \"-\" char', maybeName);\n }\n let punycode;\n try {\n const u = new URL(`http://${name}.${suffix}`);\n if (u.username + u.password + u.port + u.search + u.hash !== '' || u.pathname !== '/') {\n throw new ArgumentError('aens name', 'valid', maybeName);\n }\n punycode = u.host;\n } catch (error) {\n if (error instanceof TypeError && error.message.includes('Invalid URL')) {\n throw new ArgumentError('aens name', 'valid', maybeName);\n }\n throw error;\n }\n if (!/^[a-z0-9.-]+$/i.test(punycode)) {\n throw new ArgumentError('aens name', 'without illegal chars', maybeName);\n }\n if (punycode.length > 63 + AENS_SUFFIX.length) {\n throw new ArgumentError('aens name', 'not too long', maybeName);\n }\n return punycode as AensName;\n}\n\n/**\n * Encode an AENS name\n * @category AENS\n * @param name - Name to encode\n * @returns `nm_` prefixed encoded AENS name\n */\nexport function produceNameId(name: AensName): Encoded.Name {\n return encode(hash(nameToPunycode(name)), Encoding.Name);\n}\n\n/**\n * Generate the commitment hash by hashing the salt and\n * name, base 58 encoding the result and prepending 'cm_'\n * @category transaction builder\n * @param name - Name to be registered\n * @param salt - Random number\n * @returns Commitment hash\n */\nexport function commitmentHash(\n name: AensName,\n salt: number = genSalt(),\n): Encoded.Commitment {\n return encode(\n hash(concatBuffers([\n Buffer.from(nameToPunycode(name)),\n Buffer.from(salt.toString(16).padStart(64, '0'), 'hex'),\n ])),\n Encoding.Commitment,\n );\n}\n\n/**\n * Utility function to convert bytes to int\n * @category transaction builder\n * @param buf - Value\n * @returns Buffer Buffer from number(BigEndian)\n */\nexport function readInt(buf: Buffer = Buffer.from([])): string {\n return new BigNumber(Buffer.from(buf).toString('hex'), 16).toString(10);\n}\n\n/**\n * Ensure that name is valid AENS name, would throw an exception otherwise\n * @category AENS\n * @param maybeName - AENS name\n */\nexport function ensureName(maybeName: string): asserts maybeName is AensName {\n nameToPunycode(maybeName);\n}\n\n/**\n * Is AENS name valid\n * @category AENS\n * @param maybeName - AENS name\n */\n// TODO: consider renaming to isName\nexport function isNameValid(maybeName: string): maybeName is AensName {\n try {\n ensureName(maybeName);\n return true;\n } catch (error) {\n return false;\n }\n}\n\nconst encodingToPointerKey = [\n [Encoding.AccountAddress, 'account_pubkey'],\n [Encoding.OracleAddress, 'oracle_pubkey'],\n [Encoding.ContractAddress, 'contract_pubkey'],\n [Encoding.Channel, 'channel'],\n] as const;\n\n/**\n * @category AENS\n * @param identifier - account/oracle/contract address, or channel\n * @returns default AENS pointer key\n */\nexport function getDefaultPointerKey(\n identifier: Encoded.Generic<typeof encodingToPointerKey[number][0]>,\n): typeof encodingToPointerKey[number][1] {\n decode(identifier);\n const encoding = identifier.substring(0, 2);\n const result = encodingToPointerKey.find(([e]) => e === encoding)?.[1];\n if (result != null) return result;\n throw new ArgumentError(\n 'identifier',\n `prefixed with one of ${encodingToPointerKey.map(([e]) => `${e}_`).join(', ')}`,\n identifier,\n );\n}\n\n/**\n * Get the minimum AENS name fee\n * @category AENS\n * @param name - the AENS name to get the fee for\n * @returns the minimum fee for the AENS name auction\n */\nexport function getMinimumNameFee(name: AensName): BigNumber {\n const nameLength = nameToPunycode(name).length - AENS_SUFFIX.length;\n return NAME_BID_RANGES[Math.min(nameLength, NAME_MAX_LENGTH_FEE)];\n}\n\n/**\n * Compute bid fee for AENS auction\n * @category AENS\n * @param name - the AENS name to get the fee for\n * @param options - Options\n * @param options.startFee - Auction start fee\n * @param options.increment - Bid multiplier(In percentage, must be between 0 and 1)\n * @returns Bid fee\n */\nexport function computeBidFee(\n name: AensName,\n { startFee, increment = NAME_FEE_BID_INCREMENT }:\n { startFee?: number | string | BigNumber; increment?: number } = {},\n): BigNumber {\n if (!(Number(increment) === increment && increment % 1 !== 0)) throw new IllegalBidFeeError(`Increment must be float. Current increment ${increment}`);\n if (increment < NAME_FEE_BID_INCREMENT) throw new IllegalBidFeeError(`minimum increment percentage is ${NAME_FEE_BID_INCREMENT}`);\n // FIXME: increment should be used somehow here\n return ceil(\n new BigNumber(startFee ?? getMinimumNameFee(name))\n .times(new BigNumber(NAME_FEE_BID_INCREMENT).plus(1)),\n );\n}\n\n/**\n * Compute auction end height\n * @category AENS\n * @param name - Name to compute auction end for\n * @param claimHeight - Auction starting height\n * @see {@link https://github.com/aeternity/aeternity/blob/72e440b8731422e335f879a31ecbbee7ac23a1cf/apps/aecore/src/aec_governance.erl#L273}\n * @returns Auction end height\n */\nexport function computeAuctionEndBlock(name: AensName, claimHeight: number): number {\n const length = nameToPunycode(name).length - AENS_SUFFIX.length;\n const h = (length <= 4 ? 62 * NAME_BID_TIMEOUT_BLOCKS : null)\n ?? (length <= 8 ? 31 * NAME_BID_TIMEOUT_BLOCKS : null)\n ?? (length <= 12 ? NAME_BID_TIMEOUT_BLOCKS : null)\n ?? 0;\n return h + claimHeight;\n}\n\n/**\n * Is name accept going to auction\n * @category AENS\n */\nexport function isAuctionName(name: AensName): boolean {\n return nameToPunycode(name).length < 13 + AENS_SUFFIX.length;\n}\n"],"mappings":";;;;AAAA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC5BC,OAAO,EAAEC,IAAI;AAAA,SAEpBC,MAAM,EAAEC,MAAM,EAAWC,QAAQ;AAAA,SAE1BC,OAAO;AAAA,SACPC,aAAa;AAAA,SAGpBC,eAAe,EACfC,uBAAuB,EACvBC,sBAAsB,EACtBC,mBAAmB;AAAA,SAEZC,IAAI;AAAA,SACJC,a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,CAACvD,IAAc,EAAEwD,WAAmB,EAAU;EAAA,IAAAC,IAAA,EAAAC,KAAA,EAAAC,KAAA;EAClF,MAAMhE,MAAM,GAAGG,cAAc,CAACE,IAAI,CAAC,CAACL,MAAM,GAAGE,WAAW,CAACF,MAAM;EAC/D,MAAMiE,CAAC,IAAAH,IAAA,IAAAC,KAAA,IAAAC,KAAA,GAAIhE,MAAM,IAAI,CAAC,GAAG,EAAE,GAAGrB,uBAAuB,GAAG,IAAI,cAAAqF,KAAA,cAAAA,KAAA,GACtDhE,MAAM,IAAI,CAAC,GAAG,EAAE,GAAGrB,uBAAuB,GAAG,IAAI,cAAAoF,KAAA,cAAAA,KAAA,GACjD/D,MAAM,IAAI,EAAE,GAAGrB,uBAAuB,GAAG,IAAI,cAAAmF,IAAA,cAAAA,IAAA,GAC9C,CAAC;EACN,OAAOG,CAAC,GAAGJ,WAAW;AACxB;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASK,aAAaA,CAAC7D,IAAc,EAAW;EACrD,OAAOF,cAAc,CAACE,IAAI,CAAC,CAACL,MAAM,GAAG,EAAE,GAAGE,WAAW,CAACF,MAAM;AAC9D"}
@@ -1,4 +1,5 @@
1
1
  import nacl from 'tweetnacl';
2
+ import { Encoded } from './encoder';
2
3
  import { CryptographyError } from './errors';
3
4
  /**
4
5
  * @category exception
@@ -16,7 +17,7 @@ interface HDWallet {
16
17
  }
17
18
  interface Account {
18
19
  secretKey: string;
19
- publicKey: string;
20
+ publicKey: Encoded.AccountAddress;
20
21
  }
21
22
  type Dec<N extends number> = [-1, 0, 1, 2, 3, 4][N];
22
23
  type Bip32PathT<MaxLen extends number, H extends 'H' | 'h' | '\''> = MaxLen extends -1 ? `${number}${H}` : Bip32PathT<Dec<MaxLen>, H> | `${Bip32PathT<Dec<MaxLen>, H>}/${number}${H}`;
@@ -1 +1 @@
1
- {"version":3,"file":"hd-wallet.mjs","names":["nacl","_tweetnaclAuth","full","hmac","_bip32Path","fromString","aesjs","sha256hash","encode","Encoding","CryptographyError","concatBuffers","Ecb","ModeOfOperation","ecb","encryptKey","password","binaryData","hashedPasswordBytes","aesEcb","encrypt","decryptKey","encrypted","encryptedBytes","_Buffer","from","decrypt","DerivationError","constructor","message","name","ED25519_CURVE","HARDENED_OFFSET","deriveChild","secretKey","chainCode","index","indexBuffer","allocUnsafe","writeUInt32BE","data","alloc","I","IL","slice","IR","derivePathFromKey","path","key","segments","toPathArray","forEach","segment","i","reduce","parentKey","getMasterKeyFromSeed","seed","derivePathFromSeed","includes","masterKey","formatAccount","keys","publicKey","toString","AccountAddress","getKeyPair","sign","keyPair","fromSeed","generateSaveHDWalletFromSeed","walletKey","getSaveHDWalletAccounts","saveHDWallet","accountCount","Array","fill","undefined","map","_","idx","getHdWalletAccountFromSeed","accountIdx","derived"],"sources":["../../src/utils/hd-wallet.ts"],"sourcesContent":["import nacl from 'tweetnacl';\nimport { full as hmac } from 'tweetnacl-auth';\nimport { fromString } from 'bip32-path';\nimport aesjs from 'aes-js';\nimport { sha256hash, encode, Encoding } from './encoder';\nimport { CryptographyError } from './errors';\nimport { concatBuffers } from './other';\n\nconst Ecb = aesjs.ModeOfOperation.ecb;\n\n// TODO: use mnemonic encryption instead of AES\n/**\n * Encrypt given data using `password`\n * @param password - Password to encrypt with\n * @param binaryData - Data to encrypt\n * @returns Encrypted data\n */\nfunction encryptKey(password: string, binaryData: Uint8Array): Uint8Array {\n const hashedPasswordBytes = sha256hash(password);\n const aesEcb = new Ecb(hashedPasswordBytes);\n return aesEcb.encrypt(binaryData);\n}\n\n/**\n * Decrypt given data using `password`\n * @param password - Password to decrypt with\n * @param encrypted - Data to decrypt\n * @returns Decrypted data\n */\nfunction decryptKey(password: string, encrypted: Uint8Array): Uint8Array {\n const encryptedBytes = Buffer.from(encrypted);\n const hashedPasswordBytes = sha256hash(password);\n const aesEcb = new Ecb(hashedPasswordBytes);\n return aesEcb.decrypt(encryptedBytes);\n}\n\n/**\n * @category exception\n */\nexport class DerivationError extends CryptographyError {\n constructor(message: string) {\n super(message);\n this.name = 'DerivationError';\n }\n}\n\nconst ED25519_CURVE = Buffer.from('ed25519 seed');\nconst HARDENED_OFFSET = 0x80000000;\n\ninterface KeyTreeNode {\n secretKey: Uint8Array;\n chainCode: Uint8Array;\n}\n\ninterface HDWallet {\n secretKey: string;\n chainCode: string;\n}\n\ninterface Account {\n secretKey: string;\n publicKey: string;\n}\n\ntype Dec<N extends number> = [-1, 0, 1, 2, 3, 4][N];\ntype Bip32PathT<MaxLen extends number, H extends 'H' | 'h' | '\\''> = MaxLen extends -1\n ? `${number}${H}`\n : Bip32PathT<Dec<MaxLen>, H> | `${Bip32PathT<Dec<MaxLen>, H>}/${number}${H}`;\ntype Bip32Path<MaxLen extends number> =\n '' | Bip32PathT<MaxLen, 'H'> | Bip32PathT<MaxLen, 'h'> | Bip32PathT<MaxLen, '\\''>;\n\n/**\n * @category hd-wallet\n * @param keyTreeNode - A node of key tree\n * @param index - index of child node to derive\n */\nexport function deriveChild({ secretKey, chainCode }: KeyTreeNode, index: number): KeyTreeNode {\n if (index < HARDENED_OFFSET) {\n throw new DerivationError(`Segment ${index} is not hardened`);\n }\n const indexBuffer = Buffer.allocUnsafe(4);\n indexBuffer.writeUInt32BE(index, 0);\n\n const data = concatBuffers([Buffer.alloc(1, 0), secretKey, indexBuffer]);\n\n const I = hmac(data, chainCode);\n const IL = I.slice(0, 32);\n const IR = I.slice(32);\n return {\n secretKey: IL,\n chainCode: IR,\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function derivePathFromKey(path: Bip32Path<5>, key: KeyTreeNode): KeyTreeNode {\n const segments = path === '' ? [] : fromString(path).toPathArray();\n segments.forEach((segment, i) => {\n if (segment < HARDENED_OFFSET) {\n throw new DerivationError(`Segment #${i + 1} is not hardened`);\n }\n });\n\n return segments.reduce((parentKey, segment) => deriveChild(parentKey, segment), key);\n}\n\n/**\n * @category hd-wallet\n */\nexport function getMasterKeyFromSeed(seed: Uint8Array): KeyTreeNode {\n const I = hmac(seed, ED25519_CURVE);\n const IL = I.slice(0, 32);\n const IR = I.slice(32);\n return {\n secretKey: IL,\n chainCode: IR,\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function derivePathFromSeed(path: 'm' | `m/${Bip32Path<5>}`, seed: Uint8Array): KeyTreeNode {\n if (!['m', 'm/'].includes(path.slice(0, 2))) {\n throw new DerivationError('Root element is required');\n }\n const masterKey = getMasterKeyFromSeed(seed);\n return derivePathFromKey(path.slice(2) as Bip32Path<5>, masterKey);\n}\n\nfunction formatAccount(keys: nacl.SignKeyPair): Account {\n const { secretKey, publicKey } = keys;\n return {\n secretKey: Buffer.from(secretKey).toString('hex'),\n publicKey: encode(publicKey, Encoding.AccountAddress),\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function getKeyPair(secretKey: Uint8Array): nacl.SignKeyPair {\n return nacl.sign.keyPair.fromSeed(secretKey);\n}\n\n/**\n * @category hd-wallet\n */\nexport function generateSaveHDWalletFromSeed(seed: Uint8Array, password: string): HDWallet {\n const walletKey = derivePathFromSeed('m/44h/457h', seed);\n return {\n secretKey: Buffer.from(encryptKey(password, walletKey.secretKey)).toString('hex'),\n chainCode: Buffer.from(encryptKey(password, walletKey.chainCode)).toString('hex'),\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function getSaveHDWalletAccounts(\n saveHDWallet: HDWallet,\n password: string,\n accountCount: number,\n): Account[] {\n const walletKey = {\n secretKey: decryptKey(password, Buffer.from(saveHDWallet.secretKey, 'hex')),\n chainCode: decryptKey(password, Buffer.from(saveHDWallet.chainCode, 'hex')),\n };\n return (new Array(accountCount)).fill(undefined)\n .map((_, idx) => formatAccount(getKeyPair(derivePathFromKey(`${idx}h/0h/0h`, walletKey).secretKey)));\n}\n\n/**\n * @category hd-wallet\n */\nexport const getHdWalletAccountFromSeed = (\n seed: Uint8Array,\n accountIdx: number,\n): Account & { idx: number } => {\n const walletKey = derivePathFromSeed('m/44h/457h', seed);\n const derived = derivePathFromKey(`${accountIdx}h/0h/0h`, walletKey);\n const keyPair = getKeyPair(derived.secretKey);\n return {\n ...formatAccount(keyPair),\n idx: accountIdx,\n };\n};\n"],"mappings":";;;;AAAA,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAAC,cAAA,MAA6B,gBAAgB;AAAC;EAAAC,IAAA,EAAAC;AAAA,IAAAF,cAAA;AAC9C,OAAAG,UAAA,MAA2B,YAAY;AAAC;EAAAC;AAAA,IAAAD,UAAA;AACxC,OAAOE,KAAK,MAAM,QAAQ;AAAC,SAClBC,UAAU,EAAEC,MAAM,EAAEC,QAAQ;AAAA,SAC5BC,iBAAiB;AAAA,SACjBC,aAAa;AAEtB,MAAMC,GAAG,GAAGN,KAAK,CAACO,eAAe,CAACC,GAAG;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,UAAUA,CAACC,QAAgB,EAAEC,UAAsB,EAAc;EACxE,MAAMC,mBAAmB,GAAGX,UAAU,CAACS,QAAQ,CAAC;EAChD,MAAMG,MAAM,GAAG,IAAIP,GAAG,CAACM,mBAAmB,CAAC;EAC3C,OAAOC,MAAM,CAACC,OAAO,CAACH,UAAU,CAAC;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAASI,UAAUA,CAACL,QAAgB,EAAEM,SAAqB,EAAc;EACvE,MAAMC,cAAc,GAAGC,OAAA,CAAOC,IAAI,CAACH,SAAS,CAAC;EAC7C,MAAMJ,mBAAmB,GAAGX,UAAU,CAACS,QAAQ,CAAC;EAChD,MAAMG,MAAM,GAAG,IAAIP,GAAG,CAACM,mBAAmB,CAAC;EAC3C,OAAOC,MAAM,CAACO,OAAO,CAACH,cAAc,CAAC;AACvC;;AAEA;AACA;AACA;AACA,OAAO,MAAMI,eAAe,SAASjB,iBAAiB,CAAC;EACrDkB,WAAWA,CAACC,OAAe,EAAE;IAC3B,KAAK,CAACA,OAAO,CAAC;IACd,IAAI,CAACC,IAAI,GAAG,iBAAiB;EAC/B;AACF;AAEA,MAAMC,a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AAMX,SAAS,GAAGb,kBAAkB,CAAC,YAAY,EAAED,IAAI,CAAC;EACxD,MAAM0B,OAAO,GAAGrC,iBAAiB,CAAE,GAAEoC,UAAW,SAAQ,EAAEX,SAAS,CAAC;EACpE,MAAMH,OAAO,GAAGF,UAAU,CAACiB,OAAO,CAACjD,SAAS,CAAC;EAC7C,OAAO;IACL,GAAG2B,aAAa,CAACO,OAAO,CAAC;IACzBY,GAAG,EAAEE;EACP,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"hd-wallet.mjs","names":["nacl","_tweetnaclAuth","full","hmac","_bip32Path","fromString","aesjs","sha256hash","encode","Encoding","CryptographyError","concatBuffers","Ecb","ModeOfOperation","ecb","encryptKey","password","binaryData","hashedPasswordBytes","aesEcb","encrypt","decryptKey","encrypted","encryptedBytes","_Buffer","from","decrypt","DerivationError","constructor","message","name","ED25519_CURVE","HARDENED_OFFSET","deriveChild","secretKey","chainCode","index","indexBuffer","allocUnsafe","writeUInt32BE","data","alloc","I","IL","slice","IR","derivePathFromKey","path","key","segments","toPathArray","forEach","segment","i","reduce","parentKey","getMasterKeyFromSeed","seed","derivePathFromSeed","includes","masterKey","formatAccount","keys","publicKey","toString","AccountAddress","getKeyPair","sign","keyPair","fromSeed","generateSaveHDWalletFromSeed","walletKey","getSaveHDWalletAccounts","saveHDWallet","accountCount","Array","fill","undefined","map","_","idx","getHdWalletAccountFromSeed","accountIdx","derived"],"sources":["../../src/utils/hd-wallet.ts"],"sourcesContent":["import nacl from 'tweetnacl';\nimport { full as hmac } from 'tweetnacl-auth';\nimport { fromString } from 'bip32-path';\nimport aesjs from 'aes-js';\nimport {\n sha256hash, encode, Encoding, Encoded,\n} from './encoder';\nimport { CryptographyError } from './errors';\nimport { concatBuffers } from './other';\n\nconst Ecb = aesjs.ModeOfOperation.ecb;\n\n// TODO: use mnemonic encryption instead of AES\n/**\n * Encrypt given data using `password`\n * @param password - Password to encrypt with\n * @param binaryData - Data to encrypt\n * @returns Encrypted data\n */\nfunction encryptKey(password: string, binaryData: Uint8Array): Uint8Array {\n const hashedPasswordBytes = sha256hash(password);\n const aesEcb = new Ecb(hashedPasswordBytes);\n return aesEcb.encrypt(binaryData);\n}\n\n/**\n * Decrypt given data using `password`\n * @param password - Password to decrypt with\n * @param encrypted - Data to decrypt\n * @returns Decrypted data\n */\nfunction decryptKey(password: string, encrypted: Uint8Array): Uint8Array {\n const encryptedBytes = Buffer.from(encrypted);\n const hashedPasswordBytes = sha256hash(password);\n const aesEcb = new Ecb(hashedPasswordBytes);\n return aesEcb.decrypt(encryptedBytes);\n}\n\n/**\n * @category exception\n */\nexport class DerivationError extends CryptographyError {\n constructor(message: string) {\n super(message);\n this.name = 'DerivationError';\n }\n}\n\nconst ED25519_CURVE = Buffer.from('ed25519 seed');\nconst HARDENED_OFFSET = 0x80000000;\n\ninterface KeyTreeNode {\n secretKey: Uint8Array;\n chainCode: Uint8Array;\n}\n\ninterface HDWallet {\n secretKey: string;\n chainCode: string;\n}\n\ninterface Account {\n secretKey: string; // TODO: use Encoded.AccountSecretKey instead hex\n publicKey: Encoded.AccountAddress;\n}\n\ntype Dec<N extends number> = [-1, 0, 1, 2, 3, 4][N];\ntype Bip32PathT<MaxLen extends number, H extends 'H' | 'h' | '\\''> = MaxLen extends -1\n ? `${number}${H}`\n : Bip32PathT<Dec<MaxLen>, H> | `${Bip32PathT<Dec<MaxLen>, H>}/${number}${H}`;\ntype Bip32Path<MaxLen extends number> =\n '' | Bip32PathT<MaxLen, 'H'> | Bip32PathT<MaxLen, 'h'> | Bip32PathT<MaxLen, '\\''>;\n\n/**\n * @category hd-wallet\n * @param keyTreeNode - A node of key tree\n * @param index - index of child node to derive\n */\nexport function deriveChild({ secretKey, chainCode }: KeyTreeNode, index: number): KeyTreeNode {\n if (index < HARDENED_OFFSET) {\n throw new DerivationError(`Segment ${index} is not hardened`);\n }\n const indexBuffer = Buffer.allocUnsafe(4);\n indexBuffer.writeUInt32BE(index, 0);\n\n const data = concatBuffers([Buffer.alloc(1, 0), secretKey, indexBuffer]);\n\n const I = hmac(data, chainCode);\n const IL = I.slice(0, 32);\n const IR = I.slice(32);\n return {\n secretKey: IL,\n chainCode: IR,\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function derivePathFromKey(path: Bip32Path<5>, key: KeyTreeNode): KeyTreeNode {\n const segments = path === '' ? [] : fromString(path).toPathArray();\n segments.forEach((segment, i) => {\n if (segment < HARDENED_OFFSET) {\n throw new DerivationError(`Segment #${i + 1} is not hardened`);\n }\n });\n\n return segments.reduce((parentKey, segment) => deriveChild(parentKey, segment), key);\n}\n\n/**\n * @category hd-wallet\n */\nexport function getMasterKeyFromSeed(seed: Uint8Array): KeyTreeNode {\n const I = hmac(seed, ED25519_CURVE);\n const IL = I.slice(0, 32);\n const IR = I.slice(32);\n return {\n secretKey: IL,\n chainCode: IR,\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function derivePathFromSeed(path: 'm' | `m/${Bip32Path<5>}`, seed: Uint8Array): KeyTreeNode {\n if (!['m', 'm/'].includes(path.slice(0, 2))) {\n throw new DerivationError('Root element is required');\n }\n const masterKey = getMasterKeyFromSeed(seed);\n return derivePathFromKey(path.slice(2) as Bip32Path<5>, masterKey);\n}\n\nfunction formatAccount(keys: nacl.SignKeyPair): Account {\n const { secretKey, publicKey } = keys;\n return {\n secretKey: Buffer.from(secretKey).toString('hex'),\n publicKey: encode(publicKey, Encoding.AccountAddress),\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function getKeyPair(secretKey: Uint8Array): nacl.SignKeyPair {\n return nacl.sign.keyPair.fromSeed(secretKey);\n}\n\n/**\n * @category hd-wallet\n */\nexport function generateSaveHDWalletFromSeed(seed: Uint8Array, password: string): HDWallet {\n const walletKey = derivePathFromSeed('m/44h/457h', seed);\n return {\n secretKey: Buffer.from(encryptKey(password, walletKey.secretKey)).toString('hex'),\n chainCode: Buffer.from(encryptKey(password, walletKey.chainCode)).toString('hex'),\n };\n}\n\n/**\n * @category hd-wallet\n */\nexport function getSaveHDWalletAccounts(\n saveHDWallet: HDWallet,\n password: string,\n accountCount: number,\n): Account[] {\n const walletKey = {\n secretKey: decryptKey(password, Buffer.from(saveHDWallet.secretKey, 'hex')),\n chainCode: decryptKey(password, Buffer.from(saveHDWallet.chainCode, 'hex')),\n };\n return (new Array(accountCount)).fill(undefined)\n .map((_, idx) => formatAccount(getKeyPair(derivePathFromKey(`${idx}h/0h/0h`, walletKey).secretKey)));\n}\n\n/**\n * @category hd-wallet\n */\nexport const getHdWalletAccountFromSeed = (\n seed: Uint8Array,\n accountIdx: number,\n): Account & { idx: number } => {\n const walletKey = derivePathFromSeed('m/44h/457h', seed);\n const derived = derivePathFromKey(`${accountIdx}h/0h/0h`, walletKey);\n const keyPair = getKeyPair(derived.secretKey);\n return {\n ...formatAccount(keyPair),\n idx: accountIdx,\n };\n};\n"],"mappings":";;;;AAAA,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAAC,cAAA,MAA6B,gBAAgB;AAAC;EAAAC,IAAA,EAAAC;AAAA,IAAAF,cAAA;AAC9C,OAAAG,UAAA,MAA2B,YAAY;AAAC;EAAAC;AAAA,IAAAD,UAAA;AACxC,OAAOE,KAAK,MAAM,QAAQ;AAAC,SAEzBC,UAAU,EAAEC,MAAM,EAAEC,QAAQ;AAAA,SAErBC,iBAAiB;AAAA,SACjBC,aAAa;AAEtB,MAAMC,GAAG,GAAGN,KAAK,CAACO,eAAe,CAACC,GAAG;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,UAAUA,CAACC,QAAgB,EAAEC,UAAsB,EAAc;EACxE,MAAMC,mBAAmB,GAAGX,UAAU,CAACS,QAAQ,CAAC;EAChD,MAAMG,MAAM,GAAG,IAAIP,GAAG,CAACM,mBAAmB,CAAC;EAC3C,OAAOC,MAAM,CAACC,OAAO,CAACH,UAAU,CAAC;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAASI,UAAUA,CAACL,QAAgB,EAAEM,SA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ACL,QAAQ,EAAEQ,OAAA,CAAOC,IAAI,CAACgD,YAAY,CAACtC,SAAS,EAAE,KAAK,CAAC;EAC5E,CAAC;EACD,OAAQ,IAAIwC,KAAK,CAACD,YAAY,CAAC,CAAEE,IAAI,CAACC,SAAS,CAAC,CAC7CC,GAAG,CAAC,CAACC,CAAC,EAAEC,GAAG,KAAKnB,aAAa,CAACK,UAAU,CAACpB,iBAAiB,CAAE,GAAEkC,GAAI,SAAQ,EAAET,SAAS,CAAC,CAACrC,SAAS,CAAC,CAAC,CAAC;AACxG;;AAEA;AACA;AACA;AACA,OAAO,MAAM+C,0BAA0B,GAAGA,CACxCxB,IAAgB,EAChByB,UAAkB,KACY;EAC9B,MAAMX,SAAS,GAAGb,kBAAkB,CAAC,YAAY,EAAED,IAAI,CAAC;EACxD,MAAM0B,OAAO,GAAGrC,iBAAiB,CAAE,GAAEoC,UAAW,SAAQ,EAAEX,SAAS,CAAC;EACpE,MAAMH,OAAO,GAAGF,UAAU,CAACiB,OAAO,CAACjD,SAAS,CAAC;EAC7C,OAAO;IACL,GAAG2B,aAAa,CAACO,OAAO,CAAC;IACzBY,GAAG,EAAEE;EACP,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeternity/aepp-sdk",
3
- "version": "13.3.2",
3
+ "version": "13.3.3",
4
4
  "description": "SDK for the æternity blockchain",
5
5
  "main": "dist/aepp-sdk.js",
6
6
  "types": "es/index.d.ts",
@@ -79,9 +79,10 @@
79
79
  "@aeternity/argon2": "^0.0.1",
80
80
  "@aeternity/uuid": "^0.0.1",
81
81
  "@azure/core-client": "^1.8.0",
82
- "@azure/core-rest-pipeline": "^1.14.0",
82
+ "@azure/core-rest-pipeline": "~1.14.0",
83
+ "@azure/logger": "~1.0.4",
83
84
  "@babel/runtime-corejs3": "^7.24.0",
84
- "@ledgerhq/hw-transport": "^6.30.4",
85
+ "@ledgerhq/hw-transport": "~6.30.6",
85
86
  "@types/aes-js": "^3.1.4",
86
87
  "@types/json-bigint": "^1.0.4",
87
88
  "@types/node": "~18.13",
package/src/AeSdkAepp.ts CHANGED
@@ -146,7 +146,7 @@ export default class AeSdkAepp extends AeSdkBase {
146
146
  * @returns Addresses from wallet
147
147
  */
148
148
  async askAddresses(): Promise<Encoded.AccountAddress[]> {
149
- this._ensureAccountAccess();
149
+ this._ensureConnected();
150
150
  return this.rpcClient.request(METHODS.address, undefined);
151
151
  }
152
152
 
@@ -358,11 +358,12 @@ export default class AeSdkWallet extends AeSdk {
358
358
  * @returns Object with wallet information
359
359
  */
360
360
  async getWalletInfo(): Promise<WalletInfo> {
361
+ const { origin } = window.location;
361
362
  return {
362
363
  id: this.id,
363
364
  name: this.name,
364
365
  networkId: await this.api.getNetworkId(),
365
- origin: window.location.origin,
366
+ origin: origin === 'file://' ? '*' : origin,
366
367
  type: this._type,
367
368
  };
368
369
  }
@@ -257,7 +257,7 @@ export default class Channel {
257
257
  * })
258
258
  * ```
259
259
  */
260
- async leave(): Promise<{ channelId: Encoded.Bytearray; signedTx: Encoded.Transaction }> {
260
+ async leave(): Promise<{ channelId: Encoded.Channel; signedTx: Encoded.Transaction }> {
261
261
  return this.enqueueAction(() => {
262
262
  notify(this, 'channels.leave');
263
263
  return { handler: handlers.awaitingLeave };
@@ -52,7 +52,7 @@ export type SignTx = (tx: Encoded.Transaction, options?: SignOptions) => (
52
52
  /**
53
53
  * @see {@link https://github.com/aeternity/protocol/blob/6734de2e4c7cce7e5e626caa8305fb535785131d/node/api/channels_api_usage.md#channel-establishing-parameters}
54
54
  */
55
- export interface ChannelOptions {
55
+ interface CommonChannelOptions {
56
56
  existingFsmId?: Encoded.Bytearray;
57
57
  /**
58
58
  * Channel url (for example: "ws://localhost:3001")
@@ -74,7 +74,7 @@ export interface ChannelOptions {
74
74
  /**
75
75
  * Initial deposit in favour of the responder by the initiator
76
76
  */
77
- pushAmount: number;
77
+ pushAmount: BigNumber | number;
78
78
  /**
79
79
  * Amount of coins the initiator has committed to the channel
80
80
  */
@@ -92,17 +92,9 @@ export interface ChannelOptions {
92
92
  */
93
93
  ttl?: number;
94
94
  /**
95
- * Host of the responder's node
96
- */
97
- host: string;
98
- /**
99
- * The port of the responders node
95
+ * The port of the responder's node
100
96
  */
101
97
  port: number;
102
- /**
103
- * Participant role
104
- */
105
- role: 'initiator' | 'responder';
106
98
  /**
107
99
  * How to calculate minimum depth (default: txfee)
108
100
  */
@@ -120,16 +112,16 @@ export interface ChannelOptions {
120
112
  */
121
113
  gasPrice?: BigNumber | number;
122
114
 
123
- signedTx?: string;
115
+ signedTx?: Encoded.Transaction;
124
116
  /**
125
117
  * Existing channel id (required if reestablishing a channel)
126
118
  */
127
- existingChannelId?: string;
119
+ existingChannelId?: Encoded.Channel;
128
120
  /**
129
121
  * Offchain transaction (required if reestablishing a channel)
130
122
  */
131
- offChainTx?: string;
132
- reconnectTx?: string;
123
+ offChainTx?: Encoded.Transaction;
124
+ reconnectTx?: Encoded.Transaction;
133
125
  /**
134
126
  * The time waiting for a new event to be initiated (default: 600000)
135
127
  */
@@ -174,7 +166,6 @@ export interface ChannelOptions {
174
166
  * Applicable only for responder (default: timeout_idle's value)
175
167
  */
176
168
  timeoutAwaitingOpen?: number;
177
- statePassword?: string;
178
169
  /**
179
170
  * Log websocket communication and state changes
180
171
  */
@@ -183,9 +174,25 @@ export interface ChannelOptions {
183
174
  * Function which verifies and signs transactions
184
175
  */
185
176
  sign: SignTxWithTag;
186
- offchainTx?: string;
177
+ offchainTx?: Encoded.Transaction;
187
178
  }
188
179
 
180
+ export type ChannelOptions = CommonChannelOptions & ({
181
+ /**
182
+ * Participant role
183
+ */
184
+ role: 'initiator';
185
+ /**
186
+ * Host of the responder's node
187
+ */
188
+ host: string;
189
+ } | {
190
+ /**
191
+ * Participant role
192
+ */
193
+ role: 'responder';
194
+ });
195
+
189
196
  export interface ChannelHandler extends Function {
190
197
  enter?: Function;
191
198
  }
@@ -70,6 +70,15 @@ export function nameToPunycode(maybeName: string): AensName {
70
70
  if (/\p{Emoji_Presentation}/u.test(name)) {
71
71
  throw new ArgumentError('aens name', 'not containing emoji', maybeName);
72
72
  }
73
+ if (name[2] === '-' && name[3] === '-') {
74
+ throw new ArgumentError('aens name', 'without "-" char in both the third and fourth positions', maybeName);
75
+ }
76
+ if (name[0] === '-') {
77
+ throw new ArgumentError('aens name', 'starting with no "-" char', maybeName);
78
+ }
79
+ if (name.at(-1) === '-') {
80
+ throw new ArgumentError('aens name', 'ending with no "-" char', maybeName);
81
+ }
73
82
  let punycode;
74
83
  try {
75
84
  const u = new URL(`http://${name}.${suffix}`);
@@ -2,7 +2,9 @@ import nacl from 'tweetnacl';
2
2
  import { full as hmac } from 'tweetnacl-auth';
3
3
  import { fromString } from 'bip32-path';
4
4
  import aesjs from 'aes-js';
5
- import { sha256hash, encode, Encoding } from './encoder';
5
+ import {
6
+ sha256hash, encode, Encoding, Encoded,
7
+ } from './encoder';
6
8
  import { CryptographyError } from './errors';
7
9
  import { concatBuffers } from './other';
8
10
 
@@ -58,8 +60,8 @@ interface HDWallet {
58
60
  }
59
61
 
60
62
  interface Account {
61
- secretKey: string;
62
- publicKey: string;
63
+ secretKey: string; // TODO: use Encoded.AccountSecretKey instead hex
64
+ publicKey: Encoded.AccountAddress;
63
65
  }
64
66
 
65
67
  type Dec<N extends number> = [-1, 0, 1, 2, 3, 4][N];
@@ -146,7 +146,7 @@ export default class Channel {
146
146
  * ```
147
147
  */
148
148
  leave(): Promise<{
149
- channelId: Encoded.Bytearray;
149
+ channelId: Encoded.Channel;
150
150
  signedTx: Encoded.Transaction;
151
151
  }>;
152
152
  /**
@@ -32,7 +32,7 @@ export type SignTx = (tx: Encoded.Transaction, options?: SignOptions) => (Promis
32
32
  /**
33
33
  * @see {@link https://github.com/aeternity/protocol/blob/6734de2e4c7cce7e5e626caa8305fb535785131d/node/api/channels_api_usage.md#channel-establishing-parameters}
34
34
  */
35
- export interface ChannelOptions {
35
+ interface CommonChannelOptions {
36
36
  existingFsmId?: Encoded.Bytearray;
37
37
  /**
38
38
  * Channel url (for example: "ws://localhost:3001")
@@ -53,7 +53,7 @@ export interface ChannelOptions {
53
53
  /**
54
54
  * Initial deposit in favour of the responder by the initiator
55
55
  */
56
- pushAmount: number;
56
+ pushAmount: BigNumber | number;
57
57
  /**
58
58
  * Amount of coins the initiator has committed to the channel
59
59
  */
@@ -71,17 +71,9 @@ export interface ChannelOptions {
71
71
  */
72
72
  ttl?: number;
73
73
  /**
74
- * Host of the responder's node
75
- */
76
- host: string;
77
- /**
78
- * The port of the responders node
74
+ * The port of the responder's node
79
75
  */
80
76
  port: number;
81
- /**
82
- * Participant role
83
- */
84
- role: 'initiator' | 'responder';
85
77
  /**
86
78
  * How to calculate minimum depth (default: txfee)
87
79
  */
@@ -98,16 +90,16 @@ export interface ChannelOptions {
98
90
  * Used for the fee computation of the channel open transaction
99
91
  */
100
92
  gasPrice?: BigNumber | number;
101
- signedTx?: string;
93
+ signedTx?: Encoded.Transaction;
102
94
  /**
103
95
  * Existing channel id (required if reestablishing a channel)
104
96
  */
105
- existingChannelId?: string;
97
+ existingChannelId?: Encoded.Channel;
106
98
  /**
107
99
  * Offchain transaction (required if reestablishing a channel)
108
100
  */
109
- offChainTx?: string;
110
- reconnectTx?: string;
101
+ offChainTx?: Encoded.Transaction;
102
+ reconnectTx?: Encoded.Transaction;
111
103
  /**
112
104
  * The time waiting for a new event to be initiated (default: 600000)
113
105
  */
@@ -152,7 +144,6 @@ export interface ChannelOptions {
152
144
  * Applicable only for responder (default: timeout_idle's value)
153
145
  */
154
146
  timeoutAwaitingOpen?: number;
155
- statePassword?: string;
156
147
  /**
157
148
  * Log websocket communication and state changes
158
149
  */
@@ -161,8 +152,23 @@ export interface ChannelOptions {
161
152
  * Function which verifies and signs transactions
162
153
  */
163
154
  sign: SignTxWithTag;
164
- offchainTx?: string;
155
+ offchainTx?: Encoded.Transaction;
165
156
  }
157
+ export type ChannelOptions = CommonChannelOptions & ({
158
+ /**
159
+ * Participant role
160
+ */
161
+ role: 'initiator';
162
+ /**
163
+ * Host of the responder's node
164
+ */
165
+ host: string;
166
+ } | {
167
+ /**
168
+ * Participant role
169
+ */
170
+ role: 'responder';
171
+ });
166
172
  export interface ChannelHandler extends Function {
167
173
  enter?: Function;
168
174
  }
@@ -1,4 +1,5 @@
1
1
  import nacl from 'tweetnacl';
2
+ import { Encoded } from './encoder';
2
3
  import { CryptographyError } from './errors';
3
4
  /**
4
5
  * @category exception
@@ -16,7 +17,7 @@ interface HDWallet {
16
17
  }
17
18
  interface Account {
18
19
  secretKey: string;
19
- publicKey: string;
20
+ publicKey: Encoded.AccountAddress;
20
21
  }
21
22
  type Dec<N extends number> = [
22
23
  -1,
@@ -146,7 +146,7 @@ export default class Channel {
146
146
  * ```
147
147
  */
148
148
  leave(): Promise<{
149
- channelId: Encoded.Bytearray;
149
+ channelId: Encoded.Channel;
150
150
  signedTx: Encoded.Transaction;
151
151
  }>;
152
152
  /**
@@ -32,7 +32,7 @@ export type SignTx = (tx: Encoded.Transaction, options?: SignOptions) => (Promis
32
32
  /**
33
33
  * @see {@link https://github.com/aeternity/protocol/blob/6734de2e4c7cce7e5e626caa8305fb535785131d/node/api/channels_api_usage.md#channel-establishing-parameters}
34
34
  */
35
- export interface ChannelOptions {
35
+ interface CommonChannelOptions {
36
36
  existingFsmId?: Encoded.Bytearray;
37
37
  /**
38
38
  * Channel url (for example: "ws://localhost:3001")
@@ -53,7 +53,7 @@ export interface ChannelOptions {
53
53
  /**
54
54
  * Initial deposit in favour of the responder by the initiator
55
55
  */
56
- pushAmount: number;
56
+ pushAmount: BigNumber | number;
57
57
  /**
58
58
  * Amount of coins the initiator has committed to the channel
59
59
  */
@@ -71,17 +71,9 @@ export interface ChannelOptions {
71
71
  */
72
72
  ttl?: number;
73
73
  /**
74
- * Host of the responder's node
75
- */
76
- host: string;
77
- /**
78
- * The port of the responders node
74
+ * The port of the responder's node
79
75
  */
80
76
  port: number;
81
- /**
82
- * Participant role
83
- */
84
- role: 'initiator' | 'responder';
85
77
  /**
86
78
  * How to calculate minimum depth (default: txfee)
87
79
  */
@@ -98,16 +90,16 @@ export interface ChannelOptions {
98
90
  * Used for the fee computation of the channel open transaction
99
91
  */
100
92
  gasPrice?: BigNumber | number;
101
- signedTx?: string;
93
+ signedTx?: Encoded.Transaction;
102
94
  /**
103
95
  * Existing channel id (required if reestablishing a channel)
104
96
  */
105
- existingChannelId?: string;
97
+ existingChannelId?: Encoded.Channel;
106
98
  /**
107
99
  * Offchain transaction (required if reestablishing a channel)
108
100
  */
109
- offChainTx?: string;
110
- reconnectTx?: string;
101
+ offChainTx?: Encoded.Transaction;
102
+ reconnectTx?: Encoded.Transaction;
111
103
  /**
112
104
  * The time waiting for a new event to be initiated (default: 600000)
113
105
  */
@@ -152,7 +144,6 @@ export interface ChannelOptions {
152
144
  * Applicable only for responder (default: timeout_idle's value)
153
145
  */
154
146
  timeoutAwaitingOpen?: number;
155
- statePassword?: string;
156
147
  /**
157
148
  * Log websocket communication and state changes
158
149
  */
@@ -161,8 +152,23 @@ export interface ChannelOptions {
161
152
  * Function which verifies and signs transactions
162
153
  */
163
154
  sign: SignTxWithTag;
164
- offchainTx?: string;
155
+ offchainTx?: Encoded.Transaction;
165
156
  }
157
+ export type ChannelOptions = CommonChannelOptions & ({
158
+ /**
159
+ * Participant role
160
+ */
161
+ role: 'initiator';
162
+ /**
163
+ * Host of the responder's node
164
+ */
165
+ host: string;
166
+ } | {
167
+ /**
168
+ * Participant role
169
+ */
170
+ role: 'responder';
171
+ });
166
172
  export interface ChannelHandler extends Function {
167
173
  enter?: Function;
168
174
  }
@@ -1,4 +1,5 @@
1
1
  import nacl from 'tweetnacl';
2
+ import { Encoded } from './encoder';
2
3
  import { CryptographyError } from './errors';
3
4
  /**
4
5
  * @category exception
@@ -16,7 +17,7 @@ interface HDWallet {
16
17
  }
17
18
  interface Account {
18
19
  secretKey: string;
19
- publicKey: string;
20
+ publicKey: Encoded.AccountAddress;
20
21
  }
21
22
  type Dec<N extends number> = [
22
23
  -1,