@aeternity/aepp-sdk 13.1.0 → 13.2.0
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.
- package/dist/aepp-sdk.browser-script.js +1 -1
- package/dist/aepp-sdk.browser-script.js.map +1 -1
- package/dist/aepp-sdk.browser.js +1 -1
- package/dist/aepp-sdk.browser.js.map +1 -1
- package/dist/aepp-sdk.js +2162 -1566
- package/dist/aepp-sdk.js.map +1 -1
- package/es/AeSdkAepp.mjs.map +1 -1
- package/es/AeSdkBase.d.ts +10 -0
- package/es/AeSdkBase.mjs +27 -0
- package/es/AeSdkBase.mjs.map +1 -1
- package/es/AeSdkMethods.mjs.map +1 -1
- package/es/AeSdkWallet.d.ts +1 -1
- package/es/AeSdkWallet.mjs +53 -20
- package/es/AeSdkWallet.mjs.map +1 -1
- package/es/Middleware.mjs.map +1 -1
- package/es/MiddlewareSubscriber.mjs +3 -3
- package/es/MiddlewareSubscriber.mjs.map +1 -1
- package/es/Node.mjs.map +1 -1
- package/es/account/Base.d.ts +44 -2
- package/es/account/Base.mjs +95 -1
- package/es/account/Base.mjs.map +1 -1
- package/es/account/Generalized.d.ts +3 -0
- package/es/account/Generalized.mjs +15 -0
- package/es/account/Generalized.mjs.map +1 -1
- package/es/account/Ledger.d.ts +3 -0
- package/es/account/Ledger.mjs +15 -0
- package/es/account/Ledger.mjs.map +1 -1
- package/es/account/LedgerFactory.mjs.map +1 -1
- package/es/account/Memory.d.ts +10 -0
- package/es/account/Memory.mjs +34 -0
- package/es/account/Memory.mjs.map +1 -1
- package/es/account/Rpc.d.ts +4 -0
- package/es/account/Rpc.mjs +29 -0
- package/es/account/Rpc.mjs.map +1 -1
- package/es/aens.mjs.map +1 -1
- package/es/aepp-wallet-communication/connection/Browser.mjs.map +1 -1
- package/es/aepp-wallet-communication/connection/BrowserRuntime.mjs.map +1 -1
- package/es/aepp-wallet-communication/connection/BrowserWindowMessage.mjs.map +1 -1
- package/es/aepp-wallet-communication/connection-proxy.mjs.map +1 -1
- package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -1
- package/es/aepp-wallet-communication/rpc/types.d.ts +9 -0
- package/es/aepp-wallet-communication/rpc/types.mjs.map +1 -1
- package/es/aepp-wallet-communication/schema.d.ts +1 -0
- package/es/aepp-wallet-communication/schema.mjs +20 -19
- package/es/aepp-wallet-communication/schema.mjs.map +1 -1
- package/es/aepp-wallet-communication/wallet-detector.mjs.map +1 -1
- package/es/apis/compiler/compiler.mjs.map +1 -1
- package/es/apis/middleware/middleware.mjs.map +1 -1
- package/es/apis/middleware/models/index.mjs +340 -124
- package/es/apis/middleware/models/index.mjs.map +1 -1
- package/es/apis/node/node.mjs.map +1 -1
- package/es/chain.mjs +1 -1
- package/es/chain.mjs.map +1 -1
- package/es/channel/Base.mjs.map +1 -1
- package/es/channel/Contract.mjs.map +1 -1
- package/es/channel/Spend.mjs.map +1 -1
- package/es/channel/handlers.mjs +2 -2
- package/es/channel/handlers.mjs.map +1 -1
- package/es/channel/internal.mjs +6 -6
- package/es/channel/internal.mjs.map +1 -1
- package/es/contract/Contract.mjs +1 -1
- package/es/contract/Contract.mjs.map +1 -1
- package/es/contract/compiler/Cli.mjs.map +1 -1
- package/es/contract/compiler/Http.mjs.map +1 -1
- package/es/contract/delegation-signature.d.ts +2 -1
- package/es/contract/delegation-signature.mjs +39 -8
- package/es/contract/delegation-signature.mjs.map +1 -1
- package/es/contract/ga.mjs.map +1 -1
- package/es/oracle.mjs.map +1 -1
- package/es/spend.d.ts +2 -1
- package/es/spend.mjs +4 -2
- package/es/spend.mjs.map +1 -1
- package/es/tx/builder/constants.mjs +26 -23
- package/es/tx/builder/constants.mjs.map +1 -1
- package/es/tx/builder/field-types/abi-version.mjs.map +1 -1
- package/es/tx/builder/field-types/coin-amount.mjs.map +1 -1
- package/es/tx/builder/field-types/ct-version.mjs.map +1 -1
- package/es/tx/builder/field-types/deposit.mjs.map +1 -1
- package/es/tx/builder/field-types/entry.mjs.map +1 -1
- package/es/tx/builder/field-types/fee.mjs.map +1 -1
- package/es/tx/builder/field-types/field.mjs.map +1 -1
- package/es/tx/builder/field-types/gas-limit.mjs.map +1 -1
- package/es/tx/builder/field-types/gas-price.mjs.map +1 -1
- package/es/tx/builder/field-types/index.d.ts +28 -150
- package/es/tx/builder/field-types/index.mjs +28 -56
- package/es/tx/builder/field-types/index.mjs.map +1 -1
- package/es/tx/builder/field-types/map.mjs.map +1 -1
- package/es/tx/builder/field-types/mptree.mjs +3 -3
- package/es/tx/builder/field-types/mptree.mjs.map +1 -1
- package/es/tx/builder/field-types/name-fee.mjs.map +1 -1
- package/es/tx/builder/field-types/pointers.mjs.map +1 -1
- package/es/tx/builder/field-types/string.mjs.map +1 -1
- package/es/tx/builder/field-types/ttl.mjs.map +1 -1
- package/es/tx/builder/field-types/u-int.mjs +1 -1
- package/es/tx/builder/field-types/u-int.mjs.map +1 -1
- package/es/tx/builder/helpers.mjs.map +1 -1
- package/es/tx/builder/index.mjs.map +1 -1
- package/es/tx/builder/schema.mjs +11 -10
- package/es/tx/builder/schema.mjs.map +1 -1
- package/es/tx/execution-cost.mjs.map +1 -1
- package/es/tx/transaction-signer.mjs.map +1 -1
- package/es/tx/validator.mjs.map +1 -1
- package/es/utils/amount-formatter.mjs +7 -7
- package/es/utils/amount-formatter.mjs.map +1 -1
- package/es/utils/autorest.mjs.map +1 -1
- package/es/utils/bignumber.mjs.map +1 -1
- package/es/utils/bytes.mjs.map +1 -1
- package/es/utils/crypto.mjs.map +1 -1
- package/es/utils/encoder-types.mjs +3 -3
- package/es/utils/encoder-types.mjs.map +1 -1
- package/es/utils/encoder.mjs.map +1 -1
- package/es/utils/errors.mjs.map +1 -1
- package/es/utils/hd-wallet.mjs.map +1 -1
- package/es/utils/keystore.mjs.map +1 -1
- package/es/utils/other.mjs.map +1 -1
- package/es/utils/semver-satisfies.mjs.map +1 -1
- package/es/utils/string.mjs.map +1 -1
- package/es/utils/typed-data.mjs +0 -1
- package/es/utils/typed-data.mjs.map +1 -1
- package/package.json +35 -35
- package/src/AeSdkBase.ts +36 -0
- package/src/AeSdkWallet.ts +36 -12
- package/src/account/Base.ts +84 -3
- package/src/account/Generalized.ts +15 -0
- package/src/account/Ledger.ts +15 -0
- package/src/account/Memory.ts +53 -1
- package/src/account/Rpc.ts +35 -0
- package/src/aepp-wallet-communication/rpc/types.ts +10 -0
- package/src/aepp-wallet-communication/schema.ts +1 -0
- package/src/chain.ts +1 -1
- package/src/contract/Contract.ts +1 -1
- package/src/contract/delegation-signature.ts +37 -11
- package/src/spend.ts +2 -2
- package/src/tx/builder/field-types/index.ts +28 -58
- package/src/tx/builder/field-types/u-int.ts +1 -1
- package/types-legacy/ts4.2/AeSdkBase.d.ts +10 -0
- package/types-legacy/ts4.2/AeSdkWallet.d.ts +1 -1
- package/types-legacy/ts4.2/account/Base.d.ts +44 -2
- package/types-legacy/ts4.2/account/Generalized.d.ts +3 -0
- package/types-legacy/ts4.2/account/Ledger.d.ts +3 -0
- package/types-legacy/ts4.2/account/Memory.d.ts +10 -0
- package/types-legacy/ts4.2/account/Rpc.d.ts +4 -0
- package/types-legacy/ts4.2/aepp-wallet-communication/rpc/types.d.ts +9 -0
- package/types-legacy/ts4.2/aepp-wallet-communication/schema.d.ts +1 -0
- package/types-legacy/ts4.2/contract/delegation-signature.d.ts +2 -1
- package/types-legacy/ts4.2/spend.d.ts +2 -1
- package/types-legacy/ts4.2/tx/builder/field-types/index.d.ts +28 -153
- package/types-legacy/ts4.5/AeSdkBase.d.ts +10 -0
- package/types-legacy/ts4.5/AeSdkWallet.d.ts +1 -1
- package/types-legacy/ts4.5/account/Base.d.ts +44 -2
- package/types-legacy/ts4.5/account/Generalized.d.ts +3 -0
- package/types-legacy/ts4.5/account/Ledger.d.ts +3 -0
- package/types-legacy/ts4.5/account/Memory.d.ts +10 -0
- package/types-legacy/ts4.5/account/Rpc.d.ts +4 -0
- package/types-legacy/ts4.5/aepp-wallet-communication/rpc/types.d.ts +9 -0
- package/types-legacy/ts4.5/aepp-wallet-communication/schema.d.ts +1 -0
- package/types-legacy/ts4.5/contract/delegation-signature.d.ts +2 -1
- package/types-legacy/ts4.5/spend.d.ts +2 -1
- package/types-legacy/ts4.5/tx/builder/field-types/index.d.ts +28 -153
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Contract.mjs","names":["_aeternityAeppCalldata","Encoder","Calldata","DRY_RUN_ACCOUNT","Tag","buildContractIdByContractTx","unpackTx","buildTxAsync","buildTxHash","decode","MissingContractDefError","MissingContractAddressError","InactiveContractError","BytecodeMismatchError","DuplicateContractError","MissingFunctionNameError","InvalidMethodInvocationError","NotPayableFunctionError","TypeError","NodeInvocationError","IllegalArgumentError","NoSuchContractFunctionError","MissingEventDefinitionError","AmbiguousEventDefinitionError","UnexpectedTsError","InternalError","NoWalletConnectedError","ContractError","hash","calcHash","getAccount","getContract","getContractByteCode","resolveName","txDryRun","sendTransaction","_getCallResult","WeakSet","_sendAndProcess","_getFunctionAci","_getContractNameByEvent","_aciContract","WeakMap","Contract","$compile","$options","bytecode","onCompiler","sourceCode","compileBySourceCode","fileSystem","sourceCodePath","compile","$getCallResultByTxHash","fnName","options","callInfo","onNode","getTransactionInfoByHash","callInfoTyped","_classPrivateMethodGet","_getCallResult2","call","undefined","result","_estimateGas","name","params","arguments","length","$call","callStatic","gasUsed","Math","floor","$deploy","_opt$gasLimit","_other$result","opt","address","onAccount","ownerId","tx","tag","ContractCreateTx","gasLimit","callData","_calldata","encode","_name","code","other","_sendAndProcess2","log","decodedEvents","$decodeEvents","owner","transaction","fn","_opt$gasLimit2","top","fnAci","_getFunctionAci2","contractId","amount","payable","callerId","error","useFallbackAccount","message","pub","nonce","topKey","txOpt","ContractCallTx","callObj","dryRunOther","rawTx","txData","events","omitUnknown","map","event","topics","t","BigInt","contractName","_getContractNameByEvent2","decoded","decodeEvent","data","args","Object","entries","contract","filter","e","initialize","_ref","aci","validateBytecode","otherOptions","res","_bytecode","resolveByNode","active","onChanBytecode","isValid","validateBySourceCode","validate","ContractWithMethods","constructor","_ref2","_this","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","writable","value","_aci","aciLast","keys","_classPrivateFieldSet","_classPrivateFieldGet","assign","fromEntries","functions","_ref3","aciArgs","stateful","_len","Array","_key","pop","_ref4","returnType","returnValue","decodedResult","decodeFateString","toString","blockHeight","find","f","returns","ctAddress","nameHash","_ref5","contractAddressToName","addressToName","isEqual","a","b","JSON","stringify","contracts","_ref6","matchedEvents","variant","_ref7","values","flat","_ref8","eventName","_ref9","idx","arr","type","slice","some","el"],"sources":["../../src/contract/Contract.ts"],"sourcesContent":["/**\n * Contract module - routines to interact with the æternity contract\n *\n * High level documentation of the contracts are available at\n * https://github.com/aeternity/protocol/tree/master/contracts and\n */\n\nimport { Encoder as Calldata } from '@aeternity/aepp-calldata';\nimport { DRY_RUN_ACCOUNT } from '../tx/builder/schema';\nimport { Tag, AensName } from '../tx/builder/constants';\nimport {\n buildContractIdByContractTx, unpackTx, buildTxAsync, BuildTxOptions, buildTxHash,\n} from '../tx/builder';\nimport { decode, Encoded } from '../utils/encoder';\nimport {\n MissingContractDefError,\n MissingContractAddressError,\n InactiveContractError,\n BytecodeMismatchError,\n DuplicateContractError,\n MissingFunctionNameError,\n InvalidMethodInvocationError,\n NotPayableFunctionError,\n TypeError,\n NodeInvocationError,\n IllegalArgumentError,\n NoSuchContractFunctionError,\n MissingEventDefinitionError,\n AmbiguousEventDefinitionError,\n UnexpectedTsError,\n InternalError,\n NoWalletConnectedError,\n ContractError,\n} from '../utils/errors';\nimport { hash as calcHash } from '../utils/crypto';\nimport {\n ContractCallObject as NodeContractCallObject, Event as NodeEvent,\n} from '../apis/node';\nimport CompilerBase, { Aci } from './compiler/Base';\nimport Node, { TransformNodeType } from '../Node';\nimport {\n getAccount, getContract, getContractByteCode, resolveName, txDryRun, sendTransaction,\n SendTransactionOptions,\n} from '../chain';\nimport AccountBase from '../account/Base';\nimport { TxUnpacked } from '../tx/builder/schema.generated';\n\ntype ContractAci = NonNullable<Aci[0]['contract']>;\ntype FunctionAci = ContractAci['functions'][0];\n\ninterface Event extends NodeEvent {\n address: Encoded.ContractAddress;\n data: Encoded.ContractBytearray;\n}\n\nexport interface ContractCallObject extends TransformNodeType<NodeContractCallObject> {\n returnValue: Encoded.ContractBytearray;\n log: Event[];\n}\n\ninterface DecodedEvent {\n name: string;\n args: unknown[];\n contract: {\n name: string;\n address: Encoded.ContractAddress;\n };\n}\n\ntype TxData = Awaited<ReturnType<typeof sendTransaction>>;\n\ninterface SendAndProcessReturnType {\n result?: ContractCallObject;\n hash: TxData['hash'];\n tx: TxUnpacked & { tag: Tag.SignedTx | Tag.ContractCallTx | Tag.ContractCreateTx };\n txData: TxData;\n rawTx: Encoded.Transaction;\n}\n\nexport interface ContractMethodsBase { [key: string]: (...args: any[]) => any }\n\ntype MethodsToContractApi<M extends ContractMethodsBase> = {\n [Name in keyof M]:\n M[Name] extends (...args: infer Args) => any\n ? (...args: [\n ...Args,\n ...[] | [Name extends 'init'\n ? Parameters<Contract<M>['$deploy']>[1] : Parameters<Contract<M>['$call']>[2]],\n ]) => ReturnType<Contract<M>['$call']>\n : never\n};\n\ntype ContractWithMethods<M extends ContractMethodsBase> = Contract<M> & MethodsToContractApi<M>;\n\ntype MethodNames<M extends ContractMethodsBase> = keyof M & string | 'init';\n\ntype MethodParameters<M extends ContractMethodsBase, Fn extends MethodNames<M>> =\n Fn extends 'init'\n ? M extends { init: any } ? Parameters<M['init']> : []\n : Parameters<M[Fn]>;\n\ninterface GetContractNameByEventOptions {\n contractAddressToName?: { [key: Encoded.ContractAddress]: string };\n}\n\ninterface GetCallResultByHashReturnType<M extends ContractMethodsBase, Fn extends MethodNames<M>> {\n decodedResult: ReturnType<M[Fn]>;\n decodedEvents?: ReturnType<Contract<M>['$decodeEvents']>;\n}\n\n/**\n * Generate contract ACI object with predefined js methods for contract usage - can be used for\n * creating a reference to already deployed contracts\n * @category contract\n * @param options - Options object\n * @returns JS Contract API\n * @example\n * ```js\n * const contractIns = await aeSdk.initializeContract({ sourceCode })\n * await contractIns.$deploy([321]) or await contractIns.init(321)\n * const callResult = await contractIns.$call('setState', [123])\n * const staticCallResult = await contractIns.$call('setState', [123], { callStatic: true })\n * ```\n * Also you can call contract like: `await contractIns.setState(123, options)`\n * Then sdk decide to make on-chain or static call(dry-run API) transaction based on function is\n * stateful or not\n */\nclass Contract<M extends ContractMethodsBase> {\n /**\n * Compile contract\n * @returns bytecode\n */\n async $compile(): Promise<Encoded.ContractBytearray> {\n if (this.$options.bytecode != null) return this.$options.bytecode;\n if (this.$options.onCompiler == null) throw new IllegalArgumentError('Can\\'t compile without compiler');\n if (this.$options.sourceCode != null) {\n const { bytecode } = await this.$options.onCompiler\n .compileBySourceCode(this.$options.sourceCode, this.$options.fileSystem);\n this.$options.bytecode = bytecode;\n }\n if (this.$options.sourceCodePath != null) {\n const { bytecode } = await this.$options.onCompiler.compile(this.$options.sourceCodePath);\n this.$options.bytecode = bytecode;\n }\n if (this.$options.bytecode == null) {\n throw new IllegalArgumentError('Can\\'t compile without sourceCode and sourceCodePath');\n }\n return this.$options.bytecode;\n }\n\n #getCallResult<Fn extends MethodNames<M>>(\n { returnType, returnValue, log }: ContractCallObject,\n fnName: Fn,\n transaction: Encoded.Transaction | undefined,\n options: Parameters<Contract<M>['$decodeEvents']>[1],\n ): GetCallResultByHashReturnType<M, Fn> {\n let message: string;\n switch (returnType) {\n case 'ok': {\n const fnAci = this.#getFunctionAci(fnName);\n return {\n decodedResult: this._calldata.decode(this._name, fnAci.name, returnValue),\n decodedEvents: this.$decodeEvents(log, options),\n };\n }\n case 'revert':\n message = this._calldata.decodeFateString(returnValue);\n break;\n case 'error':\n message = decode(returnValue).toString();\n break;\n default:\n throw new InternalError(`Unknown return type: ${returnType}`);\n }\n throw new NodeInvocationError(message, transaction);\n }\n\n async #sendAndProcess<Fn extends MethodNames<M>>(\n tx: Encoded.Transaction,\n fnName: Fn,\n options: SendTransactionOptions & Parameters<Contract<M>['$getCallResultByTxHash']>[2],\n ): Promise<SendAndProcessReturnType & Partial<GetCallResultByHashReturnType<M, Fn>>> {\n const txData = await sendTransaction(tx, { ...this.$options, ...options });\n return {\n hash: txData.hash,\n tx: unpackTx<Tag.ContractCallTx | Tag.ContractCreateTx>(txData.rawTx),\n txData,\n rawTx: txData.rawTx,\n ...txData.blockHeight != null && (\n await this.$getCallResultByTxHash(txData.hash, fnName, options)\n ),\n };\n }\n\n async $getCallResultByTxHash<Fn extends MethodNames<M>>(\n hash: Encoded.TxHash,\n fnName: Fn,\n options?: Parameters<Contract<M>['$decodeEvents']>[1],\n ): Promise<GetCallResultByHashReturnType<M, Fn> & { result: ContractCallObject }> {\n const { callInfo } = await this.$options.onNode.getTransactionInfoByHash(hash);\n if (callInfo == null) {\n throw new ContractError(`callInfo is not available for transaction ${hash}`);\n }\n const callInfoTyped = callInfo as ContractCallObject;\n return {\n ...this.#getCallResult(callInfoTyped, fnName, undefined, options),\n result: callInfoTyped,\n };\n }\n\n async _estimateGas<Fn extends MethodNames<M>>(\n name: Fn,\n params: MethodParameters<M, Fn>,\n options: Omit<Parameters<Contract<M>['$call']>[2], 'callStatic'> = {},\n ): Promise<number> {\n const { result } = await this.$call(name, params, { ...options, callStatic: true });\n if (result == null) throw new UnexpectedTsError();\n const { gasUsed } = result;\n // taken from https://github.com/aeternity/aepp-sdk-js/issues/1286#issuecomment-977814771\n return Math.floor(gasUsed * 1.25);\n }\n\n /**\n * Deploy contract\n * @param params - Contract init function arguments array\n * @param options - Options\n * @returns deploy info\n */\n async $deploy(\n params: MethodParameters<M, 'init'>,\n options?: Parameters<Contract<M>['$call']>[2]\n & Partial<BuildTxOptions<Tag.ContractCreateTx, 'ownerId' | 'code' | 'callData'>>,\n ): Promise<Omit<SendAndProcessReturnType, 'hash'> & {\n transaction?: Encoded.TxHash;\n owner?: Encoded.AccountAddress;\n address?: Encoded.ContractAddress;\n decodedEvents?: ReturnType<Contract<M>['$decodeEvents']>;\n }> {\n const { callStatic, ...opt } = { ...this.$options, ...options };\n if (this.$options.bytecode == null) await this.$compile();\n if (callStatic === true) return this.$call('init', params, { ...opt, callStatic });\n if (this.$options.address != null) throw new DuplicateContractError();\n\n if (opt.onAccount == null) throw new IllegalArgumentError('Can\\'t deploy without account');\n const ownerId = opt.onAccount.address;\n if (this.$options.bytecode == null) throw new IllegalArgumentError('Can\\'t deploy without bytecode');\n const tx = await buildTxAsync({\n ...opt,\n tag: Tag.ContractCreateTx,\n gasLimit: opt.gasLimit ?? await this._estimateGas('init', params, opt),\n callData: this._calldata.encode(this._name, 'init', params),\n code: this.$options.bytecode,\n ownerId,\n });\n this.$options.address = buildContractIdByContractTx(tx);\n const { hash, ...other } = await this.#sendAndProcess(\n tx,\n 'init',\n { ...opt, onAccount: opt.onAccount },\n );\n return {\n ...other,\n ...other.result?.log != null && {\n decodedEvents: this.$decodeEvents(other.result.log, opt),\n },\n owner: ownerId,\n transaction: hash,\n address: this.$options.address,\n };\n }\n\n /**\n * Get function schema from contract ACI object\n * @param name - Function name\n * @returns function ACI\n */\n #getFunctionAci(name: string): FunctionAci {\n const fn = this.#aciContract.functions.find(\n (f: { name: string }) => f.name === name,\n );\n if (fn != null) {\n return fn;\n }\n if (name === 'init') {\n return {\n arguments: [], name: 'init', payable: false, returns: 'unit', stateful: true,\n };\n }\n throw new NoSuchContractFunctionError(`Function ${name} doesn't exist in contract`);\n }\n\n /**\n * Call contract function\n * @param fn - Function name\n * @param params - Array of function arguments\n * @param options - Array of function arguments\n * @returns CallResult\n */\n async $call<Fn extends MethodNames<M>>(\n fn: Fn,\n params: MethodParameters<M, Fn>,\n options: Partial<BuildTxOptions<Tag.ContractCallTx, 'callerId' | 'contractId' | 'callData'>>\n & Parameters<Contract<M>['$decodeEvents']>[1]\n & Omit<SendTransactionOptions, 'onAccount' | 'onNode'>\n & Omit<Parameters<typeof txDryRun>[2], 'onNode'>\n & { onAccount?: AccountBase; onNode?: Node; callStatic?: boolean } = {},\n ): Promise<SendAndProcessReturnType & Partial<GetCallResultByHashReturnType<M, Fn>>> {\n const { callStatic, top, ...opt } = { ...this.$options, ...options };\n const fnAci = this.#getFunctionAci(fn);\n const contractId = this.$options.address;\n const { onNode } = opt;\n\n if (fn == null) throw new MissingFunctionNameError();\n if (fn === 'init' && callStatic !== true) throw new InvalidMethodInvocationError('\"init\" can be called only via dryRun');\n if (fn !== 'init' && opt.amount != null && opt.amount > 0 && !fnAci.payable) {\n throw new NotPayableFunctionError(opt.amount, fn);\n }\n\n let callerId;\n try {\n if (opt.onAccount == null) throw new InternalError('Use fallback account');\n callerId = opt.onAccount.address;\n } catch (error) {\n const useFallbackAccount = callStatic === true && (\n (error instanceof TypeError && error.message === 'Account should be an address (ak-prefixed string), or instance of AccountBase, got undefined instead')\n || (error instanceof NoWalletConnectedError)\n || (error instanceof InternalError && error.message === 'Use fallback account')\n );\n if (!useFallbackAccount) throw error;\n callerId = DRY_RUN_ACCOUNT.pub;\n }\n const callData = this._calldata.encode(this._name, fn, params);\n\n if (callStatic === true) {\n if (opt.nonce == null && top != null) {\n const topKey = typeof top === 'number' ? 'height' : 'hash';\n opt.nonce = (await getAccount(callerId, { [topKey]: top, onNode })).nonce + 1;\n }\n const txOpt = { ...opt, onNode, callData };\n let tx;\n if (fn === 'init') {\n if (this.$options.bytecode == null) throw new IllegalArgumentError('Can\\'t dry-run \"init\" without bytecode');\n tx = await buildTxAsync({\n ...txOpt, tag: Tag.ContractCreateTx, code: this.$options.bytecode, ownerId: callerId,\n });\n } else {\n if (contractId == null) throw new MissingContractAddressError('Can\\'t dry-run contract without address');\n tx = await buildTxAsync({\n ...txOpt, tag: Tag.ContractCallTx, callerId, contractId,\n });\n }\n\n const { callObj, ...dryRunOther } = await txDryRun(tx, callerId, { ...opt, top });\n if (callObj == null) {\n throw new InternalError(`callObj is not available for transaction ${tx}`);\n }\n const callInfoTyped = callObj as ContractCallObject;\n return {\n ...dryRunOther,\n ...this.#getCallResult(callInfoTyped, fn, tx, opt),\n tx: unpackTx(tx),\n result: callInfoTyped,\n rawTx: tx,\n hash: buildTxHash(tx),\n txData: undefined as any,\n };\n }\n\n if (top != null) throw new IllegalArgumentError('Can\\'t handle `top` option in on-chain contract call');\n if (contractId == null) throw new MissingContractAddressError('Can\\'t call contract without address');\n const tx = await buildTxAsync({\n ...opt,\n tag: Tag.ContractCallTx,\n gasLimit: opt.gasLimit ?? await this._estimateGas(fn, params, opt),\n callerId,\n contractId,\n callData,\n });\n if (opt.onAccount == null) throw new IllegalArgumentError('Can\\'t call contract on chain without account');\n return this.#sendAndProcess(tx, fn, { ...opt, onAccount: opt.onAccount });\n }\n\n /**\n * @param ctAddress - Contract address that emitted event\n * @param nameHash - Hash of emitted event name\n * @param options - Options\n * @returns Contract name\n * @throws {@link MissingEventDefinitionError}\n * @throws {@link AmbiguousEventDefinitionError}\n */\n #getContractNameByEvent(\n ctAddress: Encoded.ContractAddress,\n nameHash: BigInt,\n { contractAddressToName }: GetContractNameByEventOptions,\n ): string {\n const addressToName = { ...this.$options.contractAddressToName, ...contractAddressToName };\n if (addressToName[ctAddress] != null) return addressToName[ctAddress];\n\n // TODO: consider using a third-party library\n const isEqual = (a: any, b: any): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n const contracts = this._aci\n .map(({ contract }) => contract)\n .filter((contract) => contract?.event) as ContractAci[];\n const matchedEvents = contracts\n .map((contract) => [contract.name, contract.event.variant])\n .map(([name, events]) => events.map((event: {}) => (\n [name, Object.keys(event)[0], Object.values(event)[0]]\n )))\n .flat()\n .filter(([, eventName]) => BigInt(`0x${calcHash(eventName).toString('hex')}`) === nameHash)\n .filter(([, , type], idx, arr) => !arr.slice(0, idx).some((el) => isEqual(el[2], type)));\n switch (matchedEvents.length) {\n case 0: throw new MissingEventDefinitionError(nameHash.toString(), ctAddress);\n case 1: return matchedEvents[0][0];\n default: throw new AmbiguousEventDefinitionError(ctAddress, matchedEvents);\n }\n }\n\n /**\n * Decode Events\n * @param events - Array of encoded events (callRes.result.log)\n * @param options - Options\n * @returns DecodedEvents\n */\n $decodeEvents(\n events: Event[],\n { omitUnknown, ...opt }: { omitUnknown?: boolean } & GetContractNameByEventOptions = {},\n ): DecodedEvent[] {\n return events\n .map((event) => {\n const topics = event.topics.map((t: string | number) => BigInt(t));\n let contractName;\n try {\n contractName = this.#getContractNameByEvent(event.address, topics[0], opt);\n } catch (error) {\n if ((omitUnknown ?? false) && error instanceof MissingEventDefinitionError) return null;\n throw error;\n }\n const decoded = this._calldata.decodeEvent(contractName, event.data, topics);\n const [name, args] = Object.entries(decoded)[0];\n return {\n name,\n args,\n contract: {\n name: contractName,\n address: event.address,\n },\n };\n }).filter((e: DecodedEvent | null): e is DecodedEvent => e != null);\n }\n\n static async initialize<M extends ContractMethodsBase>(\n {\n onCompiler,\n onNode,\n bytecode,\n aci,\n address,\n sourceCodePath,\n sourceCode,\n fileSystem,\n validateBytecode,\n ...otherOptions\n }: Omit<ConstructorParameters<typeof Contract>[0], 'aci' | 'address'> & {\n validateBytecode?: boolean;\n aci?: Aci;\n address?: Encoded.ContractAddress | AensName;\n },\n ): Promise<ContractWithMethods<M>> {\n if (aci == null && onCompiler != null) {\n let res;\n if (sourceCodePath != null) res = await onCompiler.compile(sourceCodePath);\n if (sourceCode != null) res = await onCompiler.compileBySourceCode(sourceCode, fileSystem);\n if (res != null) {\n aci = res.aci;\n bytecode ??= res.bytecode;\n }\n }\n if (aci == null) throw new MissingContractDefError();\n\n if (address != null) {\n address = await resolveName(\n address,\n 'contract_pubkey',\n { resolveByNode: true, onNode },\n ) as Encoded.ContractAddress;\n }\n\n if (address == null && sourceCode == null && sourceCodePath == null && bytecode == null) {\n throw new MissingContractAddressError('Can\\'t create instance by ACI without address');\n }\n\n if (address != null) {\n const contract = await getContract(address, { onNode });\n if (contract.active == null) throw new InactiveContractError(address);\n }\n\n if (validateBytecode === true) {\n if (address == null) throw new MissingContractAddressError('Can\\'t validate bytecode without contract address');\n const onChanBytecode = (await getContractByteCode(address, { onNode })).bytecode;\n let isValid = false;\n if (bytecode != null) isValid = bytecode === onChanBytecode;\n else if (sourceCode != null) {\n if (onCompiler == null) throw new IllegalArgumentError('Can\\'t validate bytecode without compiler');\n isValid = await onCompiler.validateBySourceCode(onChanBytecode, sourceCode, fileSystem);\n } else if (sourceCodePath != null) {\n if (onCompiler == null) throw new IllegalArgumentError('Can\\'t validate bytecode without compiler');\n isValid = await onCompiler.validate(onChanBytecode, sourceCodePath);\n }\n if (!isValid) {\n throw new BytecodeMismatchError((sourceCode ?? sourceCodePath) != null ? 'source code' : 'bytecode');\n }\n }\n\n return new ContractWithMethods<M>({\n onCompiler,\n onNode,\n sourceCode,\n sourceCodePath,\n bytecode,\n aci,\n address,\n fileSystem,\n ...otherOptions,\n });\n }\n\n _aci: Aci;\n\n #aciContract: ContractAci;\n\n _name: string;\n\n _calldata: Calldata;\n\n $options: Omit<ConstructorParameters<typeof Contract>[0], 'aci'>;\n\n constructor({ aci, ...otherOptions }: {\n onCompiler?: CompilerBase;\n onNode: Node;\n bytecode?: Encoded.ContractBytearray;\n aci: Aci;\n address?: Encoded.ContractAddress;\n sourceCodePath?: Parameters<CompilerBase['compile']>[0];\n sourceCode?: Parameters<CompilerBase['compileBySourceCode']>[0];\n fileSystem?: Parameters<CompilerBase['compileBySourceCode']>[1];\n } & Parameters<Contract<M>['$deploy']>[1]) {\n this._aci = aci;\n const aciLast = aci[aci.length - 1];\n if (aciLast.contract == null) {\n throw new IllegalArgumentError(`The last 'aci' item should have 'contract' key, got ${Object.keys(aciLast)} keys instead`);\n }\n this.#aciContract = aciLast.contract;\n this._name = this.#aciContract.name;\n this._calldata = new Calldata(aci);\n this.$options = otherOptions;\n\n /**\n * Generate proto function based on contract function using Contract ACI schema\n * All function can be called like:\n * ```js\n * await contract.testFunction()\n * ```\n * then sdk will decide to use dry-run or send tx\n * on-chain base on if function stateful or not.\n * Also, you can manually do that:\n * ```js\n * await contract.testFunction({ callStatic: true }) // use call-static (dry-run)\n * await contract.testFunction({ callStatic: false }) // send tx on-chain\n * ```\n */\n Object.assign(\n this,\n Object.fromEntries(this.#aciContract.functions\n .map(({ name, arguments: aciArgs, stateful }: FunctionAci) => {\n const callStatic = name !== 'init' && !stateful;\n return [\n name,\n async (...args: any) => {\n const options = args.length === aciArgs.length + 1 ? args.pop() : {};\n if (typeof options !== 'object') throw new TypeError(`Options should be an object: ${options}`);\n if (name === 'init') return this.$deploy(args, { callStatic, ...options });\n return this.$call(name, args, { callStatic, ...options });\n },\n ];\n })),\n );\n }\n}\n\ninterface ContractWithMethodsClass {\n new <M extends ContractMethodsBase>(\n options: ConstructorParameters<typeof Contract>[0],\n ): ContractWithMethods<M>;\n initialize: typeof Contract['initialize'];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst ContractWithMethods: ContractWithMethodsClass = Contract as any;\n\nexport default ContractWithMethods;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAAA,sBAAA,MAAoC,0BAA0B;AAAC;EAAAC,OAAA,EAAAC;AAAA,IAAAF,sBAAA;AAAA,SACtDG,eAAe;AAAA,SACfC,GAAG;AAAA,SAEVC,2BAA2B,EAAEC,QAAQ,EAAEC,YAAY,EAAkBC,WAAW;AAAA,SAEzEC,MAAM;AAAA,SAEbC,uBAAuB,EACvBC,2BAA2B,EAC3BC,qBAAqB,EACrBC,qBAAqB,EACrBC,sBAAsB,EACtBC,wBAAwB,EACxBC,4BAA4B,EAC5BC,uBAAuB,EACvBC,SAAS,IAATA,UAAS,EACTC,mBAAmB,EACnBC,oBAAoB,EACpBC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,iBAAiB,EACjBC,aAAa,EACbC,sBAAsB,EACtBC,aAAa;AAAA,SAENC,IAAI,IAAIC,QAAQ;AAAA,SAOvBC,UAAU,EAAEC,WAAW,EAAEC,mBAAmB,EAAEC,WAAW,EAAEC,QAAQ,EAAEC,eAAe;AAAA,IAAAC,cAAA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D,KAAA;IAAA,OAAK3E,MAAM,CAAE,KAAIhG,QAAQ,CAAC4K,SAAS,CAAC,CAACvB,QAAQ,CAAC,KAAK,CAAE,EAAC,CAAC,KAAKM,QAAQ;EAAA,EAAC,CAC1FjD,MAAM,CAAC,CAAAmE,KAAA,EAAaC,GAAG,EAAEC,GAAG;IAAA,IAApB,IAAKC,IAAI,CAAC,GAAAH,KAAA;IAAA,OAAe,CAACE,GAAG,CAACE,KAAK,CAAC,CAAC,EAAEH,GAAG,CAAC,CAACI,IAAI,CAAEC,EAAE,IAAKpB,OAAO,CAACoB,EAAE,CAAC,CAAC,CAAC,EAAEH,IAAI,CAAC,CAAC;EAAA,EAAC;EAC1F,QAAQV,aAAa,CAAC9H,MAAM;IAC1B,KAAK,CAAC;MAAE,MAAM,IAAI/C,2BAA2B,CAACkK,QAAQ,CAACN,QAAQ,EAAE,EAAEK,SAAS,CAAC;IAC7E,KAAK,CAAC;MAAE,OAAOY,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClC;MAAS,MAAM,IAAI5K,6BAA6B,CAACgK,SAAS,EAAEY,aAAa,CAAC;EAAC;AAE/E;AAqLF;AACA,MAAM7C,mBAA6C,GAAG3G,QAAe;AAErE,eAAe2G,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"Contract.mjs","names":["_aeternityAeppCalldata","Encoder","Calldata","DRY_RUN_ACCOUNT","Tag","buildContractIdByContractTx","unpackTx","buildTxAsync","buildTxHash","decode","MissingContractDefError","MissingContractAddressError","InactiveContractError","BytecodeMismatchError","DuplicateContractError","MissingFunctionNameError","InvalidMethodInvocationError","NotPayableFunctionError","TypeError","NodeInvocationError","IllegalArgumentError","NoSuchContractFunctionError","MissingEventDefinitionError","AmbiguousEventDefinitionError","UnexpectedTsError","InternalError","NoWalletConnectedError","ContractError","hash","calcHash","getAccount","getContract","getContractByteCode","resolveName","txDryRun","sendTransaction","_getCallResult","WeakSet","_sendAndProcess","_getFunctionAci","_getContractNameByEvent","_aciContract","WeakMap","Contract","$compile","$options","bytecode","onCompiler","sourceCode","compileBySourceCode","fileSystem","sourceCodePath","compile","$getCallResultByTxHash","fnName","options","callInfo","onNode","getTransactionInfoByHash","callInfoTyped","_classPrivateMethodGet","_getCallResult2","call","undefined","result","_estimateGas","name","params","arguments","length","$call","callStatic","gasUsed","Math","floor","$deploy","_opt$gasLimit","_other$result","opt","address","onAccount","ownerId","tx","tag","ContractCreateTx","gasLimit","callData","_calldata","encode","_name","code","other","_sendAndProcess2","log","decodedEvents","$decodeEvents","owner","transaction","fn","_opt$gasLimit2","top","fnAci","_getFunctionAci2","contractId","amount","payable","callerId","error","useFallbackAccount","message","pub","nonce","topKey","txOpt","ContractCallTx","callObj","dryRunOther","rawTx","txData","events","omitUnknown","map","event","topics","t","BigInt","contractName","_getContractNameByEvent2","decoded","decodeEvent","data","args","Object","entries","contract","filter","e","initialize","_ref","aci","validateBytecode","otherOptions","res","_bytecode","resolveByNode","active","onChanBytecode","isValid","validateBySourceCode","validate","ContractWithMethods","constructor","_ref2","_this","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","writable","value","_aci","aciLast","keys","_classPrivateFieldSet","_classPrivateFieldGet","assign","fromEntries","functions","_ref3","aciArgs","stateful","_len","Array","_key","pop","_ref4","returnType","returnValue","decodedResult","decodeFateString","toString","blockHeight","find","f","returns","ctAddress","nameHash","_ref5","contractAddressToName","addressToName","isEqual","a","b","JSON","stringify","contracts","_ref6","matchedEvents","variant","_ref7","values","flat","_ref8","eventName","_ref9","idx","arr","type","slice","some","el"],"sources":["../../src/contract/Contract.ts"],"sourcesContent":["/**\n * Contract module - routines to interact with the æternity contract\n *\n * High level documentation of the contracts are available at\n * https://github.com/aeternity/protocol/tree/master/contracts and\n */\n\nimport { Encoder as Calldata } from '@aeternity/aepp-calldata';\nimport { DRY_RUN_ACCOUNT } from '../tx/builder/schema';\nimport { Tag, AensName } from '../tx/builder/constants';\nimport {\n buildContractIdByContractTx, unpackTx, buildTxAsync, BuildTxOptions, buildTxHash,\n} from '../tx/builder';\nimport { decode, Encoded } from '../utils/encoder';\nimport {\n MissingContractDefError,\n MissingContractAddressError,\n InactiveContractError,\n BytecodeMismatchError,\n DuplicateContractError,\n MissingFunctionNameError,\n InvalidMethodInvocationError,\n NotPayableFunctionError,\n TypeError,\n NodeInvocationError,\n IllegalArgumentError,\n NoSuchContractFunctionError,\n MissingEventDefinitionError,\n AmbiguousEventDefinitionError,\n UnexpectedTsError,\n InternalError,\n NoWalletConnectedError,\n ContractError,\n} from '../utils/errors';\nimport { hash as calcHash } from '../utils/crypto';\nimport {\n ContractCallObject as NodeContractCallObject, Event as NodeEvent,\n} from '../apis/node';\nimport CompilerBase, { Aci } from './compiler/Base';\nimport Node, { TransformNodeType } from '../Node';\nimport {\n getAccount, getContract, getContractByteCode, resolveName, txDryRun, sendTransaction,\n SendTransactionOptions,\n} from '../chain';\nimport AccountBase from '../account/Base';\nimport { TxUnpacked } from '../tx/builder/schema.generated';\n\ntype ContractAci = NonNullable<Aci[0]['contract']>;\ntype FunctionAci = ContractAci['functions'][0];\n\ninterface Event extends NodeEvent {\n address: Encoded.ContractAddress;\n data: Encoded.ContractBytearray;\n}\n\nexport interface ContractCallObject extends TransformNodeType<NodeContractCallObject> {\n returnValue: Encoded.ContractBytearray;\n log: Event[];\n}\n\ninterface DecodedEvent {\n name: string;\n args: unknown[];\n contract: {\n name: string;\n address: Encoded.ContractAddress;\n };\n}\n\ntype TxData = Awaited<ReturnType<typeof sendTransaction>>;\n\ninterface SendAndProcessReturnType {\n result?: ContractCallObject;\n hash: TxData['hash'];\n tx: TxUnpacked & { tag: Tag.SignedTx | Tag.ContractCallTx | Tag.ContractCreateTx };\n txData: TxData;\n rawTx: Encoded.Transaction;\n}\n\nexport interface ContractMethodsBase { [key: string]: (...args: any[]) => any }\n\ntype MethodsToContractApi<M extends ContractMethodsBase> = {\n [Name in keyof M]:\n M[Name] extends (...args: infer Args) => any\n ? (...args: [\n ...Args,\n ...[] | [Name extends 'init'\n ? Parameters<Contract<M>['$deploy']>[1] : Parameters<Contract<M>['$call']>[2]],\n ]) => ReturnType<Contract<M>['$call']>\n : never\n};\n\ntype ContractWithMethods<M extends ContractMethodsBase> = Contract<M> & MethodsToContractApi<M>;\n\ntype MethodNames<M extends ContractMethodsBase> = keyof M & string | 'init';\n\ntype MethodParameters<M extends ContractMethodsBase, Fn extends MethodNames<M>> =\n Fn extends 'init'\n ? M extends { init: any } ? Parameters<M['init']> : []\n : Parameters<M[Fn]>;\n\ninterface GetContractNameByEventOptions {\n contractAddressToName?: { [key: Encoded.ContractAddress]: string };\n}\n\ninterface GetCallResultByHashReturnType<M extends ContractMethodsBase, Fn extends MethodNames<M>> {\n decodedResult: ReturnType<M[Fn]>;\n decodedEvents?: ReturnType<Contract<M>['$decodeEvents']>;\n}\n\n/**\n * Generate contract ACI object with predefined js methods for contract usage - can be used for\n * creating a reference to already deployed contracts\n * @category contract\n * @param options - Options object\n * @returns JS Contract API\n * @example\n * ```js\n * const contractIns = await aeSdk.initializeContract({ sourceCode })\n * await contractIns.$deploy([321]) or await contractIns.init(321)\n * const callResult = await contractIns.$call('setState', [123])\n * const staticCallResult = await contractIns.$call('setState', [123], { callStatic: true })\n * ```\n * Also you can call contract like: `await contractIns.setState(123, options)`\n * Then sdk decide to make on-chain or static call(dry-run API) transaction based on function is\n * stateful or not\n */\nclass Contract<M extends ContractMethodsBase> {\n /**\n * Compile contract\n * @returns bytecode\n */\n async $compile(): Promise<Encoded.ContractBytearray> {\n if (this.$options.bytecode != null) return this.$options.bytecode;\n if (this.$options.onCompiler == null) throw new IllegalArgumentError('Can\\'t compile without compiler');\n if (this.$options.sourceCode != null) {\n const { bytecode } = await this.$options.onCompiler\n .compileBySourceCode(this.$options.sourceCode, this.$options.fileSystem);\n this.$options.bytecode = bytecode;\n }\n if (this.$options.sourceCodePath != null) {\n const { bytecode } = await this.$options.onCompiler.compile(this.$options.sourceCodePath);\n this.$options.bytecode = bytecode;\n }\n if (this.$options.bytecode == null) {\n throw new IllegalArgumentError('Can\\'t compile without sourceCode and sourceCodePath');\n }\n return this.$options.bytecode;\n }\n\n #getCallResult<Fn extends MethodNames<M>>(\n { returnType, returnValue, log }: ContractCallObject,\n fnName: Fn,\n transaction: Encoded.Transaction | undefined,\n options: Parameters<Contract<M>['$decodeEvents']>[1],\n ): GetCallResultByHashReturnType<M, Fn> {\n let message: string;\n switch (returnType) {\n case 'ok': {\n const fnAci = this.#getFunctionAci(fnName);\n return {\n decodedResult: this._calldata.decode(this._name, fnAci.name, returnValue),\n decodedEvents: this.$decodeEvents(log, options),\n };\n }\n case 'revert':\n message = this._calldata.decodeFateString(returnValue);\n break;\n case 'error':\n message = decode(returnValue).toString();\n break;\n default:\n throw new InternalError(`Unknown return type: ${returnType}`);\n }\n throw new NodeInvocationError(message, transaction);\n }\n\n async #sendAndProcess<Fn extends MethodNames<M>>(\n tx: Encoded.Transaction,\n fnName: Fn,\n options: SendTransactionOptions & Parameters<Contract<M>['$getCallResultByTxHash']>[2],\n ): Promise<SendAndProcessReturnType & Partial<GetCallResultByHashReturnType<M, Fn>>> {\n const txData = await sendTransaction(tx, { ...this.$options, ...options });\n return {\n hash: txData.hash,\n tx: unpackTx<Tag.ContractCallTx | Tag.ContractCreateTx>(txData.rawTx),\n txData,\n rawTx: txData.rawTx,\n ...txData.blockHeight != null && (\n await this.$getCallResultByTxHash(txData.hash, fnName, options)\n ),\n };\n }\n\n async $getCallResultByTxHash<Fn extends MethodNames<M>>(\n hash: Encoded.TxHash,\n fnName: Fn,\n options?: Parameters<Contract<M>['$decodeEvents']>[1],\n ): Promise<GetCallResultByHashReturnType<M, Fn> & { result: ContractCallObject }> {\n const { callInfo } = await this.$options.onNode.getTransactionInfoByHash(hash);\n if (callInfo == null) {\n throw new ContractError(`callInfo is not available for transaction ${hash}`);\n }\n const callInfoTyped = callInfo as ContractCallObject;\n return {\n ...this.#getCallResult(callInfoTyped, fnName, undefined, options),\n result: callInfoTyped,\n };\n }\n\n async _estimateGas<Fn extends MethodNames<M>>(\n name: Fn,\n params: MethodParameters<M, Fn>,\n options: Omit<Parameters<Contract<M>['$call']>[2], 'callStatic'> = {},\n ): Promise<number> {\n const { result } = await this.$call(name, params, { ...options, callStatic: true });\n if (result == null) throw new UnexpectedTsError();\n const { gasUsed } = result;\n // taken from https://github.com/aeternity/aepp-sdk-js/issues/1286#issuecomment-977814771\n return Math.floor(gasUsed * 1.25);\n }\n\n /**\n * Deploy contract\n * @param params - Contract init function arguments array\n * @param options - Options\n * @returns deploy info\n */\n async $deploy(\n params: MethodParameters<M, 'init'>,\n options?: Parameters<Contract<M>['$call']>[2]\n & Partial<BuildTxOptions<Tag.ContractCreateTx, 'ownerId' | 'code' | 'callData'>>,\n ): Promise<Omit<SendAndProcessReturnType, 'hash'> & {\n transaction?: Encoded.TxHash;\n owner?: Encoded.AccountAddress;\n address?: Encoded.ContractAddress;\n decodedEvents?: ReturnType<Contract<M>['$decodeEvents']>;\n }> {\n const { callStatic, ...opt } = { ...this.$options, ...options };\n if (this.$options.bytecode == null) await this.$compile();\n if (callStatic === true) return this.$call('init', params, { ...opt, callStatic });\n if (this.$options.address != null) throw new DuplicateContractError();\n\n if (opt.onAccount == null) throw new IllegalArgumentError('Can\\'t deploy without account');\n const ownerId = opt.onAccount.address;\n if (this.$options.bytecode == null) throw new IllegalArgumentError('Can\\'t deploy without bytecode');\n const tx = await buildTxAsync({\n ...opt,\n tag: Tag.ContractCreateTx,\n gasLimit: opt.gasLimit ?? await this._estimateGas('init', params, opt),\n callData: this._calldata.encode(this._name, 'init', params),\n code: this.$options.bytecode,\n ownerId,\n });\n this.$options.address = buildContractIdByContractTx(tx);\n const { hash, ...other } = await this.#sendAndProcess(\n tx,\n 'init',\n { ...opt, onAccount: opt.onAccount },\n );\n return {\n ...other,\n ...other.result?.log != null && {\n decodedEvents: this.$decodeEvents(other.result.log, opt),\n },\n owner: ownerId,\n transaction: hash,\n address: this.$options.address,\n };\n }\n\n /**\n * Get function schema from contract ACI object\n * @param name - Function name\n * @returns function ACI\n */\n #getFunctionAci(name: string): FunctionAci {\n const fn = this.#aciContract.functions.find(\n (f: { name: string }) => f.name === name,\n );\n if (fn != null) {\n return fn;\n }\n if (name === 'init') {\n return {\n arguments: [], name: 'init', payable: false, returns: 'unit', stateful: true,\n };\n }\n throw new NoSuchContractFunctionError(`Function ${name} doesn't exist in contract`);\n }\n\n /**\n * Call contract function\n * @param fn - Function name\n * @param params - Array of function arguments\n * @param options - Array of function arguments\n * @returns CallResult\n */\n async $call<Fn extends MethodNames<M>>(\n fn: Fn,\n params: MethodParameters<M, Fn>,\n options: Partial<BuildTxOptions<Tag.ContractCallTx, 'callerId' | 'contractId' | 'callData'>>\n & Parameters<Contract<M>['$decodeEvents']>[1]\n & Omit<SendTransactionOptions, 'onAccount' | 'onNode'>\n & Omit<Parameters<typeof txDryRun>[2], 'onNode'>\n & { onAccount?: AccountBase; onNode?: Node; callStatic?: boolean } = {},\n ): Promise<SendAndProcessReturnType & Partial<GetCallResultByHashReturnType<M, Fn>>> {\n const { callStatic, top, ...opt } = { ...this.$options, ...options };\n const fnAci = this.#getFunctionAci(fn);\n const contractId = this.$options.address;\n const { onNode } = opt;\n\n if (fn == null) throw new MissingFunctionNameError();\n if (fn === 'init' && callStatic !== true) throw new InvalidMethodInvocationError('\"init\" can be called only via dryRun');\n if (fn !== 'init' && opt.amount != null && +opt.amount > 0 && !fnAci.payable) {\n throw new NotPayableFunctionError(opt.amount, fn);\n }\n\n let callerId;\n try {\n if (opt.onAccount == null) throw new InternalError('Use fallback account');\n callerId = opt.onAccount.address;\n } catch (error) {\n const useFallbackAccount = callStatic === true && (\n (error instanceof TypeError && error.message === 'Account should be an address (ak-prefixed string), or instance of AccountBase, got undefined instead')\n || (error instanceof NoWalletConnectedError)\n || (error instanceof InternalError && error.message === 'Use fallback account')\n );\n if (!useFallbackAccount) throw error;\n callerId = DRY_RUN_ACCOUNT.pub;\n }\n const callData = this._calldata.encode(this._name, fn, params);\n\n if (callStatic === true) {\n if (opt.nonce == null && top != null) {\n const topKey = typeof top === 'number' ? 'height' : 'hash';\n opt.nonce = (await getAccount(callerId, { [topKey]: top, onNode })).nonce + 1;\n }\n const txOpt = { ...opt, onNode, callData };\n let tx;\n if (fn === 'init') {\n if (this.$options.bytecode == null) throw new IllegalArgumentError('Can\\'t dry-run \"init\" without bytecode');\n tx = await buildTxAsync({\n ...txOpt, tag: Tag.ContractCreateTx, code: this.$options.bytecode, ownerId: callerId,\n });\n } else {\n if (contractId == null) throw new MissingContractAddressError('Can\\'t dry-run contract without address');\n tx = await buildTxAsync({\n ...txOpt, tag: Tag.ContractCallTx, callerId, contractId,\n });\n }\n\n const { callObj, ...dryRunOther } = await txDryRun(tx, callerId, { ...opt, top });\n if (callObj == null) {\n throw new InternalError(`callObj is not available for transaction ${tx}`);\n }\n const callInfoTyped = callObj as ContractCallObject;\n return {\n ...dryRunOther,\n ...this.#getCallResult(callInfoTyped, fn, tx, opt),\n tx: unpackTx(tx),\n result: callInfoTyped,\n rawTx: tx,\n hash: buildTxHash(tx),\n txData: undefined as any,\n };\n }\n\n if (top != null) throw new IllegalArgumentError('Can\\'t handle `top` option in on-chain contract call');\n if (contractId == null) throw new MissingContractAddressError('Can\\'t call contract without address');\n const tx = await buildTxAsync({\n ...opt,\n tag: Tag.ContractCallTx,\n gasLimit: opt.gasLimit ?? await this._estimateGas(fn, params, opt),\n callerId,\n contractId,\n callData,\n });\n if (opt.onAccount == null) throw new IllegalArgumentError('Can\\'t call contract on chain without account');\n return this.#sendAndProcess(tx, fn, { ...opt, onAccount: opt.onAccount });\n }\n\n /**\n * @param ctAddress - Contract address that emitted event\n * @param nameHash - Hash of emitted event name\n * @param options - Options\n * @returns Contract name\n * @throws {@link MissingEventDefinitionError}\n * @throws {@link AmbiguousEventDefinitionError}\n */\n #getContractNameByEvent(\n ctAddress: Encoded.ContractAddress,\n nameHash: BigInt,\n { contractAddressToName }: GetContractNameByEventOptions,\n ): string {\n const addressToName = { ...this.$options.contractAddressToName, ...contractAddressToName };\n if (addressToName[ctAddress] != null) return addressToName[ctAddress];\n\n // TODO: consider using a third-party library\n const isEqual = (a: any, b: any): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n const contracts = this._aci\n .map(({ contract }) => contract)\n .filter((contract) => contract?.event) as ContractAci[];\n const matchedEvents = contracts\n .map((contract) => [contract.name, contract.event.variant])\n .map(([name, events]) => events.map((event: {}) => (\n [name, Object.keys(event)[0], Object.values(event)[0]]\n )))\n .flat()\n .filter(([, eventName]) => BigInt(`0x${calcHash(eventName).toString('hex')}`) === nameHash)\n .filter(([, , type], idx, arr) => !arr.slice(0, idx).some((el) => isEqual(el[2], type)));\n switch (matchedEvents.length) {\n case 0: throw new MissingEventDefinitionError(nameHash.toString(), ctAddress);\n case 1: return matchedEvents[0][0];\n default: throw new AmbiguousEventDefinitionError(ctAddress, matchedEvents);\n }\n }\n\n /**\n * Decode Events\n * @param events - Array of encoded events (callRes.result.log)\n * @param options - Options\n * @returns DecodedEvents\n */\n $decodeEvents(\n events: Event[],\n { omitUnknown, ...opt }: { omitUnknown?: boolean } & GetContractNameByEventOptions = {},\n ): DecodedEvent[] {\n return events\n .map((event) => {\n const topics = event.topics.map((t: string | number) => BigInt(t));\n let contractName;\n try {\n contractName = this.#getContractNameByEvent(event.address, topics[0], opt);\n } catch (error) {\n if ((omitUnknown ?? false) && error instanceof MissingEventDefinitionError) return null;\n throw error;\n }\n const decoded = this._calldata.decodeEvent(contractName, event.data, topics);\n const [name, args] = Object.entries(decoded)[0];\n return {\n name,\n args,\n contract: {\n name: contractName,\n address: event.address,\n },\n };\n }).filter((e: DecodedEvent | null): e is DecodedEvent => e != null);\n }\n\n static async initialize<M extends ContractMethodsBase>(\n {\n onCompiler,\n onNode,\n bytecode,\n aci,\n address,\n sourceCodePath,\n sourceCode,\n fileSystem,\n validateBytecode,\n ...otherOptions\n }: Omit<ConstructorParameters<typeof Contract>[0], 'aci' | 'address'> & {\n validateBytecode?: boolean;\n aci?: Aci;\n address?: Encoded.ContractAddress | AensName;\n },\n ): Promise<ContractWithMethods<M>> {\n if (aci == null && onCompiler != null) {\n let res;\n if (sourceCodePath != null) res = await onCompiler.compile(sourceCodePath);\n if (sourceCode != null) res = await onCompiler.compileBySourceCode(sourceCode, fileSystem);\n if (res != null) {\n aci = res.aci;\n bytecode ??= res.bytecode;\n }\n }\n if (aci == null) throw new MissingContractDefError();\n\n if (address != null) {\n address = await resolveName(\n address,\n 'contract_pubkey',\n { resolveByNode: true, onNode },\n ) as Encoded.ContractAddress;\n }\n\n if (address == null && sourceCode == null && sourceCodePath == null && bytecode == null) {\n throw new MissingContractAddressError('Can\\'t create instance by ACI without address');\n }\n\n if (address != null) {\n const contract = await getContract(address, { onNode });\n if (contract.active == null) throw new InactiveContractError(address);\n }\n\n if (validateBytecode === true) {\n if (address == null) throw new MissingContractAddressError('Can\\'t validate bytecode without contract address');\n const onChanBytecode = (await getContractByteCode(address, { onNode })).bytecode;\n let isValid = false;\n if (bytecode != null) isValid = bytecode === onChanBytecode;\n else if (sourceCode != null) {\n if (onCompiler == null) throw new IllegalArgumentError('Can\\'t validate bytecode without compiler');\n isValid = await onCompiler.validateBySourceCode(onChanBytecode, sourceCode, fileSystem);\n } else if (sourceCodePath != null) {\n if (onCompiler == null) throw new IllegalArgumentError('Can\\'t validate bytecode without compiler');\n isValid = await onCompiler.validate(onChanBytecode, sourceCodePath);\n }\n if (!isValid) {\n throw new BytecodeMismatchError((sourceCode ?? sourceCodePath) != null ? 'source code' : 'bytecode');\n }\n }\n\n return new ContractWithMethods<M>({\n onCompiler,\n onNode,\n sourceCode,\n sourceCodePath,\n bytecode,\n aci,\n address,\n fileSystem,\n ...otherOptions,\n });\n }\n\n _aci: Aci;\n\n #aciContract: ContractAci;\n\n _name: string;\n\n _calldata: Calldata;\n\n $options: Omit<ConstructorParameters<typeof Contract>[0], 'aci'>;\n\n constructor({ aci, ...otherOptions }: {\n onCompiler?: CompilerBase;\n onNode: Node;\n bytecode?: Encoded.ContractBytearray;\n aci: Aci;\n address?: Encoded.ContractAddress;\n sourceCodePath?: Parameters<CompilerBase['compile']>[0];\n sourceCode?: Parameters<CompilerBase['compileBySourceCode']>[0];\n fileSystem?: Parameters<CompilerBase['compileBySourceCode']>[1];\n } & Parameters<Contract<M>['$deploy']>[1]) {\n this._aci = aci;\n const aciLast = aci[aci.length - 1];\n if (aciLast.contract == null) {\n throw new IllegalArgumentError(`The last 'aci' item should have 'contract' key, got ${Object.keys(aciLast)} keys instead`);\n }\n this.#aciContract = aciLast.contract;\n this._name = this.#aciContract.name;\n this._calldata = new Calldata(aci);\n this.$options = otherOptions;\n\n /**\n * Generate proto function based on contract function using Contract ACI schema\n * All function can be called like:\n * ```js\n * await contract.testFunction()\n * ```\n * then sdk will decide to use dry-run or send tx\n * on-chain base on if function stateful or not.\n * Also, you can manually do that:\n * ```js\n * await contract.testFunction({ callStatic: true }) // use call-static (dry-run)\n * await contract.testFunction({ callStatic: false }) // send tx on-chain\n * ```\n */\n Object.assign(\n this,\n Object.fromEntries(this.#aciContract.functions\n .map(({ name, arguments: aciArgs, stateful }: FunctionAci) => {\n const callStatic = name !== 'init' && !stateful;\n return [\n name,\n async (...args: any) => {\n const options = args.length === aciArgs.length + 1 ? args.pop() : {};\n if (typeof options !== 'object') throw new TypeError(`Options should be an object: ${options}`);\n if (name === 'init') return this.$deploy(args, { callStatic, ...options });\n return this.$call(name, args, { callStatic, ...options });\n },\n ];\n })),\n );\n }\n}\n\ninterface ContractWithMethodsClass {\n new <M extends ContractMethodsBase>(\n options: ConstructorParameters<typeof Contract>[0],\n ): ContractWithMethods<M>;\n initialize: typeof Contract['initialize'];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst ContractWithMethods: ContractWithMethodsClass = Contract as any;\n\nexport default ContractWithMethods;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAAA,sBAAA,MAAoC,0BAA0B;AAAC;EAA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AAC;MAAE,OAAOY,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClC;MAAS,MAAM,IAAI5K,6BAA6B,CAACgK,SAAS,EAAEY,aAAa,CAAC;EAC5E;AACF;AAqLF;AACA,MAAM7C,mBAA6C,GAAG3G,QAAe;AAErE,eAAe2G,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Cli.mjs","names":["_child_process","execFile","_os","tmpdir","_path","resolve","dirname","basename","_fsPromises","mkdir","writeFile","rm","_url","fileURLToPath","CompilerBase","CompilerError","InternalError","UnsupportedVersionError","semverSatisfies","ensureError","getPackagePath","path","import","meta","url","_path2","WeakMap","_ensureCompatibleVersion","_run","WeakSet","CompilerCli","constructor","compilerPath","arguments","length","undefined","ignoreVersion","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","writable","value","Promise","_classPrivateFieldSet","version","then","versions","compile","_classPrivateFieldGet","bytecode","aci","all","_classPrivateMethodGet","_run2","call","res","JSON","parse","trimEnd","error","message","compileBySourceCode","sourceCode","fileSystem","tmp","_classStaticPrivateMethodGet","_saveContractToTmpDir","recursive","generateAci","generateAciBySourceCode","validate","includes","validateBySourceCode","_verMessage$match","verMessage","ver","match","_len","parameters","Array","_key","pResolve","pReject","stdout","stderr","randomName","Math","random","toString","slice","sourceCodePath","Object","entries","map","_ref","name","src","p"],"sources":["../../../src/contract/compiler/Cli.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { tmpdir } from 'os';\nimport { resolve, dirname, basename } from 'path';\nimport { mkdir, writeFile, rm } from 'fs/promises';\nimport { fileURLToPath } from 'url';\nimport CompilerBase, { Aci } from './Base';\nimport { Encoded } from '../../utils/encoder';\nimport { CompilerError, InternalError, UnsupportedVersionError } from '../../utils/errors';\nimport semverSatisfies from '../../utils/semver-satisfies';\nimport { ensureError } from '../../utils/other';\n\nconst getPackagePath = (): string => {\n const path = dirname(fileURLToPath(import.meta.url));\n if (basename(path) === 'dist') return resolve(path, '..');\n if (basename(path) === 'compiler') return resolve(path, '../../..');\n throw new InternalError('Can\\'t get package path');\n};\n\n/**\n * A wrapper around aesophia_cli, available only in Node.js\n * Assumes that `escript` is available in PATH.\n */\nexport default class CompilerCli extends CompilerBase {\n #path: string;\n\n #ensureCompatibleVersion = Promise.resolve();\n\n constructor(\n compilerPath = resolve(getPackagePath(), './bin/aesophia_cli'),\n { ignoreVersion }: { ignoreVersion?: boolean } = {},\n ) {\n super();\n this.#path = compilerPath;\n if (ignoreVersion !== true) {\n this.#ensureCompatibleVersion = this.version().then((version) => {\n const versions = [version, '7.2.1', '8.0.0'] as const;\n if (!semverSatisfies(...versions)) throw new UnsupportedVersionError('compiler', ...versions);\n });\n }\n }\n\n async #run(...parameters: string[]): Promise<string> {\n return new Promise((pResolve, pReject) => {\n execFile('escript', [this.#path, ...parameters], (error, stdout, stderr) => {\n if (error != null) pReject(error);\n else if (stderr !== '') pReject(new CompilerError(stderr));\n else pResolve(stdout);\n });\n });\n }\n\n static async #saveContractToTmpDir(\n sourceCode: string,\n fileSystem: Record<string, string> = {},\n ): Promise<string> {\n const randomName = (): string => Math.random().toString(36).slice(2);\n const path = resolve(tmpdir(), `aepp-sdk-js-${randomName()}`);\n await mkdir(path);\n const sourceCodePath = resolve(path, `${randomName()}.aes`);\n await writeFile(sourceCodePath, sourceCode);\n await Promise.all(Object.entries(fileSystem)\n .map(async ([name, src]) => {\n const p = resolve(path, name);\n await mkdir(dirname(p), { recursive: true });\n return writeFile(p, src);\n }));\n return sourceCodePath;\n }\n\n async compile(path: string): Promise<{\n bytecode: Encoded.ContractBytearray;\n aci: Aci;\n }> {\n await this.#ensureCompatibleVersion;\n try {\n const [bytecode, aci] = await Promise.all([\n this.#run(path),\n this.#run('--create_json_aci', path).then((res) => JSON.parse(res)),\n ]);\n return {\n bytecode: bytecode.trimEnd() as Encoded.ContractBytearray,\n aci,\n };\n } catch (error) {\n ensureError(error);\n throw new CompilerError(error.message);\n }\n }\n\n async compileBySourceCode(sourceCode: string, fileSystem?: Record<string, string>): Promise<{\n bytecode: Encoded.ContractBytearray;\n aci: Aci;\n }> {\n const tmp = await CompilerCli.#saveContractToTmpDir(sourceCode, fileSystem);\n try {\n return await this.compile(tmp);\n } finally {\n await rm(dirname(tmp), { recursive: true });\n }\n }\n\n async generateAci(path: string): Promise<Aci> {\n await this.#ensureCompatibleVersion;\n try {\n return JSON.parse(await this.#run('--no_code', '--create_json_aci', path));\n } catch (error) {\n ensureError(error);\n throw new CompilerError(error.message);\n }\n }\n\n async generateAciBySourceCode(\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<Aci> {\n const tmp = await CompilerCli.#saveContractToTmpDir(sourceCode, fileSystem);\n try {\n return await this.generateAci(tmp);\n } finally {\n await rm(dirname(tmp), { recursive: true });\n }\n }\n\n async validate(bytecode: Encoded.ContractBytearray, path: string): Promise<boolean> {\n await this.#ensureCompatibleVersion;\n try {\n return (await this.#run(path, '--validate', bytecode)).includes('Validation successful.');\n } catch (error) {\n return false;\n }\n }\n\n async validateBySourceCode(\n bytecode: Encoded.ContractBytearray,\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<boolean> {\n const tmp = await CompilerCli.#saveContractToTmpDir(sourceCode, fileSystem);\n try {\n return await this.validate(bytecode, tmp);\n } finally {\n await rm(dirname(tmp), { recursive: true });\n }\n }\n\n async version(): Promise<string> {\n const verMessage = await this.#run('--version');\n const ver = verMessage.match(/Sophia compiler version ([\\d.]+)\\n/)?.[1];\n if (ver == null) throw new CompilerError('Can\\'t get compiler version');\n return ver;\n }\n}\n"],"mappings":";;;;;;;;AAAA,OAAAA,cAAA,MAAyB,eAAe;AAAC;EAAAC;AAAA,IAAAD,cAAA;AACzC,OAAAE,GAAA,MAAuB,IAAI;AAAC;EAAAC;AAAA,IAAAD,GAAA;AAC5B,OAAAE,KAAA,MAA2C,MAAM;AAAC;EAAAC,OAAA;EAAAC,OAAA;EAAAC;AAAA,IAAAH,KAAA;AAClD,OAAAI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AAC,CACzC8B,GAAG,CAAC,MAAAC,IAAA,IAAuB;IAAA,IAAhB,CAACC,IAAI,EAAEC,GAAG,CAAC,GAAAF,IAAA;IACrB,MAAMG,CAAC,GAAG3F,OAAO,CAACgB,IAAI,EAAEyE,IAAI,CAAC;IAC7B,MAAMrF,KAAK,CAACH,OAAO,CAAC0F,CAAC,CAAC,EAAE;MAAE9B,SAAS,EAAE;IAAK,CAAC,CAAC;IAC5C,OAAOxD,SAAS,CAACsF,CAAC,EAAED,GAAG,CAAC;EAC1B,CAAC,CAAC,CAAC;EACL,OAAON,cAAc;AACvB"}
|
|
1
|
+
{"version":3,"file":"Cli.mjs","names":["_child_process","execFile","_os","tmpdir","_path","resolve","dirname","basename","_fsPromises","mkdir","writeFile","rm","_url","fileURLToPath","CompilerBase","CompilerError","InternalError","UnsupportedVersionError","semverSatisfies","ensureError","getPackagePath","path","import","meta","url","_path2","WeakMap","_ensureCompatibleVersion","_run","WeakSet","CompilerCli","constructor","compilerPath","arguments","length","undefined","ignoreVersion","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","writable","value","Promise","_classPrivateFieldSet","version","then","versions","compile","_classPrivateFieldGet","bytecode","aci","all","_classPrivateMethodGet","_run2","call","res","JSON","parse","trimEnd","error","message","compileBySourceCode","sourceCode","fileSystem","tmp","_classStaticPrivateMethodGet","_saveContractToTmpDir","recursive","generateAci","generateAciBySourceCode","validate","includes","validateBySourceCode","_verMessage$match","verMessage","ver","match","_len","parameters","Array","_key","pResolve","pReject","stdout","stderr","randomName","Math","random","toString","slice","sourceCodePath","Object","entries","map","_ref","name","src","p"],"sources":["../../../src/contract/compiler/Cli.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { tmpdir } from 'os';\nimport { resolve, dirname, basename } from 'path';\nimport { mkdir, writeFile, rm } from 'fs/promises';\nimport { fileURLToPath } from 'url';\nimport CompilerBase, { Aci } from './Base';\nimport { Encoded } from '../../utils/encoder';\nimport { CompilerError, InternalError, UnsupportedVersionError } from '../../utils/errors';\nimport semverSatisfies from '../../utils/semver-satisfies';\nimport { ensureError } from '../../utils/other';\n\nconst getPackagePath = (): string => {\n const path = dirname(fileURLToPath(import.meta.url));\n if (basename(path) === 'dist') return resolve(path, '..');\n if (basename(path) === 'compiler') return resolve(path, '../../..');\n throw new InternalError('Can\\'t get package path');\n};\n\n/**\n * A wrapper around aesophia_cli, available only in Node.js\n * Assumes that `escript` is available in PATH.\n */\nexport default class CompilerCli extends CompilerBase {\n #path: string;\n\n #ensureCompatibleVersion = Promise.resolve();\n\n constructor(\n compilerPath = resolve(getPackagePath(), './bin/aesophia_cli'),\n { ignoreVersion }: { ignoreVersion?: boolean } = {},\n ) {\n super();\n this.#path = compilerPath;\n if (ignoreVersion !== true) {\n this.#ensureCompatibleVersion = this.version().then((version) => {\n const versions = [version, '7.2.1', '8.0.0'] as const;\n if (!semverSatisfies(...versions)) throw new UnsupportedVersionError('compiler', ...versions);\n });\n }\n }\n\n async #run(...parameters: string[]): Promise<string> {\n return new Promise((pResolve, pReject) => {\n execFile('escript', [this.#path, ...parameters], (error, stdout, stderr) => {\n if (error != null) pReject(error);\n else if (stderr !== '') pReject(new CompilerError(stderr));\n else pResolve(stdout);\n });\n });\n }\n\n static async #saveContractToTmpDir(\n sourceCode: string,\n fileSystem: Record<string, string> = {},\n ): Promise<string> {\n const randomName = (): string => Math.random().toString(36).slice(2);\n const path = resolve(tmpdir(), `aepp-sdk-js-${randomName()}`);\n await mkdir(path);\n const sourceCodePath = resolve(path, `${randomName()}.aes`);\n await writeFile(sourceCodePath, sourceCode);\n await Promise.all(Object.entries(fileSystem)\n .map(async ([name, src]) => {\n const p = resolve(path, name);\n await mkdir(dirname(p), { recursive: true });\n return writeFile(p, src);\n }));\n return sourceCodePath;\n }\n\n async compile(path: string): Promise<{\n bytecode: Encoded.ContractBytearray;\n aci: Aci;\n }> {\n await this.#ensureCompatibleVersion;\n try {\n const [bytecode, aci] = await Promise.all([\n this.#run(path),\n this.#run('--create_json_aci', path).then((res) => JSON.parse(res)),\n ]);\n return {\n bytecode: bytecode.trimEnd() as Encoded.ContractBytearray,\n aci,\n };\n } catch (error) {\n ensureError(error);\n throw new CompilerError(error.message);\n }\n }\n\n async compileBySourceCode(sourceCode: string, fileSystem?: Record<string, string>): Promise<{\n bytecode: Encoded.ContractBytearray;\n aci: Aci;\n }> {\n const tmp = await CompilerCli.#saveContractToTmpDir(sourceCode, fileSystem);\n try {\n return await this.compile(tmp);\n } finally {\n await rm(dirname(tmp), { recursive: true });\n }\n }\n\n async generateAci(path: string): Promise<Aci> {\n await this.#ensureCompatibleVersion;\n try {\n return JSON.parse(await this.#run('--no_code', '--create_json_aci', path));\n } catch (error) {\n ensureError(error);\n throw new CompilerError(error.message);\n }\n }\n\n async generateAciBySourceCode(\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<Aci> {\n const tmp = await CompilerCli.#saveContractToTmpDir(sourceCode, fileSystem);\n try {\n return await this.generateAci(tmp);\n } finally {\n await rm(dirname(tmp), { recursive: true });\n }\n }\n\n async validate(bytecode: Encoded.ContractBytearray, path: string): Promise<boolean> {\n await this.#ensureCompatibleVersion;\n try {\n return (await this.#run(path, '--validate', bytecode)).includes('Validation successful.');\n } catch (error) {\n return false;\n }\n }\n\n async validateBySourceCode(\n bytecode: Encoded.ContractBytearray,\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<boolean> {\n const tmp = await CompilerCli.#saveContractToTmpDir(sourceCode, fileSystem);\n try {\n return await this.validate(bytecode, tmp);\n } finally {\n await rm(dirname(tmp), { recursive: true });\n }\n }\n\n async version(): Promise<string> {\n const verMessage = await this.#run('--version');\n const ver = verMessage.match(/Sophia compiler version ([\\d.]+)\\n/)?.[1];\n if (ver == null) throw new CompilerError('Can\\'t get compiler version');\n return ver;\n }\n}\n"],"mappings":";;;;;;;;AAAA,OAAAA,cAAA,MAAyB,eAAe;AAAC;EAAAC;AAAA,IAAAD,cAAA;AACzC,OAAAE,GAAA,MAAuB,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F,OAAO,CAACgB,IAAI,EAAG,GAAE+D,UAAU,CAAC,CAAE,MAAK,CAAC;EAC3D,MAAM1E,SAAS,CAAC+E,cAAc,EAAE5B,UAAU,CAAC;EAC3C,MAAMpB,OAAO,CAACS,GAAG,CAACwC,MAAM,CAACC,OAAO,CAAC7B,UAAU,CAAC,CACzC8B,GAAG,CAAC,MAAAC,IAAA,IAAuB;IAAA,IAAhB,CAACC,IAAI,EAAEC,GAAG,CAAC,GAAAF,IAAA;IACrB,MAAMG,CAAC,GAAG3F,OAAO,CAACgB,IAAI,EAAEyE,IAAI,CAAC;IAC7B,MAAMrF,KAAK,CAACH,OAAO,CAAC0F,CAAC,CAAC,EAAE;MAAE9B,SAAS,EAAE;IAAK,CAAC,CAAC;IAC5C,OAAOxD,SAAS,CAACsF,CAAC,EAAED,GAAG,CAAC;EAC1B,CAAC,CAAC,CAAC;EACL,OAAON,cAAc;AACvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Http.mjs","names":["RestError","Compiler","CompilerApi","genErrorFormatterPolicy","genVersionCheckPolicy","CompilerBase","CompilerError","NotImplementedError","CompilerHttp","constructor","compilerUrl","ignoreVersion","arguments","length","undefined","api","allowInsecureConnection","additionalPolicies","body","message","reason","parameter","info","JSON","stringify","Array","isArray","map","e","type","pos","line","col","context","join","versionPromise","apiVersion","then","_ref","error","pipeline","addPolicy","compileBySourceCode","sourceCode","fileSystem","res","compileContract","code","options","statusCode","compile","path","generateAciBySourceCode","generateACI","generateAci","validateBySourceCode","bytecode","validateByteCode","source","validate","version"],"sources":["../../../src/contract/compiler/Http.ts"],"sourcesContent":["import { RestError } from '@azure/core-rest-pipeline';\nimport {\n Compiler as CompilerApi,\n ErrorModel,\n CompilerError as CompilerErrorApi,\n} from '../../apis/compiler';\nimport { genErrorFormatterPolicy, genVersionCheckPolicy } from '../../utils/autorest';\nimport CompilerBase, { Aci } from './Base';\nimport { Encoded } from '../../utils/encoder';\nimport { CompilerError, NotImplementedError } from '../../utils/errors';\n\ntype GeneralCompilerError = ErrorModel & {\n info?: object;\n parameter?: string;\n};\n\n/**\n * Contract Compiler over HTTP\n *\n * This class include api call's related to contract compiler functionality.\n * @category contract\n * @example CompilerHttp('COMPILER_URL')\n */\nexport default class CompilerHttp extends CompilerBase {\n readonly api: CompilerApi;\n\n /**\n * @param compilerUrl - Url for compiler API\n * @param options - Options\n * @param options.ignoreVersion - Don't check compiler version\n */\n constructor(compilerUrl: string, { ignoreVersion }: { ignoreVersion?: boolean } = {}) {\n super();\n this.api = new CompilerApi(compilerUrl, {\n allowInsecureConnection: true,\n additionalPolicies: [\n genErrorFormatterPolicy((body: GeneralCompilerError | CompilerErrorApi[]) => {\n let message = '';\n if ('reason' in body) {\n message += ` ${body.reason\n }${body.parameter != null ? ` in ${body.parameter}` : ''\n // TODO: revising after improving documentation https://github.com/aeternity/aesophia_http/issues/78\n }${body.info != null ? ` (${JSON.stringify(body.info)})` : ''}`;\n }\n if (Array.isArray(body)) {\n message += `\\n${body\n .map((e) => `${e.type}:${e.pos.line}:${e.pos.col}: ${e.message}${e.context != null ? ` (${e.context})` : ''}`)\n .join('\\n')}`;\n }\n return message;\n }),\n ],\n });\n if (ignoreVersion !== true) {\n const versionPromise = this.api.apiVersion()\n .then(({ apiVersion }) => apiVersion, (error) => error);\n this.api.pipeline.addPolicy(\n genVersionCheckPolicy('compiler', '/api-version', versionPromise, '7.3.0', '8.0.0'),\n );\n }\n }\n\n async compileBySourceCode(\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<{ bytecode: Encoded.ContractBytearray; aci: Aci }> {\n try {\n const res = await this.api.compileContract({ code: sourceCode, options: { fileSystem } });\n // TODO: should be fixed when the compiledAci interface gets updated\n return res as { bytecode: Encoded.ContractBytearray; aci: Aci };\n } catch (error) {\n if (error instanceof RestError && error.statusCode === 400) {\n throw new CompilerError(error.message);\n }\n throw error;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n async compile(path: string): Promise<{ bytecode: Encoded.ContractBytearray; aci: Aci }> {\n throw new NotImplementedError('File system access, use CompilerHttpNode instead');\n }\n\n async generateAciBySourceCode(\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<Aci> {\n try {\n return await this.api.generateACI({ code: sourceCode, options: { fileSystem } });\n } catch (error) {\n if (error instanceof RestError && error.statusCode === 400) {\n throw new CompilerError(error.message);\n }\n throw error;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n async generateAci(path: string): Promise<Aci> {\n throw new NotImplementedError('File system access, use CompilerHttpNode instead');\n }\n\n async validateBySourceCode(\n bytecode: Encoded.ContractBytearray,\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<boolean> {\n try {\n await this.api.validateByteCode({ bytecode, source: sourceCode, options: { fileSystem } });\n return true;\n } catch {\n return false;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n async validate(bytecode: Encoded.ContractBytearray, path: string): Promise<boolean> {\n throw new NotImplementedError('File system access, use CompilerHttpNode instead');\n }\n\n async version(): Promise<string> {\n return (await this.api.version()).version;\n }\n}\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,2BAA2B;AAAC,SAEpDC,QAAQ,IAAIC,WAAW;AAAA,SAIhBC,uBAAuB,EAAEC,qBAAqB;AAAA,OAChDC,YAAY;AAAA,SAEVC,aAAa,EAAEC,mBAAmB;AAO3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAMC,YAAY,SAASH,YAAY,CAAC;EAGrD;AACF;AACA;AACA;AACA;EACEI,WAAWA,CAACC,WAAmB,EAAuD;IAAA,IAArD;MAAEC;IAA2C,CAAC,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;IAClF,KAAK,
|
|
1
|
+
{"version":3,"file":"Http.mjs","names":["RestError","Compiler","CompilerApi","genErrorFormatterPolicy","genVersionCheckPolicy","CompilerBase","CompilerError","NotImplementedError","CompilerHttp","constructor","compilerUrl","ignoreVersion","arguments","length","undefined","api","allowInsecureConnection","additionalPolicies","body","message","reason","parameter","info","JSON","stringify","Array","isArray","map","e","type","pos","line","col","context","join","versionPromise","apiVersion","then","_ref","error","pipeline","addPolicy","compileBySourceCode","sourceCode","fileSystem","res","compileContract","code","options","statusCode","compile","path","generateAciBySourceCode","generateACI","generateAci","validateBySourceCode","bytecode","validateByteCode","source","validate","version"],"sources":["../../../src/contract/compiler/Http.ts"],"sourcesContent":["import { RestError } from '@azure/core-rest-pipeline';\nimport {\n Compiler as CompilerApi,\n ErrorModel,\n CompilerError as CompilerErrorApi,\n} from '../../apis/compiler';\nimport { genErrorFormatterPolicy, genVersionCheckPolicy } from '../../utils/autorest';\nimport CompilerBase, { Aci } from './Base';\nimport { Encoded } from '../../utils/encoder';\nimport { CompilerError, NotImplementedError } from '../../utils/errors';\n\ntype GeneralCompilerError = ErrorModel & {\n info?: object;\n parameter?: string;\n};\n\n/**\n * Contract Compiler over HTTP\n *\n * This class include api call's related to contract compiler functionality.\n * @category contract\n * @example CompilerHttp('COMPILER_URL')\n */\nexport default class CompilerHttp extends CompilerBase {\n readonly api: CompilerApi;\n\n /**\n * @param compilerUrl - Url for compiler API\n * @param options - Options\n * @param options.ignoreVersion - Don't check compiler version\n */\n constructor(compilerUrl: string, { ignoreVersion }: { ignoreVersion?: boolean } = {}) {\n super();\n this.api = new CompilerApi(compilerUrl, {\n allowInsecureConnection: true,\n additionalPolicies: [\n genErrorFormatterPolicy((body: GeneralCompilerError | CompilerErrorApi[]) => {\n let message = '';\n if ('reason' in body) {\n message += ` ${body.reason\n }${body.parameter != null ? ` in ${body.parameter}` : ''\n // TODO: revising after improving documentation https://github.com/aeternity/aesophia_http/issues/78\n }${body.info != null ? ` (${JSON.stringify(body.info)})` : ''}`;\n }\n if (Array.isArray(body)) {\n message += `\\n${body\n .map((e) => `${e.type}:${e.pos.line}:${e.pos.col}: ${e.message}${e.context != null ? ` (${e.context})` : ''}`)\n .join('\\n')}`;\n }\n return message;\n }),\n ],\n });\n if (ignoreVersion !== true) {\n const versionPromise = this.api.apiVersion()\n .then(({ apiVersion }) => apiVersion, (error) => error);\n this.api.pipeline.addPolicy(\n genVersionCheckPolicy('compiler', '/api-version', versionPromise, '7.3.0', '8.0.0'),\n );\n }\n }\n\n async compileBySourceCode(\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<{ bytecode: Encoded.ContractBytearray; aci: Aci }> {\n try {\n const res = await this.api.compileContract({ code: sourceCode, options: { fileSystem } });\n // TODO: should be fixed when the compiledAci interface gets updated\n return res as { bytecode: Encoded.ContractBytearray; aci: Aci };\n } catch (error) {\n if (error instanceof RestError && error.statusCode === 400) {\n throw new CompilerError(error.message);\n }\n throw error;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n async compile(path: string): Promise<{ bytecode: Encoded.ContractBytearray; aci: Aci }> {\n throw new NotImplementedError('File system access, use CompilerHttpNode instead');\n }\n\n async generateAciBySourceCode(\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<Aci> {\n try {\n return await this.api.generateACI({ code: sourceCode, options: { fileSystem } });\n } catch (error) {\n if (error instanceof RestError && error.statusCode === 400) {\n throw new CompilerError(error.message);\n }\n throw error;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n async generateAci(path: string): Promise<Aci> {\n throw new NotImplementedError('File system access, use CompilerHttpNode instead');\n }\n\n async validateBySourceCode(\n bytecode: Encoded.ContractBytearray,\n sourceCode: string,\n fileSystem?: Record<string, string>,\n ): Promise<boolean> {\n try {\n await this.api.validateByteCode({ bytecode, source: sourceCode, options: { fileSystem } });\n return true;\n } catch {\n return false;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n async validate(bytecode: Encoded.ContractBytearray, path: string): Promise<boolean> {\n throw new NotImplementedError('File system access, use CompilerHttpNode instead');\n }\n\n async version(): Promise<string> {\n return (await this.api.version()).version;\n }\n}\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,2BAA2B;AAAC,SAEpDC,QAAQ,IAAIC,WAAW;AAAA,SAIhBC,uBAAuB,EAAEC,qBAAqB;AAAA,OAChDC,YAAY;AAAA,SAEVC,aAAa,EAAEC,mBAAmB;AAO3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAMC,YAAY,SAASH,YAAY,CAAC;EAGrD;AACF;AACA;AACA;AACA;EACEI,WAAWA,CAACC,WAAmB,EAAuD;IAAA,IAArD;MAAEC;IAA2C,CAAC,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;IAClF,KAAK,CAAC,CAAC;IACP,IAAI,CAACG,GAAG,GAAG,IAAIb,WAAW,CAACQ,WAAW,EAAE;MACtCM,uBAAuB,EAAE,IAAI;MAC7BC,kBAAkB,EAAE,CAClBd,uBAAuB,CAAEe,IAA+C,IAAK;QAC3E,IAAIC,OAAO,GAAG,EAAE;QAChB,IAAI,QAAQ,IAAID,IAAI,EAAE;UACpBC,OAAO,IAAK,IAAGD,IAAI,CAACE,MACnB,GAAEF,IAAI,CAACG,SAAS,IAAI,IAAI,GAAI,OAAMH,IAAI,CAACG,SAAU,EAAC,GAAG;UACpD;UACD,GAAEH,IAAI,CAACI,IAAI,IAAI,IAAI,GAAI,KAAIC,IAAI,CAACC,SAAS,CAACN,IAAI,CAACI,IAAI,CAAE,GAAE,GAAG,EAAG,EAAC;QACjE;QACA,IAAIG,KAAK,CAACC,OAAO,CAACR,IAAI,CAAC,EAAE;UACvBC,OAAO,IAAK,KAAID,IAAI,CACjBS,GAAG,CAAEC,CAAC,IAAM,GAAEA,CAAC,CAACC,IAAK,IAAGD,CAAC,CAACE,GAAG,CAACC,IAAK,IAAGH,CAAC,CAACE,GAAG,CAACE,GAAI,K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IAAI;MACF,OAAO,MAAM,IAAI,CAAC7B,GAAG,CAACsC,WAAW,CAAC;QAAEN,IAAI,EAAEJ,UAAU;QAAEK,OAAO,EAAE;UAAEJ;QAAW;MAAE,CAAC,CAAC;IAClF,CAAC,CAAC,OAAOL,KAAK,EAAE;MACd,IAAIA,KAAK,YAAYvC,SAAS,IAAIuC,KAAK,CAACU,UAAU,KAAK,GAAG,EAAE;QAC1D,MAAM,IAAI3C,aAAa,CAACiC,KAAK,CAACpB,OAAO,CAAC;MACxC;MACA,MAAMoB,KAAK;IACb;EACF;;EAEA;EACA,MAAMe,WAAWA,CAACH,IAAY,EAAgB;IAC5C,MAAM,IAAI5C,mBAAmB,CAAC,kDAAkD,CAAC;EACnF;EAEA,MAAMgD,oBAAoBA,CACxBC,QAAmC,EACnCb,UAAkB,EAClBC,UAAmC,EACjB;IAClB,IAAI;MACF,MAAM,IAAI,CAAC7B,GAAG,CAAC0C,gBAAgB,CAAC;QAAED,QAAQ;QAAEE,MAAM,EAAEf,UAAU;QAAEK,OAAO,EAAE;UAAEJ;QAAW;MAAE,CAAC,CAAC;MAC1F,OAAO,IAAI;IACb,CAAC,CAAC,MAAM;MACN,OAAO,KAAK;IACd;EACF;;EAEA;EACA,MAAMe,QAAQA,CAACH,QAAmC,EAAEL,IAAY,EAAoB;IAClF,MAAM,IAAI5C,mBAAmB,CAAC,kDAAkD,CAAC;EACnF;EAEA,MAAMqD,OAAOA,CAAA,EAAoB;IAC/B,OAAO,CAAC,MAAM,IAAI,CAAC7C,GAAG,CAAC6C,OAAO,CAAC,CAAC,EAAEA,OAAO;EAC3C;AACF"}
|
|
@@ -14,6 +14,7 @@ import Node from '../Node';
|
|
|
14
14
|
* @param options.onAccount - Account to use
|
|
15
15
|
* @param options.onNode - Node to use
|
|
16
16
|
* @returns Signature
|
|
17
|
+
* @deprecated use methods `sign*DelegationToContract` of Account instance instead
|
|
17
18
|
* @example
|
|
18
19
|
* ```js
|
|
19
20
|
* const aeSdk = new AeSdk({ ... })
|
|
@@ -36,7 +37,7 @@ import Node from '../Node';
|
|
|
36
37
|
* .createDelegationSignature(contractAddress, [oracleQueryId], { onAccount, omitAddress: true })
|
|
37
38
|
* ```
|
|
38
39
|
*/
|
|
39
|
-
export default function createDelegationSignature(contractAddress: Encoded.ContractAddress, ids: Array<Encoded.Any | AensName>, options: {
|
|
40
|
+
export default function createDelegationSignature(contractAddress: Encoded.ContractAddress, ids: Array<Encoded.Any | AensName>, { onAccount, omitAddress, ...options }: {
|
|
40
41
|
omitAddress?: boolean;
|
|
41
42
|
onAccount: AccountBase;
|
|
42
43
|
onNode: Node;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import _buffer from "buffer";
|
|
2
|
-
const {
|
|
3
|
-
Buffer: _Buffer
|
|
4
|
-
} = _buffer;
|
|
5
1
|
import { decode } from "../utils/encoder.mjs";
|
|
6
|
-
import {
|
|
7
|
-
import { isNameValid
|
|
2
|
+
import { ArgumentError } from "../utils/errors.mjs";
|
|
3
|
+
import { isNameValid } from "../tx/builder/helpers.mjs";
|
|
4
|
+
function ensureOracleQuery(oq) {
|
|
5
|
+
if (!oq.startsWith('oq_')) throw new ArgumentError('oq', 'oracle query', oq);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
8
|
/**
|
|
9
9
|
* Helper to generate a signature to delegate
|
|
10
10
|
* - pre-claim/claim/transfer/revoke of a name to a contract.
|
|
@@ -17,6 +17,7 @@ import { isNameValid, produceNameId } from "../tx/builder/helpers.mjs";
|
|
|
17
17
|
* @param options.onAccount - Account to use
|
|
18
18
|
* @param options.onNode - Node to use
|
|
19
19
|
* @returns Signature
|
|
20
|
+
* @deprecated use methods `sign*DelegationToContract` of Account instance instead
|
|
20
21
|
* @example
|
|
21
22
|
* ```js
|
|
22
23
|
* const aeSdk = new AeSdk({ ... })
|
|
@@ -39,7 +40,37 @@ import { isNameValid, produceNameId } from "../tx/builder/helpers.mjs";
|
|
|
39
40
|
* .createDelegationSignature(contractAddress, [oracleQueryId], { onAccount, omitAddress: true })
|
|
40
41
|
* ```
|
|
41
42
|
*/
|
|
42
|
-
export default async function createDelegationSignature(contractAddress, ids,
|
|
43
|
-
|
|
43
|
+
export default async function createDelegationSignature(contractAddress, ids, _ref) {
|
|
44
|
+
let {
|
|
45
|
+
onAccount,
|
|
46
|
+
omitAddress,
|
|
47
|
+
...options
|
|
48
|
+
} = _ref;
|
|
49
|
+
if (ids.length > 1) throw new ArgumentError('ids', 'shorter than 2', ids);
|
|
50
|
+
const networkId = await options.onNode.getNetworkId();
|
|
51
|
+
if (ids.length === 0) {
|
|
52
|
+
if (omitAddress === true) {
|
|
53
|
+
throw new ArgumentError('omitAddress', 'equal false', omitAddress);
|
|
54
|
+
}
|
|
55
|
+
return decode(await onAccount.signDelegationToContract(contractAddress, {
|
|
56
|
+
networkId
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
const [payload] = ids;
|
|
60
|
+
if (isNameValid(payload)) {
|
|
61
|
+
if (omitAddress === true) {
|
|
62
|
+
throw new ArgumentError('omitAddress', 'equal false', omitAddress);
|
|
63
|
+
}
|
|
64
|
+
return decode(await onAccount.signNameDelegationToContract(contractAddress, payload, {
|
|
65
|
+
networkId
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
ensureOracleQuery(payload);
|
|
69
|
+
if (omitAddress !== true) {
|
|
70
|
+
throw new ArgumentError('omitAddress', 'equal true', omitAddress);
|
|
71
|
+
}
|
|
72
|
+
return decode(await onAccount.signOracleQueryDelegationToContract(contractAddress, payload, {
|
|
73
|
+
networkId
|
|
74
|
+
}));
|
|
44
75
|
}
|
|
45
76
|
//# sourceMappingURL=delegation-signature.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delegation-signature.mjs","names":["decode","
|
|
1
|
+
{"version":3,"file":"delegation-signature.mjs","names":["decode","ArgumentError","isNameValid","ensureOracleQuery","oq","startsWith","createDelegationSignature","contractAddress","ids","_ref","onAccount","omitAddress","options","length","networkId","onNode","getNetworkId","signDelegationToContract","payload","signNameDelegationToContract","signOracleQueryDelegationToContract"],"sources":["../../src/contract/delegation-signature.ts"],"sourcesContent":["import { decode, Encoded } from '../utils/encoder';\nimport { ArgumentError } from '../utils/errors';\nimport { AensName } from '../tx/builder/constants';\nimport AccountBase from '../account/Base';\nimport { isNameValid } from '../tx/builder/helpers';\nimport Node from '../Node';\n\nfunction ensureOracleQuery(oq: string): asserts oq is Encoded.OracleQueryId {\n if (!oq.startsWith('oq_')) throw new ArgumentError('oq', 'oracle query', oq);\n}\n\n/**\n * Helper to generate a signature to delegate\n * - pre-claim/claim/transfer/revoke of a name to a contract.\n * - register/extend/respond of an Oracle to a contract.\n * @category contract\n * @param contractAddress - Address of contract to delegate access\n * @param ids - The list of id's to prepend\n * @param options - Options\n * @param options.omitAddress - Prepend delegation signature with an account address\n * @param options.onAccount - Account to use\n * @param options.onNode - Node to use\n * @returns Signature\n * @deprecated use methods `sign*DelegationToContract` of Account instance instead\n * @example\n * ```js\n * const aeSdk = new AeSdk({ ... })\n * const contractAddress = 'ct_asd2ks...'\n * const aensName = 'example.chain'\n * const onAccount = new MemoryAccount(...) // Sign with a specific account\n * // Preclaim signature\n * const preclaimSig = await aeSdk.createDelegationSignature(contractAddress, [], { onAccount })\n * // Claim, transfer and revoke signature\n * const aensDelegationSig = await aeSdk\n * .createDelegationSignature(contractAddress, [aensName], { onAccount })\n *\n * const oracleQueryId = 'oq_...'\n * const onAccount = new MemoryAccount(...) // Sign with a specific account\n * // Oracle register and extend signature\n * const oracleDelegationSig = await aeSdk\n * .createDelegationSignature(contractAddress, [], { onAccount })\n * // Oracle respond signature\n * const respondSig = await aeSdk\n * .createDelegationSignature(contractAddress, [oracleQueryId], { onAccount, omitAddress: true })\n * ```\n */\nexport default async function createDelegationSignature(\n contractAddress: Encoded.ContractAddress,\n ids: Array<Encoded.Any | AensName>,\n { onAccount, omitAddress, ...options }: {\n omitAddress?: boolean;\n onAccount: AccountBase;\n onNode: Node;\n },\n): Promise<Uint8Array> {\n if (ids.length > 1) throw new ArgumentError('ids', 'shorter than 2', ids);\n const networkId = await options.onNode.getNetworkId();\n if (ids.length === 0) {\n if (omitAddress === true) {\n throw new ArgumentError('omitAddress', 'equal false', omitAddress);\n }\n return decode(await onAccount.signDelegationToContract(contractAddress, { networkId }));\n }\n\n const [payload] = ids;\n if (isNameValid(payload)) {\n if (omitAddress === true) {\n throw new ArgumentError('omitAddress', 'equal false', omitAddress);\n }\n return decode(\n await onAccount.signNameDelegationToContract(contractAddress, payload, { networkId }),\n );\n }\n\n ensureOracleQuery(payload);\n if (omitAddress !== true) {\n throw new ArgumentError('omitAddress', 'equal true', omitAddress);\n }\n return decode(\n await onAccount.signOracleQueryDelegationToContract(contractAddress, payload, { networkId }),\n );\n}\n"],"mappings":"SAASA,MAAM;AAAA,SACNC,aAAa;AAAA,SAGbC,WAAW;AAGpB,SAASC,iBAAiBA,CAACC,EAAU,EAAuC;EAC1E,IAAI,CAACA,EAAE,CAACC,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,IAAIJ,aAAa,CAAC,IAAI,EAAE,cAAc,EAAEG,EAAE,CAAC;AAC9E;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,eAAeE,yBAAyBA,CACrDC,eAAwC,EACxCC,GAAkC,EAAAC,IAAA,EAMb;EAAA,IALrB;IAAEC,SAAS;IAAEC,WAAW;IAAE,GAAGC;EAI7B,CAAC,GAAAH,IAAA;EAED,IAAID,GAAG,CAACK,MAAM,GAAG,CAAC,EAAE,MAAM,IAAIZ,aAAa,CAAC,KAAK,EAAE,gBAAgB,EAAEO,GAAG,CAAC;EACzE,MAAMM,SAAS,GAAG,MAAMF,OAAO,CAACG,MAAM,CAACC,YAAY,CAAC,CAAC;EACrD,IAAIR,GAAG,CAACK,MAAM,KAAK,CAAC,EAAE;IACpB,IAAIF,WAAW,KAAK,IAAI,EAAE;MACxB,MAAM,IAAIV,aAAa,CAAC,aAAa,EAAE,aAAa,EAAEU,WAAW,CAAC;IACpE;IACA,OAAOX,MAAM,CAAC,MAAMU,SAAS,CAACO,wBAAwB,CAACV,eAAe,EAAE;MAAEO;IAAU,CAAC,CAAC,CAAC;EACzF;EAEA,MAAM,CAACI,OAAO,CAAC,GAAGV,GAAG;EACrB,IAAIN,WAAW,CAACgB,OAAO,CAAC,EAAE;IACxB,IAAIP,WAAW,KAAK,IAAI,EAAE;MACxB,MAAM,IAAIV,aAAa,CAAC,aAAa,EAAE,aAAa,EAAEU,WAAW,CAAC;IACpE;IACA,OAAOX,MAAM,CACX,MAAMU,SAAS,CAACS,4BAA4B,CAACZ,eAAe,EAAEW,OAAO,EAAE;MAAEJ;IAAU,CAAC,CACtF,CAAC;EACH;EAEAX,iBAAiB,CAACe,OAAO,CAAC;EAC1B,IAAIP,WAAW,KAAK,IAAI,EAAE;IACxB,MAAM,IAAIV,aAAa,CAAC,aAAa,EAAE,YAAY,EAAEU,WAAW,CAAC;EACnE;EACA,OAAOX,MAAM,CACX,MAAMU,SAAS,CAACU,mCAAmC,CAACb,eAAe,EAAEW,OAAO,EAAE;IAAEJ;EAAU,CAAC,CAC7F,CAAC;AACH"}
|
package/es/contract/ga.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ga.mjs","names":["ConsensusProtocolVersion","Tag","buildContractIdByContractTx","buildTx","buildTxAsync","unpackTx","hash","decode","encode","Encoding","ArgumentError","IllegalArgumentError","concatBuffers","Contract","sendTransaction","getAccount","createGeneralizedAccount","authFnName","args","_ref","_options$gasLimit","onAccount","onCompiler","onNode","bytecode","aci","sourceCodePath","sourceCode","fileSystem","options","ownerId","address","kind","contract","initialize","tx","tag","GaAttachTx","code","$compile","gasLimit","_estimateGas","callData","_calldata","_name","authFun","contractId","transaction","rawTx","Object","freeze","owner","gaContractId","buildAuthTxHash","_ref2","fee","gasPrice","nodeNetworkId","consensusProtocolVersion","getNodeInfo","payload","_Buffer","from","Ceres","GaMetaTxAuthData","txHash","TxHash","buildAuthTxHashByGaMetaTx","_ref3","txParams","SignedTx","encodedTx","GaMetaTx"],"sources":["../../src/contract/ga.ts"],"sourcesContent":["/**\n * Generalized Account module - routines to use generalized account\n */\n\nimport { ConsensusProtocolVersion, Int, Tag } from '../tx/builder/constants';\nimport {\n buildContractIdByContractTx, buildTx, buildTxAsync, BuildTxOptions, unpackTx,\n} from '../tx/builder';\nimport { hash } from '../utils/crypto';\nimport {\n decode, encode, Encoded, Encoding,\n} from '../utils/encoder';\nimport { ArgumentError, IllegalArgumentError } from '../utils/errors';\nimport { concatBuffers } from '../utils/other';\nimport AccountBase from '../account/Base';\nimport Contract from './Contract';\nimport Node from '../Node';\nimport { sendTransaction, SendTransactionOptions, getAccount } from '../chain';\nimport CompilerBase from './compiler/Base';\n\n/**\n * Convert current account to GA\n * @category contract\n * @param authFnName - Authorization function name\n * @param sourceCode - Auth contract source code\n * @param args - init arguments\n * @param options - Options\n * @returns General Account Object\n */\nexport async function createGeneralizedAccount(\n authFnName: string,\n args: any[],\n {\n onAccount, onCompiler, onNode, bytecode, aci, sourceCodePath, sourceCode, fileSystem, ...options\n }: CreateGeneralizedAccountOptions,\n): Promise<Readonly<{\n owner: Encoded.AccountAddress;\n transaction: Encoded.TxHash;\n rawTx: Encoded.Transaction;\n gaContractId: Encoded.ContractAddress;\n }>> {\n const ownerId = onAccount.address;\n if ((await getAccount(ownerId, { onNode })).kind === 'generalized') {\n throw new IllegalArgumentError(`Account ${ownerId} is already GA`);\n }\n\n const contract = await Contract.initialize<{ init: (...a: any[]) => void }>({\n onAccount, onCompiler, onNode, bytecode, aci, sourceCodePath, sourceCode, fileSystem,\n });\n\n const tx = await buildTxAsync({\n ...options,\n tag: Tag.GaAttachTx,\n onNode,\n code: await contract.$compile(),\n gasLimit: options.gasLimit ?? await contract._estimateGas('init', args, options),\n ownerId,\n callData: contract._calldata.encode(contract._name, 'init', args),\n authFun: hash(authFnName),\n });\n const contractId = buildContractIdByContractTx(tx);\n const { hash: transaction, rawTx } = await sendTransaction(tx, {\n onNode, onAccount, onCompiler, ...options,\n });\n\n return Object.freeze({\n owner: ownerId,\n transaction,\n rawTx,\n gaContractId: contractId,\n });\n}\n\ninterface CreateGeneralizedAccountOptions extends\n BuildTxOptions<Tag.GaAttachTx, 'authFun' | 'callData' | 'code' | 'ownerId' | 'gasLimit'>,\n SendTransactionOptions,\n Pick<\n Parameters<typeof Contract.initialize>[0],\n 'bytecode' | 'aci' | 'sourceCodePath' | 'sourceCode' | 'fileSystem'\n > {\n onAccount: AccountBase;\n onCompiler: CompilerBase;\n onNode: Node;\n gasLimit?: number;\n}\n\n/**\n * Build a transaction hash the same as `Auth.tx_hash` by GaMetaTx payload\n * @category contract\n * @param transaction - tx-encoded transaction\n * @param options - Options\n * @param options.fee - GaMetaTx fee, required in Ceres\n * @param options.gasPrice - GaMetaTx gasPrice, required in Ceres\n * @param options.onNode - Node to use\n * @returns Transaction hash\n */\nexport async function buildAuthTxHash(\n transaction: Encoded.Transaction,\n { fee, gasPrice, onNode }: { fee?: Int; gasPrice?: Int; onNode: Node },\n): Promise<Buffer> {\n const { nodeNetworkId, consensusProtocolVersion } = await onNode.getNodeInfo();\n let payload = hash(concatBuffers([Buffer.from(nodeNetworkId), decode(transaction)]));\n if (consensusProtocolVersion === ConsensusProtocolVersion.Ceres) {\n if (fee == null) throw new ArgumentError('fee', 'provided (in Ceres)', fee);\n if (gasPrice == null) throw new ArgumentError('gasPrice', 'provided (in Ceres)', gasPrice);\n payload = hash(decode(buildTx({\n tag: Tag.GaMetaTxAuthData,\n fee,\n gasPrice,\n txHash: encode(payload, Encoding.TxHash),\n })));\n }\n return payload;\n}\n\n/**\n * Build a transaction hash the same as `Auth.tx_hash` by GaMetaTx\n * @category contract\n * @param transaction - tx-encoded signed GaMeta transaction\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Transaction hash\n */\nexport async function buildAuthTxHashByGaMetaTx(\n transaction: Encoded.Transaction,\n { onNode }: { onNode: Node },\n): Promise<Buffer> {\n const txParams = unpackTx(transaction, Tag.SignedTx);\n if (txParams.encodedTx.tag !== Tag.GaMetaTx) {\n throw new ArgumentError('transaction', 'to include GaMetaTx', Tag[txParams.encodedTx.tag]);\n }\n return buildAuthTxHash(buildTx(txParams.encodedTx.tx.encodedTx), {\n fee: txParams.encodedTx.fee,\n gasPrice: txParams.encodedTx.gasPrice,\n onNode,\n });\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AAFA,SAISA,wBAAwB,EAAOC,GAAG;AAAA,SAEzCC,2BAA2B,EAAEC,OAAO,EAAEC,YAAY,EAAkBC,QAAQ;AAAA,SAErEC,IAAI;AAAA,SAEXC,MAAM,EAAEC,MAAM,EAAWC,QAAQ;AAAA,SAE1BC,aAAa,EAAEC,oBAAoB;AAAA,SACnCC,aAAa;AAAA,OAEfC,QAAQ;AAAA,SAENC,eAAe,EAA0BC,UAAU;AAG5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,wBAAwBA,CAC5CC,UAAkB,EAClBC,IAAW,EAAAC,IAAA,EASP;EAAA,IAAAC,iBAAA;EAAA,IARJ;IACEC,SAAS;IAAEC,UAAU;IAAEC,MAAM;IAAEC,QAAQ;IAAEC,GAAG;IAAEC,cAAc;IAAEC,UAAU;IAAEC,UAAU;IAAE,GAAGC;EAC1D,CAAC,GAAAV,IAAA;EAOlC,MAAMW,OAAO,GAAGT,SAAS,CAACU,OAAO;EACjC,IAAI,CAAC,MAAMhB,UAAU,CAACe,OAAO,EAAE;IAAEP;EAAO,CAAC,CAAC,EAAES,IAAI,KAAK,aAAa,EAAE;IAClE,MAAM,IAAIrB,oBAAoB,CAAE,WAAUmB,OAAQ,gBAAe,CAAC;EACpE;EAEA,MAAMG,QAAQ,GAAG,MAAMpB,QAAQ,CAACqB,UAAU,CAAkC;IAC1Eb,SAAS;IAAEC,UAAU;IAAEC,MAAM;IAAEC,QAAQ;IAAEC,GAAG;IAAEC,cAAc;IAAEC,UAAU;IAAEC;EAC5E,CAAC,CAAC;EAEF,MAAMO,EAAE,GAAG,MAAM/B,YAAY,CAAC;IAC5B,GAAGyB,OAAO;IACVO,GAAG,EAAEnC,GAAG,CAACoC,UAAU;IACnBd,MAAM;IACNe,IAAI,EAAE,MAAML,QAAQ,CAACM,QAAQ,
|
|
1
|
+
{"version":3,"file":"ga.mjs","names":["ConsensusProtocolVersion","Tag","buildContractIdByContractTx","buildTx","buildTxAsync","unpackTx","hash","decode","encode","Encoding","ArgumentError","IllegalArgumentError","concatBuffers","Contract","sendTransaction","getAccount","createGeneralizedAccount","authFnName","args","_ref","_options$gasLimit","onAccount","onCompiler","onNode","bytecode","aci","sourceCodePath","sourceCode","fileSystem","options","ownerId","address","kind","contract","initialize","tx","tag","GaAttachTx","code","$compile","gasLimit","_estimateGas","callData","_calldata","_name","authFun","contractId","transaction","rawTx","Object","freeze","owner","gaContractId","buildAuthTxHash","_ref2","fee","gasPrice","nodeNetworkId","consensusProtocolVersion","getNodeInfo","payload","_Buffer","from","Ceres","GaMetaTxAuthData","txHash","TxHash","buildAuthTxHashByGaMetaTx","_ref3","txParams","SignedTx","encodedTx","GaMetaTx"],"sources":["../../src/contract/ga.ts"],"sourcesContent":["/**\n * Generalized Account module - routines to use generalized account\n */\n\nimport { ConsensusProtocolVersion, Int, Tag } from '../tx/builder/constants';\nimport {\n buildContractIdByContractTx, buildTx, buildTxAsync, BuildTxOptions, unpackTx,\n} from '../tx/builder';\nimport { hash } from '../utils/crypto';\nimport {\n decode, encode, Encoded, Encoding,\n} from '../utils/encoder';\nimport { ArgumentError, IllegalArgumentError } from '../utils/errors';\nimport { concatBuffers } from '../utils/other';\nimport AccountBase from '../account/Base';\nimport Contract from './Contract';\nimport Node from '../Node';\nimport { sendTransaction, SendTransactionOptions, getAccount } from '../chain';\nimport CompilerBase from './compiler/Base';\n\n/**\n * Convert current account to GA\n * @category contract\n * @param authFnName - Authorization function name\n * @param sourceCode - Auth contract source code\n * @param args - init arguments\n * @param options - Options\n * @returns General Account Object\n */\nexport async function createGeneralizedAccount(\n authFnName: string,\n args: any[],\n {\n onAccount, onCompiler, onNode, bytecode, aci, sourceCodePath, sourceCode, fileSystem, ...options\n }: CreateGeneralizedAccountOptions,\n): Promise<Readonly<{\n owner: Encoded.AccountAddress;\n transaction: Encoded.TxHash;\n rawTx: Encoded.Transaction;\n gaContractId: Encoded.ContractAddress;\n }>> {\n const ownerId = onAccount.address;\n if ((await getAccount(ownerId, { onNode })).kind === 'generalized') {\n throw new IllegalArgumentError(`Account ${ownerId} is already GA`);\n }\n\n const contract = await Contract.initialize<{ init: (...a: any[]) => void }>({\n onAccount, onCompiler, onNode, bytecode, aci, sourceCodePath, sourceCode, fileSystem,\n });\n\n const tx = await buildTxAsync({\n ...options,\n tag: Tag.GaAttachTx,\n onNode,\n code: await contract.$compile(),\n gasLimit: options.gasLimit ?? await contract._estimateGas('init', args, options),\n ownerId,\n callData: contract._calldata.encode(contract._name, 'init', args),\n authFun: hash(authFnName),\n });\n const contractId = buildContractIdByContractTx(tx);\n const { hash: transaction, rawTx } = await sendTransaction(tx, {\n onNode, onAccount, onCompiler, ...options,\n });\n\n return Object.freeze({\n owner: ownerId,\n transaction,\n rawTx,\n gaContractId: contractId,\n });\n}\n\ninterface CreateGeneralizedAccountOptions extends\n BuildTxOptions<Tag.GaAttachTx, 'authFun' | 'callData' | 'code' | 'ownerId' | 'gasLimit'>,\n SendTransactionOptions,\n Pick<\n Parameters<typeof Contract.initialize>[0],\n 'bytecode' | 'aci' | 'sourceCodePath' | 'sourceCode' | 'fileSystem'\n > {\n onAccount: AccountBase;\n onCompiler: CompilerBase;\n onNode: Node;\n gasLimit?: number;\n}\n\n/**\n * Build a transaction hash the same as `Auth.tx_hash` by GaMetaTx payload\n * @category contract\n * @param transaction - tx-encoded transaction\n * @param options - Options\n * @param options.fee - GaMetaTx fee, required in Ceres\n * @param options.gasPrice - GaMetaTx gasPrice, required in Ceres\n * @param options.onNode - Node to use\n * @returns Transaction hash\n */\nexport async function buildAuthTxHash(\n transaction: Encoded.Transaction,\n { fee, gasPrice, onNode }: { fee?: Int; gasPrice?: Int; onNode: Node },\n): Promise<Buffer> {\n const { nodeNetworkId, consensusProtocolVersion } = await onNode.getNodeInfo();\n let payload = hash(concatBuffers([Buffer.from(nodeNetworkId), decode(transaction)]));\n if (consensusProtocolVersion === ConsensusProtocolVersion.Ceres) {\n if (fee == null) throw new ArgumentError('fee', 'provided (in Ceres)', fee);\n if (gasPrice == null) throw new ArgumentError('gasPrice', 'provided (in Ceres)', gasPrice);\n payload = hash(decode(buildTx({\n tag: Tag.GaMetaTxAuthData,\n fee,\n gasPrice,\n txHash: encode(payload, Encoding.TxHash),\n })));\n }\n return payload;\n}\n\n/**\n * Build a transaction hash the same as `Auth.tx_hash` by GaMetaTx\n * @category contract\n * @param transaction - tx-encoded signed GaMeta transaction\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Transaction hash\n */\nexport async function buildAuthTxHashByGaMetaTx(\n transaction: Encoded.Transaction,\n { onNode }: { onNode: Node },\n): Promise<Buffer> {\n const txParams = unpackTx(transaction, Tag.SignedTx);\n if (txParams.encodedTx.tag !== Tag.GaMetaTx) {\n throw new ArgumentError('transaction', 'to include GaMetaTx', Tag[txParams.encodedTx.tag]);\n }\n return buildAuthTxHash(buildTx(txParams.encodedTx.tx.encodedTx), {\n fee: txParams.encodedTx.fee,\n gasPrice: txParams.encodedTx.gasPrice,\n onNode,\n });\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AAFA,SAISA,wBAAwB,EAAOC,GAAG;AAAA,SAEzCC,2BAA2B,EAAEC,OAAO,EAAEC,YAAY,EAAkBC,QAAQ;AAAA,SAErEC,IAAI;AAAA,SAEXC,MAAM,EAAEC,MAAM,E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,CAAC;MAC5BiC,GAAG,EAAEnC,GAAG,CAAC+D,gBAAgB;MACzBT,GAAG;MACHC,QAAQ;MACRS,MAAM,EAAEzD,MAAM,CAACoD,OAAO,EAAEnD,QAAQ,CAACyD,MAAM;IACzC,CAAC,CAAC,CAAC,CAAC;EACN;EACA,OAAON,OAAO;AAChB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeO,yBAAyBA,CAC7CpB,WAAgC,EAAAqB,KAAA,EAEf;EAAA,IADjB;IAAE7C;EAAyB,CAAC,GAAA6C,KAAA;EAE5B,MAAMC,QAAQ,GAAGhE,QAAQ,CAAC0C,WAAW,EAAE9C,GAAG,CAACqE,QAAQ,CAAC;EACpD,IAAID,QAAQ,CAACE,SAAS,CAACnC,GAAG,KAAKnC,GAAG,CAACuE,QAAQ,EAAE;IAC3C,MAAM,IAAI9D,aAAa,CAAC,aAAa,EAAE,qBAAqB,EAAET,GAAG,CAACoE,QAAQ,CAACE,SAAS,CAACnC,GAAG,CAAC,CAAC;EAC5F;EACA,OAAOiB,eAAe,CAAClD,OAAO,CAACkE,QAAQ,CAACE,SAAS,CAACpC,EAAE,CAACoC,SAAS,CAAC,EAAE;IAC/DhB,GAAG,EAAEc,QAAQ,CAACE,SAAS,CAAChB,GAAG;IAC3BC,QAAQ,EAAEa,QAAQ,CAACE,SAAS,CAACf,QAAQ;IACrCjC;EACF,CAAC,CAAC;AACJ"}
|
package/es/oracle.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oracle.mjs","names":["mapObject","pause","oracleQueryId","unpackTx","buildTxAsync","ORACLE_TTL","QUERY_TTL","RESPONSE_TTL","Tag","RequestTimedOutError","decode","encode","Encoding","_getPollInterval","getHeight","sendTransaction","pollForQueries","oracleId","onQuery","_ref","_interval","interval","onNode","options","knownQueryIds","Set","checkNewQueries","_await$onNode$getOrac","queries","getOracleQueriesByPubkey","oracleQueries","filter","_ref2","id","has","forEach","query","add","stopped","catch","console","error","pollForQueryResponse","queryId","_ref3","_interval2","height","ttl","response","getOracleQueryByPubkeyAndQueryId","responseBuffer","length","toString","getQueryObject","record","decodedQuery","decodedResponse","respond","opt","respondToQuery","pollForResponse","postQueryToOracle","_options$queryFee","queryFee","getOracleByPubkey","senderId","onAccount","address","oracleQueryTx","queryTtlType","type","queryTtlValue","value","responseTtlType","responseTtlValue","tag","OracleQueryTx","nonce","extendOracleTtl","OracleAddress","oracleExtendTx","oracleTtlType","oracleTtlValue","OracleExtendTx","getOracleObject","oracleRespondTx","OracleResponseTx","pollQueries","postQuery","extendOracle","getQuery","_ref4","name","handler","_len","arguments","args","Array","_key","lastArg","constructor","Object","assign","push","includes","registerOracle","queryFormat","responseFormat","accountId","oracleRegisterTx","OracleRegisterTx"],"sources":["../src/oracle.ts"],"sourcesContent":["/**\n * Oracle methods - routines to interact with the æternity oracle system\n *\n * The high-level description of the oracle system is\n * https://github.com/aeternity/protocol/blob/master/ORACLE.md in the protocol\n * repository.\n */\n\nimport { mapObject, pause } from './utils/other';\nimport { oracleQueryId } from './tx/builder/helpers';\nimport { unpackTx, buildTxAsync, BuildTxOptions } from './tx/builder';\nimport {\n ORACLE_TTL,\n ORACLE_TTL_TYPES,\n QUERY_TTL,\n RESPONSE_TTL,\n} from './tx/builder/schema';\nimport { Tag } from './tx/builder/constants';\nimport { RequestTimedOutError } from './utils/errors';\nimport {\n decode, encode, Encoded, Encoding,\n} from './utils/encoder';\nimport {\n _getPollInterval, getHeight, sendTransaction, SendTransactionOptions,\n} from './chain';\nimport Node from './Node';\nimport AccountBase from './account/Base';\n\ntype OracleQueries = Awaited<ReturnType<Node['getOracleQueriesByPubkey']>>['oracleQueries'];\n\n/**\n * Poll for oracle queries\n * @category oracle\n * @param oracleId - Oracle public key\n * @param onQuery - OnQuery callback\n * @param options - Options object\n * @param options.interval - Poll interval(default: 5000)\n * @param options.onNode - Node to use\n * @returns Callback to stop polling function\n */\nexport function pollForQueries(\n oracleId: Encoded.OracleAddress,\n onQuery: (query: OracleQueries[number]) => void,\n { interval, onNode, ...options }: { interval?: number; onNode: Node }\n & Parameters<typeof _getPollInterval>[1],\n): () => void {\n interval ??= _getPollInterval('microblock', options);\n const knownQueryIds = new Set();\n const checkNewQueries = async (): Promise<void> => {\n const queries = ((await onNode.getOracleQueriesByPubkey(oracleId)).oracleQueries ?? [])\n .filter(({ id }) => !knownQueryIds.has(id));\n queries.forEach((query) => {\n knownQueryIds.add(query.id);\n onQuery(query);\n });\n };\n\n let stopped = false;\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (async () => {\n while (!stopped) { // eslint-disable-line no-unmodified-loop-condition\n // TODO: allow to handle this error somehow\n await checkNewQueries().catch(console.error);\n await pause(interval);\n }\n })();\n return () => { stopped = true; };\n}\n\n/**\n * Poll for oracle query response\n * @category oracle\n * @param oracleId - Oracle public key\n * @param queryId - Oracle Query id\n * @param options - Options object\n * @param options.interval - Poll interval\n * @param options.onNode - Node to use\n * @returns OracleQuery object\n */\nexport async function pollForQueryResponse(\n oracleId: Encoded.OracleAddress,\n queryId: Encoded.OracleQueryId,\n { interval, onNode, ...options }:\n { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<string> {\n interval ??= _getPollInterval('microblock', options);\n let height;\n let ttl;\n let response;\n do {\n ({ response, ttl } = await onNode.getOracleQueryByPubkeyAndQueryId(oracleId, queryId));\n const responseBuffer = decode(response as Encoded.OracleResponse);\n if (responseBuffer.length > 0) return responseBuffer.toString();\n await pause(interval);\n height = await getHeight({ onNode });\n } while (ttl >= height);\n throw new RequestTimedOutError(height);\n}\n\n/**\n * Constructor for OracleQuery Object (helper object for using OracleQuery)\n * @category oracle\n * @param oracleId - Oracle public key\n * @param queryId - Oracle Query id\n * @param options - Options\n * @returns OracleQuery object\n */\nexport async function getQueryObject(\n oracleId: Encoded.OracleAddress,\n queryId: Encoded.OracleQueryId,\n options: RespondToQueryOptions & Parameters<typeof pollForQueryResponse>[2],\n): Promise<GetQueryObjectReturnType> {\n const record = await options.onNode.getOracleQueryByPubkeyAndQueryId(oracleId, queryId);\n return {\n ...record,\n decodedQuery: decode(record.query as Encoded.OracleQueryId).toString(),\n decodedResponse: decode(record.response as Encoded.OracleResponse).toString(),\n respond: async (response, opt) => (\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n respondToQuery(queryId, response, { ...options, ...opt })\n ),\n pollForResponse: async (opt) => pollForQueryResponse(oracleId, queryId, { ...options, ...opt }),\n };\n}\n\ninterface GetQueryObjectReturnType extends Awaited<ReturnType<Node['getOracleQueryByPubkeyAndQueryId']>> {\n decodedQuery: string;\n decodedResponse: string;\n respond: (response: string, options?: Parameters<typeof respondToQuery>[2]) =>\n ReturnType<typeof respondToQuery>;\n pollForResponse: (options?: Parameters<typeof pollForQueryResponse>[2]) =>\n ReturnType<typeof pollForQueryResponse>;\n}\n\n/**\n * Post query to oracle\n * @category oracle\n * @param oracleId - Oracle public key\n * @param query - Oracle query object\n * @param options - Options object\n * @param options.queryTtl - queryTtl Oracle query time to leave\n * @param options.responseTtl - queryFee Oracle query response time to leave\n * @param options.queryFee - queryFee Oracle query fee\n * @param options.fee - fee Transaction fee\n * @param options.ttl - Transaction time to leave\n * @returns Query object\n */\nexport async function postQueryToOracle(\n oracleId: Encoded.OracleAddress,\n query: string,\n options: PostQueryToOracleOptions,\n): Promise<\n Awaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getQueryObject>>\n > {\n options.queryFee ??= (await options.onNode.getOracleByPubkey(oracleId)).queryFee.toString();\n const senderId = options.onAccount.address;\n\n const oracleQueryTx = await buildTxAsync({\n queryTtlType: QUERY_TTL.type,\n queryTtlValue: QUERY_TTL.value,\n responseTtlType: RESPONSE_TTL.type,\n responseTtlValue: RESPONSE_TTL.value,\n ...options,\n tag: Tag.OracleQueryTx,\n oracleId,\n senderId,\n query,\n });\n const { nonce } = unpackTx(oracleQueryTx, Tag.OracleQueryTx);\n const queryId = oracleQueryId(senderId, nonce, oracleId);\n return {\n ...await sendTransaction(oracleQueryTx, options),\n ...await getQueryObject(oracleId, queryId, options),\n };\n}\n\ntype PostQueryToOracleOptionsType = Parameters<typeof sendTransaction>[1]\n& Parameters<typeof getQueryObject>[2]\n& BuildTxOptions<Tag.OracleQueryTx, 'oracleId' | 'senderId' | 'query' | 'queryTtlType' | 'queryTtlValue' | 'responseTtlType' | 'responseTtlValue'>\n& {\n queryTtlType?: ORACLE_TTL_TYPES;\n queryTtlValue?: number;\n responseTtlType?: ORACLE_TTL_TYPES;\n responseTtlValue?: number;\n};\ninterface PostQueryToOracleOptions extends PostQueryToOracleOptionsType {}\n\n/**\n * Extend oracle ttl\n * @category oracle\n * @param options - Options object\n * @param options.fee - fee Transaction fee\n * @param options.ttl - Transaction time to leave\n * @param options.oracleTtlType - Oracle time to leave for extend\n * @param options.oracleTtlValue - Oracle time to leave for extend\n * @returns Oracle object\n */\nexport async function extendOracleTtl(options: ExtendOracleTtlOptions): Promise<\nAwaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getOracleObject>>\n> {\n const oracleId = encode(decode(options.onAccount.address), Encoding.OracleAddress);\n const oracleExtendTx = await buildTxAsync({\n oracleTtlType: ORACLE_TTL.type,\n oracleTtlValue: ORACLE_TTL.value,\n ...options,\n tag: Tag.OracleExtendTx,\n oracleId,\n });\n return {\n ...await sendTransaction(oracleExtendTx, options),\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n ...await getOracleObject(oracleId, options),\n };\n}\n\ntype ExtendOracleTtlOptionsType = SendTransactionOptions & Parameters<typeof getOracleObject>[1]\n& BuildTxOptions<Tag.OracleExtendTx, 'oracleTtlType' | 'oracleTtlValue' | 'callerId' | 'oracleId'>\n& { oracleTtlType?: ORACLE_TTL_TYPES; oracleTtlValue?: number };\ninterface ExtendOracleTtlOptions extends ExtendOracleTtlOptionsType {}\n\n/**\n * Extend oracle ttl\n * @category oracle\n * @param queryId - Oracle query id\n * @param response - Oracle query response\n * @param options - Options object\n * @param options.responseTtl - responseTtl Query response time to leave\n * @param options.fee - Transaction fee\n * @param options.ttl - Transaction time to leave\n * @returns Oracle object\n */\nexport async function respondToQuery(\n queryId: Encoded.OracleQueryId,\n response: string,\n options: RespondToQueryOptions,\n): Promise<\n Awaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getOracleObject>>\n > {\n const oracleId = encode(decode(options.onAccount.address), Encoding.OracleAddress);\n const oracleRespondTx = await buildTxAsync({\n responseTtlType: RESPONSE_TTL.type,\n responseTtlValue: RESPONSE_TTL.value,\n ...options,\n tag: Tag.OracleResponseTx,\n oracleId,\n queryId,\n response,\n });\n return {\n ...await sendTransaction(oracleRespondTx, options),\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n ...await getOracleObject(oracleId, options),\n };\n}\n\ntype RespondToQueryOptionsType = SendTransactionOptions & Parameters<typeof getOracleObject>[1]\n& BuildTxOptions<Tag.OracleResponseTx, 'callerId' | 'oracleId' | 'queryId' | 'response' | 'responseTtlType' | 'responseTtlValue'>\n& { responseTtlType?: ORACLE_TTL_TYPES; responseTtlValue?: number };\ninterface RespondToQueryOptions extends RespondToQueryOptionsType {}\n\n/**\n * Constructor for Oracle Object (helper object for using Oracle)\n * @category oracle\n * @param oracleId - Oracle public key\n * @param options - Options\n * @returns Oracle object\n */\nexport async function getOracleObject(\n oracleId: Encoded.OracleAddress,\n options: { onNode: Node; onAccount: AccountBase },\n): Promise<GetOracleObjectReturnType> {\n return {\n ...await options.onNode.getOracleByPubkey(oracleId),\n queries: (await options.onNode.getOracleQueriesByPubkey(oracleId)).oracleQueries,\n ...mapObject<Function, Function>(\n {\n pollQueries: pollForQueries,\n postQuery: postQueryToOracle,\n respondToQuery,\n extendOracle: extendOracleTtl,\n getQuery: getQueryObject,\n },\n ([name, handler]) => [\n name,\n (...args: any) => {\n const lastArg = args[args.length - 1];\n if (lastArg != null && typeof lastArg === 'object' && lastArg.constructor === Object) {\n Object.assign(lastArg, { ...options, ...lastArg });\n } else args.push(options);\n return handler(\n ...['extendOracle', 'respondToQuery'].includes(name) ? [] : [oracleId],\n ...args,\n );\n },\n ],\n ),\n } as any;\n}\n\ninterface GetOracleObjectReturnType extends Awaited<ReturnType<Node['getOracleByPubkey']>> {\n id: Encoded.OracleAddress;\n queries: OracleQueries;\n // TODO: replace getOracleObject with a class\n pollQueries: (cb: Parameters<typeof pollForQueries>[1]) => ReturnType<typeof pollForQueries>;\n postQuery: Function;\n respondToQuery: Function;\n extendOracle: Function;\n getQuery: Function;\n}\n\n/**\n * Register oracle\n * @category oracle\n * @param queryFormat - Format of query\n * @param responseFormat - Format of query response\n * @param options - Options\n * @param options.queryFee - Oracle query Fee\n * @param options - Options object\n * @param options.abiVersion - Always 0 (do not use virtual machine)\n * @param options.fee - Transaction fee\n * @param options.ttl - Transaction time to leave\n * @returns Oracle object\n */\nexport async function registerOracle(\n queryFormat: string,\n responseFormat: string,\n options: RegisterOracleOptions,\n): Promise<\n Awaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getOracleObject>>\n > {\n const accountId = options.onAccount.address;\n const oracleRegisterTx = await buildTxAsync({\n oracleTtlValue: ORACLE_TTL.value,\n oracleTtlType: ORACLE_TTL.type,\n ...options,\n tag: Tag.OracleRegisterTx,\n accountId,\n queryFormat,\n responseFormat,\n });\n return {\n ...await sendTransaction(oracleRegisterTx, options),\n ...await getOracleObject(encode(decode(accountId), Encoding.OracleAddress), options),\n };\n}\n\ntype RegisterOracleOptionsType = SendTransactionOptions & Parameters<typeof getOracleObject>[1]\n& BuildTxOptions<Tag.OracleRegisterTx, 'accountId' | 'queryFormat' | 'responseFormat' | 'oracleTtlType' | 'oracleTtlValue'>\n& {\n oracleTtlType?: ORACLE_TTL_TYPES;\n oracleTtlValue?: number;\n};\ninterface RegisterOracleOptions extends RegisterOracleOptionsType {}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,SAQSA,SAAS,EAAEC,KAAK;AAAA,SAChBC,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s","names":["mapObject","pause","oracleQueryId","unpackTx","buildTxAsync","ORACLE_TTL","QUERY_TTL","RESPONSE_TTL","Tag","RequestTimedOutError","decode","encode","Encoding","_getPollInterval","getHeight","sendTransaction","pollForQueries","oracleId","onQuery","_ref","_interval","interval","onNode","options","knownQueryIds","Set","checkNewQueries","_await$onNode$getOrac","queries","getOracleQueriesByPubkey","oracleQueries","filter","_ref2","id","has","forEach","query","add","stopped","catch","console","error","pollForQueryResponse","queryId","_ref3","_interval2","height","ttl","response","getOracleQueryByPubkeyAndQueryId","responseBuffer","length","toString","getQueryObject","record","decodedQuery","decodedResponse","respond","opt","respondToQuery","pollForResponse","postQueryToOracle","_options$queryFee","queryFee","getOracleByPubkey","senderId","onAccount","address","oracleQueryTx","queryTtlType","type","queryTtlValue","value","responseTtlType","responseTtlValue","tag","OracleQueryTx","nonce","extendOracleTtl","OracleAddress","oracleExtendTx","oracleTtlType","oracleTtlValue","OracleExtendTx","getOracleObject","oracleRespondTx","OracleResponseTx","pollQueries","postQuery","extendOracle","getQuery","_ref4","name","handler","_len","arguments","args","Array","_key","lastArg","constructor","Object","assign","push","includes","registerOracle","queryFormat","responseFormat","accountId","oracleRegisterTx","OracleRegisterTx"],"sources":["../src/oracle.ts"],"sourcesContent":["/**\n * Oracle methods - routines to interact with the æternity oracle system\n *\n * The high-level description of the oracle system is\n * https://github.com/aeternity/protocol/blob/master/ORACLE.md in the protocol\n * repository.\n */\n\nimport { mapObject, pause } from './utils/other';\nimport { oracleQueryId } from './tx/builder/helpers';\nimport { unpackTx, buildTxAsync, BuildTxOptions } from './tx/builder';\nimport {\n ORACLE_TTL,\n ORACLE_TTL_TYPES,\n QUERY_TTL,\n RESPONSE_TTL,\n} from './tx/builder/schema';\nimport { Tag } from './tx/builder/constants';\nimport { RequestTimedOutError } from './utils/errors';\nimport {\n decode, encode, Encoded, Encoding,\n} from './utils/encoder';\nimport {\n _getPollInterval, getHeight, sendTransaction, SendTransactionOptions,\n} from './chain';\nimport Node from './Node';\nimport AccountBase from './account/Base';\n\ntype OracleQueries = Awaited<ReturnType<Node['getOracleQueriesByPubkey']>>['oracleQueries'];\n\n/**\n * Poll for oracle queries\n * @category oracle\n * @param oracleId - Oracle public key\n * @param onQuery - OnQuery callback\n * @param options - Options object\n * @param options.interval - Poll interval(default: 5000)\n * @param options.onNode - Node to use\n * @returns Callback to stop polling function\n */\nexport function pollForQueries(\n oracleId: Encoded.OracleAddress,\n onQuery: (query: OracleQueries[number]) => void,\n { interval, onNode, ...options }: { interval?: number; onNode: Node }\n & Parameters<typeof _getPollInterval>[1],\n): () => void {\n interval ??= _getPollInterval('microblock', options);\n const knownQueryIds = new Set();\n const checkNewQueries = async (): Promise<void> => {\n const queries = ((await onNode.getOracleQueriesByPubkey(oracleId)).oracleQueries ?? [])\n .filter(({ id }) => !knownQueryIds.has(id));\n queries.forEach((query) => {\n knownQueryIds.add(query.id);\n onQuery(query);\n });\n };\n\n let stopped = false;\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (async () => {\n while (!stopped) { // eslint-disable-line no-unmodified-loop-condition\n // TODO: allow to handle this error somehow\n await checkNewQueries().catch(console.error);\n await pause(interval);\n }\n })();\n return () => { stopped = true; };\n}\n\n/**\n * Poll for oracle query response\n * @category oracle\n * @param oracleId - Oracle public key\n * @param queryId - Oracle Query id\n * @param options - Options object\n * @param options.interval - Poll interval\n * @param options.onNode - Node to use\n * @returns OracleQuery object\n */\nexport async function pollForQueryResponse(\n oracleId: Encoded.OracleAddress,\n queryId: Encoded.OracleQueryId,\n { interval, onNode, ...options }:\n { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<string> {\n interval ??= _getPollInterval('microblock', options);\n let height;\n let ttl;\n let response;\n do {\n ({ response, ttl } = await onNode.getOracleQueryByPubkeyAndQueryId(oracleId, queryId));\n const responseBuffer = decode(response as Encoded.OracleResponse);\n if (responseBuffer.length > 0) return responseBuffer.toString();\n await pause(interval);\n height = await getHeight({ onNode });\n } while (ttl >= height);\n throw new RequestTimedOutError(height);\n}\n\n/**\n * Constructor for OracleQuery Object (helper object for using OracleQuery)\n * @category oracle\n * @param oracleId - Oracle public key\n * @param queryId - Oracle Query id\n * @param options - Options\n * @returns OracleQuery object\n */\nexport async function getQueryObject(\n oracleId: Encoded.OracleAddress,\n queryId: Encoded.OracleQueryId,\n options: RespondToQueryOptions & Parameters<typeof pollForQueryResponse>[2],\n): Promise<GetQueryObjectReturnType> {\n const record = await options.onNode.getOracleQueryByPubkeyAndQueryId(oracleId, queryId);\n return {\n ...record,\n decodedQuery: decode(record.query as Encoded.OracleQueryId).toString(),\n decodedResponse: decode(record.response as Encoded.OracleResponse).toString(),\n respond: async (response, opt) => (\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n respondToQuery(queryId, response, { ...options, ...opt })\n ),\n pollForResponse: async (opt) => pollForQueryResponse(oracleId, queryId, { ...options, ...opt }),\n };\n}\n\ninterface GetQueryObjectReturnType extends Awaited<ReturnType<Node['getOracleQueryByPubkeyAndQueryId']>> {\n decodedQuery: string;\n decodedResponse: string;\n respond: (response: string, options?: Parameters<typeof respondToQuery>[2]) =>\n ReturnType<typeof respondToQuery>;\n pollForResponse: (options?: Parameters<typeof pollForQueryResponse>[2]) =>\n ReturnType<typeof pollForQueryResponse>;\n}\n\n/**\n * Post query to oracle\n * @category oracle\n * @param oracleId - Oracle public key\n * @param query - Oracle query object\n * @param options - Options object\n * @param options.queryTtl - queryTtl Oracle query time to leave\n * @param options.responseTtl - queryFee Oracle query response time to leave\n * @param options.queryFee - queryFee Oracle query fee\n * @param options.fee - fee Transaction fee\n * @param options.ttl - Transaction time to leave\n * @returns Query object\n */\nexport async function postQueryToOracle(\n oracleId: Encoded.OracleAddress,\n query: string,\n options: PostQueryToOracleOptions,\n): Promise<\n Awaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getQueryObject>>\n > {\n options.queryFee ??= (await options.onNode.getOracleByPubkey(oracleId)).queryFee.toString();\n const senderId = options.onAccount.address;\n\n const oracleQueryTx = await buildTxAsync({\n queryTtlType: QUERY_TTL.type,\n queryTtlValue: QUERY_TTL.value,\n responseTtlType: RESPONSE_TTL.type,\n responseTtlValue: RESPONSE_TTL.value,\n ...options,\n tag: Tag.OracleQueryTx,\n oracleId,\n senderId,\n query,\n });\n const { nonce } = unpackTx(oracleQueryTx, Tag.OracleQueryTx);\n const queryId = oracleQueryId(senderId, nonce, oracleId);\n return {\n ...await sendTransaction(oracleQueryTx, options),\n ...await getQueryObject(oracleId, queryId, options),\n };\n}\n\ntype PostQueryToOracleOptionsType = Parameters<typeof sendTransaction>[1]\n& Parameters<typeof getQueryObject>[2]\n& BuildTxOptions<Tag.OracleQueryTx, 'oracleId' | 'senderId' | 'query' | 'queryTtlType' | 'queryTtlValue' | 'responseTtlType' | 'responseTtlValue'>\n& {\n queryTtlType?: ORACLE_TTL_TYPES;\n queryTtlValue?: number;\n responseTtlType?: ORACLE_TTL_TYPES;\n responseTtlValue?: number;\n};\ninterface PostQueryToOracleOptions extends PostQueryToOracleOptionsType {}\n\n/**\n * Extend oracle ttl\n * @category oracle\n * @param options - Options object\n * @param options.fee - fee Transaction fee\n * @param options.ttl - Transaction time to leave\n * @param options.oracleTtlType - Oracle time to leave for extend\n * @param options.oracleTtlValue - Oracle time to leave for extend\n * @returns Oracle object\n */\nexport async function extendOracleTtl(options: ExtendOracleTtlOptions): Promise<\nAwaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getOracleObject>>\n> {\n const oracleId = encode(decode(options.onAccount.address), Encoding.OracleAddress);\n const oracleExtendTx = await buildTxAsync({\n oracleTtlType: ORACLE_TTL.type,\n oracleTtlValue: ORACLE_TTL.value,\n ...options,\n tag: Tag.OracleExtendTx,\n oracleId,\n });\n return {\n ...await sendTransaction(oracleExtendTx, options),\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n ...await getOracleObject(oracleId, options),\n };\n}\n\ntype ExtendOracleTtlOptionsType = SendTransactionOptions & Parameters<typeof getOracleObject>[1]\n& BuildTxOptions<Tag.OracleExtendTx, 'oracleTtlType' | 'oracleTtlValue' | 'callerId' | 'oracleId'>\n& { oracleTtlType?: ORACLE_TTL_TYPES; oracleTtlValue?: number };\ninterface ExtendOracleTtlOptions extends ExtendOracleTtlOptionsType {}\n\n/**\n * Extend oracle ttl\n * @category oracle\n * @param queryId - Oracle query id\n * @param response - Oracle query response\n * @param options - Options object\n * @param options.responseTtl - responseTtl Query response time to leave\n * @param options.fee - Transaction fee\n * @param options.ttl - Transaction time to leave\n * @returns Oracle object\n */\nexport async function respondToQuery(\n queryId: Encoded.OracleQueryId,\n response: string,\n options: RespondToQueryOptions,\n): Promise<\n Awaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getOracleObject>>\n > {\n const oracleId = encode(decode(options.onAccount.address), Encoding.OracleAddress);\n const oracleRespondTx = await buildTxAsync({\n responseTtlType: RESPONSE_TTL.type,\n responseTtlValue: RESPONSE_TTL.value,\n ...options,\n tag: Tag.OracleResponseTx,\n oracleId,\n queryId,\n response,\n });\n return {\n ...await sendTransaction(oracleRespondTx, options),\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n ...await getOracleObject(oracleId, options),\n };\n}\n\ntype RespondToQueryOptionsType = SendTransactionOptions & Parameters<typeof getOracleObject>[1]\n& BuildTxOptions<Tag.OracleResponseTx, 'callerId' | 'oracleId' | 'queryId' | 'response' | 'responseTtlType' | 'responseTtlValue'>\n& { responseTtlType?: ORACLE_TTL_TYPES; responseTtlValue?: number };\ninterface RespondToQueryOptions extends RespondToQueryOptionsType {}\n\n/**\n * Constructor for Oracle Object (helper object for using Oracle)\n * @category oracle\n * @param oracleId - Oracle public key\n * @param options - Options\n * @returns Oracle object\n */\nexport async function getOracleObject(\n oracleId: Encoded.OracleAddress,\n options: { onNode: Node; onAccount: AccountBase },\n): Promise<GetOracleObjectReturnType> {\n return {\n ...await options.onNode.getOracleByPubkey(oracleId),\n queries: (await options.onNode.getOracleQueriesByPubkey(oracleId)).oracleQueries,\n ...mapObject<Function, Function>(\n {\n pollQueries: pollForQueries,\n postQuery: postQueryToOracle,\n respondToQuery,\n extendOracle: extendOracleTtl,\n getQuery: getQueryObject,\n },\n ([name, handler]) => [\n name,\n (...args: any) => {\n const lastArg = args[args.length - 1];\n if (lastArg != null && typeof lastArg === 'object' && lastArg.constructor === Object) {\n Object.assign(lastArg, { ...options, ...lastArg });\n } else args.push(options);\n return handler(\n ...['extendOracle', 'respondToQuery'].includes(name) ? [] : [oracleId],\n ...args,\n );\n },\n ],\n ),\n } as any;\n}\n\ninterface GetOracleObjectReturnType extends Awaited<ReturnType<Node['getOracleByPubkey']>> {\n id: Encoded.OracleAddress;\n queries: OracleQueries;\n // TODO: replace getOracleObject with a class\n pollQueries: (cb: Parameters<typeof pollForQueries>[1]) => ReturnType<typeof pollForQueries>;\n postQuery: Function;\n respondToQuery: Function;\n extendOracle: Function;\n getQuery: Function;\n}\n\n/**\n * Register oracle\n * @category oracle\n * @param queryFormat - Format of query\n * @param responseFormat - Format of query response\n * @param options - Options\n * @param options.queryFee - Oracle query Fee\n * @param options - Options object\n * @param options.abiVersion - Always 0 (do not use virtual machine)\n * @param options.fee - Transaction fee\n * @param options.ttl - Transaction time to leave\n * @returns Oracle object\n */\nexport async function registerOracle(\n queryFormat: string,\n responseFormat: string,\n options: RegisterOracleOptions,\n): Promise<\n Awaited<ReturnType<typeof sendTransaction>> & Awaited<ReturnType<typeof getOracleObject>>\n > {\n const accountId = options.onAccount.address;\n const oracleRegisterTx = await buildTxAsync({\n oracleTtlValue: ORACLE_TTL.value,\n oracleTtlType: ORACLE_TTL.type,\n ...options,\n tag: Tag.OracleRegisterTx,\n accountId,\n queryFormat,\n responseFormat,\n });\n return {\n ...await sendTransaction(oracleRegisterTx, options),\n ...await getOracleObject(encode(decode(accountId), Encoding.OracleAddress), options),\n };\n}\n\ntype RegisterOracleOptionsType = SendTransactionOptions & Parameters<typeof getOracleObject>[1]\n& BuildTxOptions<Tag.OracleRegisterTx, 'accountId' | 'queryFormat' | 'responseFormat' | 'oracleTtlType' | 'oracleTtlValue'>\n& {\n oracleTtlType?: ORACLE_TTL_TYPES;\n oracleTtlValue?: number;\n};\ninterface RegisterOracleOptions extends RegisterOracleOptionsType {}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,SAQSA,SAAS,EAAEC,KAAK;AAAA,SAChBC,aAAa;AAAA,SACbC,QAAQ,EAAEC,YAAY;AAAA,SAE7BC,UAAU,EAEVC,SAAS,EACTC,YAAY;AAAA,SAELC,GAAG;AAAA,SACHC,oBAAoB;AAAA,SAE3BC,MAAM,EAAEC,MAAM,EAAWC,QAAQ;AAAA,SAGjCC,gBAAgB,EAAEC,SAAS,EAAEC,eAAe;AAO9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAC5BC,QAA+B,EAC/BC,OAA+C,EAAAC,IAAA,EAGnC;EAAA,IAAAC,SAAA;EAAA,IAFZ;IAAEC,QAAQ;IAAEC,MAAM;IAAE,GAAGC;EACgB,CAAC,GAAAJ,IAAA;EAExC,CAAAC,SAAA,GAAAC,QAAQ,cAAAD,SAAA,cAAAA,SAAA,GAARC,QAAQ,GAAKR,gBAAgB,CAAC,YAAY,EAAEU,OAAO,CAAC;EACpD,MAAMC,aAAa,GAAG,IAAIC,GAAG,CAAC,CAAC;EAC/B,MAAMC,eAAe,GAAG,MAAAA,CAAA,KAA2B;IAAA,IAAAC,qBAAA;IACjD,MAAMC,OAAO,GAAG,EAAAD,qBAAA,GAAC,CAAC,MAAML,MAAM,CAACO,wBAAwB,CAACZ,QAAQ,CAAC,EAAEa,aAAa,cAAAH,qBAAA,cAAAA,qBAAA,GAAI,EAAE,EACnFI,MAAM,CAACC,KAAA;MAAA,IAAC;QAAEC;MAAG,CAAC,GAAAD,KAAA;MAAA,OAAK,CAACR,aAAa,CAACU,GAAG,CAACD,EAAE,CAAC;IAAA,EAA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