@aeternity/aepp-sdk 13.3.0 → 13.3.2

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.
Files changed (43) hide show
  1. package/bin/aesophia_cli_8 +0 -0
  2. package/dist/aepp-sdk.browser-script.js +1 -1
  3. package/dist/aepp-sdk.browser-script.js.map +1 -1
  4. package/dist/aepp-sdk.browser.js +1 -1
  5. package/dist/aepp-sdk.browser.js.map +1 -1
  6. package/dist/aepp-sdk.js +37 -44
  7. package/dist/aepp-sdk.js.map +1 -1
  8. package/es/Node.mjs +1 -1
  9. package/es/Node.mjs.map +1 -1
  10. package/es/chain.d.ts +5 -5
  11. package/es/chain.mjs +18 -20
  12. package/es/chain.mjs.map +1 -1
  13. package/es/contract/Contract.mjs +3 -0
  14. package/es/contract/Contract.mjs.map +1 -1
  15. package/es/oracle.d.ts +2 -2
  16. package/es/oracle.mjs +6 -10
  17. package/es/oracle.mjs.map +1 -1
  18. package/es/tx/builder/field-types/gas-price.mjs +1 -4
  19. package/es/tx/builder/field-types/gas-price.mjs.map +1 -1
  20. package/es/tx/builder/field-types/ttl.d.ts +3 -2
  21. package/es/tx/builder/field-types/ttl.mjs.map +1 -1
  22. package/es/tx/builder/schema.d.ts +69 -46
  23. package/es/utils/semver-satisfies.d.ts +1 -1
  24. package/es/utils/semver-satisfies.mjs +8 -9
  25. package/es/utils/semver-satisfies.mjs.map +1 -1
  26. package/package.json +2 -2
  27. package/src/Node.ts +1 -1
  28. package/src/chain.ts +28 -18
  29. package/src/contract/Contract.ts +3 -0
  30. package/src/oracle.ts +7 -7
  31. package/src/tx/builder/field-types/gas-price.ts +1 -4
  32. package/src/tx/builder/field-types/ttl.ts +1 -1
  33. package/src/utils/semver-satisfies.ts +14 -13
  34. package/types-legacy/ts4.2/chain.d.ts +5 -5
  35. package/types-legacy/ts4.2/oracle.d.ts +2 -2
  36. package/types-legacy/ts4.2/tx/builder/field-types/ttl.d.ts +3 -2
  37. package/types-legacy/ts4.2/tx/builder/schema.d.ts +69 -46
  38. package/types-legacy/ts4.2/utils/semver-satisfies.d.ts +1 -1
  39. package/types-legacy/ts4.5/chain.d.ts +5 -5
  40. package/types-legacy/ts4.5/oracle.d.ts +2 -2
  41. package/types-legacy/ts4.5/tx/builder/field-types/ttl.d.ts +3 -2
  42. package/types-legacy/ts4.5/tx/builder/schema.d.ts +69 -46
  43. package/types-legacy/ts4.5/utils/semver-satisfies.d.ts +1 -1
package/es/Node.mjs CHANGED
@@ -76,7 +76,7 @@ export default class Node extends NodeTransformed {
76
76
  // eslint-disable-next-line constructor-super
77
77
  super(url, {
78
78
  allowInsecureConnection: true,
79
- additionalPolicies: [...(ignoreVersion ? [] : [genVersionCheckPolicy('node', getVersion, '6.2.0', '7.0.0')]), genRequestQueuesPolicy(), genCombineGetRequestsPolicy(), genRetryOnFailurePolicy(retryCount, retryOverallDelay), genErrorFormatterPolicy(body => [' ', body.reason, body.errorCode == null ? '' : ` (${body.errorCode})`].join(''))],
79
+ additionalPolicies: [...(ignoreVersion ? [] : [genVersionCheckPolicy('node', getVersion, '6.2.0', '8.0.0')]), genRequestQueuesPolicy(), genCombineGetRequestsPolicy(), genRetryOnFailurePolicy(retryCount, retryOverallDelay), genErrorFormatterPolicy(body => [' ', body.reason, body.errorCode == null ? '' : ` (${body.errorCode})`].join(''))],
80
80
  ...options
81
81
  });
82
82
  _classPrivateFieldInitSpec(this, _cachedStatusPromise, {
package/es/Node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Node.mjs","names":["BigNumber","userAgentPolicyName","setClientRequestIdPolicyName","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Node","NodeApi","mapObject","UnsupportedVersionError","ConsensusProtocolVersion","bigIntPropertyNames","numberPropertyNames","_mapData","WeakSet","_encodeArg","_decodeRes","NodeTransformed","constructor","args","_classPrivateMethodInitSpec","sendOperationRequest","operationArguments","operationSpec","key","value","_classPrivateMethodGet","_encodeArg2","call","_decodeRes2","_mapData2","data","transform","Array","isArray","map","d","some","k","bigInt","number","toFixed","toString","BigInt","_cachedStatusPromise","WeakMap","url","ignoreVersion","retryCount","retryOverallDelay","options","getVersion","opts","_getCachedStatus","nodeVersion","allowInsecureConnection","additionalPolicies","body","reason","errorCode","join","_classPrivateFieldInitSpec","writable","pipeline","removePolicy","name","intAsString","_classPrivateFieldGet","getStatus","promise","then","_classPrivateFieldSet","getNetworkId","networkId","getNodeInfo","nodeNetworkId","protocols","topBlockHeight","consensusProtocolVersion","filter","effectiveAtHeight","reduce","acc","p","version","versions","Object","values","el","geVersion","Math","min","ltVersion","max","$host"],"sources":["../src/Node.ts"],"sourcesContent":["// eslint-disable-next-line max-classes-per-file\nimport BigNumber from 'bignumber.js';\nimport { OperationArguments, OperationOptions, OperationSpec } from '@azure/core-client';\nimport { userAgentPolicyName, setClientRequestIdPolicyName } from '@azure/core-rest-pipeline';\nimport {\n genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,\n genVersionCheckPolicy, genRetryOnFailurePolicy,\n} from './utils/autorest';\nimport { Node as NodeApi, NodeOptionalParams, ErrorModel } from './apis/node';\nimport { mapObject } from './utils/other';\nimport { UnsupportedVersionError } from './utils/errors';\nimport { Encoded } from './utils/encoder';\nimport { ConsensusProtocolVersion } from './tx/builder/constants';\n\nconst bigIntPropertyNames = [\n 'balance', 'queryFee', 'fee', 'amount', 'nameFee', 'channelAmount',\n 'initiatorAmount', 'responderAmount', 'channelReserve', 'initiatorAmountFinal',\n 'responderAmountFinal', 'gasPrice', 'minGasPrice', 'deposit',\n] as const;\n\nconst numberPropertyNames = [\n 'time', 'gas', 'gasUsed', 'nameSalt',\n 'nonce', 'nextNonce', 'height', 'blockHeight', 'topBlockHeight',\n 'ttl', 'nameTtl', 'clientTtl',\n 'inbound', 'outbound', 'peerCount', 'pendingTransactionsCount', 'effectiveAtHeight',\n 'version', 'solutions', 'round', 'minutes', 'utilization', 'difficulty', 'hashrate',\n] as const;\n\nclass NodeTransformed extends NodeApi {\n override async sendOperationRequest(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<any> {\n const args = mapObject(\n operationArguments,\n ([key, value]) => [key, this.#encodeArg(value)],\n ) as OperationArguments;\n return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));\n }\n\n #mapData(data: any, transform: {\n bigInt: (v: any) => any;\n number: (v: any) => any;\n }): unknown {\n if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));\n if (data != null && typeof data === 'object') {\n return mapObject(data, ([key, value]) => {\n if (value == null) return [key, value];\n if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];\n if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];\n return [key, this.#mapData(value, transform)];\n });\n }\n return data;\n }\n\n #encodeArg(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => {\n if (value instanceof BigNumber) return value.toFixed();\n return value.toString();\n },\n number: (value) => value.toString(),\n });\n }\n\n #decodeRes(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => BigInt(value),\n number: (value) => +value,\n });\n }\n}\n\ntype BigIntPropertyNames = typeof bigIntPropertyNames[number];\ntype NumberPropertyNames = typeof numberPropertyNames[number];\ntype PreserveOptional<NewType, OrigType> =\n OrigType extends undefined ? NewType | undefined : NewType;\nexport type TransformNodeType<Type> =\n Type extends (...args: infer Args) => infer Ret\n ? (...args: TransformNodeType<Args>) => TransformNodeType<Ret>\n : Type extends [infer Item, ...infer Rest]\n ? [TransformNodeType<Item>, ...TransformNodeType<Rest>]\n : Type extends Array<infer Item>\n ? Array<TransformNodeType<Item>>\n : Type extends Promise<infer T>\n ? Promise<TransformNodeType<T>>\n : Type extends { [P in any]: any }\n ? {\n [Property in keyof Type]:\n Property extends BigIntPropertyNames\n ? PreserveOptional<bigint, Type[Property]>\n : Property extends NumberPropertyNames\n ? PreserveOptional<number, Type[Property]>\n : Property extends 'txHash'\n ? PreserveOptional<Encoded.TxHash, Type[Property]>\n : Property extends 'bytecode'\n ? PreserveOptional<Encoded.ContractBytearray, Type[Property]>\n : TransformNodeType<Type[Property]>\n }\n : Type;\ntype NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) => {\n [Name in keyof InstanceType<typeof NodeApi>]:\n Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'\n ? NodeApi[Name] : TransformNodeType<NodeApi[Name]>\n};\n\ninterface NodeInfo {\n url: string;\n nodeNetworkId: string;\n version: string;\n consensusProtocolVersion: ConsensusProtocolVersion;\n}\n\nexport default class Node extends (NodeTransformed as unknown as NodeTransformedApi) {\n /**\n * @param url - Url for node API\n * @param options - Options\n * @param options.ignoreVersion - Don't ensure that the node is supported\n * @param options.retryCount - Amount of extra requests to do in case of failure\n * @param options.retryOverallDelay - Time in ms to wait between all retries\n */\n constructor(\n url: string,\n {\n ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options\n }: NodeOptionalParams & {\n ignoreVersion?: boolean;\n retryCount?: number;\n retryOverallDelay?: number;\n } = {},\n ) {\n const getVersion = async (opts: OperationOptions): Promise<string> => (\n (await this._getCachedStatus(opts)).nodeVersion\n );\n // eslint-disable-next-line constructor-super\n super(url, {\n allowInsecureConnection: true,\n additionalPolicies: [\n ...ignoreVersion ? [] : [genVersionCheckPolicy('node', getVersion, '6.2.0', '7.0.0')],\n genRequestQueuesPolicy(),\n genCombineGetRequestsPolicy(),\n genRetryOnFailurePolicy(retryCount, retryOverallDelay),\n genErrorFormatterPolicy((body: ErrorModel) => [\n ' ', body.reason, body.errorCode == null ? '' : ` (${body.errorCode})`,\n ].join('')),\n ],\n ...options,\n });\n this.pipeline.removePolicy({ name: userAgentPolicyName });\n this.pipeline.removePolicy({ name: setClientRequestIdPolicyName });\n // TODO: use instead our retry policy\n this.pipeline.removePolicy({ name: 'defaultRetryPolicy' });\n this.intAsString = true;\n }\n\n #cachedStatusPromise?: ReturnType<Node['getStatus']>;\n\n async _getCachedStatus(options?: OperationOptions): ReturnType<Node['getStatus']> {\n if (this.#cachedStatusPromise != null) return this.#cachedStatusPromise;\n return this.getStatus(options);\n }\n\n // eslint-disable-next-line rulesdir/tsdoc-syntax\n /** @ts-expect-error use code generation to create node class? */\n override async getStatus(\n ...args: Parameters<InstanceType<NodeTransformedApi>['getStatus']>\n ): ReturnType<InstanceType<NodeTransformedApi>['getStatus']> {\n const promise = super.getStatus(...args);\n promise.then(() => { this.#cachedStatusPromise = promise; }, () => {});\n return promise;\n }\n\n /**\n * Returns network ID provided by node.\n * This method won't do extra requests on subsequent calls.\n */\n async getNetworkId(): Promise<string> {\n return (await this._getCachedStatus()).networkId;\n }\n\n async getNodeInfo(): Promise<NodeInfo> {\n const {\n nodeVersion,\n networkId: nodeNetworkId,\n protocols,\n topBlockHeight,\n } = await this.getStatus();\n\n const consensusProtocolVersion = protocols\n .filter(({ effectiveAtHeight }) => topBlockHeight >= effectiveAtHeight)\n .reduce(\n (acc, p) => (p.effectiveAtHeight > acc.effectiveAtHeight ? p : acc),\n { effectiveAtHeight: -1, version: 0 },\n )\n .version;\n if (ConsensusProtocolVersion[consensusProtocolVersion] == null) {\n const version = consensusProtocolVersion.toString();\n const versions = Object.values(ConsensusProtocolVersion)\n .filter((el) => typeof el === 'number').map((el) => +el);\n const geVersion = Math.min(...versions).toString();\n const ltVersion = (Math.max(...versions) + 1).toString();\n throw new UnsupportedVersionError('consensus protocol', version, geVersion, ltVersion);\n }\n\n return {\n url: this.$host,\n nodeNetworkId,\n version: nodeVersion,\n consensusProtocolVersion,\n };\n }\n}\n"],"mappings":";;;;;;;AAAA;AACA,OAAOA,SAAS,MAAM,cAAc;AAEpC,SAASC,mBAAmB,EAAEC,4BAA4B,QAAQ,2BAA2B;AAAC,SAE5FC,sBAAsB,EAAEC,2BAA2B,EAAEC,uBAAuB,EAC5EC,qBAAqB,EAAEC,uBAAuB;AAAA,SAEvCC,IAAI,IAAIC,OAAO;AAAA,SACf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IdPolicyName","genRequestQueuesPolicy","genCombineGetRequestsPolicy","genErrorFormatterPolicy","genVersionCheckPolicy","genRetryOnFailurePolicy","Node","NodeApi","mapObject","UnsupportedVersionError","ConsensusProtocolVersion","bigIntPropertyNames","numberPropertyNames","_mapData","WeakSet","_encodeArg","_decodeRes","NodeTransformed","constructor","args","_classPrivateMethodInitSpec","sendOperationRequest","operationArguments","operationSpec","key","value","_classPrivateMethodGet","_encodeArg2","call","_decodeRes2","_mapData2","data","transform","Array","isArray","map","d","some","k","bigInt","number","toFixed","toString","BigInt","_cachedStatusPromise","WeakMap","url","ignoreVersion","retryCount","retryOverallDelay","options","getVersion","opts","_getCachedStatus","nodeVersion","allowInsecureConnection","additionalPolicies","body","reason","errorCode","join","_classPrivateFieldInitSpec","writable","pipeline","removePolicy","name","intAsString","_classPrivateFieldGet","getStatus","promise","then","_classPrivateFieldSet","getNetworkId","networkId","getNodeInfo","nodeNetworkId","protocols","topBlockHeight","consensusProtocolVersion","filter","effectiveAtHeight","reduce","acc","p","version","versions","Object","values","el","geVersion","Math","min","ltVersion","max","$host"],"sources":["../src/Node.ts"],"sourcesContent":["// eslint-disable-next-line max-classes-per-file\nimport BigNumber from 'bignumber.js';\nimport { OperationArguments, OperationOptions, OperationSpec } from '@azure/core-client';\nimport { userAgentPolicyName, setClientRequestIdPolicyName } from '@azure/core-rest-pipeline';\nimport {\n genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,\n genVersionCheckPolicy, genRetryOnFailurePolicy,\n} from './utils/autorest';\nimport { Node as NodeApi, NodeOptionalParams, ErrorModel } from './apis/node';\nimport { mapObject } from './utils/other';\nimport { UnsupportedVersionError } from './utils/errors';\nimport { Encoded } from './utils/encoder';\nimport { ConsensusProtocolVersion } from './tx/builder/constants';\n\nconst bigIntPropertyNames = [\n 'balance', 'queryFee', 'fee', 'amount', 'nameFee', 'channelAmount',\n 'initiatorAmount', 'responderAmount', 'channelReserve', 'initiatorAmountFinal',\n 'responderAmountFinal', 'gasPrice', 'minGasPrice', 'deposit',\n] as const;\n\nconst numberPropertyNames = [\n 'time', 'gas', 'gasUsed', 'nameSalt',\n 'nonce', 'nextNonce', 'height', 'blockHeight', 'topBlockHeight',\n 'ttl', 'nameTtl', 'clientTtl',\n 'inbound', 'outbound', 'peerCount', 'pendingTransactionsCount', 'effectiveAtHeight',\n 'version', 'solutions', 'round', 'minutes', 'utilization', 'difficulty', 'hashrate',\n] as const;\n\nclass NodeTransformed extends NodeApi {\n override async sendOperationRequest(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n ): Promise<any> {\n const args = mapObject(\n operationArguments,\n ([key, value]) => [key, this.#encodeArg(value)],\n ) as OperationArguments;\n return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));\n }\n\n #mapData(data: any, transform: {\n bigInt: (v: any) => any;\n number: (v: any) => any;\n }): unknown {\n if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));\n if (data != null && typeof data === 'object') {\n return mapObject(data, ([key, value]) => {\n if (value == null) return [key, value];\n if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];\n if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];\n return [key, this.#mapData(value, transform)];\n });\n }\n return data;\n }\n\n #encodeArg(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => {\n if (value instanceof BigNumber) return value.toFixed();\n return value.toString();\n },\n number: (value) => value.toString(),\n });\n }\n\n #decodeRes(data: any): any {\n return this.#mapData(data, {\n bigInt: (value) => BigInt(value),\n number: (value) => +value,\n });\n }\n}\n\ntype BigIntPropertyNames = typeof bigIntPropertyNames[number];\ntype NumberPropertyNames = typeof numberPropertyNames[number];\ntype PreserveOptional<NewType, OrigType> =\n OrigType extends undefined ? NewType | undefined : NewType;\nexport type TransformNodeType<Type> =\n Type extends (...args: infer Args) => infer Ret\n ? (...args: TransformNodeType<Args>) => TransformNodeType<Ret>\n : Type extends [infer Item, ...infer Rest]\n ? [TransformNodeType<Item>, ...TransformNodeType<Rest>]\n : Type extends Array<infer Item>\n ? Array<TransformNodeType<Item>>\n : Type extends Promise<infer T>\n ? Promise<TransformNodeType<T>>\n : Type extends { [P in any]: any }\n ? {\n [Property in keyof Type]:\n Property extends BigIntPropertyNames\n ? PreserveOptional<bigint, Type[Property]>\n : Property extends NumberPropertyNames\n ? PreserveOptional<number, Type[Property]>\n : Property extends 'txHash'\n ? PreserveOptional<Encoded.TxHash, Type[Property]>\n : Property extends 'bytecode'\n ? PreserveOptional<Encoded.ContractBytearray, Type[Property]>\n : TransformNodeType<Type[Property]>\n }\n : Type;\ntype NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) => {\n [Name in keyof InstanceType<typeof NodeApi>]:\n Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'\n ? NodeApi[Name] : TransformNodeType<NodeApi[Name]>\n};\n\ninterface NodeInfo {\n url: string;\n nodeNetworkId: string;\n version: string;\n consensusProtocolVersion: ConsensusProtocolVersion;\n}\n\nexport default class Node extends (NodeTransformed as unknown as NodeTransformedApi) {\n /**\n * @param url - Url for node API\n * @param options - Options\n * @param options.ignoreVersion - Don't ensure that the node is supported\n * @param options.retryCount - Amount of extra requests to do in case of failure\n * @param options.retryOverallDelay - Time in ms to wait between all retries\n */\n constructor(\n url: string,\n {\n ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options\n }: NodeOptionalParams & {\n ignoreVersion?: boolean;\n retryCount?: number;\n retryOverallDelay?: number;\n } = {},\n ) {\n const getVersion = async (opts: OperationOptions): Promise<string> => (\n (await this._getCachedStatus(opts)).nodeVersion\n );\n // eslint-disable-next-line constructor-super\n super(url, {\n allowInsecureConnection: true,\n additionalPolicies: [\n ...ignoreVersion ? [] : [genVersionCheckPolicy('node', getVersion, '6.2.0', '8.0.0')],\n genRequestQueuesPolicy(),\n genCombineGetRequestsPolicy(),\n genRetryOnFailurePolicy(retryCount, retryOverallDelay),\n genErrorFormatterPolicy((body: ErrorModel) => [\n ' ', body.reason, body.errorCode == null ? '' : ` (${body.errorCode})`,\n ].join('')),\n ],\n ...options,\n });\n this.pipeline.removePolicy({ name: userAgentPolicyName });\n this.pipeline.removePolicy({ name: setClientRequestIdPolicyName });\n // TODO: use instead our retry policy\n this.pipeline.removePolicy({ name: 'defaultRetryPolicy' });\n this.intAsString = true;\n }\n\n #cachedStatusPromise?: ReturnType<Node['getStatus']>;\n\n async _getCachedStatus(options?: OperationOptions): ReturnType<Node['getStatus']> {\n if (this.#cachedStatusPromise != null) return this.#cachedStatusPromise;\n return this.getStatus(options);\n }\n\n // eslint-disable-next-line rulesdir/tsdoc-syntax\n /** @ts-expect-error use code generation to create node class? */\n override async getStatus(\n ...args: Parameters<InstanceType<NodeTransformedApi>['getStatus']>\n ): ReturnType<InstanceType<NodeTransformedApi>['getStatus']> {\n const promise = super.getStatus(...args);\n promise.then(() => { this.#cachedStatusPromise = promise; }, () => {});\n return promise;\n }\n\n /**\n * Returns network ID provided by node.\n * This method won't do extra requests on subsequent calls.\n */\n async getNetworkId(): Promise<string> {\n return (await this._getCachedStatus()).networkId;\n }\n\n async getNodeInfo(): Promise<NodeInfo> {\n const {\n nodeVersion,\n networkId: nodeNetworkId,\n protocols,\n topBlockHeight,\n } = await this.getStatus();\n\n const consensusProtocolVersion = protocols\n .filter(({ effectiveAtHeight }) => topBlockHeight >= effectiveAtHeight)\n .reduce(\n (acc, p) => (p.effectiveAtHeight > acc.effectiveAtHeight ? p : acc),\n { effectiveAtHeight: -1, version: 0 },\n )\n .version;\n if (ConsensusProtocolVersion[consensusProtocolVersion] == null) {\n const version = consensusProtocolVersion.toString();\n const versions = Object.values(ConsensusProtocolVersion)\n .filter((el) => typeof el === 'number').map((el) => +el);\n const geVersion = Math.min(...versions).toString();\n const ltVersion = (Math.max(...versions) + 1).toString();\n throw new UnsupportedVersionError('consensus protocol', version, geVersion, ltVersion);\n }\n\n return {\n url: this.$host,\n nodeNetworkId,\n version: nodeVersion,\n consensusProtocolVersion,\n };\n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AAC,oBAAoB,EAAE2E,OAAO,EAAEK,SAAS,EAAEG,SAAS,CAAC;IACxF;IAEA,OAAO;MACL9C,GAAG,EAAE,IAAI,CAACgD,KAAK;MACfnB,aAAa;MACbS,OAAO,EAAE9B,WAAW;MACpBwB;IACF,CAAC;EACH;AACF"}
package/es/chain.d.ts CHANGED
@@ -8,11 +8,11 @@ import { Encoded, Encoding } from './utils/encoder';
8
8
  * @param type - Type
9
9
  * @param options - Options
10
10
  */
11
- export declare function _getPollInterval(type: 'block' | 'microblock', // TODO: rename to 'key-block' | 'micro-block'
12
- { _expectedMineRate, _microBlockCycle }: {
11
+ export declare function _getPollInterval(type: 'key-block' | 'micro-block', { _expectedMineRate, _microBlockCycle, onNode }: {
13
12
  _expectedMineRate?: number;
14
13
  _microBlockCycle?: number;
15
- }): number;
14
+ onNode: Node;
15
+ }): Promise<number>;
16
16
  /**
17
17
  * Obtain current height of the chain
18
18
  * @category chain
@@ -38,7 +38,7 @@ export declare function getHeight({ cached, ...options }: {
38
38
  * @param options.onNode - Node to use
39
39
  * @returns The transaction as it was mined
40
40
  */
41
- export declare function poll(th: Encoded.TxHash, { blocks, interval, onNode, ...options }: {
41
+ export declare function poll(th: Encoded.TxHash, { blocks, interval, ...options }: {
42
42
  blocks?: number;
43
43
  interval?: number;
44
44
  onNode: Node;
@@ -52,7 +52,7 @@ export declare function poll(th: Encoded.TxHash, { blocks, interval, onNode, ...
52
52
  * @param options.onNode - Node to use
53
53
  * @returns Current chain height
54
54
  */
55
- export declare function awaitHeight(height: number, { interval, onNode, ...options }: {
55
+ export declare function awaitHeight(height: number, { interval, ...options }: {
56
56
  interval?: number;
57
57
  onNode: Node;
58
58
  } & Parameters<typeof _getPollInterval>[1]): Promise<number>;
package/es/chain.mjs CHANGED
@@ -10,16 +10,20 @@ import { decode, encode, Encoding } from "./utils/encoder.mjs";
10
10
  * @param type - Type
11
11
  * @param options - Options
12
12
  */
13
- export function _getPollInterval(type,
14
- // TODO: rename to 'key-block' | 'micro-block'
15
- {
16
- _expectedMineRate = 180000,
17
- _microBlockCycle = 3000
13
+ export async function _getPollInterval(type, {
14
+ _expectedMineRate,
15
+ _microBlockCycle,
16
+ onNode
18
17
  }) {
19
- const base = {
20
- block: _expectedMineRate,
21
- microblock: _microBlockCycle
22
- }[type];
18
+ var _ref, _await$getVal;
19
+ const getVal = async (t, val, devModeDef, def) => {
20
+ if (t !== type) return null;
21
+ if (val != null) return val;
22
+ return (await (onNode === null || onNode === void 0 ? void 0 : onNode.getNetworkId())) === 'ae_dev' ? devModeDef : def;
23
+ };
24
+ const base = (_ref = (_await$getVal = await getVal('key-block', _expectedMineRate, 0, 180000)) !== null && _await$getVal !== void 0 ? _await$getVal : await getVal('micro-block', _microBlockCycle, 0, 3000)) !== null && _ref !== void 0 ? _ref : (() => {
25
+ throw new InternalError(`Unknown type: ${type}`);
26
+ })();
23
27
  return Math.floor(base / 3);
24
28
  }
25
29
  const heightCache = new WeakMap();
@@ -40,7 +44,7 @@ export async function getHeight({
40
44
  const onNode = unwrapProxy(options.onNode);
41
45
  if (cached) {
42
46
  const cache = heightCache.get(onNode);
43
- if (cache != null && cache.time > Date.now() - _getPollInterval('block', options)) {
47
+ if (cache != null && cache.time > Date.now() - (await _getPollInterval('key-block', options))) {
44
48
  return cache.height;
45
49
  }
46
50
  }
@@ -69,26 +73,23 @@ export async function getHeight({
69
73
  export async function poll(th, {
70
74
  blocks = 5,
71
75
  interval,
72
- onNode,
73
76
  ...options
74
77
  }) {
75
78
  var _interval;
76
- (_interval = interval) !== null && _interval !== void 0 ? _interval : interval = _getPollInterval('microblock', options);
79
+ (_interval = interval) !== null && _interval !== void 0 ? _interval : interval = await _getPollInterval('micro-block', options);
77
80
  let max;
78
81
  do {
79
- const tx = await onNode.getTransactionByHash(th);
82
+ const tx = await options.onNode.getTransactionByHash(th);
80
83
  if (tx.blockHeight !== -1) return tx;
81
84
  if (max == null) {
82
85
  max = tx.tx.ttl !== 0 ? -1 : (await getHeight({
83
86
  ...options,
84
- onNode,
85
87
  cached: true
86
88
  })) + blocks;
87
89
  }
88
90
  await pause(interval);
89
91
  } while (max === -1 ? true : (await getHeight({
90
92
  ...options,
91
- onNode,
92
93
  cached: true
93
94
  })) < max);
94
95
  throw new TxTimedOutError(blocks, th);
@@ -105,17 +106,14 @@ export async function poll(th, {
105
106
  */
106
107
  export async function awaitHeight(height, {
107
108
  interval,
108
- onNode,
109
109
  ...options
110
110
  }) {
111
111
  var _interval2;
112
- (_interval2 = interval) !== null && _interval2 !== void 0 ? _interval2 : interval = Math.min(_getPollInterval('block', options), 5000);
112
+ (_interval2 = interval) !== null && _interval2 !== void 0 ? _interval2 : interval = Math.min(await _getPollInterval('key-block', options), 5000);
113
113
  let currentHeight;
114
114
  do {
115
115
  if (currentHeight != null) await pause(interval);
116
- currentHeight = await getHeight({
117
- onNode
118
- });
116
+ currentHeight = await getHeight(options);
119
117
  } while (currentHeight < height);
120
118
  return currentHeight;
121
119
  }
package/es/chain.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"chain.mjs","names":["AE_AMOUNT_FORMATS","formatAmount","isAccountNotFoundError","pause","unwrapProxy","isNameValid","produceNameId","DRY_RUN_ACCOUNT","AensPointerContextError","DryRunError","InvalidAensNameError","TxTimedOutError","TxNotInChainError","InternalError","decode","encode","Encoding","_getPollInterval","type","_expectedMineRate","_microBlockCycle","base","block","microblock","Math","floor","heightCache","WeakMap","getHeight","cached","options","onNode","cache","get","time","Date","now","height","getCurrentKeyBlockHeight","set","poll","th","blocks","interval","_interval","max","tx","getTransactionByHash","blockHeight","ttl","awaitHeight","_interval2","min","currentHeight","waitForTxConfirm","txHash","confirm","newBlockHeight","getAccount","address","hash","getAccountByPubkeyAndHeight","getAccountByPubkeyAndHash","getAccountByPubkey","getBalance","format","AETTOS","addr","startsWith","AccountAddress","balance","catch","error","targetDenomination","getCurrentGeneration","getGeneration","hashOrHeight","getGenerationByHeight","getGenerationByHash","getMicroBlockTransactions","getMicroBlockTransactionsByHash","transactions","getKeyBlock","getKeyBlockByHeight","getKeyBlockByHash","getMicroBlockHeader","getMicroBlockHeaderByHash","txDryRunRequests","Map","txDryRunHandler","key","rs","delete","dryRunRes","top","protectedDryRunTxs","txEvents","txs","map","req","accounts","Array","from","Set","accountAddress","pubKey","amount","forEach","reject","results","result","reason","resultPayload","idx","resolve","Object","assign","txDryRun","combine","_txDryRunRequests$get","join","requests","Promise","_requests$timeout","push","timeout","setTimeout","getContractByteCode","contractId","getContractCode","getContract","getName","name","getNameEntryByName","resolveName","nameOrId","verify","resolveByNode","pointer","pointers","find","p","id"],"sources":["../src/chain.ts"],"sourcesContent":["import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';\nimport { isAccountNotFoundError, pause } from './utils/other';\nimport { unwrapProxy } from './utils/wrap-proxy';\nimport { isNameValid, produceNameId } from './tx/builder/helpers';\nimport { AensName, DRY_RUN_ACCOUNT } from './tx/builder/constants';\nimport {\n AensPointerContextError, DryRunError, InvalidAensNameError,\n TxTimedOutError, TxNotInChainError, InternalError,\n} from './utils/errors';\nimport Node, { TransformNodeType } from './Node';\nimport {\n Account as AccountNode, ByteCode, ContractObject, DryRunResult, DryRunResults,\n Generation, KeyBlock, MicroBlockHeader, NameEntry, SignedTx,\n} from './apis/node';\nimport {\n decode, encode, Encoded, Encoding,\n} from './utils/encoder';\n\n/**\n * @category chain\n * @param type - Type\n * @param options - Options\n */\nexport function _getPollInterval(\n type: 'block' | 'microblock', // TODO: rename to 'key-block' | 'micro-block'\n { _expectedMineRate = 180000, _microBlockCycle = 3000 }:\n { _expectedMineRate?: number; _microBlockCycle?: number },\n): number {\n const base = {\n block: _expectedMineRate,\n microblock: _microBlockCycle,\n }[type];\n return Math.floor(base / 3);\n}\n\nconst heightCache: WeakMap<Node, { time: number; height: number }> = new WeakMap();\n\n/**\n * Obtain current height of the chain\n * @category chain\n * @param options - Options\n * @param options.cached - Get height from the cache. The lag behind the actual height shouldn't\n * be more than 1 block. Use if needed to reduce requests count, and approximate value can be used.\n * For example, for timeout check in transaction status polling.\n * @returns Current chain height\n */\nexport async function getHeight(\n { cached = false, ...options }: {\n onNode: Node;\n cached?: boolean;\n } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n const onNode = unwrapProxy(options.onNode);\n if (cached) {\n const cache = heightCache.get(onNode);\n if (cache != null && cache.time > Date.now() - _getPollInterval('block', options)) {\n return cache.height;\n }\n }\n const { height } = await onNode.getCurrentKeyBlockHeight();\n heightCache.set(onNode, { height, time: Date.now() });\n return height;\n}\n\n/**\n * Return transaction details if it is mined, fail otherwise.\n * If the transaction has ttl specified then would wait till it leaves the mempool.\n * Otherwise would fail if a specified amount of blocks were mined.\n * @category chain\n * @param th - The hash of transaction to poll\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.blocks - Number of blocks mined after which to fail if transaction ttl is not set\n * @param options.onNode - Node to use\n * @returns The transaction as it was mined\n */\nexport async function poll(\n th: Encoded.TxHash,\n {\n blocks = 5, interval, onNode, ...options\n }:\n { blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<TransformNodeType<SignedTx>> {\n interval ??= _getPollInterval('microblock', options);\n let max;\n do {\n const tx = await onNode.getTransactionByHash(th);\n if (tx.blockHeight !== -1) return tx;\n if (max == null) {\n max = tx.tx.ttl !== 0 ? -1\n : await getHeight({ ...options, onNode, cached: true }) + blocks;\n }\n await pause(interval);\n } while (max === -1 ? true : await getHeight({ ...options, onNode, cached: true }) < max);\n throw new TxTimedOutError(blocks, th);\n}\n\n/**\n * Wait for the chain to reach a specific height\n * @category chain\n * @param height - Height to wait for\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.onNode - Node to use\n * @returns Current chain height\n */\nexport async function awaitHeight(\n height: number,\n { interval, onNode, ...options }:\n { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n interval ??= Math.min(_getPollInterval('block', options), 5000);\n let currentHeight;\n do {\n if (currentHeight != null) await pause(interval);\n currentHeight = await getHeight({ onNode });\n } while (currentHeight < height);\n return currentHeight;\n}\n\n/**\n * Wait for transaction confirmation\n * @category chain\n * @param txHash - Transaction hash\n * @param options - Options\n * @param options.confirm - Number of micro blocks to wait for transaction confirmation\n * @param options.onNode - Node to use\n * @returns Current Height\n */\nexport async function waitForTxConfirm(\n txHash: Encoded.TxHash,\n { confirm = 3, onNode, ...options }:\n { confirm?: number; onNode: Node } & Parameters<typeof awaitHeight>[1],\n): Promise<number> {\n const { blockHeight } = await onNode.getTransactionByHash(txHash);\n const height = await awaitHeight(blockHeight + confirm, { onNode, ...options });\n const { blockHeight: newBlockHeight } = await onNode.getTransactionByHash(txHash);\n switch (newBlockHeight) {\n case -1:\n throw new TxNotInChainError(txHash);\n case blockHeight:\n return height;\n default:\n return waitForTxConfirm(txHash, { onNode, confirm, ...options });\n }\n}\n\n/**\n * Get account by account public key\n * @category chain\n * @param address - Account address (public key)\n * @param options - Options\n * @param options.height - Get account on specific block by block height\n * @param options.hash - Get account on specific block by micro block hash or key block hash\n * @param options.onNode - Node to use\n */\nexport async function getAccount(\n address: Encoded.AccountAddress | Encoded.ContractAddress,\n { height, hash, onNode }:\n { height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },\n): Promise<TransformNodeType<AccountNode>> {\n if (height != null) return onNode.getAccountByPubkeyAndHeight(address, height);\n if (hash != null) return onNode.getAccountByPubkeyAndHash(address, hash);\n return onNode.getAccountByPubkey(address);\n}\n\n/**\n * Request the balance of specified account\n * @category chain\n * @param address - The public account address to obtain the balance for\n * @param options - Options\n * @param options.format\n * @param options.height - The chain height at which to obtain the balance for\n * (default: top of chain)\n * @param options.hash - The block hash on which to obtain the balance for (default: top of chain)\n */\nexport async function getBalance(\n address: Encoded.AccountAddress | Encoded.ContractAddress | Encoded.OracleAddress,\n { format = AE_AMOUNT_FORMATS.AETTOS, ...options }:\n { format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],\n): Promise<string> {\n const addr = address.startsWith('ok_')\n ? encode(decode(address), Encoding.AccountAddress)\n : address as Encoded.AccountAddress | Encoded.ContractAddress;\n\n const { balance } = await getAccount(addr, options).catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { balance: 0n };\n });\n\n return formatAmount(balance, { targetDenomination: format });\n}\n\n/**\n * Obtain current generation\n * @category chain\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Current Generation\n */\nexport async function getCurrentGeneration(\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<Generation>> {\n return onNode.getCurrentGeneration();\n}\n\n/**\n * Get generation by hash or height\n * @category chain\n * @param hashOrHeight - Generation hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Generation\n */\nexport async function getGeneration(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<Generation>> {\n if (typeof hashOrHeight === 'number') return onNode.getGenerationByHeight(hashOrHeight);\n return onNode.getGenerationByHash(hashOrHeight);\n}\n\n/**\n * Get micro block transactions\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Transactions\n */\nexport async function getMicroBlockTransactions(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<SignedTx[]>> {\n return (await onNode.getMicroBlockTransactionsByHash(hash)).transactions;\n}\n\n/**\n * Get key block\n * @category chain\n * @param hashOrHeight - Key block hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Key Block\n */\nexport async function getKeyBlock(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<KeyBlock>> {\n if (typeof hashOrHeight === 'number') return onNode.getKeyBlockByHeight(hashOrHeight);\n return onNode.getKeyBlockByHash(hashOrHeight);\n}\n\n/**\n * Get micro block header\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Micro block header\n */\nexport async function getMicroBlockHeader(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<MicroBlockHeader>> {\n return onNode.getMicroBlockHeaderByHash(hash);\n}\n\ninterface TxDryRunArguments {\n tx: Encoded.Transaction;\n accountAddress: Encoded.AccountAddress;\n top?: number | Encoded.KeyBlockHash | Encoded.MicroBlockHash;\n txEvents?: any;\n resolve: Function;\n reject: Function;\n}\nconst txDryRunRequests: Map<string, TxDryRunArguments[] & { timeout?: NodeJS.Timeout }> = new Map();\n\nasync function txDryRunHandler(key: string, onNode: Node): Promise<void> {\n const rs = txDryRunRequests.get(key);\n txDryRunRequests.delete(key);\n if (rs == null) throw new InternalError('Can\\'t get dry-run request');\n\n let dryRunRes;\n try {\n const top = typeof rs[0].top === 'number'\n ? (await getKeyBlock(rs[0].top, { onNode })).hash : rs[0].top;\n dryRunRes = await onNode.protectedDryRunTxs({\n top,\n txEvents: rs[0].txEvents,\n txs: rs.map((req) => ({ tx: req.tx })),\n accounts: Array.from(new Set(rs.map((req) => req.accountAddress)))\n .map((pubKey) => ({ pubKey, amount: DRY_RUN_ACCOUNT.amount })),\n });\n } catch (error) {\n rs.forEach(({ reject }) => reject(error));\n return;\n }\n\n const { results, txEvents } = dryRunRes;\n results.forEach(({ result, reason, ...resultPayload }, idx) => {\n const {\n resolve, reject, tx, accountAddress,\n } = rs[idx];\n if (result === 'ok') resolve({ ...resultPayload, txEvents });\n else reject(Object.assign(new DryRunError(reason as string), { tx, accountAddress }));\n });\n}\n\n/**\n * Transaction dry-run\n * @category chain\n * @param tx - transaction to execute\n * @param accountAddress - address that will be used to execute transaction\n * @param options - Options\n * @param options.top - hash of block on which to make dry-run\n * @param options.txEvents - collect and return on-chain tx events that would result from the call\n * @param options.combine - Enables combining of similar requests to a single dry-run call\n * @param options.onNode - Node to use\n */\nexport async function txDryRun(\n tx: Encoded.Transaction,\n accountAddress: Encoded.AccountAddress,\n {\n top, txEvents, combine, onNode,\n }:\n { top?: TxDryRunArguments['top']; txEvents?: boolean; combine?: boolean; onNode: Node },\n): Promise<{\n txEvents?: TransformNodeType<DryRunResults['txEvents']>;\n } & TransformNodeType<DryRunResult>> {\n const key = combine === true ? [top, txEvents].join() : 'immediate';\n const requests = txDryRunRequests.get(key) ?? [];\n txDryRunRequests.set(key, requests);\n return new Promise((resolve, reject) => {\n requests.push({\n tx, accountAddress, top, txEvents, resolve, reject,\n });\n if (combine !== true) {\n void txDryRunHandler(key, onNode);\n return;\n }\n requests.timeout ??= setTimeout(() => { void txDryRunHandler(key, onNode); });\n });\n}\n\n/**\n * Get contract byte code\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getContractByteCode(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<ByteCode>> {\n return onNode.getContractCode(contractId);\n}\n\n/**\n * Get contract entry\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getContract(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<ContractObject>> {\n return onNode.getContract(contractId);\n}\n\n/**\n * Get name entry\n * @category AENS\n * @param name - AENS name\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getName(\n name: AensName,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<NameEntry>> {\n return onNode.getNameEntryByName(name);\n}\n\n/**\n * Resolve AENS name and return name hash\n * @category AENS\n * @param nameOrId - AENS name or address\n * @param key - in AENS pointers record\n * @param options - Options\n * @param options.verify - To ensure that name exist and have a corresponding pointer\n * // TODO: avoid that to don't trust to current api gateway\n * @param options.resolveByNode - Enables pointer resolving using node\n * @param options.onNode - Node to use\n * @returns Address or AENS name hash\n */\nexport async function resolveName <\n Type extends Encoding.AccountAddress | Encoding.ContractAddress,\n>(\n nameOrId: AensName | Encoded.Generic<Type>,\n key: string,\n { verify = true, resolveByNode = false, onNode }:\n { verify?: boolean; resolveByNode?: boolean; onNode: Node },\n): Promise<Encoded.Generic<Type | Encoding.Name>> {\n if (isNameValid(nameOrId)) {\n if (verify || resolveByNode) {\n const name = await onNode.getNameEntryByName(nameOrId);\n const pointer = name.pointers.find((p) => p.key === key);\n if (pointer == null) throw new AensPointerContextError(nameOrId, key);\n if (resolveByNode) return pointer.id as Encoded.Generic<Type>;\n }\n return produceNameId(nameOrId);\n }\n try {\n decode(nameOrId);\n return nameOrId;\n } catch (error) {\n throw new InvalidAensNameError(`Invalid name or address: ${nameOrId}`);\n }\n}\n"],"mappings":"SAASA,iBAAiB,EAAEC,YAAY;AAAA,SAC/BC,sBAAsB,EAAEC,KAAK;AAAA,SAC7BC,WAAW;AAAA,SACXC,WAAW,EAAEC,aAAa;AAAA,SAChBC,eAAe;AAAA,SAEhCC,uBAAuB,EAAEC,WAAW,EAAEC,oBAAoB,EAC1DC,eAAe,EAAEC,iBAAiB,EAAEC,aAAa;AAAA,SAQjDC,MAAM,EAAEC,MAAM,EAAWC,QAAQ;AAGnC;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,gBAAgBA,CAC9BC,IAA4B;AAAE;AAC9B;EAAEC,iBAAiB,GAAG,MAAM;EAAEC,gBAAgB,GAAG;AACO,CAAC,EACjD;EACR,MAAMC,IAAI,GAAG;IACXC,KAAK,EAAEH,iBAAiB;IACxBI,UAAU,EAAEH;EACd,CAAC,CAACF,IAAI,CAAC;EACP,OAAOM,IAAI,CAACC,KAAK,CAACJ,IAAI,GAAG,CAAC,CAAC;AAC7B;AAEA,MAAMK,WAA4D,GAAG,IAAIC,OAAO,CAAC,CAAC;;AAElF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,SAASA,CAC7B;EAAEC,MAAM,GAAG,KAAK;EAAE,GAAGC;AAGoB,CAAC,EACzB;EACjB,MAAMC,MAAM,GAAG3B,WAAW,CAAC0B,OAAO,CAACC,MAAM,CAAC;EA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CAACE,QAAQ,CAAC;MACtD,MAAMG,OAAO,GAAGN,IAAI,CAACO,QAAQ,CAACC,IAAI,CAAEC,CAAC,IAAKA,CAAC,CAACnD,GAAG,KAAKA,GAAG,CAAC;MACxD,IAAIgD,OAAO,IAAI,IAAI,EAAE,MAAM,IAAIlI,uBAAuB,CAAC+H,QAAQ,EAAE7C,GAAG,CAAC;MACrE,IAAI+C,aAAa,EAAE,OAAOC,OAAO,CAACI,EAAE;IACtC;IACA,OAAOxI,aAAa,CAACiI,QAAQ,CAAC;EAChC;EACA,IAAI;IACFzH,MAAM,CAACyH,QAAQ,CAAC;IAChB,OAAOA,QAAQ;EACjB,CAAC,CAAC,OAAO/D,KAAK,EAAE;IACd,MAAM,IAAI9D,oBAAoB,CAAE,4BAA2B6H,QAAS,EAAC,CAAC;EACxE;AACF"}
1
+ {"version":3,"file":"chain.mjs","names":["AE_AMOUNT_FORMATS","formatAmount","isAccountNotFoundError","pause","unwrapProxy","isNameValid","produceNameId","DRY_RUN_ACCOUNT","AensPointerContextError","DryRunError","InvalidAensNameError","TxTimedOutError","TxNotInChainError","InternalError","decode","encode","Encoding","_getPollInterval","type","_expectedMineRate","_microBlockCycle","onNode","_ref","_await$getVal","getVal","t","val","devModeDef","def","getNetworkId","base","Math","floor","heightCache","WeakMap","getHeight","cached","options","cache","get","time","Date","now","height","getCurrentKeyBlockHeight","set","poll","th","blocks","interval","_interval","max","tx","getTransactionByHash","blockHeight","ttl","awaitHeight","_interval2","min","currentHeight","waitForTxConfirm","txHash","confirm","newBlockHeight","getAccount","address","hash","getAccountByPubkeyAndHeight","getAccountByPubkeyAndHash","getAccountByPubkey","getBalance","format","AETTOS","addr","startsWith","AccountAddress","balance","catch","error","targetDenomination","getCurrentGeneration","getGeneration","hashOrHeight","getGenerationByHeight","getGenerationByHash","getMicroBlockTransactions","getMicroBlockTransactionsByHash","transactions","getKeyBlock","getKeyBlockByHeight","getKeyBlockByHash","getMicroBlockHeader","getMicroBlockHeaderByHash","txDryRunRequests","Map","txDryRunHandler","key","rs","delete","dryRunRes","top","protectedDryRunTxs","txEvents","txs","map","req","accounts","Array","from","Set","accountAddress","pubKey","amount","forEach","reject","results","result","reason","resultPayload","idx","resolve","Object","assign","txDryRun","combine","_txDryRunRequests$get","join","requests","Promise","_requests$timeout","push","timeout","setTimeout","getContractByteCode","contractId","getContractCode","getContract","getName","name","getNameEntryByName","resolveName","nameOrId","verify","resolveByNode","pointer","pointers","find","p","id"],"sources":["../src/chain.ts"],"sourcesContent":["import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';\nimport { isAccountNotFoundError, pause } from './utils/other';\nimport { unwrapProxy } from './utils/wrap-proxy';\nimport { isNameValid, produceNameId } from './tx/builder/helpers';\nimport { AensName, DRY_RUN_ACCOUNT } from './tx/builder/constants';\nimport {\n AensPointerContextError, DryRunError, InvalidAensNameError,\n TxTimedOutError, TxNotInChainError, InternalError,\n} from './utils/errors';\nimport Node, { TransformNodeType } from './Node';\nimport {\n Account as AccountNode, ByteCode, ContractObject, DryRunResult, DryRunResults,\n Generation, KeyBlock, MicroBlockHeader, NameEntry, SignedTx,\n} from './apis/node';\nimport {\n decode, encode, Encoded, Encoding,\n} from './utils/encoder';\n\n/**\n * @category chain\n * @param type - Type\n * @param options - Options\n */\nexport async function _getPollInterval(\n type: 'key-block' | 'micro-block',\n { _expectedMineRate, _microBlockCycle, onNode }:\n { _expectedMineRate?: number; _microBlockCycle?: number; onNode: Node },\n): Promise<number> {\n const getVal = async (\n t: string,\n val: number | undefined,\n devModeDef: number,\n def: number,\n ): Promise<number | null> => {\n if (t !== type) return null;\n if (val != null) return val;\n return await onNode?.getNetworkId() === 'ae_dev' ? devModeDef : def;\n };\n\n const base = await getVal('key-block', _expectedMineRate, 0, 180000)\n ?? await getVal('micro-block', _microBlockCycle, 0, 3000)\n ?? (() => { throw new InternalError(`Unknown type: ${type}`); })();\n return Math.floor(base / 3);\n}\n\nconst heightCache: WeakMap<Node, { time: number; height: number }> = new WeakMap();\n\n/**\n * Obtain current height of the chain\n * @category chain\n * @param options - Options\n * @param options.cached - Get height from the cache. The lag behind the actual height shouldn't\n * be more than 1 block. Use if needed to reduce requests count, and approximate value can be used.\n * For example, for timeout check in transaction status polling.\n * @returns Current chain height\n */\nexport async function getHeight(\n { cached = false, ...options }: {\n onNode: Node;\n cached?: boolean;\n } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n const onNode = unwrapProxy(options.onNode);\n if (cached) {\n const cache = heightCache.get(onNode);\n if (cache != null && cache.time > Date.now() - await _getPollInterval('key-block', options)) {\n return cache.height;\n }\n }\n const { height } = await onNode.getCurrentKeyBlockHeight();\n heightCache.set(onNode, { height, time: Date.now() });\n return height;\n}\n\n/**\n * Return transaction details if it is mined, fail otherwise.\n * If the transaction has ttl specified then would wait till it leaves the mempool.\n * Otherwise would fail if a specified amount of blocks were mined.\n * @category chain\n * @param th - The hash of transaction to poll\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.blocks - Number of blocks mined after which to fail if transaction ttl is not set\n * @param options.onNode - Node to use\n * @returns The transaction as it was mined\n */\nexport async function poll(\n th: Encoded.TxHash,\n {\n blocks = 5, interval, ...options\n }:\n { blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<TransformNodeType<SignedTx>> {\n interval ??= await _getPollInterval('micro-block', options);\n let max;\n do {\n const tx = await options.onNode.getTransactionByHash(th);\n if (tx.blockHeight !== -1) return tx;\n if (max == null) {\n max = tx.tx.ttl !== 0 ? -1\n : await getHeight({ ...options, cached: true }) + blocks;\n }\n await pause(interval);\n } while (max === -1 ? true : await getHeight({ ...options, cached: true }) < max);\n throw new TxTimedOutError(blocks, th);\n}\n\n/**\n * Wait for the chain to reach a specific height\n * @category chain\n * @param height - Height to wait for\n * @param options - Options\n * @param options.interval - Interval (in ms) at which to poll the chain\n * @param options.onNode - Node to use\n * @returns Current chain height\n */\nexport async function awaitHeight(\n height: number,\n { interval, ...options }:\n { interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],\n): Promise<number> {\n interval ??= Math.min(await _getPollInterval('key-block', options), 5000);\n let currentHeight;\n do {\n if (currentHeight != null) await pause(interval);\n currentHeight = await getHeight(options);\n } while (currentHeight < height);\n return currentHeight;\n}\n\n/**\n * Wait for transaction confirmation\n * @category chain\n * @param txHash - Transaction hash\n * @param options - Options\n * @param options.confirm - Number of micro blocks to wait for transaction confirmation\n * @param options.onNode - Node to use\n * @returns Current Height\n */\nexport async function waitForTxConfirm(\n txHash: Encoded.TxHash,\n { confirm = 3, onNode, ...options }:\n { confirm?: number; onNode: Node } & Parameters<typeof awaitHeight>[1],\n): Promise<number> {\n const { blockHeight } = await onNode.getTransactionByHash(txHash);\n const height = await awaitHeight(blockHeight + confirm, { onNode, ...options });\n const { blockHeight: newBlockHeight } = await onNode.getTransactionByHash(txHash);\n switch (newBlockHeight) {\n case -1:\n throw new TxNotInChainError(txHash);\n case blockHeight:\n return height;\n default:\n return waitForTxConfirm(txHash, { onNode, confirm, ...options });\n }\n}\n\n/**\n * Get account by account public key\n * @category chain\n * @param address - Account address (public key)\n * @param options - Options\n * @param options.height - Get account on specific block by block height\n * @param options.hash - Get account on specific block by micro block hash or key block hash\n * @param options.onNode - Node to use\n */\nexport async function getAccount(\n address: Encoded.AccountAddress | Encoded.ContractAddress,\n { height, hash, onNode }:\n { height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },\n): Promise<TransformNodeType<AccountNode>> {\n if (height != null) return onNode.getAccountByPubkeyAndHeight(address, height);\n if (hash != null) return onNode.getAccountByPubkeyAndHash(address, hash);\n return onNode.getAccountByPubkey(address);\n}\n\n/**\n * Request the balance of specified account\n * @category chain\n * @param address - The public account address to obtain the balance for\n * @param options - Options\n * @param options.format\n * @param options.height - The chain height at which to obtain the balance for\n * (default: top of chain)\n * @param options.hash - The block hash on which to obtain the balance for (default: top of chain)\n */\nexport async function getBalance(\n address: Encoded.AccountAddress | Encoded.ContractAddress | Encoded.OracleAddress,\n { format = AE_AMOUNT_FORMATS.AETTOS, ...options }:\n { format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],\n): Promise<string> {\n const addr = address.startsWith('ok_')\n ? encode(decode(address), Encoding.AccountAddress)\n : address as Encoded.AccountAddress | Encoded.ContractAddress;\n\n const { balance } = await getAccount(addr, options).catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { balance: 0n };\n });\n\n return formatAmount(balance, { targetDenomination: format });\n}\n\n/**\n * Obtain current generation\n * @category chain\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Current Generation\n */\nexport async function getCurrentGeneration(\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<Generation>> {\n return onNode.getCurrentGeneration();\n}\n\n/**\n * Get generation by hash or height\n * @category chain\n * @param hashOrHeight - Generation hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Generation\n */\nexport async function getGeneration(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<Generation>> {\n if (typeof hashOrHeight === 'number') return onNode.getGenerationByHeight(hashOrHeight);\n return onNode.getGenerationByHash(hashOrHeight);\n}\n\n/**\n * Get micro block transactions\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Transactions\n */\nexport async function getMicroBlockTransactions(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<SignedTx[]>> {\n return (await onNode.getMicroBlockTransactionsByHash(hash)).transactions;\n}\n\n/**\n * Get key block\n * @category chain\n * @param hashOrHeight - Key block hash or height\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Key Block\n */\nexport async function getKeyBlock(\n hashOrHeight: Encoded.KeyBlockHash | number,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<KeyBlock>> {\n if (typeof hashOrHeight === 'number') return onNode.getKeyBlockByHeight(hashOrHeight);\n return onNode.getKeyBlockByHash(hashOrHeight);\n}\n\n/**\n * Get micro block header\n * @category chain\n * @param hash - Micro block hash\n * @param options - Options\n * @param options.onNode - Node to use\n * @returns Micro block header\n */\nexport async function getMicroBlockHeader(\n hash: Encoded.MicroBlockHash,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<MicroBlockHeader>> {\n return onNode.getMicroBlockHeaderByHash(hash);\n}\n\ninterface TxDryRunArguments {\n tx: Encoded.Transaction;\n accountAddress: Encoded.AccountAddress;\n top?: number | Encoded.KeyBlockHash | Encoded.MicroBlockHash;\n txEvents?: any;\n resolve: Function;\n reject: Function;\n}\nconst txDryRunRequests: Map<string, TxDryRunArguments[] & { timeout?: NodeJS.Timeout }> = new Map();\n\nasync function txDryRunHandler(key: string, onNode: Node): Promise<void> {\n const rs = txDryRunRequests.get(key);\n txDryRunRequests.delete(key);\n if (rs == null) throw new InternalError('Can\\'t get dry-run request');\n\n let dryRunRes;\n try {\n const top = typeof rs[0].top === 'number'\n ? (await getKeyBlock(rs[0].top, { onNode })).hash : rs[0].top;\n dryRunRes = await onNode.protectedDryRunTxs({\n top,\n txEvents: rs[0].txEvents,\n txs: rs.map((req) => ({ tx: req.tx })),\n accounts: Array.from(new Set(rs.map((req) => req.accountAddress)))\n .map((pubKey) => ({ pubKey, amount: DRY_RUN_ACCOUNT.amount })),\n });\n } catch (error) {\n rs.forEach(({ reject }) => reject(error));\n return;\n }\n\n const { results, txEvents } = dryRunRes;\n results.forEach(({ result, reason, ...resultPayload }, idx) => {\n const {\n resolve, reject, tx, accountAddress,\n } = rs[idx];\n if (result === 'ok') resolve({ ...resultPayload, txEvents });\n else reject(Object.assign(new DryRunError(reason as string), { tx, accountAddress }));\n });\n}\n\n/**\n * Transaction dry-run\n * @category chain\n * @param tx - transaction to execute\n * @param accountAddress - address that will be used to execute transaction\n * @param options - Options\n * @param options.top - hash of block on which to make dry-run\n * @param options.txEvents - collect and return on-chain tx events that would result from the call\n * @param options.combine - Enables combining of similar requests to a single dry-run call\n * @param options.onNode - Node to use\n */\nexport async function txDryRun(\n tx: Encoded.Transaction,\n accountAddress: Encoded.AccountAddress,\n {\n top, txEvents, combine, onNode,\n }:\n { top?: TxDryRunArguments['top']; txEvents?: boolean; combine?: boolean; onNode: Node },\n): Promise<{\n txEvents?: TransformNodeType<DryRunResults['txEvents']>;\n } & TransformNodeType<DryRunResult>> {\n const key = combine === true ? [top, txEvents].join() : 'immediate';\n const requests = txDryRunRequests.get(key) ?? [];\n txDryRunRequests.set(key, requests);\n return new Promise((resolve, reject) => {\n requests.push({\n tx, accountAddress, top, txEvents, resolve, reject,\n });\n if (combine !== true) {\n void txDryRunHandler(key, onNode);\n return;\n }\n requests.timeout ??= setTimeout(() => { void txDryRunHandler(key, onNode); });\n });\n}\n\n/**\n * Get contract byte code\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getContractByteCode(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<ByteCode>> {\n return onNode.getContractCode(contractId);\n}\n\n/**\n * Get contract entry\n * @category contract\n * @param contractId - Contract address\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getContract(\n contractId: Encoded.ContractAddress,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<ContractObject>> {\n return onNode.getContract(contractId);\n}\n\n/**\n * Get name entry\n * @category AENS\n * @param name - AENS name\n * @param options - Options\n * @param options.onNode - Node to use\n */\nexport async function getName(\n name: AensName,\n { onNode }: { onNode: Node },\n): Promise<TransformNodeType<NameEntry>> {\n return onNode.getNameEntryByName(name);\n}\n\n/**\n * Resolve AENS name and return name hash\n * @category AENS\n * @param nameOrId - AENS name or address\n * @param key - in AENS pointers record\n * @param options - Options\n * @param options.verify - To ensure that name exist and have a corresponding pointer\n * // TODO: avoid that to don't trust to current api gateway\n * @param options.resolveByNode - Enables pointer resolving using node\n * @param options.onNode - Node to use\n * @returns Address or AENS name hash\n */\nexport async function resolveName <\n Type extends Encoding.AccountAddress | Encoding.ContractAddress,\n>(\n nameOrId: AensName | Encoded.Generic<Type>,\n key: string,\n { verify = true, resolveByNode = false, onNode }:\n { verify?: boolean; resolveByNode?: boolean; onNode: Node },\n): Promise<Encoded.Generic<Type | Encoding.Name>> {\n if (isNameValid(nameOrId)) {\n if (verify || resolveByNode) {\n const name = await onNode.getNameEntryByName(nameOrId);\n const pointer = name.pointers.find((p) => p.key === key);\n if (pointer == null) throw new AensPointerContextError(nameOrId, key);\n if (resolveByNode) return pointer.id as Encoded.Generic<Type>;\n }\n return produceNameId(nameOrId);\n }\n try {\n decode(nameOrId);\n return nameOrId;\n } catch (error) {\n throw new InvalidAensNameError(`Invalid name or address: ${nameOrId}`);\n }\n}\n"],"mappings":"SAASA,iBAAiB,EAAEC,YAAY;AAAA,SAC/BC,sBAAsB,EAAEC,KAAK;AAAA,SAC7BC,WAAW;AAAA,SACXC,WAAW,EAAEC,aAAa;AAAA,SAChBC,eAAe;AAAA,SAEhCC,uBAAuB,EAAEC,WAAW,EAAEC,oBAAoB,EAC1DC,eAAe,EAAEC,iBAAiB,EAAEC,aAAa;AAAA,SAQjDC,MAAM,EAAEC,MAAM,EAAWC,QAAQ;AAGnC;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,gBAAgBA,CACpCC,IAAiC,EACjC;EAAEC,iBAAiB;EAAEC,gBAAgB;EAAEC;AAC+B,CAAC,EACtD;EAAA,IAAAC,IAAA,EAAAC,aAAA;EACjB,MAAMC,MAAM,GAAG,MAAAA,CACbC,CAAS,EACTC,GAAuB,EACvBC,UAAkB,EAClBC,GAAW,KACgB;IAC3B,IAAIH,CAAC,KAAKP,IAAI,EAAE,OAAO,IAAI;IAC3B,IAAIQ,GAAG,IAAI,IAAI,EAAE,OAAOA,GAAG;IAC3B,OAAO,QAAML,MAAM,aAANA,MAAM,uBAANA,MAAM,CAAEQ,YAAY,CAAC,CAAC,OAAK,QAAQ,GAAGF,UAAU,GAAGC,GA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  break;
473
473
  case 'error':
474
474
  message = decode(returnValue).toString();
475
+ if (/Expected \d+ arguments, got \d+/.test(message)) {
476
+ throw new ContractError(`ACI doesn't match called contract. Error provided by node: ${message}`);
477
+ }
475
478
  break;
476
479
  default:
477
480
  throw new InternalError(`Unknown return type: ${returnType}`);
@@ -1 +1 @@
1
- {"version":3,"file":"Contract.mjs","names":["_aeternityAeppCalldata","Encoder","Calldata","Tag","ConsensusProtocolVersion","DRY_RUN_ACCOUNT","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","isAccountNotFoundError","isNameValid","produceNameId","_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","$call","callStatic","gasUsed","Math","floor","$deploy","_opt$gasLimit","_other$result","opt","address","onAccount","ownerId","tx","_isInternalBuild","tag","ContractCreateTx","gasLimit","callData","_calldata","encode","_name","code","other","_sendAndProcess2","rawTx","log","decodedEvents","$decodeEvents","owner","transaction","fn","_opt$gasLimit2","top","fnAci","_getFunctionAci2","contractId","amount","Number","payable","callerId","error","useFallbackAccount","message","pub","nonce","topOption","account","catch","kind","txOpt","ContractCallTx","callObj","dryRunOther","txData","events","omitUnknown","map","event","topics","t","BigInt","contractName","_getContractNameByEvent2","decoded","decodeEvent","data","args","Object","entries","contract","filter","e","initialize","aci","validateBytecode","otherOptions","res","_bytecode","resolveByNode","isIris","getNodeInfo","consensusProtocolVersion","Iris","active","onChanBytecode","isValid","validateBySourceCode","validate","ContractWithMethods","constructor","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","writable","value","_aci","aciLast","length","keys","_classPrivateFieldSet","_classPrivateFieldGet","assign","fromEntries","functions","arguments","aciArgs","stateful","pop","_Contract","returnType","returnValue","decodedResult","decodeFateString","toString","blockHeight","find","f","returns","ctAddress","nameHash","contractAddressToName","addressToName","isEqual","a","b","JSON","stringify","contracts","matchedEvents","variant","values","flat","eventName","type","idx","arr","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 {\n Tag, AensName, ConsensusProtocolVersion, DRY_RUN_ACCOUNT,\n} 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,\n} from '../chain';\nimport { sendTransaction, SendTransactionOptions } from '../send-transaction';\nimport AccountBase from '../account/Base';\nimport { TxUnpacked } from '../tx/builder/schema.generated';\nimport { isAccountNotFoundError } from '../utils/other';\nimport { isNameValid, produceNameId } from '../tx/builder/helpers';\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 _isInternalBuild: true,\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 const { hash, ...other } = await this.#sendAndProcess(\n tx,\n 'init',\n { ...opt, onAccount: opt.onAccount },\n );\n this.$options.address = buildContractIdByContractTx(other.rawTx);\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(name);\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 { address, name } = this.$options;\n // TODO: call `produceNameId` on buildTx side\n const contractId = name != null ? produceNameId(name) : 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 && Number(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) {\n const topOption = top != null && { [typeof top === 'number' ? 'height' : 'hash']: top };\n const account = await getAccount(callerId, { ...topOption, onNode }).catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { kind: 'basic', nonce: 0 };\n });\n opt.nonce = account.kind === 'generalized' ? 0 : account.nonce + 1;\n }\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 _isInternalBuild: true,\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 let name;\n if (address != null) {\n address = await resolveName(\n address,\n 'contract_pubkey',\n { resolveByNode: true, onNode },\n ) as Encoded.ContractAddress;\n const isIris = (await onNode.getNodeInfo())\n .consensusProtocolVersion === ConsensusProtocolVersion.Iris;\n if (!isIris && isNameValid(address)) name = address;\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 name,\n fileSystem,\n ...otherOptions,\n });\n }\n\n _aci: Aci;\n\n readonly #aciContract: ContractAci;\n\n _name: string;\n\n _calldata: Calldata;\n\n $options: Omit<ConstructorParameters<typeof Contract>[0], 'aci'>;\n\n /**\n * @param options - Options\n */\n constructor({ aci, ...otherOptions }: {\n onCompiler?: CompilerBase;\n onNode: Node;\n bytecode?: Encoded.ContractBytearray;\n aci: Aci;\n address?: Encoded.ContractAddress;\n /**\n * Supported only in Ceres\n */\n name?: AensName;\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,SAE7DG,GAAG,EAAYC,wBAAwB,EAAEC,eAAe;AAAA,SAGxDC,2BAA2B,EAAEC,QAAQ,EAAEC,YAAY,EAAk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ACqK,SAAS,EAAEU,aAAa,CAAC;EAC5E;AACF;AAiMF;AACA,MAAMvC,mBAA6C,GAAGjH,QAAe;AAErE,eAAeiH,mBAAmB"}
1
+ {"version":3,"file":"Contract.mjs","names":["_aeternityAeppCalldata","Encoder","Calldata","Tag","ConsensusProtocolVersion","DRY_RUN_ACCOUNT","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","isAccountNotFoundError","isNameValid","produceNameId","_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","$call","callStatic","gasUsed","Math","floor","$deploy","_opt$gasLimit","_other$result","opt","address","onAccount","ownerId","tx","_isInternalBuild","tag","ContractCreateTx","gasLimit","callData","_calldata","encode","_name","code","other","_sendAndProcess2","rawTx","log","decodedEvents","$decodeEvents","owner","transaction","fn","_opt$gasLimit2","top","fnAci","_getFunctionAci2","contractId","amount","Number","payable","callerId","error","useFallbackAccount","message","pub","nonce","topOption","account","catch","kind","txOpt","ContractCallTx","callObj","dryRunOther","txData","events","omitUnknown","map","event","topics","t","BigInt","contractName","_getContractNameByEvent2","decoded","decodeEvent","data","args","Object","entries","contract","filter","e","initialize","aci","validateBytecode","otherOptions","res","_bytecode","resolveByNode","isIris","getNodeInfo","consensusProtocolVersion","Iris","active","onChanBytecode","isValid","validateBySourceCode","validate","ContractWithMethods","constructor","_classPrivateMethodInitSpec","_classPrivateFieldInitSpec","writable","value","_aci","aciLast","length","keys","_classPrivateFieldSet","_classPrivateFieldGet","assign","fromEntries","functions","arguments","aciArgs","stateful","pop","_Contract","returnType","returnValue","decodedResult","decodeFateString","toString","test","blockHeight","find","f","returns","ctAddress","nameHash","contractAddressToName","addressToName","isEqual","a","b","JSON","stringify","contracts","matchedEvents","variant","values","flat","eventName","type","idx","arr","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 {\n Tag, AensName, ConsensusProtocolVersion, DRY_RUN_ACCOUNT,\n} 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,\n} from '../chain';\nimport { sendTransaction, SendTransactionOptions } from '../send-transaction';\nimport AccountBase from '../account/Base';\nimport { TxUnpacked } from '../tx/builder/schema.generated';\nimport { isAccountNotFoundError } from '../utils/other';\nimport { isNameValid, produceNameId } from '../tx/builder/helpers';\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 if (/Expected \\d+ arguments, got \\d+/.test(message)) {\n throw new ContractError(`ACI doesn't match called contract. Error provided by node: ${message}`);\n }\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 _isInternalBuild: true,\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 const { hash, ...other } = await this.#sendAndProcess(\n tx,\n 'init',\n { ...opt, onAccount: opt.onAccount },\n );\n this.$options.address = buildContractIdByContractTx(other.rawTx);\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(name);\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 { address, name } = this.$options;\n // TODO: call `produceNameId` on buildTx side\n const contractId = name != null ? produceNameId(name) : 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 && Number(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) {\n const topOption = top != null && { [typeof top === 'number' ? 'height' : 'hash']: top };\n const account = await getAccount(callerId, { ...topOption, onNode }).catch((error) => {\n if (!isAccountNotFoundError(error)) throw error;\n return { kind: 'basic', nonce: 0 };\n });\n opt.nonce = account.kind === 'generalized' ? 0 : account.nonce + 1;\n }\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 _isInternalBuild: true,\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 let name;\n if (address != null) {\n address = await resolveName(\n address,\n 'contract_pubkey',\n { resolveByNode: true, onNode },\n ) as Encoded.ContractAddress;\n const isIris = (await onNode.getNodeInfo())\n .consensusProtocolVersion === ConsensusProtocolVersion.Iris;\n if (!isIris && isNameValid(address)) name = address;\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 name,\n fileSystem,\n ...otherOptions,\n });\n }\n\n _aci: Aci;\n\n readonly #aciContract: ContractAci;\n\n _name: string;\n\n _calldata: Calldata;\n\n $options: Omit<ConstructorParameters<typeof Contract>[0], 'aci'>;\n\n /**\n * @param options - Options\n */\n constructor({ aci, ...otherOptions }: {\n onCompiler?: CompilerBase;\n onNode: Node;\n bytecode?: Encoded.ContractBytearray;\n aci: Aci;\n address?: Encoded.ContractAddress;\n /**\n * Supported only in Ceres\n */\n name?: AensName;\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,SAE7DG,GAAG,EAAYC,wBAAwB,EAAEC,eAAe;AAAA,SAGxDC,2BAA2B,EAAEC,QAAQ,EAAEC,YAAY,EAAkBC,W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,CAAC;IAC7E,KAAK,CAAC;MAAE,OAAOU,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClC;MAAS,MAAM,IAAIhL,6BAA6B,CAACsK,SAAS,EAAEU,aAAa,CAAC;EAC5E;AACF;AAiMF;AACA,MAAMxC,mBAA6C,GAAGjH,QAAe;AAErE,eAAeiH,mBAAmB"}
package/es/oracle.d.ts CHANGED
@@ -23,7 +23,7 @@ type OracleQueries = Awaited<ReturnType<Node['getOracleQueriesByPubkey']>>['orac
23
23
  * @param options.onNode - Node to use
24
24
  * @returns Callback to stop polling function
25
25
  */
26
- export declare function pollForQueries(oracleId: Encoded.OracleAddress, onQuery: (query: OracleQueries[number]) => void, { interval, onNode, ...options }: {
26
+ export declare function pollForQueries(oracleId: Encoded.OracleAddress, onQuery: (query: OracleQueries[number]) => void, { interval, ...options }: {
27
27
  interval?: number;
28
28
  onNode: Node;
29
29
  } & Parameters<typeof _getPollInterval>[1]): () => void;
@@ -37,7 +37,7 @@ export declare function pollForQueries(oracleId: Encoded.OracleAddress, onQuery:
37
37
  * @param options.onNode - Node to use
38
38
  * @returns OracleQuery object
39
39
  */
40
- export declare function pollForQueryResponse(oracleId: Encoded.OracleAddress, queryId: Encoded.OracleQueryId, { interval, onNode, ...options }: {
40
+ export declare function pollForQueryResponse(oracleId: Encoded.OracleAddress, queryId: Encoded.OracleQueryId, { interval, ...options }: {
41
41
  interval?: number;
42
42
  onNode: Node;
43
43
  } & Parameters<typeof _getPollInterval>[1]): Promise<string>;