@aeternity/aepp-sdk 13.0.0 → 13.0.1

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.
@@ -4,7 +4,6 @@
4
4
  * High level documentation of the contracts are available at
5
5
  * https://github.com/aeternity/protocol/tree/master/contracts and
6
6
  */
7
- /// <reference types="@aeternity__aepp-calldata" />
8
7
  import { Encoder as Calldata } from '@aeternity/aepp-calldata';
9
8
  import { Tag, AensName } from '../tx/builder/constants';
10
9
  import { BuildTxOptions } from '../tx/builder';
@@ -36,7 +35,7 @@ interface SendAndProcessReturnType {
36
35
  result?: ContractCallObject;
37
36
  hash: TxData['hash'];
38
37
  tx: TxUnpacked & {
39
- tag: Tag.ContractCallTx | Tag.ContractCreateTx;
38
+ tag: Tag.SignedTx | Tag.ContractCallTx | Tag.ContractCreateTx;
40
39
  };
41
40
  txData: TxData;
42
41
  rawTx: Encoded.Transaction;
@@ -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.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 );\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,sBAAs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AM,CAACE,GAAG,CAAEC,KAAS,IAC5C,CAACxD,IAAI,EAAEkE,MAAM,CAAC4B,IAAI,CAACtC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAEU,MAAM,CAACkE,MAAM,CAAC5E,KAAK,CAAC,CAAC,CAAC,CAAC,CACtD,CAAC;EAAA,EAAC,CACF6E,IAAI,EAAE,CACNhE,MAAM,CAACiE,KAAA;IAAA,IAAC,GAAGC,SAAS,CAAC,GAAAD,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 );\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,oBAAAC,OAAA;AAAA,IAAAC,eAAA,oBAAAD,OAAA;AAAA,IAAAE,eAAA,oBAAAF,OAAA;AAAA,IAAAG,uBAAA,oBAAAH,OAAA;AAAA,IAAAI,YAAA,oBAAAC,OAAA;AAqEtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,QAAQ,CAAgC;EAC5C;AACF;AACA;AACA;EACE,MAAMC,QAAQA,CAAA,EAAuC;IACnD,IAAI,IAAI,CAACC,QAAQ,CAACC,QAAQ,IAAI,IAAI,EAAE,OAAO,IAAI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;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"}
@@ -4,6 +4,23 @@ import Node from '../Node';
4
4
  * Calculates the cost of transaction execution
5
5
  * Provides an upper cost of contract-call-related transactions because of `gasLimit`.
6
6
  * Also assumes that oracle query fee is 0 unless it is provided in options.
7
+ *
8
+ * The idea is that if you need to show transaction details with some accuracy you can define
9
+ * expense fields that you want to show separately. And to show `getExecutionCost` result as a fee,
10
+ * subtracting all fields shown separately.
11
+ *
12
+ * @example
13
+ * ```vue
14
+ * <template>
15
+ * Amount: {{ txUnpacked.amount }}
16
+ * Name fee: {{ txUnpacked.nameFee }}
17
+ * Other fees: {{ getExecutionCost(txEncoded) - txUnpacked.amount - txUnpacked.nameFee }}
18
+ * </template>
19
+ * ```
20
+ *
21
+ * Doing this way you won't worry to show wrong fee for a transaction you may not support. Because
22
+ * the SDK calculates the overall price of any transaction on its side.
23
+ *
7
24
  * @param transaction - Transaction to calculate the cost of
8
25
  * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx
9
26
  * @param gasUsed - Amount of gas actually used to make calculation more accurate
@@ -8,6 +8,23 @@ import getTransactionSignerAddress from "./transaction-signer.mjs";
8
8
  * Calculates the cost of transaction execution
9
9
  * Provides an upper cost of contract-call-related transactions because of `gasLimit`.
10
10
  * Also assumes that oracle query fee is 0 unless it is provided in options.
11
+ *
12
+ * The idea is that if you need to show transaction details with some accuracy you can define
13
+ * expense fields that you want to show separately. And to show `getExecutionCost` result as a fee,
14
+ * subtracting all fields shown separately.
15
+ *
16
+ * @example
17
+ * ```vue
18
+ * <template>
19
+ * Amount: {{ txUnpacked.amount }}
20
+ * Name fee: {{ txUnpacked.nameFee }}
21
+ * Other fees: {{ getExecutionCost(txEncoded) - txUnpacked.amount - txUnpacked.nameFee }}
22
+ * </template>
23
+ * ```
24
+ *
25
+ * Doing this way you won't worry to show wrong fee for a transaction you may not support. Because
26
+ * the SDK calculates the overall price of any transaction on its side.
27
+ *
11
28
  * @param transaction - Transaction to calculate the cost of
12
29
  * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx
13
30
  * @param gasUsed - Amount of gas actually used to make calculation more accurate
@@ -1 +1 @@
1
- {"version":3,"file":"execution-cost.mjs","names":["buildTx","buildTxHash","unpackTx","Tag","verify","getBufferToSign","IllegalArgumentError","InternalError","TransactionError","getTransactionSignerAddress","getExecutionCost","transaction","innerTx","gasUsed","queryFee","isInitiator","arguments","length","undefined","params","tag","SignedTx","res","BigInt","fee","NameClaimTx","nameFee","OracleQueryTx","OracleResponseTx","ChannelSettleTx","initiatorAmountFinal","responderAmountFinal","SpendTx","senderId","recipientId","ContractCreateTx","ContractCallTx","ChannelDepositTx","amount","deposit","GaAttachTx","GaMetaTx","gasPrice","gasLimit","PayingForTx","tx","encodedTx","getExecutionCostBySignedTx","networkId","options","address","isInnerTx","isNotInnerTx","map","f","signatures","getExecutionCostUsingNode","node","isMined","isSignedTx","txHash","includes","callInfo","gaInfo","getTransactionInfoByHash","combinedInfo","getOracleByPubkey","oracleId","toString","initiatorId","getChannelByPubkey","channelId","fromId","getNetworkId"],"sources":["../../src/tx/execution-cost.ts"],"sourcesContent":["import { Encoded } from '../utils/encoder';\nimport { buildTx, buildTxHash, unpackTx } from './builder';\nimport { Tag } from './builder/constants';\nimport { verify } from '../utils/crypto';\nimport { getBufferToSign } from '../account/Memory';\nimport { IllegalArgumentError, InternalError, TransactionError } from '../utils/errors';\nimport Node from '../Node';\nimport getTransactionSignerAddress from './transaction-signer';\n\n/**\n * Calculates the cost of transaction execution\n * Provides an upper cost of contract-call-related transactions because of `gasLimit`.\n * Also assumes that oracle query fee is 0 unless it is provided in options.\n * @param transaction - Transaction to calculate the cost of\n * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx\n * @param gasUsed - Amount of gas actually used to make calculation more accurate\n * @param queryFee - Oracle query fee\n * @param isInitiator - Is transaction signer an initiator of state channel\n */\nexport function getExecutionCost(\n transaction: Encoded.Transaction,\n {\n innerTx, gasUsed, queryFee, isInitiator,\n }: {\n innerTx?: 'fee-payer' | 'freeloader';\n gasUsed?: number;\n queryFee?: string;\n isInitiator?: boolean;\n } = {},\n): bigint {\n const params = unpackTx(transaction);\n if (params.tag === Tag.SignedTx) {\n throw new IllegalArgumentError('Transaction shouldn\\'t be a SignedTx, use `getExecutionCostBySignedTx` instead');\n }\n\n let res = 0n;\n if ('fee' in params && innerTx !== 'freeloader') {\n res += BigInt(params.fee);\n }\n if (params.tag === Tag.NameClaimTx) {\n res += BigInt(params.nameFee);\n }\n if (params.tag === Tag.OracleQueryTx) {\n res += BigInt(params.queryFee);\n }\n if (params.tag === Tag.OracleResponseTx) {\n res -= BigInt(queryFee ?? 0);\n }\n if (params.tag === Tag.ChannelSettleTx) {\n if (isInitiator === true) res -= BigInt(params.initiatorAmountFinal);\n if (isInitiator === false) res -= BigInt(params.responderAmountFinal);\n }\n if (\n ((params.tag === Tag.SpendTx && params.senderId !== params.recipientId)\n || params.tag === Tag.ContractCreateTx || params.tag === Tag.ContractCallTx\n || params.tag === Tag.ChannelDepositTx) && innerTx !== 'fee-payer'\n ) {\n res += BigInt(params.amount);\n }\n if (params.tag === Tag.ContractCreateTx) res += BigInt(params.deposit);\n if (\n (params.tag === Tag.ContractCreateTx || params.tag === Tag.ContractCallTx\n || params.tag === Tag.GaAttachTx || params.tag === Tag.GaMetaTx)\n && innerTx !== 'freeloader'\n ) {\n res += BigInt(params.gasPrice) * BigInt(gasUsed ?? params.gasLimit);\n }\n if (params.tag === Tag.GaMetaTx || params.tag === Tag.PayingForTx) {\n res += getExecutionCost(\n buildTx(params.tx.encodedTx),\n params.tag === Tag.PayingForTx ? { innerTx: 'fee-payer' } : {},\n );\n }\n return res;\n}\n\n/**\n * Calculates the cost of signed transaction execution\n * @param transaction - Transaction to calculate the cost of\n * @param networkId - Network id used to sign the transaction\n * @param options - Options\n */\nexport function getExecutionCostBySignedTx(\n transaction: Encoded.Transaction,\n networkId: string,\n options?: Omit<Parameters<typeof getExecutionCost>[1], 'innerTx'>,\n): bigint {\n const params = unpackTx(transaction, Tag.SignedTx);\n if (params.encodedTx.tag === Tag.GaMetaTx) {\n return getExecutionCost(buildTx(params.encodedTx), options);\n }\n\n const tx = buildTx(params.encodedTx);\n const address = getTransactionSignerAddress(tx);\n const [isInnerTx, isNotInnerTx] = [true, false]\n .map((f) => verify(getBufferToSign(tx, networkId, f), params.signatures[0], address));\n if (!isInnerTx && !isNotInnerTx) throw new TransactionError('Can\\'t verify signature');\n return getExecutionCost(\n buildTx(params.encodedTx),\n { ...isInnerTx && { innerTx: 'freeloader' }, ...options },\n );\n}\n\n/**\n * Calculates the cost of signed and not signed transaction execution using node\n * @param transaction - Transaction to calculate the cost of\n * @param node - Node to use\n * @param isMined - Is transaction already mined or not\n * @param options - Options\n */\nexport async function getExecutionCostUsingNode(\n transaction: Encoded.Transaction,\n node: Node,\n { isMined, ...options }: { isMined?: boolean } & Parameters<typeof getExecutionCost>[1] = {},\n): Promise<bigint> {\n let params = unpackTx(transaction);\n const isSignedTx = params.tag === Tag.SignedTx;\n const txHash = isSignedTx && isMined === true && buildTxHash(transaction);\n if (params.tag === Tag.SignedTx) params = params.encodedTx;\n\n // TODO: set gasUsed for PayingForTx after solving https://github.com/aeternity/aeternity/issues/4087\n if (\n options.gasUsed == null && txHash !== false\n && [Tag.ContractCreateTx, Tag.ContractCallTx, Tag.GaAttachTx, Tag.GaMetaTx].includes(params.tag)\n ) {\n const { callInfo, gaInfo } = await node.getTransactionInfoByHash(txHash);\n const combinedInfo = callInfo ?? gaInfo;\n if (combinedInfo == null) {\n throw new InternalError(`callInfo and gaInfo is not available for transaction ${txHash}`);\n }\n options.gasUsed = combinedInfo.gasUsed;\n }\n\n if (options.queryFee == null && Tag.OracleResponseTx === params.tag) {\n options.queryFee = (await node.getOracleByPubkey(params.oracleId)).queryFee.toString();\n }\n\n if (options.isInitiator == null && Tag.ChannelSettleTx === params.tag && isMined !== true) {\n const { initiatorId } = await node.getChannelByPubkey(params.channelId);\n options.isInitiator = params.fromId === initiatorId;\n }\n\n return isSignedTx\n ? getExecutionCostBySignedTx(transaction, await node.getNetworkId(), options)\n : getExecutionCost(transaction, options);\n}\n"],"mappings":"SACSA,OAAO,EAAEC,WAAW,EAAEC,QAAQ;AAAA,SAC9BC,GAAG;AAAA,SACHC,MAAM;AAAA,SACNC,eAAe;AAAA,SACfC,oBAAoB,EAAEC,aAAa,EAAEC,gBAAgB;AAAA,OAEvDC,2BAA2B;AAElC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,gBAAgBA,CAC9BC,WAAgC,EASxB;EAAA,IARR;IACEC,OAAO;IAAEC,OAAO;IAAEC,QAAQ;IAAEC;EAM9B,CAAC,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEN,MAAMG,MAAM,GAAGjB,QAAQ,CAACS,WAAW,CAAC;EACpC,IAAIQ,MAAM,CAACC,GAAG,KAAKjB,GAAG,CAACkB,QAAQ,EAAE;IAC/B,MAAM,IAAIf,oBAAoB,CAAC,gFAAgF,CAAC;EAClH;EAEA,IAAIgB,GAAG,GAAG,EAAE;EACZ,IAAI,KAAK,IAAIH,MAAM,IAAIP,OAAO,KAAK,YAAY,EAAE;IAC/CU,GAAG,IAAIC,MAAM,CAACJ,MAAM,CAACK,GAAG,CAAC;EAC3B;EACA,IAAIL,MAAM,CAACC,GAAG,KAAKjB,GAAG,CAACsB,WAAW,EAAE;IAClCH,GAAG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M;MAAE0C,QAAQ;MAAEC;IAAO,CAAC,GAAG,MAAMN,IAAI,CAACO,wBAAwB,CAACJ,MAAM,CAAC;IACxE,MAAMK,YAAY,GAAGH,QAAQ,aAARA,QAAQ,cAARA,QAAQ,GAAIC,MAAM;IACvC,IAAIE,YAAY,IAAI,IAAI,EAAE;MACxB,MAAM,IAAI1D,aAAa,CAAE,wDAAuDqD,MAAO,EAAC,CAAC;IAC3F;IACAX,OAAO,CAACpC,OAAO,GAAGoD,YAAY,CAACpD,OAAO;EACxC;EAEA,IAAIoC,OAAO,CAACnC,QAAQ,IAAI,IAAI,IAAIX,GAAG,CAACyB,gBAAgB,KAAKT,MAAM,CAACC,GAAG,EAAE;IACnE6B,OAAO,CAACnC,QAAQ,GAAG,CAAC,MAAM2C,IAAI,CAACS,iBAAiB,CAAC/C,MAAM,CAACgD,QAAQ,CAAC,EAAErD,QAAQ,CAACsD,QAAQ,EAAE;EACxF;EAEA,IAAInB,OAAO,CAAClC,WAAW,IAAI,IAAI,IAAIZ,GAAG,CAAC0B,eAAe,KAAKV,MAAM,CAACC,GAAG,IAAIsC,OAAO,KAAK,IAAI,EAAE;IACzF,MAAM;MAAEW;IAAY,CAAC,GAAG,MAAMZ,IAAI,CAACa,kBAAkB,CAACnD,MAAM,CAACoD,SAAS,CAAC;IACvEtB,OAAO,CAAClC,WAAW,GAAGI,MAAM,CAACqD,MAAM,KAAKH,WAAW;EACrD;EAEA,OAAOV,UAAU,GACbZ,0BAA0B,CAACpC,WAAW,EAAE,MAAM8C,IAAI,CAACgB,YAAY,EAAE,EAAExB,OAAO,CAAC,GAC3EvC,gBAAgB,CAACC,WAAW,EAAEsC,OAAO,CAAC;AAC5C"}
1
+ {"version":3,"file":"execution-cost.mjs","names":["buildTx","buildTxHash","unpackTx","Tag","verify","getBufferToSign","IllegalArgumentError","InternalError","TransactionError","getTransactionSignerAddress","getExecutionCost","transaction","innerTx","gasUsed","queryFee","isInitiator","arguments","length","undefined","params","tag","SignedTx","res","BigInt","fee","NameClaimTx","nameFee","OracleQueryTx","OracleResponseTx","ChannelSettleTx","initiatorAmountFinal","responderAmountFinal","SpendTx","senderId","recipientId","ContractCreateTx","ContractCallTx","ChannelDepositTx","amount","deposit","GaAttachTx","GaMetaTx","gasPrice","gasLimit","PayingForTx","tx","encodedTx","getExecutionCostBySignedTx","networkId","options","address","isInnerTx","isNotInnerTx","map","f","signatures","getExecutionCostUsingNode","node","isMined","isSignedTx","txHash","includes","callInfo","gaInfo","getTransactionInfoByHash","combinedInfo","getOracleByPubkey","oracleId","toString","initiatorId","getChannelByPubkey","channelId","fromId","getNetworkId"],"sources":["../../src/tx/execution-cost.ts"],"sourcesContent":["import { Encoded } from '../utils/encoder';\nimport { buildTx, buildTxHash, unpackTx } from './builder';\nimport { Tag } from './builder/constants';\nimport { verify } from '../utils/crypto';\nimport { getBufferToSign } from '../account/Memory';\nimport { IllegalArgumentError, InternalError, TransactionError } from '../utils/errors';\nimport Node from '../Node';\nimport getTransactionSignerAddress from './transaction-signer';\n\n/**\n * Calculates the cost of transaction execution\n * Provides an upper cost of contract-call-related transactions because of `gasLimit`.\n * Also assumes that oracle query fee is 0 unless it is provided in options.\n *\n * The idea is that if you need to show transaction details with some accuracy you can define\n * expense fields that you want to show separately. And to show `getExecutionCost` result as a fee,\n * subtracting all fields shown separately.\n *\n * @example\n * ```vue\n * <template>\n * Amount: {{ txUnpacked.amount }}\n * Name fee: {{ txUnpacked.nameFee }}\n * Other fees: {{ getExecutionCost(txEncoded) - txUnpacked.amount - txUnpacked.nameFee }}\n * </template>\n * ```\n *\n * Doing this way you won't worry to show wrong fee for a transaction you may not support. Because\n * the SDK calculates the overall price of any transaction on its side.\n *\n * @param transaction - Transaction to calculate the cost of\n * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx\n * @param gasUsed - Amount of gas actually used to make calculation more accurate\n * @param queryFee - Oracle query fee\n * @param isInitiator - Is transaction signer an initiator of state channel\n */\nexport function getExecutionCost(\n transaction: Encoded.Transaction,\n {\n innerTx, gasUsed, queryFee, isInitiator,\n }: {\n innerTx?: 'fee-payer' | 'freeloader';\n gasUsed?: number;\n queryFee?: string;\n isInitiator?: boolean;\n } = {},\n): bigint {\n const params = unpackTx(transaction);\n if (params.tag === Tag.SignedTx) {\n throw new IllegalArgumentError('Transaction shouldn\\'t be a SignedTx, use `getExecutionCostBySignedTx` instead');\n }\n\n let res = 0n;\n if ('fee' in params && innerTx !== 'freeloader') {\n res += BigInt(params.fee);\n }\n if (params.tag === Tag.NameClaimTx) {\n res += BigInt(params.nameFee);\n }\n if (params.tag === Tag.OracleQueryTx) {\n res += BigInt(params.queryFee);\n }\n if (params.tag === Tag.OracleResponseTx) {\n res -= BigInt(queryFee ?? 0);\n }\n if (params.tag === Tag.ChannelSettleTx) {\n if (isInitiator === true) res -= BigInt(params.initiatorAmountFinal);\n if (isInitiator === false) res -= BigInt(params.responderAmountFinal);\n }\n if (\n ((params.tag === Tag.SpendTx && params.senderId !== params.recipientId)\n || params.tag === Tag.ContractCreateTx || params.tag === Tag.ContractCallTx\n || params.tag === Tag.ChannelDepositTx) && innerTx !== 'fee-payer'\n ) {\n res += BigInt(params.amount);\n }\n if (params.tag === Tag.ContractCreateTx) res += BigInt(params.deposit);\n if (\n (params.tag === Tag.ContractCreateTx || params.tag === Tag.ContractCallTx\n || params.tag === Tag.GaAttachTx || params.tag === Tag.GaMetaTx)\n && innerTx !== 'freeloader'\n ) {\n res += BigInt(params.gasPrice) * BigInt(gasUsed ?? params.gasLimit);\n }\n if (params.tag === Tag.GaMetaTx || params.tag === Tag.PayingForTx) {\n res += getExecutionCost(\n buildTx(params.tx.encodedTx),\n params.tag === Tag.PayingForTx ? { innerTx: 'fee-payer' } : {},\n );\n }\n return res;\n}\n\n/**\n * Calculates the cost of signed transaction execution\n * @param transaction - Transaction to calculate the cost of\n * @param networkId - Network id used to sign the transaction\n * @param options - Options\n */\nexport function getExecutionCostBySignedTx(\n transaction: Encoded.Transaction,\n networkId: string,\n options?: Omit<Parameters<typeof getExecutionCost>[1], 'innerTx'>,\n): bigint {\n const params = unpackTx(transaction, Tag.SignedTx);\n if (params.encodedTx.tag === Tag.GaMetaTx) {\n return getExecutionCost(buildTx(params.encodedTx), options);\n }\n\n const tx = buildTx(params.encodedTx);\n const address = getTransactionSignerAddress(tx);\n const [isInnerTx, isNotInnerTx] = [true, false]\n .map((f) => verify(getBufferToSign(tx, networkId, f), params.signatures[0], address));\n if (!isInnerTx && !isNotInnerTx) throw new TransactionError('Can\\'t verify signature');\n return getExecutionCost(\n buildTx(params.encodedTx),\n { ...isInnerTx && { innerTx: 'freeloader' }, ...options },\n );\n}\n\n/**\n * Calculates the cost of signed and not signed transaction execution using node\n * @param transaction - Transaction to calculate the cost of\n * @param node - Node to use\n * @param isMined - Is transaction already mined or not\n * @param options - Options\n */\nexport async function getExecutionCostUsingNode(\n transaction: Encoded.Transaction,\n node: Node,\n { isMined, ...options }: { isMined?: boolean } & Parameters<typeof getExecutionCost>[1] = {},\n): Promise<bigint> {\n let params = unpackTx(transaction);\n const isSignedTx = params.tag === Tag.SignedTx;\n const txHash = isSignedTx && isMined === true && buildTxHash(transaction);\n if (params.tag === Tag.SignedTx) params = params.encodedTx;\n\n // TODO: set gasUsed for PayingForTx after solving https://github.com/aeternity/aeternity/issues/4087\n if (\n options.gasUsed == null && txHash !== false\n && [Tag.ContractCreateTx, Tag.ContractCallTx, Tag.GaAttachTx, Tag.GaMetaTx].includes(params.tag)\n ) {\n const { callInfo, gaInfo } = await node.getTransactionInfoByHash(txHash);\n const combinedInfo = callInfo ?? gaInfo;\n if (combinedInfo == null) {\n throw new InternalError(`callInfo and gaInfo is not available for transaction ${txHash}`);\n }\n options.gasUsed = combinedInfo.gasUsed;\n }\n\n if (options.queryFee == null && Tag.OracleResponseTx === params.tag) {\n options.queryFee = (await node.getOracleByPubkey(params.oracleId)).queryFee.toString();\n }\n\n if (options.isInitiator == null && Tag.ChannelSettleTx === params.tag && isMined !== true) {\n const { initiatorId } = await node.getChannelByPubkey(params.channelId);\n options.isInitiator = params.fromId === initiatorId;\n }\n\n return isSignedTx\n ? getExecutionCostBySignedTx(transaction, await node.getNetworkId(), options)\n : getExecutionCost(transaction, options);\n}\n"],"mappings":"SACSA,OAAO,EAAEC,WAAW,EAAEC,QAAQ;AAAA,SAC9BC,GAAG;AAAA,SACHC,MAAM;AAAA,SACNC,eAAe;AAAA,SACfC,oBAAoB,EAAEC,aAAa,EAAEC,gBAAgB;AAAA,OAEvDC,2BAA2B;AAElC;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,OAAO,SAASC,gBAAgBA,CAC9BC,WAAgC,EASxB;EAAA,IARR;IACEC,OAAO;IAAEC,OAAO;IAAEC,QAAQ;IAAEC;EAM9B,CAAC,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEN,MAAMG,MAAM,GAAGjB,QAAQ,CAACS,WAAW,CAAC;EACpC,IAAIQ,MAAM,CAACC,GAAG,KAAKjB,GAAG,CAACkB,QAAQ,EAAE;IAC/B,MAAM,IAAIf,oBAAoB,CAAC,gFAAgF,CAAC;EAClH;EAEA,IAAIgB,GAAG,GAAG,EAAE;EACZ,IAAI,KAAK,IAAIH,MAAM,IAAIP,OAAO,KAAK,YAAY,EAAE;IAC/CU,GAAG,IAAIC,MAAM,CAACJ,MAAM,CAACK,GAAG,CAAC;EAC3B;EACA,IAAIL,MAAM,CAACC,GAAG,KAAKjB,GAAG,CAACsB,WAAW,EAAE;IAClCH,GAAG,IAAIC,MAAM,CAACJ,MAAM,CAACO,OAAO,CAAC;EAC/B;EACA,IAAIP,MAAM,CAACC,GAAG,KAAKjB,GAAG,CAACwB,aAAa,EAAE;IACpCL,GAAG,IAAIC,MAAM,CAACJ,MAAM,CAACL,QAAQ,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IAAIE,YAAY,IAAI,IAAI,EAAE;MACxB,MAAM,IAAI1D,aAAa,CAAE,wDAAuDqD,MAAO,EAAC,CAAC;IAC3F;IACAX,OAAO,CAACpC,OAAO,GAAGoD,YAAY,CAACpD,OAAO;EACxC;EAEA,IAAIoC,OAAO,CAACnC,QAAQ,IAAI,IAAI,IAAIX,GAAG,CAACyB,gBAAgB,KAAKT,MAAM,CAACC,GAAG,EAAE;IACnE6B,OAAO,CAACnC,QAAQ,GAAG,CAAC,MAAM2C,IAAI,CAACS,iBAAiB,CAAC/C,MAAM,CAACgD,QAAQ,CAAC,EAAErD,QAAQ,CAACsD,QAAQ,EAAE;EACxF;EAEA,IAAInB,OAAO,CAAClC,WAAW,IAAI,IAAI,IAAIZ,GAAG,CAAC0B,eAAe,KAAKV,MAAM,CAACC,GAAG,IAAIsC,OAAO,KAAK,IAAI,EAAE;IACzF,MAAM;MAAEW;IAAY,CAAC,GAAG,MAAMZ,IAAI,CAACa,kBAAkB,CAACnD,MAAM,CAACoD,SAAS,CAAC;IACvEtB,OAAO,CAAClC,WAAW,GAAGI,MAAM,CAACqD,MAAM,KAAKH,WAAW;EACrD;EAEA,OAAOV,UAAU,GACbZ,0BAA0B,CAACpC,WAAW,EAAE,MAAM8C,IAAI,CAACgB,YAAY,EAAE,EAAExB,OAAO,CAAC,GAC3EvC,gBAAgB,CAACC,WAAW,EAAEsC,OAAO,CAAC;AAC5C"}
@@ -38,5 +38,4 @@ export declare const toAe: (value: string | number | BigNumber, { denomination }
38
38
  export declare const toAettos: (value: string | number | BigNumber, { denomination }?: {
39
39
  denomination?: AE_AMOUNT_FORMATS | undefined;
40
40
  }) => string;
41
- declare const _default: (rawValue: string | number | BigNumber) => string;
42
- export default _default;
41
+ export declare const prefixedAmount: (rawValue: string | number | BigNumber) => string;
@@ -90,7 +90,7 @@ const getLowerBoundPrefix = exponent => {
90
90
  var _prefixes$find;
91
91
  return (_prefixes$find = prefixes.find(p => p.magnitude <= exponent)) !== null && _prefixes$find !== void 0 ? _prefixes$find : prefixes[prefixes.length - 1];
92
92
  };
93
- export default (rawValue => {
93
+ export const prefixedAmount = rawValue => {
94
94
  var _value$e;
95
95
  const value = new BigNumber(rawValue);
96
96
  const exp = (_value$e = value.e) !== null && _value$e !== void 0 ? _value$e : 0;
@@ -100,5 +100,5 @@ export default (rawValue => {
100
100
  } = (exp < 0 ? getNearestPrefix : getLowerBoundPrefix)(exp);
101
101
  const v = value.shiftedBy(-magnitude).precision(9 + Math.min(exp - magnitude, 0)).toFixed();
102
102
  return `${v}${name !== '' ? ' ' : ''}${name}`;
103
- });
103
+ };
104
104
  //# sourceMappingURL=amount-formatter.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"amount-formatter.mjs","names":["BigNumber","isBigNumber","ArgumentError","AE_AMOUNT_FORMATS","DENOMINATION_MAGNITUDE","AE","MILI_AE","MICRO_AE","NANO_AE","PICO_AE","FEMTO_AE","AETTOS","formatAmount","value","_ref","denomination","targetDenomination","toString","shiftedBy","toFixed","toAe","arguments","length","undefined","toAettos","prefixes","name","magnitude","getNearestPrefix","exponent","reduce","p","n","Math","abs","getLowerBoundPrefix","_prefixes$find","find","rawValue","_value$e","exp","e","v","precision","min"],"sources":["../../src/utils/amount-formatter.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { isBigNumber } from './bignumber';\nimport { ArgumentError } from './errors';\n\nexport enum AE_AMOUNT_FORMATS {\n AE = 'ae',\n MILI_AE = 'miliAE',\n MICRO_AE = 'microAE',\n NANO_AE = 'nanoAE',\n PICO_AE = 'picoAE',\n FEMTO_AE = 'femtoAE',\n AETTOS = 'aettos',\n}\n\n/**\n * DENOMINATION_MAGNITUDE\n */\nconst DENOMINATION_MAGNITUDE = {\n [AE_AMOUNT_FORMATS.AE]: 0,\n [AE_AMOUNT_FORMATS.MILI_AE]: -3,\n [AE_AMOUNT_FORMATS.MICRO_AE]: -6,\n [AE_AMOUNT_FORMATS.NANO_AE]: -9,\n [AE_AMOUNT_FORMATS.PICO_AE]: -12,\n [AE_AMOUNT_FORMATS.FEMTO_AE]: -15,\n [AE_AMOUNT_FORMATS.AETTOS]: -18,\n} as const;\n\n/**\n * Convert amount from one to other denomination\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n * @param options.targetDenomination - target denomination,\n * can be ['ae', 'aettos']\n */\nexport const formatAmount = (\n value: string | number | bigint | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS, targetDenomination = AE_AMOUNT_FORMATS.AETTOS }:\n { denomination?: AE_AMOUNT_FORMATS; targetDenomination?: AE_AMOUNT_FORMATS },\n): string => {\n if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value);\n\n return new BigNumber(typeof value === 'bigint' ? value.toString() : value)\n .shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination])\n .toFixed();\n};\n\n/**\n * Convert amount to AE\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAe = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination, targetDenomination: AE_AMOUNT_FORMATS.AE });\n\n/**\n * Convert amount to aettos\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAettos = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AE }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination });\n\ninterface Prefix {\n name: string;\n magnitude: number;\n}\n\nconst prefixes: Prefix[] = [\n { name: 'exa', magnitude: 18 },\n { name: 'giga', magnitude: 9 },\n { name: '', magnitude: 0 },\n { name: 'pico', magnitude: -12 },\n];\n\nconst getNearestPrefix = (exponent: number): Prefix => prefixes.reduce((p, n) => (\n Math.abs(n.magnitude - exponent) < Math.abs(p.magnitude - exponent) ? n : p));\n\nconst getLowerBoundPrefix = (exponent: number): Prefix => prefixes\n .find((p) => p.magnitude <= exponent) ?? prefixes[prefixes.length - 1];\n\nexport default (rawValue: string | number | BigNumber): string => {\n const value: BigNumber = new BigNumber(rawValue);\n\n const exp = value.e ?? 0;\n const { name, magnitude } = (exp < 0 ? getNearestPrefix : getLowerBoundPrefix)(exp);\n const v = value\n .shiftedBy(-magnitude)\n .precision(9 + Math.min(exp - magnitude, 0))\n .toFixed();\n return `${v}${name !== '' ? ' ' : ''}${name}`;\n};\n"],"mappings":"AAAA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC5BC,WAAW;AAAA,SACXC,aAAa;AAEtB,WAAYC,iBAAiB;;AAU7B;AACA;AACA;AAFA,WAVYA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;EAAjBA,iBAAiB;AAAA,GAAjBA,iBAAiB,KAAjBA,iBAAiB;AAa7B,MAAMC,sBAAsB,GAAG;EAC7B,CAACD,iBAAiB,CAACE,EAAE,GAAG,CAAC;EACzB,CAACF,iBAAiB,CAACG,OAAO,GAAG,CAAC,CAAC;EAC/B,CAACH,iBAAiB,CAACI,QAAQ,GAAG,CAAC,CAAC;EAChC,CAACJ,iBAAiB,CAACK,OAAO,GAAG,CAAC,CAAC;EAC/B,CAACL,iBAAiB,CAACM,OAAO,GAAG,CAAC,EAAE;EAChC,CAACN,iBAAiB,CAACO,QAAQ,GAAG,CAAC,EAAE;EACjC,CAACP,iBAAiB,CAACQ,MAAM,GAAG,CAAC;AAC/B,CAAU;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,YAAY,GAAGA,CAC1BC,KAA2C,EAAAC,IAAA,KAGhC;EAAA,IAFX;IAAEC,YAAY,GAAGZ,iBAAiB,CAACQ,MAAM;IAAEK,kBAAkB,GAAGb,iBAAi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,CAAC"}
1
+ {"version":3,"file":"amount-formatter.mjs","names":["BigNumber","isBigNumber","ArgumentError","AE_AMOUNT_FORMATS","DENOMINATION_MAGNITUDE","AE","MILI_AE","MICRO_AE","NANO_AE","PICO_AE","FEMTO_AE","AETTOS","formatAmount","value","_ref","denomination","targetDenomination","toString","shiftedBy","toFixed","toAe","arguments","length","undefined","toAettos","prefixes","name","magnitude","getNearestPrefix","exponent","reduce","p","n","Math","abs","getLowerBoundPrefix","_prefixes$find","find","prefixedAmount","rawValue","_value$e","exp","e","v","precision","min"],"sources":["../../src/utils/amount-formatter.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { isBigNumber } from './bignumber';\nimport { ArgumentError } from './errors';\n\nexport enum AE_AMOUNT_FORMATS {\n AE = 'ae',\n MILI_AE = 'miliAE',\n MICRO_AE = 'microAE',\n NANO_AE = 'nanoAE',\n PICO_AE = 'picoAE',\n FEMTO_AE = 'femtoAE',\n AETTOS = 'aettos',\n}\n\n/**\n * DENOMINATION_MAGNITUDE\n */\nconst DENOMINATION_MAGNITUDE = {\n [AE_AMOUNT_FORMATS.AE]: 0,\n [AE_AMOUNT_FORMATS.MILI_AE]: -3,\n [AE_AMOUNT_FORMATS.MICRO_AE]: -6,\n [AE_AMOUNT_FORMATS.NANO_AE]: -9,\n [AE_AMOUNT_FORMATS.PICO_AE]: -12,\n [AE_AMOUNT_FORMATS.FEMTO_AE]: -15,\n [AE_AMOUNT_FORMATS.AETTOS]: -18,\n} as const;\n\n/**\n * Convert amount from one to other denomination\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n * @param options.targetDenomination - target denomination,\n * can be ['ae', 'aettos']\n */\nexport const formatAmount = (\n value: string | number | bigint | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS, targetDenomination = AE_AMOUNT_FORMATS.AETTOS }:\n { denomination?: AE_AMOUNT_FORMATS; targetDenomination?: AE_AMOUNT_FORMATS },\n): string => {\n if (!isBigNumber(value)) throw new ArgumentError('value', 'a number', value);\n\n return new BigNumber(typeof value === 'bigint' ? value.toString() : value)\n .shiftedBy(DENOMINATION_MAGNITUDE[denomination] - DENOMINATION_MAGNITUDE[targetDenomination])\n .toFixed();\n};\n\n/**\n * Convert amount to AE\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAe = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AETTOS }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination, targetDenomination: AE_AMOUNT_FORMATS.AE });\n\n/**\n * Convert amount to aettos\n * @param value - amount to convert\n * @param options - options\n * @param options.denomination - denomination of amount, can be ['ae', 'aettos']\n */\nexport const toAettos = (\n value: string | number | BigNumber,\n { denomination = AE_AMOUNT_FORMATS.AE }: { denomination?: AE_AMOUNT_FORMATS } = {},\n): string => formatAmount(value, { denomination });\n\ninterface Prefix {\n name: string;\n magnitude: number;\n}\n\nconst prefixes: Prefix[] = [\n { name: 'exa', magnitude: 18 },\n { name: 'giga', magnitude: 9 },\n { name: '', magnitude: 0 },\n { name: 'pico', magnitude: -12 },\n];\n\nconst getNearestPrefix = (exponent: number): Prefix => prefixes.reduce((p, n) => (\n Math.abs(n.magnitude - exponent) < Math.abs(p.magnitude - exponent) ? n : p));\n\nconst getLowerBoundPrefix = (exponent: number): Prefix => prefixes\n .find((p) => p.magnitude <= exponent) ?? prefixes[prefixes.length - 1];\n\nexport const prefixedAmount = (rawValue: string | number | BigNumber): string => {\n const value: BigNumber = new BigNumber(rawValue);\n\n const exp = value.e ?? 0;\n const { name, magnitude } = (exp < 0 ? getNearestPrefix : getLowerBoundPrefix)(exp);\n const v = value\n .shiftedBy(-magnitude)\n .precision(9 + Math.min(exp - magnitude, 0))\n .toFixed();\n return `${v}${name !== '' ? ' ' : ''}${name}`;\n};\n"],"mappings":"AAAA,OAAOA,SAAS,MAAM,cAAc;AAAC,SAC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AA;EAAA,QAAAA,cAAA,GAAaX,QAAQ,CAC/DY,IAAI,CAAEN,CAAC,IAAKA,CAAC,CAACJ,SAAS,IAAIE,QAAQ,CAAC,cAAAO,cAAA,cAAAA,cAAA,GAAIX,QAAQ,CAACA,QAAQ,CAACH,MAAM,GAAG,CAAC,CAAC;AAAA;AAExE,OAAO,MAAMgB,cAAc,GAAIC,QAAqC,IAAa;EAAA,IAAAC,QAAA;EAC/E,MAAM3B,KAAgB,GAAG,IAAIb,SAAS,CAACuC,QAAQ,CAAC;EAEhD,MAAME,GAAG,IAAAD,QAAA,GAAG3B,KAAK,CAAC6B,CAAC,cAAAF,QAAA,cAAAA,QAAA,GAAI,CAAC;EACxB,MAAM;IAAEd,IAAI;IAAEC;EAAU,CAAC,GAAG,CAACc,GAAG,GAAG,CAAC,GAAGb,gBAAgB,GAAGO,mBAAmB,EAAEM,GAAG,CAAC;EACnF,MAAME,CAAC,GAAG9B,KAAK,CACZK,SAAS,CAAC,CAACS,SAAS,CAAC,CACrBiB,SAAS,CAAC,CAAC,GAAGX,IAAI,CAACY,GAAG,CAACJ,GAAG,GAAGd,SAAS,EAAE,CAAC,CAAC,CAAC,CAC3CR,OAAO,EAAE;EACZ,OAAQ,GAAEwB,CAAE,GAAEjB,IAAI,KAAK,EAAE,GAAG,GAAG,GAAG,EAAG,GAAEA,IAAK,EAAC;AAC/C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeternity/aepp-sdk",
3
- "version": "13.0.0",
3
+ "version": "13.0.1",
4
4
  "description": "SDK for the æternity blockchain",
5
5
  "main": "dist/aepp-sdk.js",
6
6
  "types": "es/index.d.ts",
@@ -72,7 +72,7 @@ type TxData = Awaited<ReturnType<typeof sendTransaction>>;
72
72
  interface SendAndProcessReturnType {
73
73
  result?: ContractCallObject;
74
74
  hash: TxData['hash'];
75
- tx: TxUnpacked & { tag: Tag.ContractCallTx | Tag.ContractCreateTx };
75
+ tx: TxUnpacked & { tag: Tag.SignedTx | Tag.ContractCallTx | Tag.ContractCreateTx };
76
76
  txData: TxData;
77
77
  rawTx: Encoded.Transaction;
78
78
  }
@@ -11,6 +11,23 @@ import getTransactionSignerAddress from './transaction-signer';
11
11
  * Calculates the cost of transaction execution
12
12
  * Provides an upper cost of contract-call-related transactions because of `gasLimit`.
13
13
  * Also assumes that oracle query fee is 0 unless it is provided in options.
14
+ *
15
+ * The idea is that if you need to show transaction details with some accuracy you can define
16
+ * expense fields that you want to show separately. And to show `getExecutionCost` result as a fee,
17
+ * subtracting all fields shown separately.
18
+ *
19
+ * @example
20
+ * ```vue
21
+ * <template>
22
+ * Amount: {{ txUnpacked.amount }}
23
+ * Name fee: {{ txUnpacked.nameFee }}
24
+ * Other fees: {{ getExecutionCost(txEncoded) - txUnpacked.amount - txUnpacked.nameFee }}
25
+ * </template>
26
+ * ```
27
+ *
28
+ * Doing this way you won't worry to show wrong fee for a transaction you may not support. Because
29
+ * the SDK calculates the overall price of any transaction on its side.
30
+ *
14
31
  * @param transaction - Transaction to calculate the cost of
15
32
  * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx
16
33
  * @param gasUsed - Amount of gas actually used to make calculation more accurate
@@ -85,7 +85,7 @@ const getNearestPrefix = (exponent: number): Prefix => prefixes.reduce((p, n) =>
85
85
  const getLowerBoundPrefix = (exponent: number): Prefix => prefixes
86
86
  .find((p) => p.magnitude <= exponent) ?? prefixes[prefixes.length - 1];
87
87
 
88
- export default (rawValue: string | number | BigNumber): string => {
88
+ export const prefixedAmount = (rawValue: string | number | BigNumber): string => {
89
89
  const value: BigNumber = new BigNumber(rawValue);
90
90
 
91
91
  const exp = value.e ?? 0;
@@ -1,4 +1,3 @@
1
- /// <reference types="@aeternity__aepp-calldata" />
2
1
  /**
3
2
  * Contract module - routines to interact with the æternity contract
4
3
  *
@@ -36,7 +35,7 @@ interface SendAndProcessReturnType {
36
35
  result?: ContractCallObject;
37
36
  hash: TxData['hash'];
38
37
  tx: TxUnpacked & {
39
- tag: Tag.ContractCallTx | Tag.ContractCreateTx;
38
+ tag: Tag.SignedTx | Tag.ContractCallTx | Tag.ContractCreateTx;
40
39
  };
41
40
  txData: TxData;
42
41
  rawTx: Encoded.Transaction;
@@ -4,6 +4,23 @@ import Node from '../Node';
4
4
  * Calculates the cost of transaction execution
5
5
  * Provides an upper cost of contract-call-related transactions because of `gasLimit`.
6
6
  * Also assumes that oracle query fee is 0 unless it is provided in options.
7
+ *
8
+ * The idea is that if you need to show transaction details with some accuracy you can define
9
+ * expense fields that you want to show separately. And to show `getExecutionCost` result as a fee,
10
+ * subtracting all fields shown separately.
11
+ *
12
+ * @example
13
+ * ```vue
14
+ * <template>
15
+ * Amount: {{ txUnpacked.amount }}
16
+ * Name fee: {{ txUnpacked.nameFee }}
17
+ * Other fees: {{ getExecutionCost(txEncoded) - txUnpacked.amount - txUnpacked.nameFee }}
18
+ * </template>
19
+ * ```
20
+ *
21
+ * Doing this way you won't worry to show wrong fee for a transaction you may not support. Because
22
+ * the SDK calculates the overall price of any transaction on its side.
23
+ *
7
24
  * @param transaction - Transaction to calculate the cost of
8
25
  * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx
9
26
  * @param gasUsed - Amount of gas actually used to make calculation more accurate
@@ -38,5 +38,4 @@ export declare const toAe: (value: string | number | BigNumber, { denomination }
38
38
  export declare const toAettos: (value: string | number | BigNumber, { denomination }?: {
39
39
  denomination?: AE_AMOUNT_FORMATS | undefined;
40
40
  }) => string;
41
- declare const _default: (rawValue: string | number | BigNumber) => string;
42
- export default _default;
41
+ export declare const prefixedAmount: (rawValue: string | number | BigNumber) => string;
@@ -1,4 +1,3 @@
1
- /// <reference types="@aeternity__aepp-calldata" />
2
1
  /**
3
2
  * Contract module - routines to interact with the æternity contract
4
3
  *
@@ -36,7 +35,7 @@ interface SendAndProcessReturnType {
36
35
  result?: ContractCallObject;
37
36
  hash: TxData['hash'];
38
37
  tx: TxUnpacked & {
39
- tag: Tag.ContractCallTx | Tag.ContractCreateTx;
38
+ tag: Tag.SignedTx | Tag.ContractCallTx | Tag.ContractCreateTx;
40
39
  };
41
40
  txData: TxData;
42
41
  rawTx: Encoded.Transaction;
@@ -4,6 +4,23 @@ import Node from '../Node';
4
4
  * Calculates the cost of transaction execution
5
5
  * Provides an upper cost of contract-call-related transactions because of `gasLimit`.
6
6
  * Also assumes that oracle query fee is 0 unless it is provided in options.
7
+ *
8
+ * The idea is that if you need to show transaction details with some accuracy you can define
9
+ * expense fields that you want to show separately. And to show `getExecutionCost` result as a fee,
10
+ * subtracting all fields shown separately.
11
+ *
12
+ * @example
13
+ * ```vue
14
+ * <template>
15
+ * Amount: {{ txUnpacked.amount }}
16
+ * Name fee: {{ txUnpacked.nameFee }}
17
+ * Other fees: {{ getExecutionCost(txEncoded) - txUnpacked.amount - txUnpacked.nameFee }}
18
+ * </template>
19
+ * ```
20
+ *
21
+ * Doing this way you won't worry to show wrong fee for a transaction you may not support. Because
22
+ * the SDK calculates the overall price of any transaction on its side.
23
+ *
7
24
  * @param transaction - Transaction to calculate the cost of
8
25
  * @param innerTx - Should be provided if transaction wrapped with Tag.PayingForTx
9
26
  * @param gasUsed - Amount of gas actually used to make calculation more accurate
@@ -38,5 +38,4 @@ export declare const toAe: (value: string | number | BigNumber, { denomination }
38
38
  export declare const toAettos: (value: string | number | BigNumber, { denomination }?: {
39
39
  denomination?: AE_AMOUNT_FORMATS | undefined;
40
40
  }) => string;
41
- declare const _default: (rawValue: string | number | BigNumber) => string;
42
- export default _default;
41
+ export declare const prefixedAmount: (rawValue: string | number | BigNumber) => string;
@@ -1,2 +0,0 @@
1
-
2
- //# sourceMappingURL=index.d.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mjs","names":[],"sources":["../../../src/typings/@aeternity__aepp-calldata/index.d.ts"],"sourcesContent":["declare module '@aeternity/aepp-calldata' {\n // eslint-disable-next-line import/prefer-default-export\n export class Encoder {\n constructor(aci: object);\n\n encode(contract: string, funName: string, args: any[]): `cb_${string}`;\n\n decode(contract: string, funName: string, data: `cb_${string}`): any;\n\n decodeString(data: `cb_${string}`): Uint8Array;\n\n decodeFateString(data: `cb_${string}`): string;\n\n decodeEvent(\n contract: string,\n encodedData: `cb_${string}`,\n topics: BigInt[],\n ): { [key: string]: any[] };\n }\n}\n"],"mappings":""}
@@ -1,20 +0,0 @@
1
- declare module '@aeternity/aepp-calldata' {
2
- // eslint-disable-next-line import/prefer-default-export
3
- export class Encoder {
4
- constructor(aci: object);
5
-
6
- encode(contract: string, funName: string, args: any[]): `cb_${string}`;
7
-
8
- decode(contract: string, funName: string, data: `cb_${string}`): any;
9
-
10
- decodeString(data: `cb_${string}`): Uint8Array;
11
-
12
- decodeFateString(data: `cb_${string}`): string;
13
-
14
- decodeEvent(
15
- contract: string,
16
- encodedData: `cb_${string}`,
17
- topics: BigInt[],
18
- ): { [key: string]: any[] };
19
- }
20
- }