@sentio/sdk-bundle 2.40.0-rc.49 → 2.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/aptos/builtin/0x1.js +1 -1
- package/lib/aptos/builtin/0x3.js +1 -1
- package/lib/aptos/builtin/index.js +1 -1
- package/lib/aptos/codegen/index.js +1 -1
- package/lib/aptos/ext/index.js +1 -1
- package/lib/aptos/index.js +1 -1
- package/lib/{chunk-EMLTM66L.js → chunk-6QU3EEK4.js} +2 -2
- package/lib/{chunk-KOBBMSPQ.js → chunk-DZBEFZKE.js} +2 -2
- package/lib/{chunk-ALQM5ZAU.js → chunk-HPOL2YBD.js} +2 -2
- package/lib/chunk-HPOL2YBD.js.map +1 -0
- package/lib/testing/index.js +1 -1
- package/package.json +2 -2
- package/src/aptos/network.ts +1 -1
- package/lib/chunk-ALQM5ZAU.js.map +0 -1
- /package/lib/{chunk-EMLTM66L.js.map → chunk-6QU3EEK4.js.map} +0 -0
- /package/lib/{chunk-KOBBMSPQ.js.map → chunk-DZBEFZKE.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js","../../../node_modules/.pnpm/@sindresorhus+is@4.6.0/node_modules/@sindresorhus/is/dist/index.js","../../../node_modules/.pnpm/p-cancelable@2.1.1/node_modules/p-cancelable/index.js","../../../node_modules/.pnpm/defer-to-connect@2.0.1/node_modules/defer-to-connect/dist/source/index.js","../../../node_modules/.pnpm/@szmarczak+http-timer@4.0.6/node_modules/@szmarczak/http-timer/dist/source/index.js","../../../node_modules/.pnpm/cacheable-lookup@5.0.4/node_modules/cacheable-lookup/source/index.js","../../../node_modules/.pnpm/normalize-url@6.1.0/node_modules/normalize-url/index.js","../../../node_modules/.pnpm/end-of-stream@1.4.4/node_modules/end-of-stream/index.js","../../../node_modules/.pnpm/pump@3.0.0/node_modules/pump/index.js","../../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js","../../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js","../../../node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js","../../../node_modules/.pnpm/lowercase-keys@2.0.0/node_modules/lowercase-keys/index.js","../../../node_modules/.pnpm/responselike@2.0.1/node_modules/responselike/src/index.js","../../../node_modules/.pnpm/mimic-response@1.0.1/node_modules/mimic-response/index.js","../../../node_modules/.pnpm/clone-response@1.0.3/node_modules/clone-response/src/index.js","../../../node_modules/.pnpm/json-buffer@3.0.1/node_modules/json-buffer/index.js","../../../node_modules/.pnpm/keyv@4.5.4/node_modules/keyv/src/index.js","../../../node_modules/.pnpm/cacheable-request@7.0.4/node_modules/cacheable-request/src/index.js","../../../node_modules/.pnpm/mimic-response@3.1.0/node_modules/mimic-response/index.js","../../../node_modules/.pnpm/decompress-response@6.0.0/node_modules/decompress-response/index.js","../../../node_modules/.pnpm/quick-lru@5.1.1/node_modules/quick-lru/index.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/agent.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/incoming-message.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/utils/url-to-options.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/utils/proxy-events.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/utils/is-request-pseudo-header.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/utils/errors.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/client-request.js","../../../node_modules/.pnpm/resolve-alpn@1.2.1/node_modules/resolve-alpn/index.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/utils/calculate-server-name.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/auto.js","../../../node_modules/.pnpm/http2-wrapper@1.0.3/node_modules/http2-wrapper/source/index.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/is-form-data.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/get-body-size.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/proxy-events.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/unhandle.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/timed-out.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/url-to-options.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/options-to-url.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/weakable-map.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/get-buffer.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/dns-ip-version.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/utils/is-response-ok.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/utils/deprecation-warning.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/as-promise/normalize-arguments.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/calculate-retry-delay.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/index.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/as-promise/types.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/as-promise/parse-body.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/as-promise/index.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/as-promise/create-rejection.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/utils/deep-freeze.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/types.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/create.js","../../../node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/index.js","../src/aptos/network.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/common.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/hex.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/consts.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/dist/esm/chunk-FVA2OPG4.mjs","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/serializer.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/accountAddress.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/types/generated/queries.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/client/types.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/version.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/client/core.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/client/get.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/client/post.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/general.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/staking.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/utils/helpers.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/utils/memoize.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/utils/const.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/transaction.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/utils.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/staking.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/identifier.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/typeTag/index.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/typeTag/parser.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/serializable/movePrimitives.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/serializable/moveStructs.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/serializable/fixedBytes.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/transactionBuilder/helpers.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/signature.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/utils.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/hdKey.ts","../../../node_modules/.pnpm/@scure+bip39@1.3.0/node_modules/@scure/bip39/esm/index.js","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/publicKey.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/authenticationKey.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/ed25519.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/multiEd25519.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/secp256k1.ts","../../../node_modules/.pnpm/@scure+bip32@1.4.0/node_modules/@scure/bip32/index.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/singleKey.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/crypto/multiKey.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/authenticator/account.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/account/Ed25519Account.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/account/SingleKeyAccount.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/core/account/Account.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/account.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/transactionBuilder/remoteAbi.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/moduleId.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/serializable/entryFunctionBytes.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/transactionPayload.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/chainId.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/rawTransaction.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/multiAgentTransaction.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/authenticator/transaction.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/signedTransaction.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/simpleTransaction.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/bcs/deserializer.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/utils/normalizeBundle.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/utils/apiEndpoints.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/transactionBuilder/transactionBuilder.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/instances/rotationProofChallenge.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/transactionSubmission.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/transactionSubmission/build.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/management/accountSequenceNumber.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/management/asyncQueue.ts","../../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.mjs","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/transactions/management/transactionWorker.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/transactionSubmission/management.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/transactionSubmission/helpers.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/transactionSubmission/simulate.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/transactionSubmission/submit.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/transaction.ts","../../../node_modules/.pnpm/@aptos-labs+aptos-client@0.1.0/node_modules/@aptos-labs/aptos-client/src/index.node.ts","../../../node_modules/.pnpm/@aptos-labs+aptos-client@0.1.0/node_modules/@aptos-labs/aptos-client/src/cookieJar.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/aptosConfig.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/coin.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/coin.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/digitalAsset.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/digitalAsset.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/event.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/event.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/faucet.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/faucet.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/fungibleAsset.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/fungibleAsset.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/view.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/general.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/account.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/internal/ans.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/ans.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/api/aptos.ts","../../../node_modules/.pnpm/@aptos-labs+ts-sdk@1.14.0/node_modules/@aptos-labs/ts-sdk/src/types/index.ts","../../../node_modules/.pnpm/@typemove+aptos@1.6.1/node_modules/@typemove/aptos/src/to-internal.ts","../../../node_modules/.pnpm/@typemove+aptos@1.6.1/node_modules/@typemove/aptos/src/aptos-chain-adapter.ts"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","\"use strict\";\n/// <reference lib=\"es2018\"/>\n/// <reference lib=\"dom\"/>\n/// <reference types=\"node\"/>\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst typedArrayTypeNames = [\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nfunction isTypedArrayName(name) {\n return typedArrayTypeNames.includes(name);\n}\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Blob',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'FormData',\n 'URLSearchParams',\n 'HTMLElement',\n ...typedArrayTypeNames\n];\nfunction isObjectTypeName(name) {\n return objectTypeNames.includes(name);\n}\nconst primitiveTypeNames = [\n 'null',\n 'undefined',\n 'string',\n 'number',\n 'bigint',\n 'boolean',\n 'symbol'\n];\nfunction isPrimitiveTypeName(name) {\n return primitiveTypeNames.includes(name);\n}\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isOfType(type) {\n return (value) => typeof value === type;\n}\nconst { toString } = Object.prototype;\nconst getObjectType = (value) => {\n const objectTypeName = toString.call(value).slice(8, -1);\n if (/HTML\\w+Element/.test(objectTypeName) && is.domElement(value)) {\n return 'HTMLElement';\n }\n if (isObjectTypeName(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n};\nconst isObjectOfType = (type) => (value) => getObjectType(value) === type;\nfunction is(value) {\n if (value === null) {\n return 'null';\n }\n switch (typeof value) {\n case 'undefined':\n return 'undefined';\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'function':\n return 'Function';\n case 'bigint':\n return 'bigint';\n case 'symbol':\n return 'symbol';\n default:\n }\n if (is.observable(value)) {\n return 'Observable';\n }\n if (is.array(value)) {\n return 'Array';\n }\n if (is.buffer(value)) {\n return 'Buffer';\n }\n const tagType = getObjectType(value);\n if (tagType) {\n return tagType;\n }\n if (value instanceof String || value instanceof Boolean || value instanceof Number) {\n throw new TypeError('Please don\\'t use object wrappers for primitive types');\n }\n return 'Object';\n}\nis.undefined = isOfType('undefined');\nis.string = isOfType('string');\nconst isNumberType = isOfType('number');\nis.number = (value) => isNumberType(value) && !is.nan(value);\nis.bigint = isOfType('bigint');\n// eslint-disable-next-line @typescript-eslint/ban-types\nis.function_ = isOfType('function');\nis.null_ = (value) => value === null;\nis.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');\nis.boolean = (value) => value === true || value === false;\nis.symbol = isOfType('symbol');\nis.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value));\nis.array = (value, assertion) => {\n if (!Array.isArray(value)) {\n return false;\n }\n if (!is.function_(assertion)) {\n return true;\n }\n return value.every(assertion);\n};\nis.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; };\nis.blob = (value) => isObjectOfType('Blob')(value);\nis.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);\nis.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value));\nis.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); };\nis.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); };\nis.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); };\nis.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw);\nis.nativePromise = (value) => isObjectOfType('Promise')(value);\nconst hasPromiseAPI = (value) => {\n var _a, _b;\n return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) &&\n is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch);\n};\nis.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);\nis.generatorFunction = isObjectOfType('GeneratorFunction');\nis.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction';\nis.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction';\n// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types\nis.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');\nis.regExp = isObjectOfType('RegExp');\nis.date = isObjectOfType('Date');\nis.error = isObjectOfType('Error');\nis.map = (value) => isObjectOfType('Map')(value);\nis.set = (value) => isObjectOfType('Set')(value);\nis.weakMap = (value) => isObjectOfType('WeakMap')(value);\nis.weakSet = (value) => isObjectOfType('WeakSet')(value);\nis.int8Array = isObjectOfType('Int8Array');\nis.uint8Array = isObjectOfType('Uint8Array');\nis.uint8ClampedArray = isObjectOfType('Uint8ClampedArray');\nis.int16Array = isObjectOfType('Int16Array');\nis.uint16Array = isObjectOfType('Uint16Array');\nis.int32Array = isObjectOfType('Int32Array');\nis.uint32Array = isObjectOfType('Uint32Array');\nis.float32Array = isObjectOfType('Float32Array');\nis.float64Array = isObjectOfType('Float64Array');\nis.bigInt64Array = isObjectOfType('BigInt64Array');\nis.bigUint64Array = isObjectOfType('BigUint64Array');\nis.arrayBuffer = isObjectOfType('ArrayBuffer');\nis.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer');\nis.dataView = isObjectOfType('DataView');\nis.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value);\nis.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype;\nis.urlInstance = (value) => isObjectOfType('URL')(value);\nis.urlString = (value) => {\n if (!is.string(value)) {\n return false;\n }\n try {\n new URL(value); // eslint-disable-line no-new\n return true;\n }\n catch (_a) {\n return false;\n }\n};\n// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);`\nis.truthy = (value) => Boolean(value);\n// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);`\nis.falsy = (value) => !value;\nis.nan = (value) => Number.isNaN(value);\nis.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value);\nis.integer = (value) => Number.isInteger(value);\nis.safeInteger = (value) => Number.isSafeInteger(value);\nis.plainObject = (value) => {\n // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js\n if (toString.call(value) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.getPrototypeOf({});\n};\nis.typedArray = (value) => isTypedArrayName(getObjectType(value));\nconst isValidLength = (value) => is.safeInteger(value) && value >= 0;\nis.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);\nis.inRange = (value, range) => {\n if (is.number(range)) {\n return value >= Math.min(0, range) && value <= Math.max(range, 0);\n }\n if (is.array(range) && range.length === 2) {\n return value >= Math.min(...range) && value <= Math.max(...range);\n }\n throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);\n};\nconst NODE_TYPE_ELEMENT = 1;\nconst DOM_PROPERTIES_TO_CHECK = [\n 'innerHTML',\n 'ownerDocument',\n 'style',\n 'attributes',\n 'nodeValue'\n];\nis.domElement = (value) => {\n return is.object(value) &&\n value.nodeType === NODE_TYPE_ELEMENT &&\n is.string(value.nodeName) &&\n !is.plainObject(value) &&\n DOM_PROPERTIES_TO_CHECK.every(property => property in value);\n};\nis.observable = (value) => {\n var _a, _b, _c, _d;\n if (!value) {\n return false;\n }\n // eslint-disable-next-line no-use-extend-native/no-use-extend-native\n if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) {\n return true;\n }\n if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) {\n return true;\n }\n return false;\n};\nis.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value);\nis.infinite = (value) => value === Infinity || value === -Infinity;\nconst isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder;\nis.evenInteger = isAbsoluteMod2(0);\nis.oddInteger = isAbsoluteMod2(1);\nis.emptyArray = (value) => is.array(value) && value.length === 0;\nis.nonEmptyArray = (value) => is.array(value) && value.length > 0;\nis.emptyString = (value) => is.string(value) && value.length === 0;\nconst isWhiteSpaceString = (value) => is.string(value) && !/\\S/.test(value);\nis.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);\n// TODO: Use `not ''` when the `not` operator is available.\nis.nonEmptyString = (value) => is.string(value) && value.length > 0;\n// TODO: Use `not ''` when the `not` operator is available.\nis.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value);\nis.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;\n// TODO: Use `not` operator here to remove `Map` and `Set` from type guard:\n// - https://github.com/Microsoft/TypeScript/pull/29317\nis.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;\nis.emptySet = (value) => is.set(value) && value.size === 0;\nis.nonEmptySet = (value) => is.set(value) && value.size > 0;\nis.emptyMap = (value) => is.map(value) && value.size === 0;\nis.nonEmptyMap = (value) => is.map(value) && value.size > 0;\n// `PropertyKey` is any value that can be used as an object key (string, number, or symbol)\nis.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value);\nis.formData = (value) => isObjectOfType('FormData')(value);\nis.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value);\nconst predicateOnArray = (method, predicate, values) => {\n if (!is.function_(predicate)) {\n throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);\n }\n if (values.length === 0) {\n throw new TypeError('Invalid number of values');\n }\n return method.call(values, predicate);\n};\nis.any = (predicate, ...values) => {\n const predicates = is.array(predicate) ? predicate : [predicate];\n return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values));\n};\nis.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);\nconst assertType = (condition, description, value, options = {}) => {\n if (!condition) {\n const { multipleValues } = options;\n const valuesMessage = multipleValues ?\n `received values of types ${[\n ...new Set(value.map(singleValue => `\\`${is(singleValue)}\\``))\n ].join(', ')}` :\n `received value of type \\`${is(value)}\\``;\n throw new TypeError(`Expected value which is \\`${description}\\`, ${valuesMessage}.`);\n }\n};\nexports.assert = {\n // Unknowns.\n undefined: (value) => assertType(is.undefined(value), 'undefined', value),\n string: (value) => assertType(is.string(value), 'string', value),\n number: (value) => assertType(is.number(value), 'number', value),\n bigint: (value) => assertType(is.bigint(value), 'bigint', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n function_: (value) => assertType(is.function_(value), 'Function', value),\n null_: (value) => assertType(is.null_(value), 'null', value),\n class_: (value) => assertType(is.class_(value), \"Class\" /* class_ */, value),\n boolean: (value) => assertType(is.boolean(value), 'boolean', value),\n symbol: (value) => assertType(is.symbol(value), 'symbol', value),\n numericString: (value) => assertType(is.numericString(value), \"string with a number\" /* numericString */, value),\n array: (value, assertion) => {\n const assert = assertType;\n assert(is.array(value), 'Array', value);\n if (assertion) {\n value.forEach(assertion);\n }\n },\n buffer: (value) => assertType(is.buffer(value), 'Buffer', value),\n blob: (value) => assertType(is.blob(value), 'Blob', value),\n nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), \"null or undefined\" /* nullOrUndefined */, value),\n object: (value) => assertType(is.object(value), 'Object', value),\n iterable: (value) => assertType(is.iterable(value), \"Iterable\" /* iterable */, value),\n asyncIterable: (value) => assertType(is.asyncIterable(value), \"AsyncIterable\" /* asyncIterable */, value),\n generator: (value) => assertType(is.generator(value), 'Generator', value),\n asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value),\n nativePromise: (value) => assertType(is.nativePromise(value), \"native Promise\" /* nativePromise */, value),\n promise: (value) => assertType(is.promise(value), 'Promise', value),\n generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value),\n asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value),\n regExp: (value) => assertType(is.regExp(value), 'RegExp', value),\n date: (value) => assertType(is.date(value), 'Date', value),\n error: (value) => assertType(is.error(value), 'Error', value),\n map: (value) => assertType(is.map(value), 'Map', value),\n set: (value) => assertType(is.set(value), 'Set', value),\n weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value),\n weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value),\n int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value),\n uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value),\n uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value),\n int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value),\n uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value),\n int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value),\n uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value),\n float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value),\n float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value),\n bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value),\n bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value),\n arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value),\n sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value),\n dataView: (value) => assertType(is.dataView(value), 'DataView', value),\n enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value),\n urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value),\n urlString: (value) => assertType(is.urlString(value), \"string with a URL\" /* urlString */, value),\n truthy: (value) => assertType(is.truthy(value), \"truthy\" /* truthy */, value),\n falsy: (value) => assertType(is.falsy(value), \"falsy\" /* falsy */, value),\n nan: (value) => assertType(is.nan(value), \"NaN\" /* nan */, value),\n primitive: (value) => assertType(is.primitive(value), \"primitive\" /* primitive */, value),\n integer: (value) => assertType(is.integer(value), \"integer\" /* integer */, value),\n safeInteger: (value) => assertType(is.safeInteger(value), \"integer\" /* safeInteger */, value),\n plainObject: (value) => assertType(is.plainObject(value), \"plain object\" /* plainObject */, value),\n typedArray: (value) => assertType(is.typedArray(value), \"TypedArray\" /* typedArray */, value),\n arrayLike: (value) => assertType(is.arrayLike(value), \"array-like\" /* arrayLike */, value),\n domElement: (value) => assertType(is.domElement(value), \"HTMLElement\" /* domElement */, value),\n observable: (value) => assertType(is.observable(value), 'Observable', value),\n nodeStream: (value) => assertType(is.nodeStream(value), \"Node.js Stream\" /* nodeStream */, value),\n infinite: (value) => assertType(is.infinite(value), \"infinite number\" /* infinite */, value),\n emptyArray: (value) => assertType(is.emptyArray(value), \"empty array\" /* emptyArray */, value),\n nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), \"non-empty array\" /* nonEmptyArray */, value),\n emptyString: (value) => assertType(is.emptyString(value), \"empty string\" /* emptyString */, value),\n emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), \"empty string or whitespace\" /* emptyStringOrWhitespace */, value),\n nonEmptyString: (value) => assertType(is.nonEmptyString(value), \"non-empty string\" /* nonEmptyString */, value),\n nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), \"non-empty string and not whitespace\" /* nonEmptyStringAndNotWhitespace */, value),\n emptyObject: (value) => assertType(is.emptyObject(value), \"empty object\" /* emptyObject */, value),\n nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), \"non-empty object\" /* nonEmptyObject */, value),\n emptySet: (value) => assertType(is.emptySet(value), \"empty set\" /* emptySet */, value),\n nonEmptySet: (value) => assertType(is.nonEmptySet(value), \"non-empty set\" /* nonEmptySet */, value),\n emptyMap: (value) => assertType(is.emptyMap(value), \"empty map\" /* emptyMap */, value),\n nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), \"non-empty map\" /* nonEmptyMap */, value),\n propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value),\n formData: (value) => assertType(is.formData(value), 'FormData', value),\n urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value),\n // Numbers.\n evenInteger: (value) => assertType(is.evenInteger(value), \"even integer\" /* evenInteger */, value),\n oddInteger: (value) => assertType(is.oddInteger(value), \"odd integer\" /* oddInteger */, value),\n // Two arguments.\n directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), \"T\" /* directInstanceOf */, instance),\n inRange: (value, range) => assertType(is.inRange(value, range), \"in range\" /* inRange */, value),\n // Variadic functions.\n any: (predicate, ...values) => {\n return assertType(is.any(predicate, ...values), \"predicate returns truthy for any value\" /* any */, values, { multipleValues: true });\n },\n all: (predicate, ...values) => assertType(is.all(predicate, ...values), \"predicate returns truthy for all values\" /* all */, values, { multipleValues: true })\n};\n// Some few keywords are reserved, but we'll populate them for Node.js users\n// See https://github.com/Microsoft/TypeScript/issues/2536\nObject.defineProperties(is, {\n class: {\n value: is.class_\n },\n function: {\n value: is.function_\n },\n null: {\n value: is.null_\n }\n});\nObject.defineProperties(exports.assert, {\n class: {\n value: exports.assert.class_\n },\n function: {\n value: exports.assert.function_\n },\n null: {\n value: exports.assert.null_\n }\n});\nexports.default = is;\n// For CommonJS default export support\nmodule.exports = is;\nmodule.exports.default = is;\nmodule.exports.assert = exports.assert;\n","'use strict';\n\nclass CancelError extends Error {\n\tconstructor(reason) {\n\t\tsuper(reason || 'Promise was canceled');\n\t\tthis.name = 'CancelError';\n\t}\n\n\tget isCanceled() {\n\t\treturn true;\n\t}\n}\n\nclass PCancelable {\n\tstatic fn(userFn) {\n\t\treturn (...arguments_) => {\n\t\t\treturn new PCancelable((resolve, reject, onCancel) => {\n\t\t\t\targuments_.push(onCancel);\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t\t\tuserFn(...arguments_).then(resolve, reject);\n\t\t\t});\n\t\t};\n\t}\n\n\tconstructor(executor) {\n\t\tthis._cancelHandlers = [];\n\t\tthis._isPending = true;\n\t\tthis._isCanceled = false;\n\t\tthis._rejectOnCancel = true;\n\n\t\tthis._promise = new Promise((resolve, reject) => {\n\t\t\tthis._reject = reject;\n\n\t\t\tconst onResolve = value => {\n\t\t\t\tif (!this._isCanceled || !onCancel.shouldReject) {\n\t\t\t\t\tthis._isPending = false;\n\t\t\t\t\tresolve(value);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onReject = error => {\n\t\t\t\tthis._isPending = false;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tconst onCancel = handler => {\n\t\t\t\tif (!this._isPending) {\n\t\t\t\t\tthrow new Error('The `onCancel` handler was attached after the promise settled.');\n\t\t\t\t}\n\n\t\t\t\tthis._cancelHandlers.push(handler);\n\t\t\t};\n\n\t\t\tObject.defineProperties(onCancel, {\n\t\t\t\tshouldReject: {\n\t\t\t\t\tget: () => this._rejectOnCancel,\n\t\t\t\t\tset: boolean => {\n\t\t\t\t\t\tthis._rejectOnCancel = boolean;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn executor(onResolve, onReject, onCancel);\n\t\t});\n\t}\n\n\tthen(onFulfilled, onRejected) {\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\treturn this._promise.then(onFulfilled, onRejected);\n\t}\n\n\tcatch(onRejected) {\n\t\treturn this._promise.catch(onRejected);\n\t}\n\n\tfinally(onFinally) {\n\t\treturn this._promise.finally(onFinally);\n\t}\n\n\tcancel(reason) {\n\t\tif (!this._isPending || this._isCanceled) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._isCanceled = true;\n\n\t\tif (this._cancelHandlers.length > 0) {\n\t\t\ttry {\n\t\t\t\tfor (const handler of this._cancelHandlers) {\n\t\t\t\t\thandler();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis._reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (this._rejectOnCancel) {\n\t\t\tthis._reject(new CancelError(reason));\n\t\t}\n\t}\n\n\tget isCanceled() {\n\t\treturn this._isCanceled;\n\t}\n}\n\nObject.setPrototypeOf(PCancelable.prototype, Promise.prototype);\n\nmodule.exports = PCancelable;\nmodule.exports.CancelError = CancelError;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isTLSSocket(socket) {\n return socket.encrypted;\n}\nconst deferToConnect = (socket, fn) => {\n let listeners;\n if (typeof fn === 'function') {\n const connect = fn;\n listeners = { connect };\n }\n else {\n listeners = fn;\n }\n const hasConnectListener = typeof listeners.connect === 'function';\n const hasSecureConnectListener = typeof listeners.secureConnect === 'function';\n const hasCloseListener = typeof listeners.close === 'function';\n const onConnect = () => {\n if (hasConnectListener) {\n listeners.connect();\n }\n if (isTLSSocket(socket) && hasSecureConnectListener) {\n if (socket.authorized) {\n listeners.secureConnect();\n }\n else if (!socket.authorizationError) {\n socket.once('secureConnect', listeners.secureConnect);\n }\n }\n if (hasCloseListener) {\n socket.once('close', listeners.close);\n }\n };\n if (socket.writable && !socket.connecting) {\n onConnect();\n }\n else if (socket.connecting) {\n socket.once('connect', onConnect);\n }\n else if (socket.destroyed && hasCloseListener) {\n listeners.close(socket._hadError);\n }\n};\nexports.default = deferToConnect;\n// For CommonJS default export support\nmodule.exports = deferToConnect;\nmodule.exports.default = deferToConnect;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst defer_to_connect_1 = require(\"defer-to-connect\");\nconst util_1 = require(\"util\");\nconst nodejsMajorVersion = Number(process.versions.node.split('.')[0]);\nconst timer = (request) => {\n if (request.timings) {\n return request.timings;\n }\n const timings = {\n start: Date.now(),\n socket: undefined,\n lookup: undefined,\n connect: undefined,\n secureConnect: undefined,\n upload: undefined,\n response: undefined,\n end: undefined,\n error: undefined,\n abort: undefined,\n phases: {\n wait: undefined,\n dns: undefined,\n tcp: undefined,\n tls: undefined,\n request: undefined,\n firstByte: undefined,\n download: undefined,\n total: undefined\n }\n };\n request.timings = timings;\n const handleError = (origin) => {\n const emit = origin.emit.bind(origin);\n origin.emit = (event, ...args) => {\n // Catches the `error` event\n if (event === 'error') {\n timings.error = Date.now();\n timings.phases.total = timings.error - timings.start;\n origin.emit = emit;\n }\n // Saves the original behavior\n return emit(event, ...args);\n };\n };\n handleError(request);\n const onAbort = () => {\n timings.abort = Date.now();\n // Let the `end` response event be responsible for setting the total phase,\n // unless the Node.js major version is >= 13.\n if (!timings.response || nodejsMajorVersion >= 13) {\n timings.phases.total = Date.now() - timings.start;\n }\n };\n request.prependOnceListener('abort', onAbort);\n const onSocket = (socket) => {\n timings.socket = Date.now();\n timings.phases.wait = timings.socket - timings.start;\n if (util_1.types.isProxy(socket)) {\n return;\n }\n const lookupListener = () => {\n timings.lookup = Date.now();\n timings.phases.dns = timings.lookup - timings.socket;\n };\n socket.prependOnceListener('lookup', lookupListener);\n defer_to_connect_1.default(socket, {\n connect: () => {\n timings.connect = Date.now();\n if (timings.lookup === undefined) {\n socket.removeListener('lookup', lookupListener);\n timings.lookup = timings.connect;\n timings.phases.dns = timings.lookup - timings.socket;\n }\n timings.phases.tcp = timings.connect - timings.lookup;\n // This callback is called before flushing any data,\n // so we don't need to set `timings.phases.request` here.\n },\n secureConnect: () => {\n timings.secureConnect = Date.now();\n timings.phases.tls = timings.secureConnect - timings.connect;\n }\n });\n };\n if (request.socket) {\n onSocket(request.socket);\n }\n else {\n request.prependOnceListener('socket', onSocket);\n }\n const onUpload = () => {\n var _a;\n timings.upload = Date.now();\n timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect);\n };\n const writableFinished = () => {\n if (typeof request.writableFinished === 'boolean') {\n return request.writableFinished;\n }\n // Node.js doesn't have `request.writableFinished` property\n return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0);\n };\n if (writableFinished()) {\n onUpload();\n }\n else {\n request.prependOnceListener('finish', onUpload);\n }\n request.prependOnceListener('response', (response) => {\n timings.response = Date.now();\n timings.phases.firstByte = timings.response - timings.upload;\n response.timings = timings;\n handleError(response);\n response.prependOnceListener('end', () => {\n timings.end = Date.now();\n timings.phases.download = timings.end - timings.response;\n timings.phases.total = timings.end - timings.start;\n });\n response.prependOnceListener('aborted', onAbort);\n });\n return timings;\n};\nexports.default = timer;\n// For CommonJS default export support\nmodule.exports = timer;\nmodule.exports.default = timer;\n","'use strict';\nconst {\n\tV4MAPPED,\n\tADDRCONFIG,\n\tALL,\n\tpromises: {\n\t\tResolver: AsyncResolver\n\t},\n\tlookup: dnsLookup\n} = require('dns');\nconst {promisify} = require('util');\nconst os = require('os');\n\nconst kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection');\nconst kCacheableLookupInstance = Symbol('cacheableLookupInstance');\nconst kExpires = Symbol('expires');\n\nconst supportsALL = typeof ALL === 'number';\n\nconst verifyAgent = agent => {\n\tif (!(agent && typeof agent.createConnection === 'function')) {\n\t\tthrow new Error('Expected an Agent instance as the first argument');\n\t}\n};\n\nconst map4to6 = entries => {\n\tfor (const entry of entries) {\n\t\tif (entry.family === 6) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.address = `::ffff:${entry.address}`;\n\t\tentry.family = 6;\n\t}\n};\n\nconst getIfaceInfo = () => {\n\tlet has4 = false;\n\tlet has6 = false;\n\n\tfor (const device of Object.values(os.networkInterfaces())) {\n\t\tfor (const iface of device) {\n\t\t\tif (iface.internal) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (iface.family === 'IPv6') {\n\t\t\t\thas6 = true;\n\t\t\t} else {\n\t\t\t\thas4 = true;\n\t\t\t}\n\n\t\t\tif (has4 && has6) {\n\t\t\t\treturn {has4, has6};\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {has4, has6};\n};\n\nconst isIterable = map => {\n\treturn Symbol.iterator in map;\n};\n\nconst ttl = {ttl: true};\nconst all = {all: true};\n\nclass CacheableLookup {\n\tconstructor({\n\t\tcache = new Map(),\n\t\tmaxTtl = Infinity,\n\t\tfallbackDuration = 3600,\n\t\terrorTtl = 0.15,\n\t\tresolver = new AsyncResolver(),\n\t\tlookup = dnsLookup\n\t} = {}) {\n\t\tthis.maxTtl = maxTtl;\n\t\tthis.errorTtl = errorTtl;\n\n\t\tthis._cache = cache;\n\t\tthis._resolver = resolver;\n\t\tthis._dnsLookup = promisify(lookup);\n\n\t\tif (this._resolver instanceof AsyncResolver) {\n\t\t\tthis._resolve4 = this._resolver.resolve4.bind(this._resolver);\n\t\t\tthis._resolve6 = this._resolver.resolve6.bind(this._resolver);\n\t\t} else {\n\t\t\tthis._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver));\n\t\t\tthis._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver));\n\t\t}\n\n\t\tthis._iface = getIfaceInfo();\n\n\t\tthis._pending = {};\n\t\tthis._nextRemovalTime = false;\n\t\tthis._hostnamesToFallback = new Set();\n\n\t\tif (fallbackDuration < 1) {\n\t\t\tthis._fallback = false;\n\t\t} else {\n\t\t\tthis._fallback = true;\n\n\t\t\tconst interval = setInterval(() => {\n\t\t\t\tthis._hostnamesToFallback.clear();\n\t\t\t}, fallbackDuration * 1000);\n\n\t\t\t/* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */\n\t\t\tif (interval.unref) {\n\t\t\t\tinterval.unref();\n\t\t\t}\n\t\t}\n\n\t\tthis.lookup = this.lookup.bind(this);\n\t\tthis.lookupAsync = this.lookupAsync.bind(this);\n\t}\n\n\tset servers(servers) {\n\t\tthis.clear();\n\n\t\tthis._resolver.setServers(servers);\n\t}\n\n\tget servers() {\n\t\treturn this._resolver.getServers();\n\t}\n\n\tlookup(hostname, options, callback) {\n\t\tif (typeof options === 'function') {\n\t\t\tcallback = options;\n\t\t\toptions = {};\n\t\t} else if (typeof options === 'number') {\n\t\t\toptions = {\n\t\t\t\tfamily: options\n\t\t\t};\n\t\t}\n\n\t\tif (!callback) {\n\t\t\tthrow new Error('Callback must be a function.');\n\t\t}\n\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tthis.lookupAsync(hostname, options).then(result => {\n\t\t\tif (options.all) {\n\t\t\t\tcallback(null, result);\n\t\t\t} else {\n\t\t\t\tcallback(null, result.address, result.family, result.expires, result.ttl);\n\t\t\t}\n\t\t}, callback);\n\t}\n\n\tasync lookupAsync(hostname, options = {}) {\n\t\tif (typeof options === 'number') {\n\t\t\toptions = {\n\t\t\t\tfamily: options\n\t\t\t};\n\t\t}\n\n\t\tlet cached = await this.query(hostname);\n\n\t\tif (options.family === 6) {\n\t\t\tconst filtered = cached.filter(entry => entry.family === 6);\n\n\t\t\tif (options.hints & V4MAPPED) {\n\t\t\t\tif ((supportsALL && options.hints & ALL) || filtered.length === 0) {\n\t\t\t\t\tmap4to6(cached);\n\t\t\t\t} else {\n\t\t\t\t\tcached = filtered;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcached = filtered;\n\t\t\t}\n\t\t} else if (options.family === 4) {\n\t\t\tcached = cached.filter(entry => entry.family === 4);\n\t\t}\n\n\t\tif (options.hints & ADDRCONFIG) {\n\t\t\tconst {_iface} = this;\n\t\t\tcached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4);\n\t\t}\n\n\t\tif (cached.length === 0) {\n\t\t\tconst error = new Error(`cacheableLookup ENOTFOUND ${hostname}`);\n\t\t\terror.code = 'ENOTFOUND';\n\t\t\terror.hostname = hostname;\n\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (options.all) {\n\t\t\treturn cached;\n\t\t}\n\n\t\treturn cached[0];\n\t}\n\n\tasync query(hostname) {\n\t\tlet cached = await this._cache.get(hostname);\n\n\t\tif (!cached) {\n\t\t\tconst pending = this._pending[hostname];\n\n\t\t\tif (pending) {\n\t\t\t\tcached = await pending;\n\t\t\t} else {\n\t\t\t\tconst newPromise = this.queryAndCache(hostname);\n\t\t\t\tthis._pending[hostname] = newPromise;\n\n\t\t\t\ttry {\n\t\t\t\t\tcached = await newPromise;\n\t\t\t\t} finally {\n\t\t\t\t\tdelete this._pending[hostname];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcached = cached.map(entry => {\n\t\t\treturn {...entry};\n\t\t});\n\n\t\treturn cached;\n\t}\n\n\tasync _resolve(hostname) {\n\t\tconst wrap = async promise => {\n\t\t\ttry {\n\t\t\t\treturn await promise;\n\t\t\t} catch (error) {\n\t\t\t\tif (error.code === 'ENODATA' || error.code === 'ENOTFOUND') {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\t// ANY is unsafe as it doesn't trigger new queries in the underlying server.\n\t\tconst [A, AAAA] = await Promise.all([\n\t\t\tthis._resolve4(hostname, ttl),\n\t\t\tthis._resolve6(hostname, ttl)\n\t\t].map(promise => wrap(promise)));\n\n\t\tlet aTtl = 0;\n\t\tlet aaaaTtl = 0;\n\t\tlet cacheTtl = 0;\n\n\t\tconst now = Date.now();\n\n\t\tfor (const entry of A) {\n\t\t\tentry.family = 4;\n\t\t\tentry.expires = now + (entry.ttl * 1000);\n\n\t\t\taTtl = Math.max(aTtl, entry.ttl);\n\t\t}\n\n\t\tfor (const entry of AAAA) {\n\t\t\tentry.family = 6;\n\t\t\tentry.expires = now + (entry.ttl * 1000);\n\n\t\t\taaaaTtl = Math.max(aaaaTtl, entry.ttl);\n\t\t}\n\n\t\tif (A.length > 0) {\n\t\t\tif (AAAA.length > 0) {\n\t\t\t\tcacheTtl = Math.min(aTtl, aaaaTtl);\n\t\t\t} else {\n\t\t\t\tcacheTtl = aTtl;\n\t\t\t}\n\t\t} else {\n\t\t\tcacheTtl = aaaaTtl;\n\t\t}\n\n\t\treturn {\n\t\t\tentries: [\n\t\t\t\t...A,\n\t\t\t\t...AAAA\n\t\t\t],\n\t\t\tcacheTtl\n\t\t};\n\t}\n\n\tasync _lookup(hostname) {\n\t\ttry {\n\t\t\tconst entries = await this._dnsLookup(hostname, {\n\t\t\t\tall: true\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tentries,\n\t\t\t\tcacheTtl: 0\n\t\t\t};\n\t\t} catch (_) {\n\t\t\treturn {\n\t\t\t\tentries: [],\n\t\t\t\tcacheTtl: 0\n\t\t\t};\n\t\t}\n\t}\n\n\tasync _set(hostname, data, cacheTtl) {\n\t\tif (this.maxTtl > 0 && cacheTtl > 0) {\n\t\t\tcacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000;\n\t\t\tdata[kExpires] = Date.now() + cacheTtl;\n\n\t\t\ttry {\n\t\t\t\tawait this._cache.set(hostname, data, cacheTtl);\n\t\t\t} catch (error) {\n\t\t\t\tthis.lookupAsync = async () => {\n\t\t\t\t\tconst cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.');\n\t\t\t\t\tcacheError.cause = error;\n\n\t\t\t\t\tthrow cacheError;\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (isIterable(this._cache)) {\n\t\t\t\tthis._tick(cacheTtl);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync queryAndCache(hostname) {\n\t\tif (this._hostnamesToFallback.has(hostname)) {\n\t\t\treturn this._dnsLookup(hostname, all);\n\t\t}\n\n\t\tlet query = await this._resolve(hostname);\n\n\t\tif (query.entries.length === 0 && this._fallback) {\n\t\t\tquery = await this._lookup(hostname);\n\n\t\t\tif (query.entries.length !== 0) {\n\t\t\t\t// Use `dns.lookup(...)` for that particular hostname\n\t\t\t\tthis._hostnamesToFallback.add(hostname);\n\t\t\t}\n\t\t}\n\n\t\tconst cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;\n\t\tawait this._set(hostname, query.entries, cacheTtl);\n\n\t\treturn query.entries;\n\t}\n\n\t_tick(ms) {\n\t\tconst nextRemovalTime = this._nextRemovalTime;\n\n\t\tif (!nextRemovalTime || ms < nextRemovalTime) {\n\t\t\tclearTimeout(this._removalTimeout);\n\n\t\t\tthis._nextRemovalTime = ms;\n\n\t\t\tthis._removalTimeout = setTimeout(() => {\n\t\t\t\tthis._nextRemovalTime = false;\n\n\t\t\t\tlet nextExpiry = Infinity;\n\n\t\t\t\tconst now = Date.now();\n\n\t\t\t\tfor (const [hostname, entries] of this._cache) {\n\t\t\t\t\tconst expires = entries[kExpires];\n\n\t\t\t\t\tif (now >= expires) {\n\t\t\t\t\t\tthis._cache.delete(hostname);\n\t\t\t\t\t} else if (expires < nextExpiry) {\n\t\t\t\t\t\tnextExpiry = expires;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (nextExpiry !== Infinity) {\n\t\t\t\t\tthis._tick(nextExpiry - now);\n\t\t\t\t}\n\t\t\t}, ms);\n\n\t\t\t/* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */\n\t\t\tif (this._removalTimeout.unref) {\n\t\t\t\tthis._removalTimeout.unref();\n\t\t\t}\n\t\t}\n\t}\n\n\tinstall(agent) {\n\t\tverifyAgent(agent);\n\n\t\tif (kCacheableLookupCreateConnection in agent) {\n\t\t\tthrow new Error('CacheableLookup has been already installed');\n\t\t}\n\n\t\tagent[kCacheableLookupCreateConnection] = agent.createConnection;\n\t\tagent[kCacheableLookupInstance] = this;\n\n\t\tagent.createConnection = (options, callback) => {\n\t\t\tif (!('lookup' in options)) {\n\t\t\t\toptions.lookup = this.lookup;\n\t\t\t}\n\n\t\t\treturn agent[kCacheableLookupCreateConnection](options, callback);\n\t\t};\n\t}\n\n\tuninstall(agent) {\n\t\tverifyAgent(agent);\n\n\t\tif (agent[kCacheableLookupCreateConnection]) {\n\t\t\tif (agent[kCacheableLookupInstance] !== this) {\n\t\t\t\tthrow new Error('The agent is not owned by this CacheableLookup instance');\n\t\t\t}\n\n\t\t\tagent.createConnection = agent[kCacheableLookupCreateConnection];\n\n\t\t\tdelete agent[kCacheableLookupCreateConnection];\n\t\t\tdelete agent[kCacheableLookupInstance];\n\t\t}\n\t}\n\n\tupdateInterfaceInfo() {\n\t\tconst {_iface} = this;\n\n\t\tthis._iface = getIfaceInfo();\n\n\t\tif ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) {\n\t\t\tthis._cache.clear();\n\t\t}\n\t}\n\n\tclear(hostname) {\n\t\tif (hostname) {\n\t\t\tthis._cache.delete(hostname);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._cache.clear();\n\t}\n}\n\nmodule.exports = CacheableLookup;\nmodule.exports.default = CacheableLookup;\n","'use strict';\n\n// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\nconst DATA_URL_DEFAULT_MIME_TYPE = 'text/plain';\nconst DATA_URL_DEFAULT_CHARSET = 'us-ascii';\n\nconst testParameter = (name, filters) => {\n\treturn filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);\n};\n\nconst normalizeDataURL = (urlString, {stripHash}) => {\n\tconst match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);\n\n\tif (!match) {\n\t\tthrow new Error(`Invalid URL: ${urlString}`);\n\t}\n\n\tlet {type, data, hash} = match.groups;\n\tconst mediaType = type.split(';');\n\thash = stripHash ? '' : hash;\n\n\tlet isBase64 = false;\n\tif (mediaType[mediaType.length - 1] === 'base64') {\n\t\tmediaType.pop();\n\t\tisBase64 = true;\n\t}\n\n\t// Lowercase MIME type\n\tconst mimeType = (mediaType.shift() || '').toLowerCase();\n\tconst attributes = mediaType\n\t\t.map(attribute => {\n\t\t\tlet [key, value = ''] = attribute.split('=').map(string => string.trim());\n\n\t\t\t// Lowercase `charset`\n\t\t\tif (key === 'charset') {\n\t\t\t\tvalue = value.toLowerCase();\n\n\t\t\t\tif (value === DATA_URL_DEFAULT_CHARSET) {\n\t\t\t\t\treturn '';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn `${key}${value ? `=${value}` : ''}`;\n\t\t})\n\t\t.filter(Boolean);\n\n\tconst normalizedMediaType = [\n\t\t...attributes\n\t];\n\n\tif (isBase64) {\n\t\tnormalizedMediaType.push('base64');\n\t}\n\n\tif (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) {\n\t\tnormalizedMediaType.unshift(mimeType);\n\t}\n\n\treturn `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`;\n};\n\nconst normalizeUrl = (urlString, options) => {\n\toptions = {\n\t\tdefaultProtocol: 'http:',\n\t\tnormalizeProtocol: true,\n\t\tforceHttp: false,\n\t\tforceHttps: false,\n\t\tstripAuthentication: true,\n\t\tstripHash: false,\n\t\tstripTextFragment: true,\n\t\tstripWWW: true,\n\t\tremoveQueryParameters: [/^utm_\\w+/i],\n\t\tremoveTrailingSlash: true,\n\t\tremoveSingleSlash: true,\n\t\tremoveDirectoryIndex: false,\n\t\tsortQueryParameters: true,\n\t\t...options\n\t};\n\n\turlString = urlString.trim();\n\n\t// Data URL\n\tif (/^data:/i.test(urlString)) {\n\t\treturn normalizeDataURL(urlString, options);\n\t}\n\n\tif (/^view-source:/i.test(urlString)) {\n\t\tthrow new Error('`view-source:` is not supported as it is a non-standard protocol');\n\t}\n\n\tconst hasRelativeProtocol = urlString.startsWith('//');\n\tconst isRelativeUrl = !hasRelativeProtocol && /^\\.*\\//.test(urlString);\n\n\t// Prepend protocol\n\tif (!isRelativeUrl) {\n\t\turlString = urlString.replace(/^(?!(?:\\w+:)?\\/\\/)|^\\/\\//, options.defaultProtocol);\n\t}\n\n\tconst urlObj = new URL(urlString);\n\n\tif (options.forceHttp && options.forceHttps) {\n\t\tthrow new Error('The `forceHttp` and `forceHttps` options cannot be used together');\n\t}\n\n\tif (options.forceHttp && urlObj.protocol === 'https:') {\n\t\turlObj.protocol = 'http:';\n\t}\n\n\tif (options.forceHttps && urlObj.protocol === 'http:') {\n\t\turlObj.protocol = 'https:';\n\t}\n\n\t// Remove auth\n\tif (options.stripAuthentication) {\n\t\turlObj.username = '';\n\t\turlObj.password = '';\n\t}\n\n\t// Remove hash\n\tif (options.stripHash) {\n\t\turlObj.hash = '';\n\t} else if (options.stripTextFragment) {\n\t\turlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, '');\n\t}\n\n\t// Remove duplicate slashes if not preceded by a protocol\n\tif (urlObj.pathname) {\n\t\turlObj.pathname = urlObj.pathname.replace(/(?<!\\b(?:[a-z][a-z\\d+\\-.]{1,50}:))\\/{2,}/g, '/');\n\t}\n\n\t// Decode URI octets\n\tif (urlObj.pathname) {\n\t\ttry {\n\t\t\turlObj.pathname = decodeURI(urlObj.pathname);\n\t\t} catch (_) {}\n\t}\n\n\t// Remove directory index\n\tif (options.removeDirectoryIndex === true) {\n\t\toptions.removeDirectoryIndex = [/^index\\.[a-z]+$/];\n\t}\n\n\tif (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {\n\t\tlet pathComponents = urlObj.pathname.split('/');\n\t\tconst lastComponent = pathComponents[pathComponents.length - 1];\n\n\t\tif (testParameter(lastComponent, options.removeDirectoryIndex)) {\n\t\t\tpathComponents = pathComponents.slice(0, pathComponents.length - 1);\n\t\t\turlObj.pathname = pathComponents.slice(1).join('/') + '/';\n\t\t}\n\t}\n\n\tif (urlObj.hostname) {\n\t\t// Remove trailing dot\n\t\turlObj.hostname = urlObj.hostname.replace(/\\.$/, '');\n\n\t\t// Remove `www.`\n\t\tif (options.stripWWW && /^www\\.(?!www\\.)(?:[a-z\\-\\d]{1,63})\\.(?:[a-z.\\-\\d]{2,63})$/.test(urlObj.hostname)) {\n\t\t\t// Each label should be max 63 at length (min: 1).\n\t\t\t// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names\n\t\t\t// Each TLD should be up to 63 characters long (min: 2).\n\t\t\t// It is technically possible to have a single character TLD, but none currently exist.\n\t\t\turlObj.hostname = urlObj.hostname.replace(/^www\\./, '');\n\t\t}\n\t}\n\n\t// Remove query unwanted parameters\n\tif (Array.isArray(options.removeQueryParameters)) {\n\t\tfor (const key of [...urlObj.searchParams.keys()]) {\n\t\t\tif (testParameter(key, options.removeQueryParameters)) {\n\t\t\t\turlObj.searchParams.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options.removeQueryParameters === true) {\n\t\turlObj.search = '';\n\t}\n\n\t// Sort query parameters\n\tif (options.sortQueryParameters) {\n\t\turlObj.searchParams.sort();\n\t}\n\n\tif (options.removeTrailingSlash) {\n\t\turlObj.pathname = urlObj.pathname.replace(/\\/$/, '');\n\t}\n\n\tconst oldUrlString = urlString;\n\n\t// Take advantage of many of the Node `url` normalizations\n\turlString = urlObj.toString();\n\n\tif (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') {\n\t\turlString = urlString.replace(/\\/$/, '');\n\t}\n\n\t// Remove ending `/` unless removeSingleSlash is false\n\tif ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) {\n\t\turlString = urlString.replace(/\\/$/, '');\n\t}\n\n\t// Restore relative protocol, if applicable\n\tif (hasRelativeProtocol && !options.normalizeProtocol) {\n\t\turlString = urlString.replace(/^http:\\/\\//, '//');\n\t}\n\n\t// Remove http/https\n\tif (options.stripProtocol) {\n\t\turlString = urlString.replace(/^(?:https?:)?\\/\\//, '');\n\t}\n\n\treturn urlString;\n};\n\nmodule.exports = normalizeUrl;\n","var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n","var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n","'use strict';\nconst {PassThrough: PassThroughStream} = require('stream');\n\nmodule.exports = options => {\n\toptions = {...options};\n\n\tconst {array} = options;\n\tlet {encoding} = options;\n\tconst isBuffer = encoding === 'buffer';\n\tlet objectMode = false;\n\n\tif (array) {\n\t\tobjectMode = !(encoding || isBuffer);\n\t} else {\n\t\tencoding = encoding || 'utf8';\n\t}\n\n\tif (isBuffer) {\n\t\tencoding = null;\n\t}\n\n\tconst stream = new PassThroughStream({objectMode});\n\n\tif (encoding) {\n\t\tstream.setEncoding(encoding);\n\t}\n\n\tlet length = 0;\n\tconst chunks = [];\n\n\tstream.on('data', chunk => {\n\t\tchunks.push(chunk);\n\n\t\tif (objectMode) {\n\t\t\tlength = chunks.length;\n\t\t} else {\n\t\t\tlength += chunk.length;\n\t\t}\n\t});\n\n\tstream.getBufferedValue = () => {\n\t\tif (array) {\n\t\t\treturn chunks;\n\t\t}\n\n\t\treturn isBuffer ? Buffer.concat(chunks, length) : chunks.join('');\n\t};\n\n\tstream.getBufferedLength = () => length;\n\n\treturn stream;\n};\n","'use strict';\nconst {constants: BufferConstants} = require('buffer');\nconst pump = require('pump');\nconst bufferStream = require('./buffer-stream');\n\nclass MaxBufferError extends Error {\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t\tthis.name = 'MaxBufferError';\n\t}\n}\n\nasync function getStream(inputStream, options) {\n\tif (!inputStream) {\n\t\treturn Promise.reject(new Error('Expected a stream'));\n\t}\n\n\toptions = {\n\t\tmaxBuffer: Infinity,\n\t\t...options\n\t};\n\n\tconst {maxBuffer} = options;\n\n\tlet stream;\n\tawait new Promise((resolve, reject) => {\n\t\tconst rejectPromise = error => {\n\t\t\t// Don't retrieve an oversized buffer.\n\t\t\tif (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {\n\t\t\t\terror.bufferedData = stream.getBufferedValue();\n\t\t\t}\n\n\t\t\treject(error);\n\t\t};\n\n\t\tstream = pump(inputStream, bufferStream(options), error => {\n\t\t\tif (error) {\n\t\t\t\trejectPromise(error);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tresolve();\n\t\t});\n\n\t\tstream.on('data', () => {\n\t\t\tif (stream.getBufferedLength() > maxBuffer) {\n\t\t\t\trejectPromise(new MaxBufferError());\n\t\t\t}\n\t\t});\n\t});\n\n\treturn stream.getBufferedValue();\n}\n\nmodule.exports = getStream;\n// TODO: Remove this for the next major release\nmodule.exports.default = getStream;\nmodule.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});\nmodule.exports.array = (stream, options) => getStream(stream, {...options, array: true});\nmodule.exports.MaxBufferError = MaxBufferError;\n","'use strict';\n// rfc7231 6.1\nconst statusCodeCacheableByDefault = new Set([\n 200,\n 203,\n 204,\n 206,\n 300,\n 301,\n 308,\n 404,\n 405,\n 410,\n 414,\n 501,\n]);\n\n// This implementation does not understand partial responses (206)\nconst understoodStatuses = new Set([\n 200,\n 203,\n 204,\n 300,\n 301,\n 302,\n 303,\n 307,\n 308,\n 404,\n 405,\n 410,\n 414,\n 501,\n]);\n\nconst errorStatusCodes = new Set([\n 500,\n 502,\n 503, \n 504,\n]);\n\nconst hopByHopHeaders = {\n date: true, // included, because we add Age update Date\n connection: true,\n 'keep-alive': true,\n 'proxy-authenticate': true,\n 'proxy-authorization': true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n};\n\nconst excludedFromRevalidationUpdate = {\n // Since the old body is reused, it doesn't make sense to change properties of the body\n 'content-length': true,\n 'content-encoding': true,\n 'transfer-encoding': true,\n 'content-range': true,\n};\n\nfunction toNumberOrZero(s) {\n const n = parseInt(s, 10);\n return isFinite(n) ? n : 0;\n}\n\n// RFC 5861\nfunction isErrorResponse(response) {\n // consider undefined response as faulty\n if(!response) {\n return true\n }\n return errorStatusCodes.has(response.status);\n}\n\nfunction parseCacheControl(header) {\n const cc = {};\n if (!header) return cc;\n\n // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),\n // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale\n const parts = header.trim().split(/,/);\n for (const part of parts) {\n const [k, v] = part.split(/=/, 2);\n cc[k.trim()] = v === undefined ? true : v.trim().replace(/^\"|\"$/g, '');\n }\n\n return cc;\n}\n\nfunction formatCacheControl(cc) {\n let parts = [];\n for (const k in cc) {\n const v = cc[k];\n parts.push(v === true ? k : k + '=' + v);\n }\n if (!parts.length) {\n return undefined;\n }\n return parts.join(', ');\n}\n\nmodule.exports = class CachePolicy {\n constructor(\n req,\n res,\n {\n shared,\n cacheHeuristic,\n immutableMinTimeToLive,\n ignoreCargoCult,\n _fromObject,\n } = {}\n ) {\n if (_fromObject) {\n this._fromObject(_fromObject);\n return;\n }\n\n if (!res || !res.headers) {\n throw Error('Response headers missing');\n }\n this._assertRequestHasHeaders(req);\n\n this._responseTime = this.now();\n this._isShared = shared !== false;\n this._cacheHeuristic =\n undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE\n this._immutableMinTtl =\n undefined !== immutableMinTimeToLive\n ? immutableMinTimeToLive\n : 24 * 3600 * 1000;\n\n this._status = 'status' in res ? res.status : 200;\n this._resHeaders = res.headers;\n this._rescc = parseCacheControl(res.headers['cache-control']);\n this._method = 'method' in req ? req.method : 'GET';\n this._url = req.url;\n this._host = req.headers.host;\n this._noAuthorization = !req.headers.authorization;\n this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used\n this._reqcc = parseCacheControl(req.headers['cache-control']);\n\n // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,\n // so there's no point stricly adhering to the blindly copy&pasted directives.\n if (\n ignoreCargoCult &&\n 'pre-check' in this._rescc &&\n 'post-check' in this._rescc\n ) {\n delete this._rescc['pre-check'];\n delete this._rescc['post-check'];\n delete this._rescc['no-cache'];\n delete this._rescc['no-store'];\n delete this._rescc['must-revalidate'];\n this._resHeaders = Object.assign({}, this._resHeaders, {\n 'cache-control': formatCacheControl(this._rescc),\n });\n delete this._resHeaders.expires;\n delete this._resHeaders.pragma;\n }\n\n // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive\n // as having the same effect as if \"Cache-Control: no-cache\" were present (see Section 5.2.1).\n if (\n res.headers['cache-control'] == null &&\n /no-cache/.test(res.headers.pragma)\n ) {\n this._rescc['no-cache'] = true;\n }\n }\n\n now() {\n return Date.now();\n }\n\n storable() {\n // The \"no-store\" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.\n return !!(\n !this._reqcc['no-store'] &&\n // A cache MUST NOT store a response to any request, unless:\n // The request method is understood by the cache and defined as being cacheable, and\n ('GET' === this._method ||\n 'HEAD' === this._method ||\n ('POST' === this._method && this._hasExplicitExpiration())) &&\n // the response status code is understood by the cache, and\n understoodStatuses.has(this._status) &&\n // the \"no-store\" cache directive does not appear in request or response header fields, and\n !this._rescc['no-store'] &&\n // the \"private\" response directive does not appear in the response, if the cache is shared, and\n (!this._isShared || !this._rescc.private) &&\n // the Authorization header field does not appear in the request, if the cache is shared,\n (!this._isShared ||\n this._noAuthorization ||\n this._allowsStoringAuthenticated()) &&\n // the response either:\n // contains an Expires header field, or\n (this._resHeaders.expires ||\n // contains a max-age response directive, or\n // contains a s-maxage response directive and the cache is shared, or\n // contains a public response directive.\n this._rescc['max-age'] ||\n (this._isShared && this._rescc['s-maxage']) ||\n this._rescc.public ||\n // has a status code that is defined as cacheable by default\n statusCodeCacheableByDefault.has(this._status))\n );\n }\n\n _hasExplicitExpiration() {\n // 4.2.1 Calculating Freshness Lifetime\n return (\n (this._isShared && this._rescc['s-maxage']) ||\n this._rescc['max-age'] ||\n this._resHeaders.expires\n );\n }\n\n _assertRequestHasHeaders(req) {\n if (!req || !req.headers) {\n throw Error('Request headers missing');\n }\n }\n\n satisfiesWithoutRevalidation(req) {\n this._assertRequestHasHeaders(req);\n\n // When presented with a request, a cache MUST NOT reuse a stored response, unless:\n // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,\n // unless the stored response is successfully validated (Section 4.3), and\n const requestCC = parseCacheControl(req.headers['cache-control']);\n if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {\n return false;\n }\n\n if (requestCC['max-age'] && this.age() > requestCC['max-age']) {\n return false;\n }\n\n if (\n requestCC['min-fresh'] &&\n this.timeToLive() < 1000 * requestCC['min-fresh']\n ) {\n return false;\n }\n\n // the stored response is either:\n // fresh, or allowed to be served stale\n if (this.stale()) {\n const allowsStale =\n requestCC['max-stale'] &&\n !this._rescc['must-revalidate'] &&\n (true === requestCC['max-stale'] ||\n requestCC['max-stale'] > this.age() - this.maxAge());\n if (!allowsStale) {\n return false;\n }\n }\n\n return this._requestMatches(req, false);\n }\n\n _requestMatches(req, allowHeadMethod) {\n // The presented effective request URI and that of the stored response match, and\n return (\n (!this._url || this._url === req.url) &&\n this._host === req.headers.host &&\n // the request method associated with the stored response allows it to be used for the presented request, and\n (!req.method ||\n this._method === req.method ||\n (allowHeadMethod && 'HEAD' === req.method)) &&\n // selecting header fields nominated by the stored response (if any) match those presented, and\n this._varyMatches(req)\n );\n }\n\n _allowsStoringAuthenticated() {\n // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.\n return (\n this._rescc['must-revalidate'] ||\n this._rescc.public ||\n this._rescc['s-maxage']\n );\n }\n\n _varyMatches(req) {\n if (!this._resHeaders.vary) {\n return true;\n }\n\n // A Vary header field-value of \"*\" always fails to match\n if (this._resHeaders.vary === '*') {\n return false;\n }\n\n const fields = this._resHeaders.vary\n .trim()\n .toLowerCase()\n .split(/\\s*,\\s*/);\n for (const name of fields) {\n if (req.headers[name] !== this._reqHeaders[name]) return false;\n }\n return true;\n }\n\n _copyWithoutHopByHopHeaders(inHeaders) {\n const headers = {};\n for (const name in inHeaders) {\n if (hopByHopHeaders[name]) continue;\n headers[name] = inHeaders[name];\n }\n // 9.1. Connection\n if (inHeaders.connection) {\n const tokens = inHeaders.connection.trim().split(/\\s*,\\s*/);\n for (const name of tokens) {\n delete headers[name];\n }\n }\n if (headers.warning) {\n const warnings = headers.warning.split(/,/).filter(warning => {\n return !/^\\s*1[0-9][0-9]/.test(warning);\n });\n if (!warnings.length) {\n delete headers.warning;\n } else {\n headers.warning = warnings.join(',').trim();\n }\n }\n return headers;\n }\n\n responseHeaders() {\n const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);\n const age = this.age();\n\n // A cache SHOULD generate 113 warning if it heuristically chose a freshness\n // lifetime greater than 24 hours and the response's age is greater than 24 hours.\n if (\n age > 3600 * 24 &&\n !this._hasExplicitExpiration() &&\n this.maxAge() > 3600 * 24\n ) {\n headers.warning =\n (headers.warning ? `${headers.warning}, ` : '') +\n '113 - \"rfc7234 5.5.4\"';\n }\n headers.age = `${Math.round(age)}`;\n headers.date = new Date(this.now()).toUTCString();\n return headers;\n }\n\n /**\n * Value of the Date response header or current time if Date was invalid\n * @return timestamp\n */\n date() {\n const serverDate = Date.parse(this._resHeaders.date);\n if (isFinite(serverDate)) {\n return serverDate;\n }\n return this._responseTime;\n }\n\n /**\n * Value of the Age header, in seconds, updated for the current time.\n * May be fractional.\n *\n * @return Number\n */\n age() {\n let age = this._ageValue();\n\n const residentTime = (this.now() - this._responseTime) / 1000;\n return age + residentTime;\n }\n\n _ageValue() {\n return toNumberOrZero(this._resHeaders.age);\n }\n\n /**\n * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.\n *\n * For an up-to-date value, see `timeToLive()`.\n *\n * @return Number\n */\n maxAge() {\n if (!this.storable() || this._rescc['no-cache']) {\n return 0;\n }\n\n // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default\n // so this implementation requires explicit opt-in via public header\n if (\n this._isShared &&\n (this._resHeaders['set-cookie'] &&\n !this._rescc.public &&\n !this._rescc.immutable)\n ) {\n return 0;\n }\n\n if (this._resHeaders.vary === '*') {\n return 0;\n }\n\n if (this._isShared) {\n if (this._rescc['proxy-revalidate']) {\n return 0;\n }\n // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.\n if (this._rescc['s-maxage']) {\n return toNumberOrZero(this._rescc['s-maxage']);\n }\n }\n\n // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.\n if (this._rescc['max-age']) {\n return toNumberOrZero(this._rescc['max-age']);\n }\n\n const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;\n\n const serverDate = this.date();\n if (this._resHeaders.expires) {\n const expires = Date.parse(this._resHeaders.expires);\n // A cache recipient MUST interpret invalid date formats, especially the value \"0\", as representing a time in the past (i.e., \"already expired\").\n if (Number.isNaN(expires) || expires < serverDate) {\n return 0;\n }\n return Math.max(defaultMinTtl, (expires - serverDate) / 1000);\n }\n\n if (this._resHeaders['last-modified']) {\n const lastModified = Date.parse(this._resHeaders['last-modified']);\n if (isFinite(lastModified) && serverDate > lastModified) {\n return Math.max(\n defaultMinTtl,\n ((serverDate - lastModified) / 1000) * this._cacheHeuristic\n );\n }\n }\n\n return defaultMinTtl;\n }\n\n timeToLive() {\n const age = this.maxAge() - this.age();\n const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']);\n const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']);\n return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000;\n }\n\n stale() {\n return this.maxAge() <= this.age();\n }\n\n _useStaleIfError() {\n return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();\n }\n\n useStaleWhileRevalidate() {\n return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age();\n }\n\n static fromObject(obj) {\n return new this(undefined, undefined, { _fromObject: obj });\n }\n\n _fromObject(obj) {\n if (this._responseTime) throw Error('Reinitialized');\n if (!obj || obj.v !== 1) throw Error('Invalid serialization');\n\n this._responseTime = obj.t;\n this._isShared = obj.sh;\n this._cacheHeuristic = obj.ch;\n this._immutableMinTtl =\n obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;\n this._status = obj.st;\n this._resHeaders = obj.resh;\n this._rescc = obj.rescc;\n this._method = obj.m;\n this._url = obj.u;\n this._host = obj.h;\n this._noAuthorization = obj.a;\n this._reqHeaders = obj.reqh;\n this._reqcc = obj.reqcc;\n }\n\n toObject() {\n return {\n v: 1,\n t: this._responseTime,\n sh: this._isShared,\n ch: this._cacheHeuristic,\n imm: this._immutableMinTtl,\n st: this._status,\n resh: this._resHeaders,\n rescc: this._rescc,\n m: this._method,\n u: this._url,\n h: this._host,\n a: this._noAuthorization,\n reqh: this._reqHeaders,\n reqcc: this._reqcc,\n };\n }\n\n /**\n * Headers for sending to the origin server to revalidate stale response.\n * Allows server to return 304 to allow reuse of the previous response.\n *\n * Hop by hop headers are always stripped.\n * Revalidation headers may be added or removed, depending on request.\n */\n revalidationHeaders(incomingReq) {\n this._assertRequestHasHeaders(incomingReq);\n const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);\n\n // This implementation does not understand range requests\n delete headers['if-range'];\n\n if (!this._requestMatches(incomingReq, true) || !this.storable()) {\n // revalidation allowed via HEAD\n // not for the same resource, or wasn't allowed to be cached anyway\n delete headers['if-none-match'];\n delete headers['if-modified-since'];\n return headers;\n }\n\n /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */\n if (this._resHeaders.etag) {\n headers['if-none-match'] = headers['if-none-match']\n ? `${headers['if-none-match']}, ${this._resHeaders.etag}`\n : this._resHeaders.etag;\n }\n\n // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.\n const forbidsWeakValidators =\n headers['accept-ranges'] ||\n headers['if-match'] ||\n headers['if-unmodified-since'] ||\n (this._method && this._method != 'GET');\n\n /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.\n Note: This implementation does not understand partial responses (206) */\n if (forbidsWeakValidators) {\n delete headers['if-modified-since'];\n\n if (headers['if-none-match']) {\n const etags = headers['if-none-match']\n .split(/,/)\n .filter(etag => {\n return !/^\\s*W\\//.test(etag);\n });\n if (!etags.length) {\n delete headers['if-none-match'];\n } else {\n headers['if-none-match'] = etags.join(',').trim();\n }\n }\n } else if (\n this._resHeaders['last-modified'] &&\n !headers['if-modified-since']\n ) {\n headers['if-modified-since'] = this._resHeaders['last-modified'];\n }\n\n return headers;\n }\n\n /**\n * Creates new CachePolicy with information combined from the previews response,\n * and the new revalidation response.\n *\n * Returns {policy, modified} where modified is a boolean indicating\n * whether the response body has been modified, and old cached body can't be used.\n *\n * @return {Object} {policy: CachePolicy, modified: Boolean}\n */\n revalidatedPolicy(request, response) {\n this._assertRequestHasHeaders(request);\n if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful\n return {\n modified: false,\n matches: false,\n policy: this,\n };\n }\n if (!response || !response.headers) {\n throw Error('Response headers missing');\n }\n\n // These aren't going to be supported exactly, since one CachePolicy object\n // doesn't know about all the other cached objects.\n let matches = false;\n if (response.status !== undefined && response.status != 304) {\n matches = false;\n } else if (\n response.headers.etag &&\n !/^\\s*W\\//.test(response.headers.etag)\n ) {\n // \"All of the stored responses with the same strong validator are selected.\n // If none of the stored responses contain the same strong validator,\n // then the cache MUST NOT use the new response to update any stored responses.\"\n matches =\n this._resHeaders.etag &&\n this._resHeaders.etag.replace(/^\\s*W\\//, '') ===\n response.headers.etag;\n } else if (this._resHeaders.etag && response.headers.etag) {\n // \"If the new response contains a weak validator and that validator corresponds\n // to one of the cache's stored responses,\n // then the most recent of those matching stored responses is selected for update.\"\n matches =\n this._resHeaders.etag.replace(/^\\s*W\\//, '') ===\n response.headers.etag.replace(/^\\s*W\\//, '');\n } else if (this._resHeaders['last-modified']) {\n matches =\n this._resHeaders['last-modified'] ===\n response.headers['last-modified'];\n } else {\n // If the new response does not include any form of validator (such as in the case where\n // a client generates an If-Modified-Since request from a source other than the Last-Modified\n // response header field), and there is only one stored response, and that stored response also\n // lacks a validator, then that stored response is selected for update.\n if (\n !this._resHeaders.etag &&\n !this._resHeaders['last-modified'] &&\n !response.headers.etag &&\n !response.headers['last-modified']\n ) {\n matches = true;\n }\n }\n\n if (!matches) {\n return {\n policy: new this.constructor(request, response),\n // Client receiving 304 without body, even if it's invalid/mismatched has no option\n // but to reuse a cached body. We don't have a good way to tell clients to do\n // error recovery in such case.\n modified: response.status != 304,\n matches: false,\n };\n }\n\n // use other header fields provided in the 304 (Not Modified) response to replace all instances\n // of the corresponding header fields in the stored response.\n const headers = {};\n for (const k in this._resHeaders) {\n headers[k] =\n k in response.headers && !excludedFromRevalidationUpdate[k]\n ? response.headers[k]\n : this._resHeaders[k];\n }\n\n const newResponse = Object.assign({}, response, {\n status: this._status,\n method: this._method,\n headers,\n });\n return {\n policy: new this.constructor(request, newResponse, {\n shared: this._isShared,\n cacheHeuristic: this._cacheHeuristic,\n immutableMinTimeToLive: this._immutableMinTtl,\n }),\n modified: false,\n matches: true,\n };\n }\n};\n","'use strict';\nmodule.exports = object => {\n\tconst result = {};\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tresult[key.toLowerCase()] = value;\n\t}\n\n\treturn result;\n};\n","'use strict';\n\nconst Readable = require('stream').Readable;\nconst lowercaseKeys = require('lowercase-keys');\n\nclass Response extends Readable {\n\tconstructor(statusCode, headers, body, url) {\n\t\tif (typeof statusCode !== 'number') {\n\t\t\tthrow new TypeError('Argument `statusCode` should be a number');\n\t\t}\n\t\tif (typeof headers !== 'object') {\n\t\t\tthrow new TypeError('Argument `headers` should be an object');\n\t\t}\n\t\tif (!(body instanceof Buffer)) {\n\t\t\tthrow new TypeError('Argument `body` should be a buffer');\n\t\t}\n\t\tif (typeof url !== 'string') {\n\t\t\tthrow new TypeError('Argument `url` should be a string');\n\t\t}\n\n\t\tsuper();\n\t\tthis.statusCode = statusCode;\n\t\tthis.headers = lowercaseKeys(headers);\n\t\tthis.body = body;\n\t\tthis.url = url;\n\t}\n\n\t_read() {\n\t\tthis.push(this.body);\n\t\tthis.push(null);\n\t}\n}\n\nmodule.exports = Response;\n","'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProps = [\n\t'destroy',\n\t'setTimeout',\n\t'socket',\n\t'headers',\n\t'trailers',\n\t'rawHeaders',\n\t'statusCode',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'rawTrailers',\n\t'statusMessage'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tconst fromProps = new Set(Object.keys(fromStream).concat(knownProps));\n\n\tfor (const prop of fromProps) {\n\t\t// Don't overwrite existing properties\n\t\tif (prop in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttoStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop];\n\t}\n};\n","'use strict';\n\nconst PassThrough = require('stream').PassThrough;\nconst mimicResponse = require('mimic-response');\n\nconst cloneResponse = response => {\n\tif (!(response && response.pipe)) {\n\t\tthrow new TypeError('Parameter `response` must be a response stream.');\n\t}\n\n\tconst clone = new PassThrough();\n\tmimicResponse(response, clone);\n\n\treturn response.pipe(clone);\n};\n\nmodule.exports = cloneResponse;\n","//TODO: handle reviver/dehydrate function like normal\n//and handle indentation, like normal.\n//if anyone needs this... please send pull request.\n\nexports.stringify = function stringify (o) {\n if('undefined' == typeof o) return o\n\n if(o && Buffer.isBuffer(o))\n return JSON.stringify(':base64:' + o.toString('base64'))\n\n if(o && o.toJSON)\n o = o.toJSON()\n\n if(o && 'object' === typeof o) {\n var s = ''\n var array = Array.isArray(o)\n s = array ? '[' : '{'\n var first = true\n\n for(var k in o) {\n var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k])\n if(Object.hasOwnProperty.call(o, k) && !ignore) {\n if(!first)\n s += ','\n first = false\n if (array) {\n if(o[k] == undefined)\n s += 'null'\n else\n s += stringify(o[k])\n } else if (o[k] !== void(0)) {\n s += stringify(k) + ':' + stringify(o[k])\n }\n }\n }\n\n s += array ? ']' : '}'\n\n return s\n } else if ('string' === typeof o) {\n return JSON.stringify(/^:/.test(o) ? ':' + o : o)\n } else if ('undefined' === typeof o) {\n return 'null';\n } else\n return JSON.stringify(o)\n}\n\nexports.parse = function (s) {\n return JSON.parse(s, function (key, value) {\n if('string' === typeof value) {\n if(/^:base64:/.test(value))\n return Buffer.from(value.substring(8), 'base64')\n else\n return /^:/.test(value) ? value.substring(1) : value \n }\n return value\n })\n}\n","'use strict';\n\nconst EventEmitter = require('events');\nconst JSONB = require('json-buffer');\n\nconst loadStore = options => {\n\tconst adapters = {\n\t\tredis: '@keyv/redis',\n\t\trediss: '@keyv/redis',\n\t\tmongodb: '@keyv/mongo',\n\t\tmongo: '@keyv/mongo',\n\t\tsqlite: '@keyv/sqlite',\n\t\tpostgresql: '@keyv/postgres',\n\t\tpostgres: '@keyv/postgres',\n\t\tmysql: '@keyv/mysql',\n\t\tetcd: '@keyv/etcd',\n\t\toffline: '@keyv/offline',\n\t\ttiered: '@keyv/tiered',\n\t};\n\tif (options.adapter || options.uri) {\n\t\tconst adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0];\n\t\treturn new (require(adapters[adapter]))(options);\n\t}\n\n\treturn new Map();\n};\n\nconst iterableAdapters = [\n\t'sqlite',\n\t'postgres',\n\t'mysql',\n\t'mongo',\n\t'redis',\n\t'tiered',\n];\n\nclass Keyv extends EventEmitter {\n\tconstructor(uri, {emitErrors = true, ...options} = {}) {\n\t\tsuper();\n\t\tthis.opts = {\n\t\t\tnamespace: 'keyv',\n\t\t\tserialize: JSONB.stringify,\n\t\t\tdeserialize: JSONB.parse,\n\t\t\t...((typeof uri === 'string') ? {uri} : uri),\n\t\t\t...options,\n\t\t};\n\n\t\tif (!this.opts.store) {\n\t\t\tconst adapterOptions = {...this.opts};\n\t\t\tthis.opts.store = loadStore(adapterOptions);\n\t\t}\n\n\t\tif (this.opts.compression) {\n\t\t\tconst compression = this.opts.compression;\n\t\t\tthis.opts.serialize = compression.serialize.bind(compression);\n\t\t\tthis.opts.deserialize = compression.deserialize.bind(compression);\n\t\t}\n\n\t\tif (typeof this.opts.store.on === 'function' && emitErrors) {\n\t\t\tthis.opts.store.on('error', error => this.emit('error', error));\n\t\t}\n\n\t\tthis.opts.store.namespace = this.opts.namespace;\n\n\t\tconst generateIterator = iterator => async function * () {\n\t\t\tfor await (const [key, raw] of typeof iterator === 'function'\n\t\t\t\t? iterator(this.opts.store.namespace)\n\t\t\t\t: iterator) {\n\t\t\t\tconst data = await this.opts.deserialize(raw);\n\t\t\t\tif (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (typeof data.expires === 'number' && Date.now() > data.expires) {\n\t\t\t\t\tthis.delete(key);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tyield [this._getKeyUnprefix(key), data.value];\n\t\t\t}\n\t\t};\n\n\t\t// Attach iterators\n\t\tif (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) {\n\t\t\tthis.iterator = generateIterator(this.opts.store);\n\t\t} else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts\n\t\t\t&& this._checkIterableAdaptar()) {\n\t\t\tthis.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store));\n\t\t}\n\t}\n\n\t_checkIterableAdaptar() {\n\t\treturn iterableAdapters.includes(this.opts.store.opts.dialect)\n\t\t\t|| iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0;\n\t}\n\n\t_getKeyPrefix(key) {\n\t\treturn `${this.opts.namespace}:${key}`;\n\t}\n\n\t_getKeyPrefixArray(keys) {\n\t\treturn keys.map(key => `${this.opts.namespace}:${key}`);\n\t}\n\n\t_getKeyUnprefix(key) {\n\t\treturn key\n\t\t\t.split(':')\n\t\t\t.splice(1)\n\t\t\t.join(':');\n\t}\n\n\tget(key, options) {\n\t\tconst {store} = this.opts;\n\t\tconst isArray = Array.isArray(key);\n\t\tconst keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);\n\t\tif (isArray && store.getMany === undefined) {\n\t\t\tconst promises = [];\n\t\t\tfor (const key of keyPrefixed) {\n\t\t\t\tpromises.push(Promise.resolve()\n\t\t\t\t\t.then(() => store.get(key))\n\t\t\t\t\t.then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data))\n\t\t\t\t\t.then(data => {\n\t\t\t\t\t\tif (data === undefined || data === null) {\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (typeof data.expires === 'number' && Date.now() > data.expires) {\n\t\t\t\t\t\t\treturn this.delete(key).then(() => undefined);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn (options && options.raw) ? data : data.value;\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn Promise.allSettled(promises)\n\t\t\t\t.then(values => {\n\t\t\t\t\tconst data = [];\n\t\t\t\t\tfor (const value of values) {\n\t\t\t\t\t\tdata.push(value.value);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn data;\n\t\t\t\t});\n\t\t}\n\n\t\treturn Promise.resolve()\n\t\t\t.then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed))\n\t\t\t.then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data))\n\t\t\t.then(data => {\n\t\t\t\tif (data === undefined || data === null) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tif (isArray) {\n\t\t\t\t\treturn data.map((row, index) => {\n\t\t\t\t\t\tif ((typeof row === 'string')) {\n\t\t\t\t\t\t\trow = this.opts.deserialize(row);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (row === undefined || row === null) {\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (typeof row.expires === 'number' && Date.now() > row.expires) {\n\t\t\t\t\t\t\tthis.delete(key[index]).then(() => undefined);\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn (options && options.raw) ? row : row.value;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (typeof data.expires === 'number' && Date.now() > data.expires) {\n\t\t\t\t\treturn this.delete(key).then(() => undefined);\n\t\t\t\t}\n\n\t\t\t\treturn (options && options.raw) ? data : data.value;\n\t\t\t});\n\t}\n\n\tset(key, value, ttl) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tif (typeof ttl === 'undefined') {\n\t\t\tttl = this.opts.ttl;\n\t\t}\n\n\t\tif (ttl === 0) {\n\t\t\tttl = undefined;\n\t\t}\n\n\t\tconst {store} = this.opts;\n\n\t\treturn Promise.resolve()\n\t\t\t.then(() => {\n\t\t\t\tconst expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;\n\t\t\t\tif (typeof value === 'symbol') {\n\t\t\t\t\tthis.emit('error', 'symbol cannot be serialized');\n\t\t\t\t}\n\n\t\t\t\tvalue = {value, expires};\n\t\t\t\treturn this.opts.serialize(value);\n\t\t\t})\n\t\t\t.then(value => store.set(keyPrefixed, value, ttl))\n\t\t\t.then(() => true);\n\t}\n\n\tdelete(key) {\n\t\tconst {store} = this.opts;\n\t\tif (Array.isArray(key)) {\n\t\t\tconst keyPrefixed = this._getKeyPrefixArray(key);\n\t\t\tif (store.deleteMany === undefined) {\n\t\t\t\tconst promises = [];\n\t\t\t\tfor (const key of keyPrefixed) {\n\t\t\t\t\tpromises.push(store.delete(key));\n\t\t\t\t}\n\n\t\t\t\treturn Promise.allSettled(promises)\n\t\t\t\t\t.then(values => values.every(x => x.value === true));\n\t\t\t}\n\n\t\t\treturn Promise.resolve()\n\t\t\t\t.then(() => store.deleteMany(keyPrefixed));\n\t\t}\n\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.delete(keyPrefixed));\n\t}\n\n\tclear() {\n\t\tconst {store} = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.clear());\n\t}\n\n\thas(key) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tconst {store} = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(async () => {\n\t\t\t\tif (typeof store.has === 'function') {\n\t\t\t\t\treturn store.has(keyPrefixed);\n\t\t\t\t}\n\n\t\t\t\tconst value = await store.get(keyPrefixed);\n\t\t\t\treturn value !== undefined;\n\t\t\t});\n\t}\n\n\tdisconnect() {\n\t\tconst {store} = this.opts;\n\t\tif (typeof store.disconnect === 'function') {\n\t\t\treturn store.disconnect();\n\t\t}\n\t}\n}\n\nmodule.exports = Keyv;\n","'use strict';\n\nconst EventEmitter = require('events');\nconst urlLib = require('url');\nconst normalizeUrl = require('normalize-url');\nconst getStream = require('get-stream');\nconst CachePolicy = require('http-cache-semantics');\nconst Response = require('responselike');\nconst lowercaseKeys = require('lowercase-keys');\nconst cloneResponse = require('clone-response');\nconst Keyv = require('keyv');\n\nclass CacheableRequest {\n\tconstructor(request, cacheAdapter) {\n\t\tif (typeof request !== 'function') {\n\t\t\tthrow new TypeError('Parameter `request` must be a function');\n\t\t}\n\n\t\tthis.cache = new Keyv({\n\t\t\turi: typeof cacheAdapter === 'string' && cacheAdapter,\n\t\t\tstore: typeof cacheAdapter !== 'string' && cacheAdapter,\n\t\t\tnamespace: 'cacheable-request'\n\t\t});\n\n\t\treturn this.createCacheableRequest(request);\n\t}\n\n\tcreateCacheableRequest(request) {\n\t\treturn (opts, cb) => {\n\t\t\tlet url;\n\t\t\tif (typeof opts === 'string') {\n\t\t\t\turl = normalizeUrlObject(urlLib.parse(opts));\n\t\t\t\topts = {};\n\t\t\t} else if (opts instanceof urlLib.URL) {\n\t\t\t\turl = normalizeUrlObject(urlLib.parse(opts.toString()));\n\t\t\t\topts = {};\n\t\t\t} else {\n\t\t\t\tconst [pathname, ...searchParts] = (opts.path || '').split('?');\n\t\t\t\tconst search = searchParts.length > 0 ?\n\t\t\t\t\t`?${searchParts.join('?')}` :\n\t\t\t\t\t'';\n\t\t\t\turl = normalizeUrlObject({ ...opts, pathname, search });\n\t\t\t}\n\n\t\t\topts = {\n\t\t\t\theaders: {},\n\t\t\t\tmethod: 'GET',\n\t\t\t\tcache: true,\n\t\t\t\tstrictTtl: false,\n\t\t\t\tautomaticFailover: false,\n\t\t\t\t...opts,\n\t\t\t\t...urlObjectToRequestOptions(url)\n\t\t\t};\n\t\t\topts.headers = lowercaseKeys(opts.headers);\n\n\t\t\tconst ee = new EventEmitter();\n\t\t\tconst normalizedUrlString = normalizeUrl(\n\t\t\t\turlLib.format(url),\n\t\t\t\t{\n\t\t\t\t\tstripWWW: false,\n\t\t\t\t\tremoveTrailingSlash: false,\n\t\t\t\t\tstripAuthentication: false\n\t\t\t\t}\n\t\t\t);\n\t\t\tconst key = `${opts.method}:${normalizedUrlString}`;\n\t\t\tlet revalidate = false;\n\t\t\tlet madeRequest = false;\n\n\t\t\tconst makeRequest = opts => {\n\t\t\t\tmadeRequest = true;\n\t\t\t\tlet requestErrored = false;\n\t\t\t\tlet requestErrorCallback;\n\n\t\t\t\tconst requestErrorPromise = new Promise(resolve => {\n\t\t\t\t\trequestErrorCallback = () => {\n\t\t\t\t\t\tif (!requestErrored) {\n\t\t\t\t\t\t\trequestErrored = true;\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\tconst handler = response => {\n\t\t\t\t\tif (revalidate && !opts.forceRefresh) {\n\t\t\t\t\t\tresponse.status = response.statusCode;\n\t\t\t\t\t\tconst revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);\n\t\t\t\t\t\tif (!revalidatedPolicy.modified) {\n\t\t\t\t\t\t\tconst headers = revalidatedPolicy.policy.responseHeaders();\n\t\t\t\t\t\t\tresponse = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);\n\t\t\t\t\t\t\tresponse.cachePolicy = revalidatedPolicy.policy;\n\t\t\t\t\t\t\tresponse.fromCache = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!response.fromCache) {\n\t\t\t\t\t\tresponse.cachePolicy = new CachePolicy(opts, response, opts);\n\t\t\t\t\t\tresponse.fromCache = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet clonedResponse;\n\t\t\t\t\tif (opts.cache && response.cachePolicy.storable()) {\n\t\t\t\t\t\tclonedResponse = cloneResponse(response);\n\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst bodyPromise = getStream.buffer(response);\n\n\t\t\t\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t\t\t\trequestErrorPromise,\n\t\t\t\t\t\t\t\t\tnew Promise(resolve => response.once('end', resolve))\n\t\t\t\t\t\t\t\t]);\n\n\t\t\t\t\t\t\t\tif (requestErrored) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst body = await bodyPromise;\n\n\t\t\t\t\t\t\t\tconst value = {\n\t\t\t\t\t\t\t\t\tcachePolicy: response.cachePolicy.toObject(),\n\t\t\t\t\t\t\t\t\turl: response.url,\n\t\t\t\t\t\t\t\t\tstatusCode: response.fromCache ? revalidate.statusCode : response.statusCode,\n\t\t\t\t\t\t\t\t\tbody\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tlet ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;\n\t\t\t\t\t\t\t\tif (opts.maxTtl) {\n\t\t\t\t\t\t\t\t\tttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tawait this.cache.set(key, value, ttl);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})();\n\t\t\t\t\t} else if (opts.cache && revalidate) {\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait this.cache.delete(key);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})();\n\t\t\t\t\t}\n\n\t\t\t\t\tee.emit('response', clonedResponse || response);\n\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\tcb(clonedResponse || response);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tconst req = request(opts, handler);\n\t\t\t\t\treq.once('error', requestErrorCallback);\n\t\t\t\t\treq.once('abort', requestErrorCallback);\n\t\t\t\t\tee.emit('request', req);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tee.emit('error', new CacheableRequest.RequestError(error));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t(async () => {\n\t\t\t\tconst get = async opts => {\n\t\t\t\t\tawait Promise.resolve();\n\n\t\t\t\t\tconst cacheEntry = opts.cache ? await this.cache.get(key) : undefined;\n\t\t\t\t\tif (typeof cacheEntry === 'undefined') {\n\t\t\t\t\t\treturn makeRequest(opts);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst policy = CachePolicy.fromObject(cacheEntry.cachePolicy);\n\t\t\t\t\tif (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {\n\t\t\t\t\t\tconst headers = policy.responseHeaders();\n\t\t\t\t\t\tconst response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);\n\t\t\t\t\t\tresponse.cachePolicy = policy;\n\t\t\t\t\t\tresponse.fromCache = true;\n\n\t\t\t\t\t\tee.emit('response', response);\n\t\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\t\tcb(response);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\trevalidate = cacheEntry;\n\t\t\t\t\t\topts.headers = policy.revalidationHeaders(opts);\n\t\t\t\t\t\tmakeRequest(opts);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tconst errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\tthis.cache.once('error', errorHandler);\n\t\t\t\tee.on('response', () => this.cache.removeListener('error', errorHandler));\n\n\t\t\t\ttry {\n\t\t\t\t\tawait get(opts);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (opts.automaticFailover && !madeRequest) {\n\t\t\t\t\t\tmakeRequest(opts);\n\t\t\t\t\t}\n\n\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t}\n\t\t\t})();\n\n\t\t\treturn ee;\n\t\t};\n\t}\n}\n\nfunction urlObjectToRequestOptions(url) {\n\tconst options = { ...url };\n\toptions.path = `${url.pathname || '/'}${url.search || ''}`;\n\tdelete options.pathname;\n\tdelete options.search;\n\treturn options;\n}\n\nfunction normalizeUrlObject(url) {\n\t// If url was parsed by url.parse or new URL:\n\t// - hostname will be set\n\t// - host will be hostname[:port]\n\t// - port will be set if it was explicit in the parsed string\n\t// Otherwise, url was from request options:\n\t// - hostname or host may be set\n\t// - host shall not have port encoded\n\treturn {\n\t\tprotocol: url.protocol,\n\t\tauth: url.auth,\n\t\thostname: url.hostname || url.host || 'localhost',\n\t\tport: url.port,\n\t\tpathname: url.pathname,\n\t\tsearch: url.search\n\t};\n}\n\nCacheableRequest.RequestError = class extends Error {\n\tconstructor(error) {\n\t\tsuper(error.message);\n\t\tthis.name = 'RequestError';\n\t\tObject.assign(this, error);\n\t}\n};\n\nCacheableRequest.CacheError = class extends Error {\n\tconstructor(error) {\n\t\tsuper(error.message);\n\t\tthis.name = 'CacheError';\n\t\tObject.assign(this, error);\n\t}\n};\n\nmodule.exports = CacheableRequest;\n","'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProperties = [\n\t'aborted',\n\t'complete',\n\t'headers',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'method',\n\t'rawHeaders',\n\t'rawTrailers',\n\t'setTimeout',\n\t'socket',\n\t'statusCode',\n\t'statusMessage',\n\t'trailers',\n\t'url'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tif (toStream._readableState.autoDestroy) {\n\t\tthrow new Error('The second stream must have the `autoDestroy` option set to `false`');\n\t}\n\n\tconst fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));\n\n\tconst properties = {};\n\n\tfor (const property of fromProperties) {\n\t\t// Don't overwrite existing properties.\n\t\tif (property in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tproperties[property] = {\n\t\t\tget() {\n\t\t\t\tconst value = fromStream[property];\n\t\t\t\tconst isFunction = typeof value === 'function';\n\n\t\t\t\treturn isFunction ? value.bind(fromStream) : value;\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tfromStream[property] = value;\n\t\t\t},\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false\n\t\t};\n\t}\n\n\tObject.defineProperties(toStream, properties);\n\n\tfromStream.once('aborted', () => {\n\t\ttoStream.destroy();\n\n\t\ttoStream.emit('aborted');\n\t});\n\n\tfromStream.once('close', () => {\n\t\tif (fromStream.complete) {\n\t\t\tif (toStream.readable) {\n\t\t\t\ttoStream.once('end', () => {\n\t\t\t\t\ttoStream.emit('close');\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoStream.emit('close');\n\t\t\t}\n\t\t} else {\n\t\t\ttoStream.emit('close');\n\t\t}\n\t});\n\n\treturn toStream;\n};\n","'use strict';\nconst {Transform, PassThrough} = require('stream');\nconst zlib = require('zlib');\nconst mimicResponse = require('mimic-response');\n\nmodule.exports = response => {\n\tconst contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();\n\n\tif (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {\n\t\treturn response;\n\t}\n\n\t// TODO: Remove this when targeting Node.js 12.\n\tconst isBrotli = contentEncoding === 'br';\n\tif (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {\n\t\tresponse.destroy(new Error('Brotli is not supported on Node.js < 12'));\n\t\treturn response;\n\t}\n\n\tlet isEmpty = true;\n\n\tconst checker = new Transform({\n\t\ttransform(data, _encoding, callback) {\n\t\t\tisEmpty = false;\n\n\t\t\tcallback(null, data);\n\t\t},\n\n\t\tflush(callback) {\n\t\t\tcallback();\n\t\t}\n\t});\n\n\tconst finalStream = new PassThrough({\n\t\tautoDestroy: false,\n\t\tdestroy(error, callback) {\n\t\t\tresponse.destroy();\n\n\t\t\tcallback(error);\n\t\t}\n\t});\n\n\tconst decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();\n\n\tdecompressStream.once('error', error => {\n\t\tif (isEmpty && !response.readable) {\n\t\t\tfinalStream.end();\n\t\t\treturn;\n\t\t}\n\n\t\tfinalStream.destroy(error);\n\t});\n\n\tmimicResponse(response, finalStream);\n\tresponse.pipe(checker).pipe(decompressStream).pipe(finalStream);\n\n\treturn finalStream;\n};\n","'use strict';\n\nclass QuickLRU {\n\tconstructor(options = {}) {\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tfor (const [key, value] of this.oldCache.entries()) {\n\t\t\t\t\tthis.onEviction(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst value = this.oldCache.get(key);\n\t\t\tthis.oldCache.delete(key);\n\t\t\tthis._set(key, value);\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tset(key, value) {\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, value);\n\t\t} else {\n\t\t\tthis._set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\thas(key) {\n\t\treturn this.cache.has(key) || this.oldCache.has(key);\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this.oldCache.get(key);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tyield item;\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget size() {\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n}\n\nmodule.exports = QuickLRU;\n","'use strict';\nconst EventEmitter = require('events');\nconst tls = require('tls');\nconst http2 = require('http2');\nconst QuickLRU = require('quick-lru');\n\nconst kCurrentStreamsCount = Symbol('currentStreamsCount');\nconst kRequest = Symbol('request');\nconst kOriginSet = Symbol('cachedOriginSet');\nconst kGracefullyClosing = Symbol('gracefullyClosing');\n\nconst nameKeys = [\n\t// `http2.connect()` options\n\t'maxDeflateDynamicTableSize',\n\t'maxSessionMemory',\n\t'maxHeaderListPairs',\n\t'maxOutstandingPings',\n\t'maxReservedRemoteStreams',\n\t'maxSendHeaderBlockLength',\n\t'paddingStrategy',\n\n\t// `tls.connect()` options\n\t'localAddress',\n\t'path',\n\t'rejectUnauthorized',\n\t'minDHSize',\n\n\t// `tls.createSecureContext()` options\n\t'ca',\n\t'cert',\n\t'clientCertEngine',\n\t'ciphers',\n\t'key',\n\t'pfx',\n\t'servername',\n\t'minVersion',\n\t'maxVersion',\n\t'secureProtocol',\n\t'crl',\n\t'honorCipherOrder',\n\t'ecdhCurve',\n\t'dhparam',\n\t'secureOptions',\n\t'sessionIdContext'\n];\n\nconst getSortedIndex = (array, value, compare) => {\n\tlet low = 0;\n\tlet high = array.length;\n\n\twhile (low < high) {\n\t\tconst mid = (low + high) >>> 1;\n\n\t\t/* istanbul ignore next */\n\t\tif (compare(array[mid], value)) {\n\t\t\t// This never gets called because we use descending sort. Better to have this anyway.\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid;\n\t\t}\n\t}\n\n\treturn low;\n};\n\nconst compareSessions = (a, b) => {\n\treturn a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams;\n};\n\n// See https://tools.ietf.org/html/rfc8336\nconst closeCoveredSessions = (where, session) => {\n\t// Clients SHOULD NOT emit new requests on any connection whose Origin\n\t// Set is a proper subset of another connection's Origin Set, and they\n\t// SHOULD close it once all outstanding requests are satisfied.\n\tfor (const coveredSession of where) {\n\t\tif (\n\t\t\t// The set is a proper subset when its length is less than the other set.\n\t\t\tcoveredSession[kOriginSet].length < session[kOriginSet].length &&\n\n\t\t\t// And the other set includes all elements of the subset.\n\t\t\tcoveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) &&\n\n\t\t\t// Makes sure that the session can handle all requests from the covered session.\n\t\t\tcoveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams\n\t\t) {\n\t\t\t// This allows pending requests to finish and prevents making new requests.\n\t\t\tgracefullyClose(coveredSession);\n\t\t}\n\t}\n};\n\n// This is basically inverted `closeCoveredSessions(...)`.\nconst closeSessionIfCovered = (where, coveredSession) => {\n\tfor (const session of where) {\n\t\tif (\n\t\t\tcoveredSession[kOriginSet].length < session[kOriginSet].length &&\n\t\t\tcoveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) &&\n\t\t\tcoveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams\n\t\t) {\n\t\t\tgracefullyClose(coveredSession);\n\t\t}\n\t}\n};\n\nconst getSessions = ({agent, isFree}) => {\n\tconst result = {};\n\n\t// eslint-disable-next-line guard-for-in\n\tfor (const normalizedOptions in agent.sessions) {\n\t\tconst sessions = agent.sessions[normalizedOptions];\n\n\t\tconst filtered = sessions.filter(session => {\n\t\t\tconst result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams;\n\n\t\t\treturn isFree ? result : !result;\n\t\t});\n\n\t\tif (filtered.length !== 0) {\n\t\t\tresult[normalizedOptions] = filtered;\n\t\t}\n\t}\n\n\treturn result;\n};\n\nconst gracefullyClose = session => {\n\tsession[kGracefullyClosing] = true;\n\n\tif (session[kCurrentStreamsCount] === 0) {\n\t\tsession.close();\n\t}\n};\n\nclass Agent extends EventEmitter {\n\tconstructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) {\n\t\tsuper();\n\n\t\t// A session is considered busy when its current streams count\n\t\t// is equal to or greater than the `maxConcurrentStreams` value.\n\n\t\t// A session is considered free when its current streams count\n\t\t// is less than the `maxConcurrentStreams` value.\n\n\t\t// SESSIONS[NORMALIZED_OPTIONS] = [];\n\t\tthis.sessions = {};\n\n\t\t// The queue for creating new sessions. It looks like this:\n\t\t// QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION\n\t\t//\n\t\t// The entry function has `listeners`, `completed` and `destroyed` properties.\n\t\t// `listeners` is an array of objects containing `resolve` and `reject` functions.\n\t\t// `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed.\n\t\t// `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet.\n\t\tthis.queue = {};\n\n\t\t// Each session will use this timeout value.\n\t\tthis.timeout = timeout;\n\n\t\t// Max sessions in total\n\t\tthis.maxSessions = maxSessions;\n\n\t\t// Max free sessions in total\n\t\t// TODO: decreasing `maxFreeSessions` should close some sessions\n\t\tthis.maxFreeSessions = maxFreeSessions;\n\n\t\tthis._freeSessionsCount = 0;\n\t\tthis._sessionsCount = 0;\n\n\t\t// We don't support push streams by default.\n\t\tthis.settings = {\n\t\t\tenablePush: false\n\t\t};\n\n\t\t// Reusing TLS sessions increases performance.\n\t\tthis.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions});\n\t}\n\n\tstatic normalizeOrigin(url, servername) {\n\t\tif (typeof url === 'string') {\n\t\t\turl = new URL(url);\n\t\t}\n\n\t\tif (servername && url.hostname !== servername) {\n\t\t\turl.hostname = servername;\n\t\t}\n\n\t\treturn url.origin;\n\t}\n\n\tnormalizeOptions(options) {\n\t\tlet normalized = '';\n\n\t\tif (options) {\n\t\t\tfor (const key of nameKeys) {\n\t\t\t\tif (options[key]) {\n\t\t\t\t\tnormalized += `:${options[key]}`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn normalized;\n\t}\n\n\t_tryToCreateNewSession(normalizedOptions, normalizedOrigin) {\n\t\tif (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst item = this.queue[normalizedOptions][normalizedOrigin];\n\n\t\t// The entry function can be run only once.\n\t\t// BUG: The session may be never created when:\n\t\t// - the first condition is false AND\n\t\t// - this function is never called with the same arguments in the future.\n\t\tif (this._sessionsCount < this.maxSessions && !item.completed) {\n\t\t\titem.completed = true;\n\n\t\t\titem();\n\t\t}\n\t}\n\n\tgetSession(origin, options, listeners) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (Array.isArray(listeners)) {\n\t\t\t\tlisteners = [...listeners];\n\n\t\t\t\t// Resolve the current promise ASAP, we're just moving the listeners.\n\t\t\t\t// They will be executed at a different time.\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\tlisteners = [{resolve, reject}];\n\t\t\t}\n\n\t\t\tconst normalizedOptions = this.normalizeOptions(options);\n\t\t\tconst normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername);\n\n\t\t\tif (normalizedOrigin === undefined) {\n\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\treject(new TypeError('The `origin` argument needs to be a string or an URL object'));\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (normalizedOptions in this.sessions) {\n\t\t\t\tconst sessions = this.sessions[normalizedOptions];\n\n\t\t\t\tlet maxConcurrentStreams = -1;\n\t\t\t\tlet currentStreamsCount = -1;\n\t\t\t\tlet optimalSession;\n\n\t\t\t\t// We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal.\n\t\t\t\t// Additionally, we are looking for session which has biggest current pending streams count.\n\t\t\t\tfor (const session of sessions) {\n\t\t\t\t\tconst sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams;\n\n\t\t\t\t\tif (sessionMaxConcurrentStreams < maxConcurrentStreams) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (session[kOriginSet].includes(normalizedOrigin)) {\n\t\t\t\t\t\tconst sessionCurrentStreamsCount = session[kCurrentStreamsCount];\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tsessionCurrentStreamsCount >= sessionMaxConcurrentStreams ||\n\t\t\t\t\t\t\tsession[kGracefullyClosing] ||\n\t\t\t\t\t\t\t// Unfortunately the `close` event isn't called immediately,\n\t\t\t\t\t\t\t// so `session.destroyed` is `true`, but `session.closed` is `false`.\n\t\t\t\t\t\t\tsession.destroyed\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We only need set this once.\n\t\t\t\t\t\tif (!optimalSession) {\n\t\t\t\t\t\t\tmaxConcurrentStreams = sessionMaxConcurrentStreams;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We're looking for the session which has biggest current pending stream count,\n\t\t\t\t\t\t// in order to minimalize the amount of active sessions.\n\t\t\t\t\t\tif (sessionCurrentStreamsCount > currentStreamsCount) {\n\t\t\t\t\t\t\toptimalSession = session;\n\t\t\t\t\t\t\tcurrentStreamsCount = sessionCurrentStreamsCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (optimalSession) {\n\t\t\t\t\t/* istanbul ignore next: safety check */\n\t\t\t\t\tif (listeners.length !== 1) {\n\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\tconst error = new Error(\n\t\t\t\t\t\t\t\t`Expected the length of listeners to be 1, got ${listeners.length}.\\n` +\n\t\t\t\t\t\t\t\t'Please report this to https://github.com/szmarczak/http2-wrapper/'\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlisteners[0].resolve(optimalSession);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (normalizedOptions in this.queue) {\n\t\t\t\tif (normalizedOrigin in this.queue[normalizedOptions]) {\n\t\t\t\t\t// There's already an item in the queue, just attach ourselves to it.\n\t\t\t\t\tthis.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners);\n\n\t\t\t\t\t// This shouldn't be executed here.\n\t\t\t\t\t// See the comment inside _tryToCreateNewSession.\n\t\t\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.queue[normalizedOptions] = {};\n\t\t\t}\n\n\t\t\t// The entry must be removed from the queue IMMEDIATELY when:\n\t\t\t// 1. the session connects successfully,\n\t\t\t// 2. an error occurs.\n\t\t\tconst removeFromQueue = () => {\n\t\t\t\t// Our entry can be replaced. We cannot remove the new one.\n\t\t\t\tif (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) {\n\t\t\t\t\tdelete this.queue[normalizedOptions][normalizedOrigin];\n\n\t\t\t\t\tif (Object.keys(this.queue[normalizedOptions]).length === 0) {\n\t\t\t\t\t\tdelete this.queue[normalizedOptions];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// The main logic is here\n\t\t\tconst entry = () => {\n\t\t\t\tconst name = `${normalizedOrigin}:${normalizedOptions}`;\n\t\t\t\tlet receivedSettings = false;\n\n\t\t\t\ttry {\n\t\t\t\t\tconst session = http2.connect(origin, {\n\t\t\t\t\t\tcreateConnection: this.createConnection,\n\t\t\t\t\t\tsettings: this.settings,\n\t\t\t\t\t\tsession: this.tlsSessionCache.get(name),\n\t\t\t\t\t\t...options\n\t\t\t\t\t});\n\t\t\t\t\tsession[kCurrentStreamsCount] = 0;\n\t\t\t\t\tsession[kGracefullyClosing] = false;\n\n\t\t\t\t\tconst isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams;\n\t\t\t\t\tlet wasFree = true;\n\n\t\t\t\t\tsession.socket.once('session', tlsSession => {\n\t\t\t\t\t\tthis.tlsSessionCache.set(name, tlsSession);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('error', error => {\n\t\t\t\t\t\t// Listeners are empty when the session successfully connected.\n\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// The connection got broken, purge the cache.\n\t\t\t\t\t\tthis.tlsSessionCache.delete(name);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.setTimeout(this.timeout, () => {\n\t\t\t\t\t\t// Terminates all streams owned by this session.\n\t\t\t\t\t\t// TODO: Maybe the streams should have a \"Session timed out\" error?\n\t\t\t\t\t\tsession.destroy();\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('close', () => {\n\t\t\t\t\t\tif (receivedSettings) {\n\t\t\t\t\t\t\t// 1. If it wasn't free then no need to decrease because\n\t\t\t\t\t\t\t// it has been decreased already in session.request().\n\t\t\t\t\t\t\t// 2. `stream.once('close')` won't increment the count\n\t\t\t\t\t\t\t// because the session is already closed.\n\t\t\t\t\t\t\tif (wasFree) {\n\t\t\t\t\t\t\t\tthis._freeSessionsCount--;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tthis._sessionsCount--;\n\n\t\t\t\t\t\t\t// This cannot be moved to the stream logic,\n\t\t\t\t\t\t\t// because there may be a session that hadn't made a single request.\n\t\t\t\t\t\t\tconst where = this.sessions[normalizedOptions];\n\t\t\t\t\t\t\twhere.splice(where.indexOf(session), 1);\n\n\t\t\t\t\t\t\tif (where.length === 0) {\n\t\t\t\t\t\t\t\tdelete this.sessions[normalizedOptions];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Broken connection\n\t\t\t\t\t\t\tconst error = new Error('Session closed without receiving a SETTINGS frame');\n\t\t\t\t\t\t\terror.code = 'HTTP2WRAPPER_NOSETTINGS';\n\n\t\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tremoveFromQueue();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// There may be another session awaiting.\n\t\t\t\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t\t\t\t});\n\n\t\t\t\t\t// Iterates over the queue and processes listeners.\n\t\t\t\t\tconst processListeners = () => {\n\t\t\t\t\t\tif (!(normalizedOptions in this.queue) || !isFree()) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const origin of session[kOriginSet]) {\n\t\t\t\t\t\t\tif (origin in this.queue[normalizedOptions]) {\n\t\t\t\t\t\t\t\tconst {listeners} = this.queue[normalizedOptions][origin];\n\n\t\t\t\t\t\t\t\t// Prevents session overloading.\n\t\t\t\t\t\t\t\twhile (listeners.length !== 0 && isFree()) {\n\t\t\t\t\t\t\t\t\t// We assume `resolve(...)` calls `request(...)` *directly*,\n\t\t\t\t\t\t\t\t\t// otherwise the session will get overloaded.\n\t\t\t\t\t\t\t\t\tlisteners.shift().resolve(session);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst where = this.queue[normalizedOptions];\n\t\t\t\t\t\t\t\tif (where[origin].listeners.length === 0) {\n\t\t\t\t\t\t\t\t\tdelete where[origin];\n\n\t\t\t\t\t\t\t\t\tif (Object.keys(where).length === 0) {\n\t\t\t\t\t\t\t\t\t\tdelete this.queue[normalizedOptions];\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// We're no longer free, no point in continuing.\n\t\t\t\t\t\t\t\tif (!isFree()) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\t// The Origin Set cannot shrink. No need to check if it suddenly became covered by another one.\n\t\t\t\t\tsession.on('origin', () => {\n\t\t\t\t\t\tsession[kOriginSet] = session.originSet;\n\n\t\t\t\t\t\tif (!isFree()) {\n\t\t\t\t\t\t\t// The session is full.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprocessListeners();\n\n\t\t\t\t\t\t// Close covered sessions (if possible).\n\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('remoteSettings', () => {\n\t\t\t\t\t\t// Fix Node.js bug preventing the process from exiting\n\t\t\t\t\t\tsession.ref();\n\t\t\t\t\t\tsession.unref();\n\n\t\t\t\t\t\tthis._sessionsCount++;\n\n\t\t\t\t\t\t// The Agent could have been destroyed already.\n\t\t\t\t\t\tif (entry.destroyed) {\n\t\t\t\t\t\t\tconst error = new Error('Agent has been destroyed');\n\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tlistener.reject(error);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsession.destroy();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsession[kOriginSet] = session.originSet;\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst where = this.sessions;\n\n\t\t\t\t\t\t\tif (normalizedOptions in where) {\n\t\t\t\t\t\t\t\tconst sessions = where[normalizedOptions];\n\t\t\t\t\t\t\t\tsessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\twhere[normalizedOptions] = [session];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._freeSessionsCount += 1;\n\t\t\t\t\t\treceivedSettings = true;\n\n\t\t\t\t\t\tthis.emit('session', session);\n\n\t\t\t\t\t\tprocessListeners();\n\t\t\t\t\t\tremoveFromQueue();\n\n\t\t\t\t\t\t// TODO: Close last recently used (or least used?) session\n\t\t\t\t\t\tif (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) {\n\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check if we haven't managed to execute all listeners.\n\t\t\t\t\t\tif (listeners.length !== 0) {\n\t\t\t\t\t\t\t// Request for a new session with predefined listeners.\n\t\t\t\t\t\t\tthis.getSession(normalizedOrigin, options, listeners);\n\t\t\t\t\t\t\tlisteners.length = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// `session.remoteSettings.maxConcurrentStreams` might get increased\n\t\t\t\t\t\tsession.on('remoteSettings', () => {\n\t\t\t\t\t\t\tprocessListeners();\n\n\t\t\t\t\t\t\t// In case the Origin Set changes\n\t\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\n\t\t\t\t\t// Shim `session.request()` in order to catch all streams\n\t\t\t\t\tsession[kRequest] = session.request;\n\t\t\t\t\tsession.request = (headers, streamOptions) => {\n\t\t\t\t\t\tif (session[kGracefullyClosing]) {\n\t\t\t\t\t\t\tthrow new Error('The session is gracefully closing. No new streams are allowed.');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst stream = session[kRequest](headers, streamOptions);\n\n\t\t\t\t\t\t// The process won't exit until the session is closed or all requests are gone.\n\t\t\t\t\t\tsession.ref();\n\n\t\t\t\t\t\t++session[kCurrentStreamsCount];\n\n\t\t\t\t\t\tif (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) {\n\t\t\t\t\t\t\tthis._freeSessionsCount--;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstream.once('close', () => {\n\t\t\t\t\t\t\twasFree = isFree();\n\n\t\t\t\t\t\t\t--session[kCurrentStreamsCount];\n\n\t\t\t\t\t\t\tif (!session.destroyed && !session.closed) {\n\t\t\t\t\t\t\t\tcloseSessionIfCovered(this.sessions[normalizedOptions], session);\n\n\t\t\t\t\t\t\t\tif (isFree() && !session.closed) {\n\t\t\t\t\t\t\t\t\tif (!wasFree) {\n\t\t\t\t\t\t\t\t\t\tthis._freeSessionsCount++;\n\n\t\t\t\t\t\t\t\t\t\twasFree = true;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst isEmpty = session[kCurrentStreamsCount] === 0;\n\n\t\t\t\t\t\t\t\t\tif (isEmpty) {\n\t\t\t\t\t\t\t\t\t\tsession.unref();\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tisEmpty &&\n\t\t\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\tthis._freeSessionsCount > this.maxFreeSessions ||\n\t\t\t\t\t\t\t\t\t\t\tsession[kGracefullyClosing]\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t\t\t\t\t\tprocessListeners();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn stream;\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener.reject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tremoveFromQueue();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tentry.listeners = listeners;\n\t\t\tentry.completed = false;\n\t\t\tentry.destroyed = false;\n\n\t\t\tthis.queue[normalizedOptions][normalizedOrigin] = entry;\n\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t});\n\t}\n\n\trequest(origin, options, headers, streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.getSession(origin, options, [{\n\t\t\t\treject,\n\t\t\t\tresolve: session => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(session.request(headers, streamOptions));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}]);\n\t\t});\n\t}\n\n\tcreateConnection(origin, options) {\n\t\treturn Agent.connect(origin, options);\n\t}\n\n\tstatic connect(origin, options) {\n\t\toptions.ALPNProtocols = ['h2'];\n\n\t\tconst port = origin.port || 443;\n\t\tconst host = origin.hostname || origin.host;\n\n\t\tif (typeof options.servername === 'undefined') {\n\t\t\toptions.servername = host;\n\t\t}\n\n\t\treturn tls.connect(port, host, options);\n\t}\n\n\tcloseFreeSessions() {\n\t\tfor (const sessions of Object.values(this.sessions)) {\n\t\t\tfor (const session of sessions) {\n\t\t\t\tif (session[kCurrentStreamsCount] === 0) {\n\t\t\t\t\tsession.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdestroy(reason) {\n\t\tfor (const sessions of Object.values(this.sessions)) {\n\t\t\tfor (const session of sessions) {\n\t\t\t\tsession.destroy(reason);\n\t\t\t}\n\t\t}\n\n\t\tfor (const entriesOfAuthority of Object.values(this.queue)) {\n\t\t\tfor (const entry of Object.values(entriesOfAuthority)) {\n\t\t\t\tentry.destroyed = true;\n\t\t\t}\n\t\t}\n\n\t\t// New requests should NOT attach to destroyed sessions\n\t\tthis.queue = {};\n\t}\n\n\tget freeSessions() {\n\t\treturn getSessions({agent: this, isFree: true});\n\t}\n\n\tget busySessions() {\n\t\treturn getSessions({agent: this, isFree: false});\n\t}\n}\n\nAgent.kCurrentStreamsCount = kCurrentStreamsCount;\nAgent.kGracefullyClosing = kGracefullyClosing;\n\nmodule.exports = {\n\tAgent,\n\tglobalAgent: new Agent()\n};\n","'use strict';\nconst {Readable} = require('stream');\n\nclass IncomingMessage extends Readable {\n\tconstructor(socket, highWaterMark) {\n\t\tsuper({\n\t\t\thighWaterMark,\n\t\t\tautoDestroy: false\n\t\t});\n\n\t\tthis.statusCode = null;\n\t\tthis.statusMessage = '';\n\t\tthis.httpVersion = '2.0';\n\t\tthis.httpVersionMajor = 2;\n\t\tthis.httpVersionMinor = 0;\n\t\tthis.headers = {};\n\t\tthis.trailers = {};\n\t\tthis.req = null;\n\n\t\tthis.aborted = false;\n\t\tthis.complete = false;\n\t\tthis.upgrade = null;\n\n\t\tthis.rawHeaders = [];\n\t\tthis.rawTrailers = [];\n\n\t\tthis.socket = socket;\n\t\tthis.connection = socket;\n\n\t\tthis._dumped = false;\n\t}\n\n\t_destroy(error) {\n\t\tthis.req._request.destroy(error);\n\t}\n\n\tsetTimeout(ms, callback) {\n\t\tthis.req.setTimeout(ms, callback);\n\t\treturn this;\n\t}\n\n\t_dump() {\n\t\tif (!this._dumped) {\n\t\t\tthis._dumped = true;\n\n\t\t\tthis.removeAllListeners('data');\n\t\t\tthis.resume();\n\t\t}\n\t}\n\n\t_read() {\n\t\tif (this.req) {\n\t\t\tthis.req._request.resume();\n\t\t}\n\t}\n}\n\nmodule.exports = IncomingMessage;\n","'use strict';\n/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */\n\nmodule.exports = url => {\n\tconst options = {\n\t\tprotocol: url.protocol,\n\t\thostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n\t\thost: url.host,\n\t\thash: url.hash,\n\t\tsearch: url.search,\n\t\tpathname: url.pathname,\n\t\thref: url.href,\n\t\tpath: `${url.pathname || ''}${url.search || ''}`\n\t};\n\n\tif (typeof url.port === 'string' && url.port.length !== 0) {\n\t\toptions.port = Number(url.port);\n\t}\n\n\tif (url.username || url.password) {\n\t\toptions.auth = `${url.username || ''}:${url.password || ''}`;\n\t}\n\n\treturn options;\n};\n","'use strict';\n\nmodule.exports = (from, to, events) => {\n\tfor (const event of events) {\n\t\tfrom.on(event, (...args) => to.emit(event, ...args));\n\t}\n};\n","'use strict';\n\nmodule.exports = header => {\n\tswitch (header) {\n\t\tcase ':method':\n\t\tcase ':scheme':\n\t\tcase ':authority':\n\t\tcase ':path':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n};\n","'use strict';\n/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */\n\nconst makeError = (Base, key, getMessage) => {\n\tmodule.exports[key] = class NodeError extends Base {\n\t\tconstructor(...args) {\n\t\t\tsuper(typeof getMessage === 'string' ? getMessage : getMessage(args));\n\t\t\tthis.name = `${super.name} [${key}]`;\n\t\t\tthis.code = key;\n\t\t}\n\t};\n};\n\nmakeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => {\n\tconst type = args[0].includes('.') ? 'property' : 'argument';\n\n\tlet valid = args[1];\n\tconst isManyTypes = Array.isArray(valid);\n\n\tif (isManyTypes) {\n\t\tvalid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`;\n\t}\n\n\treturn `The \"${args[0]}\" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_PROTOCOL', args => {\n\treturn `Protocol \"${args[0]}\" not supported. Expected \"${args[1]}\"`;\n});\n\nmakeError(Error, 'ERR_HTTP_HEADERS_SENT', args => {\n\treturn `Cannot ${args[0]} headers after they are sent to the client`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => {\n\treturn `${args[0]} must be a valid HTTP token [${args[1]}]`;\n});\n\nmakeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => {\n\treturn `Invalid value \"${args[0]} for header \"${args[1]}\"`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_CHAR', args => {\n\treturn `Invalid character in ${args[0]} [${args[1]}]`;\n});\n","'use strict';\nconst http2 = require('http2');\nconst {Writable} = require('stream');\nconst {Agent, globalAgent} = require('./agent');\nconst IncomingMessage = require('./incoming-message');\nconst urlToOptions = require('./utils/url-to-options');\nconst proxyEvents = require('./utils/proxy-events');\nconst isRequestPseudoHeader = require('./utils/is-request-pseudo-header');\nconst {\n\tERR_INVALID_ARG_TYPE,\n\tERR_INVALID_PROTOCOL,\n\tERR_HTTP_HEADERS_SENT,\n\tERR_INVALID_HTTP_TOKEN,\n\tERR_HTTP_INVALID_HEADER_VALUE,\n\tERR_INVALID_CHAR\n} = require('./utils/errors');\n\nconst {\n\tHTTP2_HEADER_STATUS,\n\tHTTP2_HEADER_METHOD,\n\tHTTP2_HEADER_PATH,\n\tHTTP2_METHOD_CONNECT\n} = http2.constants;\n\nconst kHeaders = Symbol('headers');\nconst kOrigin = Symbol('origin');\nconst kSession = Symbol('session');\nconst kOptions = Symbol('options');\nconst kFlushedHeaders = Symbol('flushedHeaders');\nconst kJobs = Symbol('jobs');\n\nconst isValidHttpToken = /^[\\^`\\-\\w!#$%&*+.|~]+$/;\nconst isInvalidHeaderValue = /[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/;\n\nclass ClientRequest extends Writable {\n\tconstructor(input, options, callback) {\n\t\tsuper({\n\t\t\tautoDestroy: false\n\t\t});\n\n\t\tconst hasInput = typeof input === 'string' || input instanceof URL;\n\t\tif (hasInput) {\n\t\t\tinput = urlToOptions(input instanceof URL ? input : new URL(input));\n\t\t}\n\n\t\tif (typeof options === 'function' || options === undefined) {\n\t\t\t// (options, callback)\n\t\t\tcallback = options;\n\t\t\toptions = hasInput ? input : {...input};\n\t\t} else {\n\t\t\t// (input, options, callback)\n\t\t\toptions = {...input, ...options};\n\t\t}\n\n\t\tif (options.h2session) {\n\t\t\tthis[kSession] = options.h2session;\n\t\t} else if (options.agent === false) {\n\t\t\tthis.agent = new Agent({maxFreeSessions: 0});\n\t\t} else if (typeof options.agent === 'undefined' || options.agent === null) {\n\t\t\tif (typeof options.createConnection === 'function') {\n\t\t\t\t// This is a workaround - we don't have to create the session on our own.\n\t\t\t\tthis.agent = new Agent({maxFreeSessions: 0});\n\t\t\t\tthis.agent.createConnection = options.createConnection;\n\t\t\t} else {\n\t\t\t\tthis.agent = globalAgent;\n\t\t\t}\n\t\t} else if (typeof options.agent.request === 'function') {\n\t\t\tthis.agent = options.agent;\n\t\t} else {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent);\n\t\t}\n\n\t\tif (options.protocol && options.protocol !== 'https:') {\n\t\t\tthrow new ERR_INVALID_PROTOCOL(options.protocol, 'https:');\n\t\t}\n\n\t\tconst port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443;\n\t\tconst host = options.hostname || options.host || 'localhost';\n\n\t\t// Don't enforce the origin via options. It may be changed in an Agent.\n\t\tdelete options.hostname;\n\t\tdelete options.host;\n\t\tdelete options.port;\n\n\t\tconst {timeout} = options;\n\t\toptions.timeout = undefined;\n\n\t\tthis[kHeaders] = Object.create(null);\n\t\tthis[kJobs] = [];\n\n\t\tthis.socket = null;\n\t\tthis.connection = null;\n\n\t\tthis.method = options.method || 'GET';\n\t\tthis.path = options.path;\n\n\t\tthis.res = null;\n\t\tthis.aborted = false;\n\t\tthis.reusedSocket = false;\n\n\t\tif (options.headers) {\n\t\t\tfor (const [header, value] of Object.entries(options.headers)) {\n\t\t\t\tthis.setHeader(header, value);\n\t\t\t}\n\t\t}\n\n\t\tif (options.auth && !('authorization' in this[kHeaders])) {\n\t\t\tthis[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64');\n\t\t}\n\n\t\toptions.session = options.tlsSession;\n\t\toptions.path = options.socketPath;\n\n\t\tthis[kOptions] = options;\n\n\t\t// Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field.\n\t\tif (port === 443) {\n\t\t\tthis[kOrigin] = `https://${host}`;\n\n\t\t\tif (!(':authority' in this[kHeaders])) {\n\t\t\t\tthis[kHeaders][':authority'] = host;\n\t\t\t}\n\t\t} else {\n\t\t\tthis[kOrigin] = `https://${host}:${port}`;\n\n\t\t\tif (!(':authority' in this[kHeaders])) {\n\t\t\t\tthis[kHeaders][':authority'] = `${host}:${port}`;\n\t\t\t}\n\t\t}\n\n\t\tif (timeout) {\n\t\t\tthis.setTimeout(timeout);\n\t\t}\n\n\t\tif (callback) {\n\t\t\tthis.once('response', callback);\n\t\t}\n\n\t\tthis[kFlushedHeaders] = false;\n\t}\n\n\tget method() {\n\t\treturn this[kHeaders][HTTP2_HEADER_METHOD];\n\t}\n\n\tset method(value) {\n\t\tif (value) {\n\t\t\tthis[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase();\n\t\t}\n\t}\n\n\tget path() {\n\t\treturn this[kHeaders][HTTP2_HEADER_PATH];\n\t}\n\n\tset path(value) {\n\t\tif (value) {\n\t\t\tthis[kHeaders][HTTP2_HEADER_PATH] = value;\n\t\t}\n\t}\n\n\tget _mustNotHaveABody() {\n\t\treturn this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE';\n\t}\n\n\t_write(chunk, encoding, callback) {\n\t\t// https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156\n\t\tif (this._mustNotHaveABody) {\n\t\t\tcallback(new Error('The GET, HEAD and DELETE methods must NOT have a body'));\n\t\t\t/* istanbul ignore next: Node.js 12 throws directly */\n\t\t\treturn;\n\t\t}\n\n\t\tthis.flushHeaders();\n\n\t\tconst callWrite = () => this._request.write(chunk, encoding, callback);\n\t\tif (this._request) {\n\t\t\tcallWrite();\n\t\t} else {\n\t\t\tthis[kJobs].push(callWrite);\n\t\t}\n\t}\n\n\t_final(callback) {\n\t\tif (this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.flushHeaders();\n\n\t\tconst callEnd = () => {\n\t\t\t// For GET, HEAD and DELETE\n\t\t\tif (this._mustNotHaveABody) {\n\t\t\t\tcallback();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._request.end(callback);\n\t\t};\n\n\t\tif (this._request) {\n\t\t\tcallEnd();\n\t\t} else {\n\t\t\tthis[kJobs].push(callEnd);\n\t\t}\n\t}\n\n\tabort() {\n\t\tif (this.res && this.res.complete) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.aborted) {\n\t\t\tprocess.nextTick(() => this.emit('abort'));\n\t\t}\n\n\t\tthis.aborted = true;\n\n\t\tthis.destroy();\n\t}\n\n\t_destroy(error, callback) {\n\t\tif (this.res) {\n\t\t\tthis.res._dump();\n\t\t}\n\n\t\tif (this._request) {\n\t\t\tthis._request.destroy();\n\t\t}\n\n\t\tcallback(error);\n\t}\n\n\tasync flushHeaders() {\n\t\tif (this[kFlushedHeaders] || this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis[kFlushedHeaders] = true;\n\n\t\tconst isConnectMethod = this.method === HTTP2_METHOD_CONNECT;\n\n\t\t// The real magic is here\n\t\tconst onStream = stream => {\n\t\t\tthis._request = stream;\n\n\t\t\tif (this.destroyed) {\n\t\t\t\tstream.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Forwards `timeout`, `continue`, `close` and `error` events to this instance.\n\t\t\tif (!isConnectMethod) {\n\t\t\t\tproxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']);\n\t\t\t}\n\n\t\t\t// Wait for the `finish` event. We don't want to emit the `response` event\n\t\t\t// before `request.end()` is called.\n\t\t\tconst waitForEnd = fn => {\n\t\t\t\treturn (...args) => {\n\t\t\t\t\tif (!this.writable && !this.destroyed) {\n\t\t\t\t\t\tfn(...args);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.once('finish', () => {\n\t\t\t\t\t\t\tfn(...args);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t};\n\n\t\t\t// This event tells we are ready to listen for the data.\n\t\t\tstream.once('response', waitForEnd((headers, flags, rawHeaders) => {\n\t\t\t\t// If we were to emit raw request stream, it would be as fast as the native approach.\n\t\t\t\t// Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it).\n\t\t\t\tconst response = new IncomingMessage(this.socket, stream.readableHighWaterMark);\n\t\t\t\tthis.res = response;\n\n\t\t\t\tresponse.req = this;\n\t\t\t\tresponse.statusCode = headers[HTTP2_HEADER_STATUS];\n\t\t\t\tresponse.headers = headers;\n\t\t\t\tresponse.rawHeaders = rawHeaders;\n\n\t\t\t\tresponse.once('end', () => {\n\t\t\t\t\tif (this.aborted) {\n\t\t\t\t\t\tresponse.aborted = true;\n\t\t\t\t\t\tresponse.emit('aborted');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.complete = true;\n\n\t\t\t\t\t\t// Has no effect, just be consistent with the Node.js behavior\n\t\t\t\t\t\tresponse.socket = null;\n\t\t\t\t\t\tresponse.connection = null;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (isConnectMethod) {\n\t\t\t\t\tresponse.upgrade = true;\n\n\t\t\t\t\t// The HTTP1 API says the socket is detached here,\n\t\t\t\t\t// but we can't do that so we pass the original HTTP2 request.\n\t\t\t\t\tif (this.emit('connect', response, stream, Buffer.alloc(0))) {\n\t\t\t\t\t\tthis.emit('close');\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No listeners attached, destroy the original request.\n\t\t\t\t\t\tstream.destroy();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Forwards data\n\t\t\t\t\tstream.on('data', chunk => {\n\t\t\t\t\t\tif (!response._dumped && !response.push(chunk)) {\n\t\t\t\t\t\t\tstream.pause();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tstream.once('end', () => {\n\t\t\t\t\t\tresponse.push(null);\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!this.emit('response', response)) {\n\t\t\t\t\t\t// No listeners attached, dump the response.\n\t\t\t\t\t\tresponse._dump();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\n\t\t\t// Emits `information` event\n\t\t\tstream.once('headers', waitForEnd(\n\t\t\t\theaders => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})\n\t\t\t));\n\n\t\t\tstream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => {\n\t\t\t\tconst {res} = this;\n\n\t\t\t\t// Assigns trailers to the response object.\n\t\t\t\tres.trailers = trailers;\n\t\t\t\tres.rawTrailers = rawTrailers;\n\t\t\t}));\n\n\t\t\tconst {socket} = stream.session;\n\t\t\tthis.socket = socket;\n\t\t\tthis.connection = socket;\n\n\t\t\tfor (const job of this[kJobs]) {\n\t\t\t\tjob();\n\t\t\t}\n\n\t\t\tthis.emit('socket', this.socket);\n\t\t};\n\n\t\t// Makes a HTTP2 request\n\t\tif (this[kSession]) {\n\t\t\ttry {\n\t\t\t\tonStream(this[kSession].request(this[kHeaders]));\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.reusedSocket = true;\n\n\t\t\ttry {\n\t\t\t\tonStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]));\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t}\n\t\t}\n\t}\n\n\tgetHeader(name) {\n\t\tif (typeof name !== 'string') {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('name', 'string', name);\n\t\t}\n\n\t\treturn this[kHeaders][name.toLowerCase()];\n\t}\n\n\tget headersSent() {\n\t\treturn this[kFlushedHeaders];\n\t}\n\n\tremoveHeader(name) {\n\t\tif (typeof name !== 'string') {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('name', 'string', name);\n\t\t}\n\n\t\tif (this.headersSent) {\n\t\t\tthrow new ERR_HTTP_HEADERS_SENT('remove');\n\t\t}\n\n\t\tdelete this[kHeaders][name.toLowerCase()];\n\t}\n\n\tsetHeader(name, value) {\n\t\tif (this.headersSent) {\n\t\t\tthrow new ERR_HTTP_HEADERS_SENT('set');\n\t\t}\n\n\t\tif (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) {\n\t\t\tthrow new ERR_INVALID_HTTP_TOKEN('Header name', name);\n\t\t}\n\n\t\tif (typeof value === 'undefined') {\n\t\t\tthrow new ERR_HTTP_INVALID_HEADER_VALUE(value, name);\n\t\t}\n\n\t\tif (isInvalidHeaderValue.test(value)) {\n\t\t\tthrow new ERR_INVALID_CHAR('header content', name);\n\t\t}\n\n\t\tthis[kHeaders][name.toLowerCase()] = value;\n\t}\n\n\tsetNoDelay() {\n\t\t// HTTP2 sockets cannot be malformed, do nothing.\n\t}\n\n\tsetSocketKeepAlive() {\n\t\t// HTTP2 sockets cannot be malformed, do nothing.\n\t}\n\n\tsetTimeout(ms, callback) {\n\t\tconst applyTimeout = () => this._request.setTimeout(ms, callback);\n\n\t\tif (this._request) {\n\t\t\tapplyTimeout();\n\t\t} else {\n\t\t\tthis[kJobs].push(applyTimeout);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tget maxHeadersCount() {\n\t\tif (!this.destroyed && this._request) {\n\t\t\treturn this._request.session.localSettings.maxHeaderListSize;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tset maxHeadersCount(_value) {\n\t\t// Updating HTTP2 settings would affect all requests, do nothing.\n\t}\n}\n\nmodule.exports = ClientRequest;\n","'use strict';\nconst tls = require('tls');\n\nmodule.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => {\n\tlet timeout = false;\n\n\tlet socket;\n\n\tconst callback = async () => {\n\t\tawait socketPromise;\n\n\t\tsocket.off('timeout', onTimeout);\n\t\tsocket.off('error', reject);\n\n\t\tif (options.resolveSocket) {\n\t\t\tresolve({alpnProtocol: socket.alpnProtocol, socket, timeout});\n\n\t\t\tif (timeout) {\n\t\t\t\tawait Promise.resolve();\n\t\t\t\tsocket.emit('timeout');\n\t\t\t}\n\t\t} else {\n\t\t\tsocket.destroy();\n\t\t\tresolve({alpnProtocol: socket.alpnProtocol, timeout});\n\t\t}\n\t};\n\n\tconst onTimeout = async () => {\n\t\ttimeout = true;\n\t\tcallback();\n\t};\n\n\tconst socketPromise = (async () => {\n\t\ttry {\n\t\t\tsocket = await connect(options, callback);\n\n\t\t\tsocket.on('error', reject);\n\t\t\tsocket.once('timeout', onTimeout);\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\t})();\n});\n","'use strict';\nconst net = require('net');\n/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */\n\nmodule.exports = options => {\n\tlet servername = options.host;\n\tconst hostHeader = options.headers && options.headers.host;\n\n\tif (hostHeader) {\n\t\tif (hostHeader.startsWith('[')) {\n\t\t\tconst index = hostHeader.indexOf(']');\n\t\t\tif (index === -1) {\n\t\t\t\tservername = hostHeader;\n\t\t\t} else {\n\t\t\t\tservername = hostHeader.slice(1, -1);\n\t\t\t}\n\t\t} else {\n\t\t\tservername = hostHeader.split(':', 1)[0];\n\t\t}\n\t}\n\n\tif (net.isIP(servername)) {\n\t\treturn '';\n\t}\n\n\treturn servername;\n};\n","'use strict';\nconst http = require('http');\nconst https = require('https');\nconst resolveALPN = require('resolve-alpn');\nconst QuickLRU = require('quick-lru');\nconst Http2ClientRequest = require('./client-request');\nconst calculateServerName = require('./utils/calculate-server-name');\nconst urlToOptions = require('./utils/url-to-options');\n\nconst cache = new QuickLRU({maxSize: 100});\nconst queue = new Map();\n\nconst installSocket = (agent, socket, options) => {\n\tsocket._httpMessage = {shouldKeepAlive: true};\n\n\tconst onFree = () => {\n\t\tagent.emit('free', socket, options);\n\t};\n\n\tsocket.on('free', onFree);\n\n\tconst onClose = () => {\n\t\tagent.removeSocket(socket, options);\n\t};\n\n\tsocket.on('close', onClose);\n\n\tconst onRemove = () => {\n\t\tagent.removeSocket(socket, options);\n\t\tsocket.off('close', onClose);\n\t\tsocket.off('free', onFree);\n\t\tsocket.off('agentRemove', onRemove);\n\t};\n\n\tsocket.on('agentRemove', onRemove);\n\n\tagent.emit('free', socket, options);\n};\n\nconst resolveProtocol = async options => {\n\tconst name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`;\n\n\tif (!cache.has(name)) {\n\t\tif (queue.has(name)) {\n\t\t\tconst result = await queue.get(name);\n\t\t\treturn result.alpnProtocol;\n\t\t}\n\n\t\tconst {path, agent} = options;\n\t\toptions.path = options.socketPath;\n\n\t\tconst resultPromise = resolveALPN(options);\n\t\tqueue.set(name, resultPromise);\n\n\t\ttry {\n\t\t\tconst {socket, alpnProtocol} = await resultPromise;\n\t\t\tcache.set(name, alpnProtocol);\n\n\t\t\toptions.path = path;\n\n\t\t\tif (alpnProtocol === 'h2') {\n\t\t\t\t// https://github.com/nodejs/node/issues/33343\n\t\t\t\tsocket.destroy();\n\t\t\t} else {\n\t\t\t\tconst {globalAgent} = https;\n\t\t\t\tconst defaultCreateConnection = https.Agent.prototype.createConnection;\n\n\t\t\t\tif (agent) {\n\t\t\t\t\tif (agent.createConnection === defaultCreateConnection) {\n\t\t\t\t\t\tinstallSocket(agent, socket, options);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsocket.destroy();\n\t\t\t\t\t}\n\t\t\t\t} else if (globalAgent.createConnection === defaultCreateConnection) {\n\t\t\t\t\tinstallSocket(globalAgent, socket, options);\n\t\t\t\t} else {\n\t\t\t\t\tsocket.destroy();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tqueue.delete(name);\n\n\t\t\treturn alpnProtocol;\n\t\t} catch (error) {\n\t\t\tqueue.delete(name);\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn cache.get(name);\n};\n\nmodule.exports = async (input, options, callback) => {\n\tif (typeof input === 'string' || input instanceof URL) {\n\t\tinput = urlToOptions(new URL(input));\n\t}\n\n\tif (typeof options === 'function') {\n\t\tcallback = options;\n\t\toptions = undefined;\n\t}\n\n\toptions = {\n\t\tALPNProtocols: ['h2', 'http/1.1'],\n\t\t...input,\n\t\t...options,\n\t\tresolveSocket: true\n\t};\n\n\tif (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) {\n\t\tthrow new Error('The `ALPNProtocols` option must be an Array with at least one entry');\n\t}\n\n\toptions.protocol = options.protocol || 'https:';\n\tconst isHttps = options.protocol === 'https:';\n\n\toptions.host = options.hostname || options.host || 'localhost';\n\toptions.session = options.tlsSession;\n\toptions.servername = options.servername || calculateServerName(options);\n\toptions.port = options.port || (isHttps ? 443 : 80);\n\toptions._defaultAgent = isHttps ? https.globalAgent : http.globalAgent;\n\n\tconst agents = options.agent;\n\n\tif (agents) {\n\t\tif (agents.addRequest) {\n\t\t\tthrow new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties');\n\t\t}\n\n\t\toptions.agent = agents[isHttps ? 'https' : 'http'];\n\t}\n\n\tif (isHttps) {\n\t\tconst protocol = await resolveProtocol(options);\n\n\t\tif (protocol === 'h2') {\n\t\t\tif (agents) {\n\t\t\t\toptions.agent = agents.http2;\n\t\t\t}\n\n\t\t\treturn new Http2ClientRequest(options, callback);\n\t\t}\n\t}\n\n\treturn http.request(options, callback);\n};\n\nmodule.exports.protocolCache = cache;\n","'use strict';\nconst http2 = require('http2');\nconst agent = require('./agent');\nconst ClientRequest = require('./client-request');\nconst IncomingMessage = require('./incoming-message');\nconst auto = require('./auto');\n\nconst request = (url, options, callback) => {\n\treturn new ClientRequest(url, options, callback);\n};\n\nconst get = (url, options, callback) => {\n\t// eslint-disable-next-line unicorn/prevent-abbreviations\n\tconst req = new ClientRequest(url, options, callback);\n\treq.end();\n\n\treturn req;\n};\n\nmodule.exports = {\n\t...http2,\n\tClientRequest,\n\tIncomingMessage,\n\t...agent,\n\trequest,\n\tget,\n\tauto\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nexports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = require(\"fs\");\nconst util_1 = require(\"util\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst is_form_data_1 = require(\"./is-form-data\");\nconst statAsync = util_1.promisify(fs_1.stat);\nexports.default = async (body, headers) => {\n if (headers && 'content-length' in headers) {\n return Number(headers['content-length']);\n }\n if (!body) {\n return 0;\n }\n if (is_1.default.string(body)) {\n return Buffer.byteLength(body);\n }\n if (is_1.default.buffer(body)) {\n return body.length;\n }\n if (is_form_data_1.default(body)) {\n return util_1.promisify(body.getLength.bind(body))();\n }\n if (body instanceof fs_1.ReadStream) {\n const { size } = await statAsync(body.path);\n if (size === 0) {\n return undefined;\n }\n return size;\n }\n return undefined;\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction default_1(from, to, events) {\n const fns = {};\n for (const event of events) {\n fns[event] = (...args) => {\n to.emit(event, ...args);\n };\n from.on(event, fns[event]);\n }\n return () => {\n for (const event of events) {\n from.off(event, fns[event]);\n }\n };\n}\nexports.default = default_1;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// When attaching listeners, it's very easy to forget about them.\n// Especially if you do error handling and set timeouts.\n// So instead of checking if it's proper to throw an error on every timeout ever,\n// use this simple tool which will remove all listeners you have attached.\nexports.default = () => {\n const handlers = [];\n return {\n once(origin, event, fn) {\n origin.once(event, fn);\n handlers.push({ origin, event, fn });\n },\n unhandleAll() {\n for (const handler of handlers) {\n const { origin, event, fn } = handler;\n origin.removeListener(event, fn);\n }\n handlers.length = 0;\n }\n };\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TimeoutError = void 0;\nconst net = require(\"net\");\nconst unhandle_1 = require(\"./unhandle\");\nconst reentry = Symbol('reentry');\nconst noop = () => { };\nclass TimeoutError extends Error {\n constructor(threshold, event) {\n super(`Timeout awaiting '${event}' for ${threshold}ms`);\n this.event = event;\n this.name = 'TimeoutError';\n this.code = 'ETIMEDOUT';\n }\n}\nexports.TimeoutError = TimeoutError;\nexports.default = (request, delays, options) => {\n if (reentry in request) {\n return noop;\n }\n request[reentry] = true;\n const cancelers = [];\n const { once, unhandleAll } = unhandle_1.default();\n const addTimeout = (delay, callback, event) => {\n var _a;\n const timeout = setTimeout(callback, delay, delay, event);\n (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout);\n const cancel = () => {\n clearTimeout(timeout);\n };\n cancelers.push(cancel);\n return cancel;\n };\n const { host, hostname } = options;\n const timeoutHandler = (delay, event) => {\n request.destroy(new TimeoutError(delay, event));\n };\n const cancelTimeouts = () => {\n for (const cancel of cancelers) {\n cancel();\n }\n unhandleAll();\n };\n request.once('error', error => {\n cancelTimeouts();\n // Save original behavior\n /* istanbul ignore next */\n if (request.listenerCount('error') === 0) {\n throw error;\n }\n });\n request.once('close', cancelTimeouts);\n once(request, 'response', (response) => {\n once(response, 'end', cancelTimeouts);\n });\n if (typeof delays.request !== 'undefined') {\n addTimeout(delays.request, timeoutHandler, 'request');\n }\n if (typeof delays.socket !== 'undefined') {\n const socketTimeoutHandler = () => {\n timeoutHandler(delays.socket, 'socket');\n };\n request.setTimeout(delays.socket, socketTimeoutHandler);\n // `request.setTimeout(0)` causes a memory leak.\n // We can just remove the listener and forget about the timer - it's unreffed.\n // See https://github.com/sindresorhus/got/issues/690\n cancelers.push(() => {\n request.removeListener('timeout', socketTimeoutHandler);\n });\n }\n once(request, 'socket', (socket) => {\n var _a;\n const { socketPath } = request;\n /* istanbul ignore next: hard to test */\n if (socket.connecting) {\n const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0);\n if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') {\n const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');\n once(socket, 'lookup', cancelTimeout);\n }\n if (typeof delays.connect !== 'undefined') {\n const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');\n if (hasPath) {\n once(socket, 'connect', timeConnect());\n }\n else {\n once(socket, 'lookup', (error) => {\n if (error === null) {\n once(socket, 'connect', timeConnect());\n }\n });\n }\n }\n if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') {\n once(socket, 'connect', () => {\n const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');\n once(socket, 'secureConnect', cancelTimeout);\n });\n }\n }\n if (typeof delays.send !== 'undefined') {\n const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');\n /* istanbul ignore next: hard to test */\n if (socket.connecting) {\n once(socket, 'connect', () => {\n once(request, 'upload-complete', timeRequest());\n });\n }\n else {\n once(request, 'upload-complete', timeRequest());\n }\n }\n });\n if (typeof delays.response !== 'undefined') {\n once(request, 'upload-complete', () => {\n const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');\n once(request, 'response', cancelTimeout);\n });\n }\n return cancelTimeouts;\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nexports.default = (url) => {\n // Cast to URL\n url = url;\n const options = {\n protocol: url.protocol,\n hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n host: url.host,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n href: url.href,\n path: `${url.pathname || ''}${url.search || ''}`\n };\n if (is_1.default.string(url.port) && url.port.length > 0) {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${url.username || ''}:${url.password || ''}`;\n }\n return options;\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* istanbul ignore file: deprecated */\nconst url_1 = require(\"url\");\nconst keys = [\n 'protocol',\n 'host',\n 'hostname',\n 'port',\n 'pathname',\n 'search'\n];\nexports.default = (origin, options) => {\n var _a, _b;\n if (options.path) {\n if (options.pathname) {\n throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.');\n }\n if (options.search) {\n throw new TypeError('Parameters `path` and `search` are mutually exclusive.');\n }\n if (options.searchParams) {\n throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.');\n }\n }\n if (options.search && options.searchParams) {\n throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.');\n }\n if (!origin) {\n if (!options.protocol) {\n throw new TypeError('No URL protocol specified');\n }\n origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`;\n }\n const url = new url_1.URL(origin);\n if (options.path) {\n const searchIndex = options.path.indexOf('?');\n if (searchIndex === -1) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.slice(0, searchIndex);\n options.search = options.path.slice(searchIndex + 1);\n }\n delete options.path;\n }\n for (const key of keys) {\n if (options[key]) {\n url[key] = options[key].toString();\n }\n }\n return url;\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass WeakableMap {\n constructor() {\n this.weakMap = new WeakMap();\n this.map = new Map();\n }\n set(key, value) {\n if (typeof key === 'object') {\n this.weakMap.set(key, value);\n }\n else {\n this.map.set(key, value);\n }\n }\n get(key) {\n if (typeof key === 'object') {\n return this.weakMap.get(key);\n }\n return this.map.get(key);\n }\n has(key) {\n if (typeof key === 'object') {\n return this.weakMap.has(key);\n }\n return this.map.has(key);\n }\n}\nexports.default = WeakableMap;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// TODO: Update https://github.com/sindresorhus/get-stream\nconst getBuffer = async (stream) => {\n const chunks = [];\n let length = 0;\n for await (const chunk of stream) {\n chunks.push(chunk);\n length += Buffer.byteLength(chunk);\n }\n if (Buffer.isBuffer(chunks[0])) {\n return Buffer.concat(chunks, length);\n }\n return Buffer.from(chunks.join(''));\n};\nexports.default = getBuffer;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0;\nconst conversionTable = {\n auto: 0,\n ipv4: 4,\n ipv6: 6\n};\nexports.isDnsLookupIpVersion = (value) => {\n return value in conversionTable;\n};\nexports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => {\n if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) {\n return conversionTable[dnsLookupIpVersion];\n }\n throw new Error('Invalid DNS lookup IP version');\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isResponseOk = void 0;\nexports.isResponseOk = (response) => {\n const { statusCode } = response;\n const limitStatusCode = response.request.options.followRedirect ? 299 : 399;\n return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst alreadyWarned = new Set();\nexports.default = (message) => {\n if (alreadyWarned.has(message)) {\n return;\n }\n alreadyWarned.add(message);\n // @ts-expect-error Missing types.\n process.emitWarning(`Got: ${message}`, {\n type: 'DeprecationWarning'\n });\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nconst normalizeArguments = (options, defaults) => {\n if (is_1.default.null_(options.encoding)) {\n throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');\n }\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType);\n // `options.responseType`\n if (options.responseType === undefined) {\n options.responseType = 'text';\n }\n // `options.retry`\n const { retry } = options;\n if (defaults) {\n options.retry = { ...defaults.retry };\n }\n else {\n options.retry = {\n calculateDelay: retryObject => retryObject.computedValue,\n limit: 0,\n methods: [],\n statusCodes: [],\n errorCodes: [],\n maxRetryAfter: undefined\n };\n }\n if (is_1.default.object(retry)) {\n options.retry = {\n ...options.retry,\n ...retry\n };\n options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];\n options.retry.statusCodes = [...new Set(options.retry.statusCodes)];\n options.retry.errorCodes = [...new Set(options.retry.errorCodes)];\n }\n else if (is_1.default.number(retry)) {\n options.retry.limit = retry;\n }\n if (is_1.default.undefined(options.retry.maxRetryAfter)) {\n options.retry.maxRetryAfter = Math.min(\n // TypeScript is not smart enough to handle `.filter(x => is.number(x))`.\n // eslint-disable-next-line unicorn/no-fn-reference-in-iterator\n ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number));\n }\n // `options.pagination`\n if (is_1.default.object(options.pagination)) {\n if (defaults) {\n options.pagination = {\n ...defaults.pagination,\n ...options.pagination\n };\n }\n const { pagination } = options;\n if (!is_1.default.function_(pagination.transform)) {\n throw new Error('`options.pagination.transform` must be implemented');\n }\n if (!is_1.default.function_(pagination.shouldContinue)) {\n throw new Error('`options.pagination.shouldContinue` must be implemented');\n }\n if (!is_1.default.function_(pagination.filter)) {\n throw new TypeError('`options.pagination.filter` must be implemented');\n }\n if (!is_1.default.function_(pagination.paginate)) {\n throw new Error('`options.pagination.paginate` must be implemented');\n }\n }\n // JSON mode\n if (options.responseType === 'json' && options.headers.accept === undefined) {\n options.headers.accept = 'application/json';\n }\n return options;\n};\nexports.default = normalizeArguments;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.retryAfterStatusCodes = void 0;\nexports.retryAfterStatusCodes = new Set([413, 429, 503]);\nconst calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => {\n if (attemptCount > retryOptions.limit) {\n return 0;\n }\n const hasMethod = retryOptions.methods.includes(error.options.method);\n const hasErrorCode = retryOptions.errorCodes.includes(error.code);\n const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode);\n if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {\n return 0;\n }\n if (error.response) {\n if (retryAfter) {\n if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) {\n return 0;\n }\n return retryAfter;\n }\n if (error.response.statusCode === 413) {\n return 0;\n }\n }\n const noise = Math.random() * 100;\n return ((2 ** (attemptCount - 1)) * 1000) + noise;\n};\nexports.default = calculateRetryDelay;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0;\nconst util_1 = require(\"util\");\nconst stream_1 = require(\"stream\");\nconst fs_1 = require(\"fs\");\nconst url_1 = require(\"url\");\nconst http = require(\"http\");\nconst http_1 = require(\"http\");\nconst https = require(\"https\");\nconst http_timer_1 = require(\"@szmarczak/http-timer\");\nconst cacheable_lookup_1 = require(\"cacheable-lookup\");\nconst CacheableRequest = require(\"cacheable-request\");\nconst decompressResponse = require(\"decompress-response\");\n// @ts-expect-error Missing types\nconst http2wrapper = require(\"http2-wrapper\");\nconst lowercaseKeys = require(\"lowercase-keys\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst get_body_size_1 = require(\"./utils/get-body-size\");\nconst is_form_data_1 = require(\"./utils/is-form-data\");\nconst proxy_events_1 = require(\"./utils/proxy-events\");\nconst timed_out_1 = require(\"./utils/timed-out\");\nconst url_to_options_1 = require(\"./utils/url-to-options\");\nconst options_to_url_1 = require(\"./utils/options-to-url\");\nconst weakable_map_1 = require(\"./utils/weakable-map\");\nconst get_buffer_1 = require(\"./utils/get-buffer\");\nconst dns_ip_version_1 = require(\"./utils/dns-ip-version\");\nconst is_response_ok_1 = require(\"./utils/is-response-ok\");\nconst deprecation_warning_1 = require(\"../utils/deprecation-warning\");\nconst normalize_arguments_1 = require(\"../as-promise/normalize-arguments\");\nconst calculate_retry_delay_1 = require(\"./calculate-retry-delay\");\nlet globalDnsCache;\nconst kRequest = Symbol('request');\nconst kResponse = Symbol('response');\nconst kResponseSize = Symbol('responseSize');\nconst kDownloadedSize = Symbol('downloadedSize');\nconst kBodySize = Symbol('bodySize');\nconst kUploadedSize = Symbol('uploadedSize');\nconst kServerResponsesPiped = Symbol('serverResponsesPiped');\nconst kUnproxyEvents = Symbol('unproxyEvents');\nconst kIsFromCache = Symbol('isFromCache');\nconst kCancelTimeouts = Symbol('cancelTimeouts');\nconst kStartedReading = Symbol('startedReading');\nconst kStopReading = Symbol('stopReading');\nconst kTriggerRead = Symbol('triggerRead');\nconst kBody = Symbol('body');\nconst kJobs = Symbol('jobs');\nconst kOriginalResponse = Symbol('originalResponse');\nconst kRetryTimeout = Symbol('retryTimeout');\nexports.kIsNormalizedAlready = Symbol('isNormalizedAlready');\nconst supportsBrotli = is_1.default.string(process.versions.brotli);\nexports.withoutBody = new Set(['GET', 'HEAD']);\nexports.knownHookEvents = [\n 'init',\n 'beforeRequest',\n 'beforeRedirect',\n 'beforeError',\n 'beforeRetry',\n // Promise-Only\n 'afterResponse'\n];\nfunction validateSearchParameters(searchParameters) {\n // eslint-disable-next-line guard-for-in\n for (const key in searchParameters) {\n const value = searchParameters[key];\n if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) {\n throw new TypeError(`The \\`searchParams\\` value '${String(value)}' must be a string, number, boolean or null`);\n }\n }\n}\nfunction isClientRequest(clientRequest) {\n return is_1.default.object(clientRequest) && !('statusCode' in clientRequest);\n}\nconst cacheableStore = new weakable_map_1.default();\nconst waitForOpenFile = async (file) => new Promise((resolve, reject) => {\n const onError = (error) => {\n reject(error);\n };\n // Node.js 12 has incomplete types\n if (!file.pending) {\n resolve();\n }\n file.once('error', onError);\n file.once('ready', () => {\n file.off('error', onError);\n resolve();\n });\n});\nconst redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]);\nconst nonEnumerableProperties = [\n 'context',\n 'body',\n 'json',\n 'form'\n];\nexports.setNonEnumerableProperties = (sources, to) => {\n // Non enumerable properties shall not be merged\n const properties = {};\n for (const source of sources) {\n if (!source) {\n continue;\n }\n for (const name of nonEnumerableProperties) {\n if (!(name in source)) {\n continue;\n }\n properties[name] = {\n writable: true,\n configurable: true,\n enumerable: false,\n // @ts-expect-error TS doesn't see the check above\n value: source[name]\n };\n }\n }\n Object.defineProperties(to, properties);\n};\n/**\nAn error to be thrown when a request fails.\nContains a `code` property with error class code, like `ECONNREFUSED`.\n*/\nclass RequestError extends Error {\n constructor(message, error, self) {\n var _a, _b;\n super(message);\n Error.captureStackTrace(this, this.constructor);\n this.name = 'RequestError';\n this.code = (_a = error.code) !== null && _a !== void 0 ? _a : 'ERR_GOT_REQUEST_ERROR';\n if (self instanceof Request) {\n Object.defineProperty(this, 'request', {\n enumerable: false,\n value: self\n });\n Object.defineProperty(this, 'response', {\n enumerable: false,\n value: self[kResponse]\n });\n Object.defineProperty(this, 'options', {\n // This fails because of TS 3.7.2 useDefineForClassFields\n // Ref: https://github.com/microsoft/TypeScript/issues/34972\n enumerable: false,\n value: self.options\n });\n }\n else {\n Object.defineProperty(this, 'options', {\n // This fails because of TS 3.7.2 useDefineForClassFields\n // Ref: https://github.com/microsoft/TypeScript/issues/34972\n enumerable: false,\n value: self\n });\n }\n this.timings = (_b = this.request) === null || _b === void 0 ? void 0 : _b.timings;\n // Recover the original stacktrace\n if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) {\n const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;\n const thisStackTrace = this.stack.slice(indexOfMessage).split('\\n').reverse();\n const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\\n').reverse();\n // Remove duplicated traces\n while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {\n thisStackTrace.shift();\n }\n this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\\n')}${errorStackTrace.reverse().join('\\n')}`;\n }\n }\n}\nexports.RequestError = RequestError;\n/**\nAn error to be thrown when the server redirects you more than ten times.\nIncludes a `response` property.\n*/\nclass MaxRedirectsError extends RequestError {\n constructor(request) {\n super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);\n this.name = 'MaxRedirectsError';\n this.code = 'ERR_TOO_MANY_REDIRECTS';\n }\n}\nexports.MaxRedirectsError = MaxRedirectsError;\n/**\nAn error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.\nIncludes a `response` property.\n*/\nclass HTTPError extends RequestError {\n constructor(response) {\n super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);\n this.name = 'HTTPError';\n this.code = 'ERR_NON_2XX_3XX_RESPONSE';\n }\n}\nexports.HTTPError = HTTPError;\n/**\nAn error to be thrown when a cache method fails.\nFor example, if the database goes down or there's a filesystem error.\n*/\nclass CacheError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'CacheError';\n this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code;\n }\n}\nexports.CacheError = CacheError;\n/**\nAn error to be thrown when the request body is a stream and an error occurs while reading from that stream.\n*/\nclass UploadError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'UploadError';\n this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code;\n }\n}\nexports.UploadError = UploadError;\n/**\nAn error to be thrown when the request is aborted due to a timeout.\nIncludes an `event` and `timings` property.\n*/\nclass TimeoutError extends RequestError {\n constructor(error, timings, request) {\n super(error.message, error, request);\n this.name = 'TimeoutError';\n this.event = error.event;\n this.timings = timings;\n }\n}\nexports.TimeoutError = TimeoutError;\n/**\nAn error to be thrown when reading from response stream fails.\n*/\nclass ReadError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'ReadError';\n this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code;\n }\n}\nexports.ReadError = ReadError;\n/**\nAn error to be thrown when given an unsupported protocol.\n*/\nclass UnsupportedProtocolError extends RequestError {\n constructor(options) {\n super(`Unsupported protocol \"${options.url.protocol}\"`, {}, options);\n this.name = 'UnsupportedProtocolError';\n this.code = 'ERR_UNSUPPORTED_PROTOCOL';\n }\n}\nexports.UnsupportedProtocolError = UnsupportedProtocolError;\nconst proxiedRequestEvents = [\n 'socket',\n 'connect',\n 'continue',\n 'information',\n 'upgrade',\n 'timeout'\n];\nclass Request extends stream_1.Duplex {\n constructor(url, options = {}, defaults) {\n super({\n // This must be false, to enable throwing after destroy\n // It is used for retry logic in Promise API\n autoDestroy: false,\n // It needs to be zero because we're just proxying the data to another stream\n highWaterMark: 0\n });\n this[kDownloadedSize] = 0;\n this[kUploadedSize] = 0;\n this.requestInitialized = false;\n this[kServerResponsesPiped] = new Set();\n this.redirects = [];\n this[kStopReading] = false;\n this[kTriggerRead] = false;\n this[kJobs] = [];\n this.retryCount = 0;\n // TODO: Remove this when targeting Node.js >= 12\n this._progressCallbacks = [];\n const unlockWrite = () => this._unlockWrite();\n const lockWrite = () => this._lockWrite();\n this.on('pipe', (source) => {\n source.prependListener('data', unlockWrite);\n source.on('data', lockWrite);\n source.prependListener('end', unlockWrite);\n source.on('end', lockWrite);\n });\n this.on('unpipe', (source) => {\n source.off('data', unlockWrite);\n source.off('data', lockWrite);\n source.off('end', unlockWrite);\n source.off('end', lockWrite);\n });\n this.on('pipe', source => {\n if (source instanceof http_1.IncomingMessage) {\n this.options.headers = {\n ...source.headers,\n ...this.options.headers\n };\n }\n });\n const { json, body, form } = options;\n if (json || body || form) {\n this._lockWrite();\n }\n if (exports.kIsNormalizedAlready in options) {\n this.options = options;\n }\n else {\n try {\n // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible\n this.options = this.constructor.normalizeArguments(url, options, defaults);\n }\n catch (error) {\n // TODO: Move this to `_destroy()`\n if (is_1.default.nodeStream(options.body)) {\n options.body.destroy();\n }\n this.destroy(error);\n return;\n }\n }\n (async () => {\n var _a;\n try {\n if (this.options.body instanceof fs_1.ReadStream) {\n await waitForOpenFile(this.options.body);\n }\n const { url: normalizedURL } = this.options;\n if (!normalizedURL) {\n throw new TypeError('Missing `url` property');\n }\n this.requestUrl = normalizedURL.toString();\n decodeURI(this.requestUrl);\n await this._finalizeBody();\n await this._makeRequest();\n if (this.destroyed) {\n (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy();\n return;\n }\n // Queued writes etc.\n for (const job of this[kJobs]) {\n job();\n }\n // Prevent memory leak\n this[kJobs].length = 0;\n this.requestInitialized = true;\n }\n catch (error) {\n if (error instanceof RequestError) {\n this._beforeError(error);\n return;\n }\n // This is a workaround for https://github.com/nodejs/node/issues/33335\n if (!this.destroyed) {\n this.destroy(error);\n }\n }\n })();\n }\n static normalizeArguments(url, options, defaults) {\n var _a, _b, _c, _d, _e;\n const rawOptions = options;\n if (is_1.default.object(url) && !is_1.default.urlInstance(url)) {\n options = { ...defaults, ...url, ...options };\n }\n else {\n if (url && options && options.url !== undefined) {\n throw new TypeError('The `url` option is mutually exclusive with the `input` argument');\n }\n options = { ...defaults, ...options };\n if (url !== undefined) {\n options.url = url;\n }\n if (is_1.default.urlInstance(options.url)) {\n options.url = new url_1.URL(options.url.toString());\n }\n }\n // TODO: Deprecate URL options in Got 12.\n // Support extend-specific options\n if (options.cache === false) {\n options.cache = undefined;\n }\n if (options.dnsCache === false) {\n options.dnsCache = undefined;\n }\n // Nice type assertions\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers);\n is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar);\n is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams);\n is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache);\n is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect);\n is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress);\n is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized);\n if (options.https) {\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized);\n is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase);\n is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx);\n }\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions);\n // `options.method`\n if (is_1.default.string(options.method)) {\n options.method = options.method.toUpperCase();\n }\n else {\n options.method = 'GET';\n }\n // `options.headers`\n if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) {\n options.headers = { ...options.headers };\n }\n else {\n options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers });\n }\n // Disallow legacy `url.Url`\n if ('slashes' in options) {\n throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.');\n }\n // `options.auth`\n if ('auth' in options) {\n throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.');\n }\n // `options.searchParams`\n if ('searchParams' in options) {\n if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) {\n let searchParameters;\n if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) {\n searchParameters = new url_1.URLSearchParams(options.searchParams);\n }\n else {\n validateSearchParameters(options.searchParams);\n searchParameters = new url_1.URLSearchParams();\n // eslint-disable-next-line guard-for-in\n for (const key in options.searchParams) {\n const value = options.searchParams[key];\n if (value === null) {\n searchParameters.append(key, '');\n }\n else if (value !== undefined) {\n searchParameters.append(key, value);\n }\n }\n }\n // `normalizeArguments()` is also used to merge options\n (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => {\n // Only use default if one isn't already defined\n if (!searchParameters.has(key)) {\n searchParameters.append(key, value);\n }\n });\n options.searchParams = searchParameters;\n }\n }\n // `options.username` & `options.password`\n options.username = (_b = options.username) !== null && _b !== void 0 ? _b : '';\n options.password = (_c = options.password) !== null && _c !== void 0 ? _c : '';\n // `options.prefixUrl` & `options.url`\n if (is_1.default.undefined(options.prefixUrl)) {\n options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : '';\n }\n else {\n options.prefixUrl = options.prefixUrl.toString();\n if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) {\n options.prefixUrl += '/';\n }\n }\n if (is_1.default.string(options.url)) {\n if (options.url.startsWith('/')) {\n throw new Error('`input` must not start with a slash when using `prefixUrl`');\n }\n options.url = options_to_url_1.default(options.prefixUrl + options.url, options);\n }\n else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) {\n options.url = options_to_url_1.default(options.prefixUrl, options);\n }\n if (options.url) {\n if ('port' in options) {\n delete options.port;\n }\n // Make it possible to change `options.prefixUrl`\n let { prefixUrl } = options;\n Object.defineProperty(options, 'prefixUrl', {\n set: (value) => {\n const url = options.url;\n if (!url.href.startsWith(value)) {\n throw new Error(`Cannot change \\`prefixUrl\\` from ${prefixUrl} to ${value}: ${url.href}`);\n }\n options.url = new url_1.URL(value + url.href.slice(prefixUrl.length));\n prefixUrl = value;\n },\n get: () => prefixUrl\n });\n // Support UNIX sockets\n let { protocol } = options.url;\n if (protocol === 'unix:') {\n protocol = 'http:';\n options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`);\n }\n // Set search params\n if (options.searchParams) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n options.url.search = options.searchParams.toString();\n }\n // Protocol check\n if (protocol !== 'http:' && protocol !== 'https:') {\n throw new UnsupportedProtocolError(options);\n }\n // Update `username`\n if (options.username === '') {\n options.username = options.url.username;\n }\n else {\n options.url.username = options.username;\n }\n // Update `password`\n if (options.password === '') {\n options.password = options.url.password;\n }\n else {\n options.url.password = options.password;\n }\n }\n // `options.cookieJar`\n const { cookieJar } = options;\n if (cookieJar) {\n let { setCookie, getCookieString } = cookieJar;\n is_1.assert.function_(setCookie);\n is_1.assert.function_(getCookieString);\n /* istanbul ignore next: Horrible `tough-cookie` v3 check */\n if (setCookie.length === 4 && getCookieString.length === 0) {\n setCookie = util_1.promisify(setCookie.bind(options.cookieJar));\n getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar));\n options.cookieJar = {\n setCookie,\n getCookieString: getCookieString\n };\n }\n }\n // `options.cache`\n const { cache } = options;\n if (cache) {\n if (!cacheableStore.has(cache)) {\n cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => {\n const result = requestOptions[kRequest](requestOptions, handler);\n // TODO: remove this when `cacheable-request` supports async request functions.\n if (is_1.default.promise(result)) {\n // @ts-expect-error\n // We only need to implement the error handler in order to support HTTP2 caching.\n // The result will be a promise anyway.\n result.once = (event, handler) => {\n if (event === 'error') {\n result.catch(handler);\n }\n else if (event === 'abort') {\n // The empty catch is needed here in case when\n // it rejects before it's `await`ed in `_makeRequest`.\n (async () => {\n try {\n const request = (await result);\n request.once('abort', handler);\n }\n catch (_a) { }\n })();\n }\n else {\n /* istanbul ignore next: safety check */\n throw new Error(`Unknown HTTP2 promise event: ${event}`);\n }\n return result;\n };\n }\n return result;\n }), cache));\n }\n }\n // `options.cacheOptions`\n options.cacheOptions = { ...options.cacheOptions };\n // `options.dnsCache`\n if (options.dnsCache === true) {\n if (!globalDnsCache) {\n globalDnsCache = new cacheable_lookup_1.default();\n }\n options.dnsCache = globalDnsCache;\n }\n else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) {\n throw new TypeError(`Parameter \\`dnsCache\\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`);\n }\n // `options.timeout`\n if (is_1.default.number(options.timeout)) {\n options.timeout = { request: options.timeout };\n }\n else if (defaults && options.timeout !== defaults.timeout) {\n options.timeout = {\n ...defaults.timeout,\n ...options.timeout\n };\n }\n else {\n options.timeout = { ...options.timeout };\n }\n // `options.context`\n if (!options.context) {\n options.context = {};\n }\n // `options.hooks`\n const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks);\n options.hooks = { ...options.hooks };\n for (const event of exports.knownHookEvents) {\n if (event in options.hooks) {\n if (is_1.default.array(options.hooks[event])) {\n // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044\n options.hooks[event] = [...options.hooks[event]];\n }\n else {\n throw new TypeError(`Parameter \\`${event}\\` must be an Array, got ${is_1.default(options.hooks[event])}`);\n }\n }\n else {\n options.hooks[event] = [];\n }\n }\n if (defaults && !areHooksDefault) {\n for (const event of exports.knownHookEvents) {\n const defaultHooks = defaults.hooks[event];\n if (defaultHooks.length > 0) {\n // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044\n options.hooks[event] = [\n ...defaults.hooks[event],\n ...options.hooks[event]\n ];\n }\n }\n }\n // DNS options\n if ('family' in options) {\n deprecation_warning_1.default('\"options.family\" was never documented, please use \"options.dnsLookupIpVersion\"');\n }\n // HTTPS options\n if (defaults === null || defaults === void 0 ? void 0 : defaults.https) {\n options.https = { ...defaults.https, ...options.https };\n }\n if ('rejectUnauthorized' in options) {\n deprecation_warning_1.default('\"options.rejectUnauthorized\" is now deprecated, please use \"options.https.rejectUnauthorized\"');\n }\n if ('checkServerIdentity' in options) {\n deprecation_warning_1.default('\"options.checkServerIdentity\" was never documented, please use \"options.https.checkServerIdentity\"');\n }\n if ('ca' in options) {\n deprecation_warning_1.default('\"options.ca\" was never documented, please use \"options.https.certificateAuthority\"');\n }\n if ('key' in options) {\n deprecation_warning_1.default('\"options.key\" was never documented, please use \"options.https.key\"');\n }\n if ('cert' in options) {\n deprecation_warning_1.default('\"options.cert\" was never documented, please use \"options.https.certificate\"');\n }\n if ('passphrase' in options) {\n deprecation_warning_1.default('\"options.passphrase\" was never documented, please use \"options.https.passphrase\"');\n }\n if ('pfx' in options) {\n deprecation_warning_1.default('\"options.pfx\" was never documented, please use \"options.https.pfx\"');\n }\n // Other options\n if ('followRedirects' in options) {\n throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');\n }\n if (options.agent) {\n for (const key in options.agent) {\n if (key !== 'http' && key !== 'https' && key !== 'http2') {\n throw new TypeError(`Expected the \\`options.agent\\` properties to be \\`http\\`, \\`https\\` or \\`http2\\`, got \\`${key}\\``);\n }\n }\n }\n options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0;\n // Set non-enumerable properties\n exports.setNonEnumerableProperties([defaults, rawOptions], options);\n return normalize_arguments_1.default(options, defaults);\n }\n _lockWrite() {\n const onLockedWrite = () => {\n throw new TypeError('The payload has been already provided');\n };\n this.write = onLockedWrite;\n this.end = onLockedWrite;\n }\n _unlockWrite() {\n this.write = super.write;\n this.end = super.end;\n }\n async _finalizeBody() {\n const { options } = this;\n const { headers } = options;\n const isForm = !is_1.default.undefined(options.form);\n const isJSON = !is_1.default.undefined(options.json);\n const isBody = !is_1.default.undefined(options.body);\n const hasPayload = isForm || isJSON || isBody;\n const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);\n this._cannotHaveBody = cannotHaveBody;\n if (hasPayload) {\n if (cannotHaveBody) {\n throw new TypeError(`The \\`${options.method}\\` method cannot be used with a body`);\n }\n if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) {\n throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');\n }\n if (isBody &&\n !(options.body instanceof stream_1.Readable) &&\n !is_1.default.string(options.body) &&\n !is_1.default.buffer(options.body) &&\n !is_form_data_1.default(options.body)) {\n throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');\n }\n if (isForm && !is_1.default.object(options.form)) {\n throw new TypeError('The `form` option must be an Object');\n }\n {\n // Serialize body\n const noContentType = !is_1.default.string(headers['content-type']);\n if (isBody) {\n // Special case for https://github.com/form-data/form-data\n if (is_form_data_1.default(options.body) && noContentType) {\n headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;\n }\n this[kBody] = options.body;\n }\n else if (isForm) {\n if (noContentType) {\n headers['content-type'] = 'application/x-www-form-urlencoded';\n }\n this[kBody] = (new url_1.URLSearchParams(options.form)).toString();\n }\n else {\n if (noContentType) {\n headers['content-type'] = 'application/json';\n }\n this[kBody] = options.stringifyJson(options.json);\n }\n const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers);\n // See https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body. For example, a Content-Length header\n // field is normally sent in a POST request even when the value is 0\n // (indicating an empty payload body). A user agent SHOULD NOT send a\n // Content-Length header field when the request message does not contain\n // a payload body and the method semantics do not anticipate such a\n // body.\n if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {\n if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) {\n headers['content-length'] = String(uploadBodySize);\n }\n }\n }\n }\n else if (cannotHaveBody) {\n this._lockWrite();\n }\n else {\n this._unlockWrite();\n }\n this[kBodySize] = Number(headers['content-length']) || undefined;\n }\n async _onResponseBase(response) {\n const { options } = this;\n const { url } = options;\n this[kOriginalResponse] = response;\n if (options.decompress) {\n response = decompressResponse(response);\n }\n const statusCode = response.statusCode;\n const typedResponse = response;\n typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];\n typedResponse.url = options.url.toString();\n typedResponse.requestUrl = this.requestUrl;\n typedResponse.redirectUrls = this.redirects;\n typedResponse.request = this;\n typedResponse.isFromCache = response.fromCache || false;\n typedResponse.ip = this.ip;\n typedResponse.retryCount = this.retryCount;\n this[kIsFromCache] = typedResponse.isFromCache;\n this[kResponseSize] = Number(response.headers['content-length']) || undefined;\n this[kResponse] = response;\n response.once('end', () => {\n this[kResponseSize] = this[kDownloadedSize];\n this.emit('downloadProgress', this.downloadProgress);\n });\n response.once('error', (error) => {\n // Force clean-up, because some packages don't do this.\n // TODO: Fix decompress-response\n response.destroy();\n this._beforeError(new ReadError(error, this));\n });\n response.once('aborted', () => {\n this._beforeError(new ReadError({\n name: 'Error',\n message: 'The server aborted pending request',\n code: 'ECONNRESET'\n }, this));\n });\n this.emit('downloadProgress', this.downloadProgress);\n const rawCookies = response.headers['set-cookie'];\n if (is_1.default.object(options.cookieJar) && rawCookies) {\n let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString()));\n if (options.ignoreInvalidCookies) {\n promises = promises.map(async (p) => p.catch(() => { }));\n }\n try {\n await Promise.all(promises);\n }\n catch (error) {\n this._beforeError(error);\n return;\n }\n }\n if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {\n // We're being redirected, we don't care about the response.\n // It'd be best to abort the request, but we can't because\n // we would have to sacrifice the TCP connection. We don't want that.\n response.resume();\n if (this[kRequest]) {\n this[kCancelTimeouts]();\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this[kRequest];\n this[kUnproxyEvents]();\n }\n const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD';\n if (shouldBeGet || !options.methodRewriting) {\n // Server responded with \"see other\", indicating that the resource exists at another location,\n // and the client should request it from that location via GET or HEAD.\n options.method = 'GET';\n if ('body' in options) {\n delete options.body;\n }\n if ('json' in options) {\n delete options.json;\n }\n if ('form' in options) {\n delete options.form;\n }\n this[kBody] = undefined;\n delete options.headers['content-length'];\n }\n if (this.redirects.length >= options.maxRedirects) {\n this._beforeError(new MaxRedirectsError(this));\n return;\n }\n try {\n // Do not remove. See https://github.com/sindresorhus/got/pull/214\n const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();\n // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604\n const redirectUrl = new url_1.URL(redirectBuffer, url);\n const redirectString = redirectUrl.toString();\n decodeURI(redirectString);\n // eslint-disable-next-line no-inner-declarations\n function isUnixSocketURL(url) {\n return url.protocol === 'unix:' || url.hostname === 'unix';\n }\n if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) {\n this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));\n return;\n }\n // Redirecting to a different site, clear sensitive data.\n if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {\n if ('host' in options.headers) {\n delete options.headers.host;\n }\n if ('cookie' in options.headers) {\n delete options.headers.cookie;\n }\n if ('authorization' in options.headers) {\n delete options.headers.authorization;\n }\n if (options.username || options.password) {\n options.username = '';\n options.password = '';\n }\n }\n else {\n redirectUrl.username = options.username;\n redirectUrl.password = options.password;\n }\n this.redirects.push(redirectString);\n options.url = redirectUrl;\n for (const hook of options.hooks.beforeRedirect) {\n // eslint-disable-next-line no-await-in-loop\n await hook(options, typedResponse);\n }\n this.emit('redirect', typedResponse, options);\n await this._makeRequest();\n }\n catch (error) {\n this._beforeError(error);\n return;\n }\n return;\n }\n if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) {\n this._beforeError(new HTTPError(typedResponse));\n return;\n }\n response.on('readable', () => {\n if (this[kTriggerRead]) {\n this._read();\n }\n });\n this.on('resume', () => {\n response.resume();\n });\n this.on('pause', () => {\n response.pause();\n });\n response.once('end', () => {\n this.push(null);\n });\n this.emit('response', response);\n for (const destination of this[kServerResponsesPiped]) {\n if (destination.headersSent) {\n continue;\n }\n // eslint-disable-next-line guard-for-in\n for (const key in response.headers) {\n const isAllowed = options.decompress ? key !== 'content-encoding' : true;\n const value = response.headers[key];\n if (isAllowed) {\n destination.setHeader(key, value);\n }\n }\n destination.statusCode = statusCode;\n }\n }\n async _onResponse(response) {\n try {\n await this._onResponseBase(response);\n }\n catch (error) {\n /* istanbul ignore next: better safe than sorry */\n this._beforeError(error);\n }\n }\n _onRequest(request) {\n const { options } = this;\n const { timeout, url } = options;\n http_timer_1.default(request);\n this[kCancelTimeouts] = timed_out_1.default(request, timeout, url);\n const responseEventName = options.cache ? 'cacheableResponse' : 'response';\n request.once(responseEventName, (response) => {\n void this._onResponse(response);\n });\n request.once('error', (error) => {\n var _a;\n // Force clean-up, because some packages (e.g. nock) don't do this.\n request.destroy();\n // Node.js <= 12.18.2 mistakenly emits the response `end` first.\n (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end');\n error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this);\n this._beforeError(error);\n });\n this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents);\n this[kRequest] = request;\n this.emit('uploadProgress', this.uploadProgress);\n // Send body\n const body = this[kBody];\n const currentRequest = this.redirects.length === 0 ? this : request;\n if (is_1.default.nodeStream(body)) {\n body.pipe(currentRequest);\n body.once('error', (error) => {\n this._beforeError(new UploadError(error, this));\n });\n }\n else {\n this._unlockWrite();\n if (!is_1.default.undefined(body)) {\n this._writeRequest(body, undefined, () => { });\n currentRequest.end();\n this._lockWrite();\n }\n else if (this._cannotHaveBody || this._noPipe) {\n currentRequest.end();\n this._lockWrite();\n }\n }\n this.emit('request', request);\n }\n async _createCacheableRequest(url, options) {\n return new Promise((resolve, reject) => {\n // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed\n Object.assign(options, url_to_options_1.default(url));\n // `http-cache-semantics` checks this\n // TODO: Fix this ignore.\n // @ts-expect-error\n delete options.url;\n let request;\n // This is ugly\n const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => {\n // TODO: Fix `cacheable-response`\n response._readableState.autoDestroy = false;\n if (request) {\n (await request).emit('cacheableResponse', response);\n }\n resolve(response);\n });\n // Restore options\n options.url = url;\n cacheRequest.once('error', reject);\n cacheRequest.once('request', async (requestOrPromise) => {\n request = requestOrPromise;\n resolve(request);\n });\n });\n }\n async _makeRequest() {\n var _a, _b, _c, _d, _e;\n const { options } = this;\n const { headers } = options;\n for (const key in headers) {\n if (is_1.default.undefined(headers[key])) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete headers[key];\n }\n else if (is_1.default.null_(headers[key])) {\n throw new TypeError(`Use \\`undefined\\` instead of \\`null\\` to delete the \\`${key}\\` header`);\n }\n }\n if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) {\n headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';\n }\n // Set cookies\n if (options.cookieJar) {\n const cookieString = await options.cookieJar.getCookieString(options.url.toString());\n if (is_1.default.nonEmptyString(cookieString)) {\n options.headers.cookie = cookieString;\n }\n }\n for (const hook of options.hooks.beforeRequest) {\n // eslint-disable-next-line no-await-in-loop\n const result = await hook(options);\n if (!is_1.default.undefined(result)) {\n // @ts-expect-error Skip the type mismatch to support abstract responses\n options.request = () => result;\n break;\n }\n }\n if (options.body && this[kBody] !== options.body) {\n this[kBody] = options.body;\n }\n const { agent, request, timeout, url } = options;\n if (options.dnsCache && !('lookup' in options)) {\n options.lookup = options.dnsCache.lookup;\n }\n // UNIX sockets\n if (url.hostname === 'unix') {\n const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);\n if (matches === null || matches === void 0 ? void 0 : matches.groups) {\n const { socketPath, path } = matches.groups;\n Object.assign(options, {\n socketPath,\n path,\n host: ''\n });\n }\n }\n const isHttps = url.protocol === 'https:';\n // Fallback function\n let fallbackFn;\n if (options.http2) {\n fallbackFn = http2wrapper.auto;\n }\n else {\n fallbackFn = isHttps ? https.request : http.request;\n }\n const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn;\n // Cache support\n const fn = options.cache ? this._createCacheableRequest : realFn;\n // Pass an agent directly when HTTP2 is disabled\n if (agent && !options.http2) {\n options.agent = agent[isHttps ? 'https' : 'http'];\n }\n // Prepare plain HTTP request options\n options[kRequest] = realFn;\n delete options.request;\n // TODO: Fix this ignore.\n // @ts-expect-error\n delete options.timeout;\n const requestOptions = options;\n requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared;\n requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic;\n requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive;\n requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult;\n // If `dnsLookupIpVersion` is not present do not override `family`\n if (options.dnsLookupIpVersion !== undefined) {\n try {\n requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion);\n }\n catch (_f) {\n throw new Error('Invalid `dnsLookupIpVersion` option value');\n }\n }\n // HTTPS options remapping\n if (options.https) {\n if ('rejectUnauthorized' in options.https) {\n requestOptions.rejectUnauthorized = options.https.rejectUnauthorized;\n }\n if (options.https.checkServerIdentity) {\n requestOptions.checkServerIdentity = options.https.checkServerIdentity;\n }\n if (options.https.certificateAuthority) {\n requestOptions.ca = options.https.certificateAuthority;\n }\n if (options.https.certificate) {\n requestOptions.cert = options.https.certificate;\n }\n if (options.https.key) {\n requestOptions.key = options.https.key;\n }\n if (options.https.passphrase) {\n requestOptions.passphrase = options.https.passphrase;\n }\n if (options.https.pfx) {\n requestOptions.pfx = options.https.pfx;\n }\n }\n try {\n let requestOrResponse = await fn(url, requestOptions);\n if (is_1.default.undefined(requestOrResponse)) {\n requestOrResponse = fallbackFn(url, requestOptions);\n }\n // Restore options\n options.request = request;\n options.timeout = timeout;\n options.agent = agent;\n // HTTPS options restore\n if (options.https) {\n if ('rejectUnauthorized' in options.https) {\n delete requestOptions.rejectUnauthorized;\n }\n if (options.https.checkServerIdentity) {\n // @ts-expect-error - This one will be removed when we remove the alias.\n delete requestOptions.checkServerIdentity;\n }\n if (options.https.certificateAuthority) {\n delete requestOptions.ca;\n }\n if (options.https.certificate) {\n delete requestOptions.cert;\n }\n if (options.https.key) {\n delete requestOptions.key;\n }\n if (options.https.passphrase) {\n delete requestOptions.passphrase;\n }\n if (options.https.pfx) {\n delete requestOptions.pfx;\n }\n }\n if (isClientRequest(requestOrResponse)) {\n this._onRequest(requestOrResponse);\n // Emit the response after the stream has been ended\n }\n else if (this.writable) {\n this.once('finish', () => {\n void this._onResponse(requestOrResponse);\n });\n this._unlockWrite();\n this.end();\n this._lockWrite();\n }\n else {\n void this._onResponse(requestOrResponse);\n }\n }\n catch (error) {\n if (error instanceof CacheableRequest.CacheError) {\n throw new CacheError(error, this);\n }\n throw new RequestError(error.message, error, this);\n }\n }\n async _error(error) {\n try {\n for (const hook of this.options.hooks.beforeError) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n }\n catch (error_) {\n error = new RequestError(error_.message, error_, this);\n }\n this.destroy(error);\n }\n _beforeError(error) {\n if (this[kStopReading]) {\n return;\n }\n const { options } = this;\n const retryCount = this.retryCount + 1;\n this[kStopReading] = true;\n if (!(error instanceof RequestError)) {\n error = new RequestError(error.message, error, this);\n }\n const typedError = error;\n const { response } = typedError;\n void (async () => {\n if (response && !response.body) {\n response.setEncoding(this._readableState.encoding);\n try {\n response.rawBody = await get_buffer_1.default(response);\n response.body = response.rawBody.toString();\n }\n catch (_a) { }\n }\n if (this.listenerCount('retry') !== 0) {\n let backoff;\n try {\n let retryAfter;\n if (response && 'retry-after' in response.headers) {\n retryAfter = Number(response.headers['retry-after']);\n if (Number.isNaN(retryAfter)) {\n retryAfter = Date.parse(response.headers['retry-after']) - Date.now();\n if (retryAfter <= 0) {\n retryAfter = 1;\n }\n }\n else {\n retryAfter *= 1000;\n }\n }\n backoff = await options.retry.calculateDelay({\n attemptCount: retryCount,\n retryOptions: options.retry,\n error: typedError,\n retryAfter,\n computedValue: calculate_retry_delay_1.default({\n attemptCount: retryCount,\n retryOptions: options.retry,\n error: typedError,\n retryAfter,\n computedValue: 0\n })\n });\n }\n catch (error_) {\n void this._error(new RequestError(error_.message, error_, this));\n return;\n }\n if (backoff) {\n const retry = async () => {\n try {\n for (const hook of this.options.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n await hook(this.options, typedError, retryCount);\n }\n }\n catch (error_) {\n void this._error(new RequestError(error_.message, error, this));\n return;\n }\n // Something forced us to abort the retry\n if (this.destroyed) {\n return;\n }\n this.destroy();\n this.emit('retry', retryCount, error);\n };\n this[kRetryTimeout] = setTimeout(retry, backoff);\n return;\n }\n }\n void this._error(typedError);\n })();\n }\n _read() {\n this[kTriggerRead] = true;\n const response = this[kResponse];\n if (response && !this[kStopReading]) {\n // We cannot put this in the `if` above\n // because `.read()` also triggers the `end` event\n if (response.readableLength) {\n this[kTriggerRead] = false;\n }\n let data;\n while ((data = response.read()) !== null) {\n this[kDownloadedSize] += data.length;\n this[kStartedReading] = true;\n const progress = this.downloadProgress;\n if (progress.percent < 1) {\n this.emit('downloadProgress', progress);\n }\n this.push(data);\n }\n }\n }\n // Node.js 12 has incorrect types, so the encoding must be a string\n _write(chunk, encoding, callback) {\n const write = () => {\n this._writeRequest(chunk, encoding, callback);\n };\n if (this.requestInitialized) {\n write();\n }\n else {\n this[kJobs].push(write);\n }\n }\n _writeRequest(chunk, encoding, callback) {\n if (this[kRequest].destroyed) {\n // Probably the `ClientRequest` instance will throw\n return;\n }\n this._progressCallbacks.push(() => {\n this[kUploadedSize] += Buffer.byteLength(chunk, encoding);\n const progress = this.uploadProgress;\n if (progress.percent < 1) {\n this.emit('uploadProgress', progress);\n }\n });\n // TODO: What happens if it's from cache? Then this[kRequest] won't be defined.\n this[kRequest].write(chunk, encoding, (error) => {\n if (!error && this._progressCallbacks.length > 0) {\n this._progressCallbacks.shift()();\n }\n callback(error);\n });\n }\n _final(callback) {\n const endRequest = () => {\n // FIX: Node.js 10 calls the write callback AFTER the end callback!\n while (this._progressCallbacks.length !== 0) {\n this._progressCallbacks.shift()();\n }\n // We need to check if `this[kRequest]` is present,\n // because it isn't when we use cache.\n if (!(kRequest in this)) {\n callback();\n return;\n }\n if (this[kRequest].destroyed) {\n callback();\n return;\n }\n this[kRequest].end((error) => {\n if (!error) {\n this[kBodySize] = this[kUploadedSize];\n this.emit('uploadProgress', this.uploadProgress);\n this[kRequest].emit('upload-complete');\n }\n callback(error);\n });\n };\n if (this.requestInitialized) {\n endRequest();\n }\n else {\n this[kJobs].push(endRequest);\n }\n }\n _destroy(error, callback) {\n var _a;\n this[kStopReading] = true;\n // Prevent further retries\n clearTimeout(this[kRetryTimeout]);\n if (kRequest in this) {\n this[kCancelTimeouts]();\n // TODO: Remove the next `if` when these get fixed:\n // - https://github.com/nodejs/node/issues/32851\n if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) {\n this[kRequest].destroy();\n }\n }\n if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) {\n error = new RequestError(error.message, error, this);\n }\n callback(error);\n }\n get _isAboutToError() {\n return this[kStopReading];\n }\n /**\n The remote IP address.\n */\n get ip() {\n var _a;\n return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress;\n }\n /**\n Indicates whether the request has been aborted or not.\n */\n get aborted() {\n var _a, _b, _c;\n return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete);\n }\n get socket() {\n var _a, _b;\n return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined;\n }\n /**\n Progress event for downloading (receiving a response).\n */\n get downloadProgress() {\n let percent;\n if (this[kResponseSize]) {\n percent = this[kDownloadedSize] / this[kResponseSize];\n }\n else if (this[kResponseSize] === this[kDownloadedSize]) {\n percent = 1;\n }\n else {\n percent = 0;\n }\n return {\n percent,\n transferred: this[kDownloadedSize],\n total: this[kResponseSize]\n };\n }\n /**\n Progress event for uploading (sending a request).\n */\n get uploadProgress() {\n let percent;\n if (this[kBodySize]) {\n percent = this[kUploadedSize] / this[kBodySize];\n }\n else if (this[kBodySize] === this[kUploadedSize]) {\n percent = 1;\n }\n else {\n percent = 0;\n }\n return {\n percent,\n transferred: this[kUploadedSize],\n total: this[kBodySize]\n };\n }\n /**\n The object contains the following properties:\n\n - `start` - Time when the request started.\n - `socket` - Time when a socket was assigned to the request.\n - `lookup` - Time when the DNS lookup finished.\n - `connect` - Time when the socket successfully connected.\n - `secureConnect` - Time when the socket securely connected.\n - `upload` - Time when the request finished uploading.\n - `response` - Time when the request fired `response` event.\n - `end` - Time when the response fired `end` event.\n - `error` - Time when the request fired `error` event.\n - `abort` - Time when the request fired `abort` event.\n - `phases`\n - `wait` - `timings.socket - timings.start`\n - `dns` - `timings.lookup - timings.socket`\n - `tcp` - `timings.connect - timings.lookup`\n - `tls` - `timings.secureConnect - timings.connect`\n - `request` - `timings.upload - (timings.secureConnect || timings.connect)`\n - `firstByte` - `timings.response - timings.upload`\n - `download` - `timings.end - timings.response`\n - `total` - `(timings.end || timings.error || timings.abort) - timings.start`\n\n If something has not been measured yet, it will be `undefined`.\n\n __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.\n */\n get timings() {\n var _a;\n return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings;\n }\n /**\n Whether the response was retrieved from the cache.\n */\n get isFromCache() {\n return this[kIsFromCache];\n }\n pipe(destination, options) {\n if (this[kStartedReading]) {\n throw new Error('Failed to pipe. The response has been emitted already.');\n }\n if (destination instanceof http_1.ServerResponse) {\n this[kServerResponsesPiped].add(destination);\n }\n return super.pipe(destination, options);\n }\n unpipe(destination) {\n if (destination instanceof http_1.ServerResponse) {\n this[kServerResponsesPiped].delete(destination);\n }\n super.unpipe(destination);\n return this;\n }\n}\nexports.default = Request;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancelError = exports.ParseError = void 0;\nconst core_1 = require(\"../core\");\n/**\nAn error to be thrown when server response code is 2xx, and parsing body fails.\nIncludes a `response` property.\n*/\nclass ParseError extends core_1.RequestError {\n constructor(error, response) {\n const { options } = response.request;\n super(`${error.message} in \"${options.url.toString()}\"`, error, response.request);\n this.name = 'ParseError';\n this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code;\n }\n}\nexports.ParseError = ParseError;\n/**\nAn error to be thrown when the request is aborted with `.cancel()`.\n*/\nclass CancelError extends core_1.RequestError {\n constructor(request) {\n super('Promise was canceled', {}, request);\n this.name = 'CancelError';\n this.code = 'ERR_CANCELED';\n }\n get isCanceled() {\n return true;\n }\n}\nexports.CancelError = CancelError;\n__exportStar(require(\"../core\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst types_1 = require(\"./types\");\nconst parseBody = (response, responseType, parseJson, encoding) => {\n const { rawBody } = response;\n try {\n if (responseType === 'text') {\n return rawBody.toString(encoding);\n }\n if (responseType === 'json') {\n return rawBody.length === 0 ? '' : parseJson(rawBody.toString());\n }\n if (responseType === 'buffer') {\n return rawBody;\n }\n throw new types_1.ParseError({\n message: `Unknown body type '${responseType}'`,\n name: 'Error'\n }, response);\n }\n catch (error) {\n throw new types_1.ParseError(error, response);\n }\n};\nexports.default = parseBody;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst events_1 = require(\"events\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst PCancelable = require(\"p-cancelable\");\nconst types_1 = require(\"./types\");\nconst parse_body_1 = require(\"./parse-body\");\nconst core_1 = require(\"../core\");\nconst proxy_events_1 = require(\"../core/utils/proxy-events\");\nconst get_buffer_1 = require(\"../core/utils/get-buffer\");\nconst is_response_ok_1 = require(\"../core/utils/is-response-ok\");\nconst proxiedRequestEvents = [\n 'request',\n 'response',\n 'redirect',\n 'uploadProgress',\n 'downloadProgress'\n];\nfunction asPromise(normalizedOptions) {\n let globalRequest;\n let globalResponse;\n const emitter = new events_1.EventEmitter();\n const promise = new PCancelable((resolve, reject, onCancel) => {\n const makeRequest = (retryCount) => {\n const request = new core_1.default(undefined, normalizedOptions);\n request.retryCount = retryCount;\n request._noPipe = true;\n onCancel(() => request.destroy());\n onCancel.shouldReject = false;\n onCancel(() => reject(new types_1.CancelError(request)));\n globalRequest = request;\n request.once('response', async (response) => {\n var _a;\n response.retryCount = retryCount;\n if (response.request.aborted) {\n // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error\n return;\n }\n // Download body\n let rawBody;\n try {\n rawBody = await get_buffer_1.default(request);\n response.rawBody = rawBody;\n }\n catch (_b) {\n // The same error is caught below.\n // See request.once('error')\n return;\n }\n if (request._isAboutToError) {\n return;\n }\n // Parse body\n const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase();\n const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding);\n const { options } = request;\n if (isCompressed && !options.decompress) {\n response.body = rawBody;\n }\n else {\n try {\n response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding);\n }\n catch (error) {\n // Fallback to `utf8`\n response.body = rawBody.toString();\n if (is_response_ok_1.isResponseOk(response)) {\n request._beforeError(error);\n return;\n }\n }\n }\n try {\n for (const [index, hook] of options.hooks.afterResponse.entries()) {\n // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise\n // eslint-disable-next-line no-await-in-loop\n response = await hook(response, async (updatedOptions) => {\n const typedOptions = core_1.default.normalizeArguments(undefined, {\n ...updatedOptions,\n retry: {\n calculateDelay: () => 0\n },\n throwHttpErrors: false,\n resolveBodyOnly: false\n }, options);\n // Remove any further hooks for that request, because we'll call them anyway.\n // The loop continues. We don't want duplicates (asPromise recursion).\n typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index);\n for (const hook of typedOptions.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n await hook(typedOptions);\n }\n const promise = asPromise(typedOptions);\n onCancel(() => {\n promise.catch(() => { });\n promise.cancel();\n });\n return promise;\n });\n }\n }\n catch (error) {\n request._beforeError(new types_1.RequestError(error.message, error, request));\n return;\n }\n globalResponse = response;\n if (!is_response_ok_1.isResponseOk(response)) {\n request._beforeError(new types_1.HTTPError(response));\n return;\n }\n request.destroy();\n resolve(request.options.resolveBodyOnly ? response.body : response);\n });\n const onError = (error) => {\n if (promise.isCanceled) {\n return;\n }\n const { options } = request;\n if (error instanceof types_1.HTTPError && !options.throwHttpErrors) {\n const { response } = error;\n resolve(request.options.resolveBodyOnly ? response.body : response);\n return;\n }\n reject(error);\n };\n request.once('error', onError);\n const previousBody = request.options.body;\n request.once('retry', (newRetryCount, error) => {\n var _a, _b;\n if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) {\n onError(error);\n return;\n }\n makeRequest(newRetryCount);\n });\n proxy_events_1.default(request, emitter, proxiedRequestEvents);\n };\n makeRequest(0);\n });\n promise.on = (event, fn) => {\n emitter.on(event, fn);\n return promise;\n };\n const shortcut = (responseType) => {\n const newPromise = (async () => {\n // Wait until downloading has ended\n await promise;\n const { options } = globalResponse.request;\n return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding);\n })();\n Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));\n return newPromise;\n };\n promise.json = () => {\n const { headers } = globalRequest.options;\n if (!globalRequest.writableFinished && headers.accept === undefined) {\n headers.accept = 'application/json';\n }\n return shortcut('json');\n };\n promise.buffer = () => shortcut('buffer');\n promise.text = () => shortcut('text');\n return promise;\n}\nexports.default = asPromise;\n__exportStar(require(\"./types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst types_1 = require(\"./types\");\nfunction createRejection(error, ...beforeErrorGroups) {\n const promise = (async () => {\n if (error instanceof types_1.RequestError) {\n try {\n for (const hooks of beforeErrorGroups) {\n if (hooks) {\n for (const hook of hooks) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n }\n }\n }\n catch (error_) {\n error = error_;\n }\n }\n throw error;\n })();\n const returnPromise = () => promise;\n promise.json = returnPromise;\n promise.text = returnPromise;\n promise.buffer = returnPromise;\n promise.on = returnPromise;\n return promise;\n}\nexports.default = createRejection;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nfunction deepFreeze(object) {\n for (const value of Object.values(object)) {\n if (is_1.default.plainObject(value) || is_1.default.array(value)) {\n deepFreeze(value);\n }\n }\n return Object.freeze(object);\n}\nexports.default = deepFreeze;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultHandler = void 0;\nconst is_1 = require(\"@sindresorhus/is\");\nconst as_promise_1 = require(\"./as-promise\");\nconst create_rejection_1 = require(\"./as-promise/create-rejection\");\nconst core_1 = require(\"./core\");\nconst deep_freeze_1 = require(\"./utils/deep-freeze\");\nconst errors = {\n RequestError: as_promise_1.RequestError,\n CacheError: as_promise_1.CacheError,\n ReadError: as_promise_1.ReadError,\n HTTPError: as_promise_1.HTTPError,\n MaxRedirectsError: as_promise_1.MaxRedirectsError,\n TimeoutError: as_promise_1.TimeoutError,\n ParseError: as_promise_1.ParseError,\n CancelError: as_promise_1.CancelError,\n UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError,\n UploadError: as_promise_1.UploadError\n};\n// The `delay` package weighs 10KB (!)\nconst delay = async (ms) => new Promise(resolve => {\n setTimeout(resolve, ms);\n});\nconst { normalizeArguments } = core_1.default;\nconst mergeOptions = (...sources) => {\n let mergedOptions;\n for (const source of sources) {\n mergedOptions = normalizeArguments(undefined, source, mergedOptions);\n }\n return mergedOptions;\n};\nconst getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options);\nconst isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults);\nconst aliases = [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'head',\n 'delete'\n];\nexports.defaultHandler = (options, next) => next(options);\nconst callInitHooks = (hooks, options) => {\n if (hooks) {\n for (const hook of hooks) {\n hook(options);\n }\n }\n};\nconst create = (defaults) => {\n // Proxy properties from next handlers\n defaults._rawHandlers = defaults.handlers;\n defaults.handlers = defaults.handlers.map(fn => ((options, next) => {\n // This will be assigned by assigning result\n let root;\n const result = fn(options, newOptions => {\n root = next(newOptions);\n return root;\n });\n if (result !== root && !options.isStream && root) {\n const typedResult = result;\n const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult;\n Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root));\n Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root));\n // These should point to the new promise\n // eslint-disable-next-line promise/prefer-await-to-then\n typedResult.then = promiseThen;\n typedResult.catch = promiseCatch;\n typedResult.finally = promiseFianlly;\n }\n return result;\n }));\n // Got interface\n const got = ((url, options = {}, _defaults) => {\n var _a, _b;\n let iteration = 0;\n const iterateHandlers = (newOptions) => {\n return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers);\n };\n // TODO: Remove this in Got 12.\n if (is_1.default.plainObject(url)) {\n const mergedOptions = {\n ...url,\n ...options\n };\n core_1.setNonEnumerableProperties([url, options], mergedOptions);\n options = mergedOptions;\n url = undefined;\n }\n try {\n // Call `init` hooks\n let initHookError;\n try {\n callInitHooks(defaults.options.hooks.init, options);\n callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options);\n }\n catch (error) {\n initHookError = error;\n }\n // Normalize options & call handlers\n const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options);\n normalizedOptions[core_1.kIsNormalizedAlready] = true;\n if (initHookError) {\n throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions);\n }\n return iterateHandlers(normalizedOptions);\n }\n catch (error) {\n if (options.isStream) {\n throw error;\n }\n else {\n return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError);\n }\n }\n });\n got.extend = (...instancesOrOptions) => {\n const optionsArray = [defaults.options];\n let handlers = [...defaults._rawHandlers];\n let isMutableDefaults;\n for (const value of instancesOrOptions) {\n if (isGotInstance(value)) {\n optionsArray.push(value.defaults.options);\n handlers.push(...value.defaults._rawHandlers);\n isMutableDefaults = value.defaults.mutableDefaults;\n }\n else {\n optionsArray.push(value);\n if ('handlers' in value) {\n handlers.push(...value.handlers);\n }\n isMutableDefaults = value.mutableDefaults;\n }\n }\n handlers = handlers.filter(handler => handler !== exports.defaultHandler);\n if (handlers.length === 0) {\n handlers.push(exports.defaultHandler);\n }\n return create({\n options: mergeOptions(...optionsArray),\n handlers,\n mutableDefaults: Boolean(isMutableDefaults)\n });\n };\n // Pagination\n const paginateEach = (async function* (url, options) {\n // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4.\n // Error: Argument of type 'Merge<Options, PaginationOptions<T, R>> | undefined' is not assignable to parameter of type 'Options | undefined'.\n // @ts-expect-error\n let normalizedOptions = normalizeArguments(url, options, defaults.options);\n normalizedOptions.resolveBodyOnly = false;\n const pagination = normalizedOptions.pagination;\n if (!is_1.default.object(pagination)) {\n throw new TypeError('`options.pagination` must be implemented');\n }\n const all = [];\n let { countLimit } = pagination;\n let numberOfRequests = 0;\n while (numberOfRequests < pagination.requestLimit) {\n if (numberOfRequests !== 0) {\n // eslint-disable-next-line no-await-in-loop\n await delay(pagination.backoff);\n }\n // @ts-expect-error FIXME!\n // TODO: Throw when result is not an instance of Response\n // eslint-disable-next-line no-await-in-loop\n const result = (await got(undefined, undefined, normalizedOptions));\n // eslint-disable-next-line no-await-in-loop\n const parsed = await pagination.transform(result);\n const current = [];\n for (const item of parsed) {\n if (pagination.filter(item, all, current)) {\n if (!pagination.shouldContinue(item, all, current)) {\n return;\n }\n yield item;\n if (pagination.stackAllItems) {\n all.push(item);\n }\n current.push(item);\n if (--countLimit <= 0) {\n return;\n }\n }\n }\n const optionsToMerge = pagination.paginate(result, all, current);\n if (optionsToMerge === false) {\n return;\n }\n if (optionsToMerge === result.request.options) {\n normalizedOptions = result.request.options;\n }\n else if (optionsToMerge !== undefined) {\n normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions);\n }\n numberOfRequests++;\n }\n });\n got.paginate = paginateEach;\n got.paginate.all = (async (url, options) => {\n const results = [];\n for await (const item of paginateEach(url, options)) {\n results.push(item);\n }\n return results;\n });\n // For those who like very descriptive names\n got.paginate.each = paginateEach;\n // Stream API\n got.stream = ((url, options) => got(url, { ...options, isStream: true }));\n // Shortcuts\n for (const method of aliases) {\n got[method] = ((url, options) => got(url, { ...options, method }));\n got.stream[method] = ((url, options) => {\n return got(url, { ...options, method, isStream: true });\n });\n }\n Object.assign(got, errors);\n Object.defineProperty(got, 'defaults', {\n value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults),\n writable: defaults.mutableDefaults,\n configurable: defaults.mutableDefaults,\n enumerable: true\n });\n got.mergeOptions = mergeOptions;\n return got;\n};\nexports.default = create;\n__exportStar(require(\"./types\"), exports);\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url_1 = require(\"url\");\nconst create_1 = require(\"./create\");\nconst defaults = {\n options: {\n method: 'GET',\n retry: {\n limit: 2,\n methods: [\n 'GET',\n 'PUT',\n 'HEAD',\n 'DELETE',\n 'OPTIONS',\n 'TRACE'\n ],\n statusCodes: [\n 408,\n 413,\n 429,\n 500,\n 502,\n 503,\n 504,\n 521,\n 522,\n 524\n ],\n errorCodes: [\n 'ETIMEDOUT',\n 'ECONNRESET',\n 'EADDRINUSE',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EAI_AGAIN'\n ],\n maxRetryAfter: undefined,\n calculateDelay: ({ computedValue }) => computedValue\n },\n timeout: {},\n headers: {\n 'user-agent': 'got (https://github.com/sindresorhus/got)'\n },\n hooks: {\n init: [],\n beforeRequest: [],\n beforeRedirect: [],\n beforeRetry: [],\n beforeError: [],\n afterResponse: []\n },\n cache: undefined,\n dnsCache: undefined,\n decompress: true,\n throwHttpErrors: true,\n followRedirect: true,\n isStream: false,\n responseType: 'text',\n resolveBodyOnly: false,\n maxRedirects: 10,\n prefixUrl: '',\n methodRewriting: true,\n ignoreInvalidCookies: false,\n context: {},\n // TODO: Set this to `true` when Got 12 gets released\n http2: false,\n allowGetBody: false,\n https: undefined,\n pagination: {\n transform: (response) => {\n if (response.request.options.responseType === 'json') {\n return response.body;\n }\n return JSON.parse(response.body);\n },\n paginate: response => {\n if (!Reflect.has(response.headers, 'link')) {\n return false;\n }\n const items = response.headers.link.split(',');\n let next;\n for (const item of items) {\n const parsed = item.split(';');\n if (parsed[1].includes('next')) {\n next = parsed[0].trimStart().trim();\n next = next.slice(1, -1);\n break;\n }\n }\n if (next) {\n const options = {\n url: new url_1.URL(next)\n };\n return options;\n }\n return false;\n },\n filter: () => true,\n shouldContinue: () => true,\n countLimit: Infinity,\n backoff: 0,\n requestLimit: 10000,\n stackAllItems: true\n },\n parseJson: (text) => JSON.parse(text),\n stringifyJson: (object) => JSON.stringify(object),\n cacheOptions: {}\n },\n handlers: [create_1.defaultHandler],\n mutableDefaults: false\n};\nconst got = create_1.default(defaults);\nexports.default = got;\n// For CommonJS default export support\nmodule.exports = got;\nmodule.exports.default = got;\nmodule.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267\n__exportStar(require(\"./create\"), exports);\n__exportStar(require(\"./as-promise\"), exports);\n","import { AptosChainId } from '@sentio/chain'\nimport { Aptos, AptosConfig } from '@aptos-labs/ts-sdk'\nimport { Labels } from '../core/index.js'\nimport { Endpoints } from '@sentio/runtime'\nimport process from 'process'\n\nexport type AptosNetwork = AptosChainId\nexport const AptosNetwork = <const>{\n MAIN_NET: AptosChainId.APTOS_MAINNET,\n TEST_NET: AptosChainId.APTOS_TESTNET,\n DEV_NET: AptosChainId.APTOS_DEVNET,\n M2_TEST_NET: AptosChainId.APTOS_M2_TESTNET,\n M2_MAIN_NET: AptosChainId.APTOS_M2_MAINNET\n}\n\nexport class AptosBindOptions {\n address: string\n network?: AptosNetwork = AptosNetwork.MAIN_NET\n client?: Aptos\n startVersion?: bigint | number\n baseLabels?: Labels\n}\n\nexport function getRpcEndpoint(network: AptosNetwork): string {\n switch (network) {\n case AptosNetwork.TEST_NET:\n return 'https://testnet.aptoslabs.com/v1'\n case AptosNetwork.M2_TEST_NET:\n return process.env.APTOS_M2_TESTNET_URL || 'https://testnet.m1.movementlabs.xyz/v1'\n case AptosNetwork.M2_MAIN_NET:\n return 'https://mainnet.m1.movementlabs.xyz/v1'\n }\n return 'https://mainnet.aptoslabs.com/v1'\n}\n\nexport function getClient(network: AptosNetwork): Aptos {\n let chainServer = Endpoints.INSTANCE.chainServer.get(network)\n if (!chainServer) {\n chainServer = getRpcEndpoint(network)\n // throw new ServerError(Status.INTERNAL, 'RPC endpoint not provided')\n } else {\n chainServer = chainServer + '/v1'\n }\n return new Aptos(new AptosConfig({ fullnode: chainServer }))\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This error is used to explain why parsing failed.\n */\nexport class ParsingError<T> extends Error {\n /**\n * This provides a programmatic way to access why parsing failed. Downstream devs\n * might want to use this to build their own error messages if the default error\n * messages are not suitable for their use case. This should be an enum.\n */\n public invalidReason: T;\n\n constructor(message: string, invalidReason: T) {\n super(message);\n this.invalidReason = invalidReason;\n }\n}\n\n/**\n * Whereas ParsingError is thrown when parsing fails, e.g. in a fromString function,\n * this type is returned from \"defensive\" functions like isValid.\n */\nexport type ParsingResult<T> = {\n /**\n * True if valid, false otherwise.\n */\n valid: boolean;\n\n /**\n * If valid is false, this will be a code explaining why parsing failed.\n */\n invalidReason?: T;\n\n /**\n * If valid is false, this will be a string explaining why parsing failed.\n */\n invalidReasonMessage?: string;\n};\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nimport { ParsingError, ParsingResult } from \"./common\";\nimport { HexInput } from \"../types\";\n\n/**\n * This enum is used to explain why parsing might have failed.\n */\nexport enum HexInvalidReason {\n TOO_SHORT = \"too_short\",\n INVALID_LENGTH = \"invalid_length\",\n INVALID_HEX_CHARS = \"invalid_hex_chars\",\n}\n\n/**\n * NOTE: Do not use this class when working with account addresses, use AccountAddress.\n *\n * NOTE: When accepting hex data as input to a function, prefer to accept HexInput and\n * then use the static helper methods of this class to convert it into the desired\n * format. This enables the greatest flexibility for the developer.\n *\n * Hex is a helper class for working with hex data. Hex data, when represented as a\n * string, generally looks like this, for example: 0xaabbcc, 45cd32, etc.\n *\n * You might use this class like this:\n *\n * ```ts\n * getTransactionByHash(txnHash: HexInput): Promise<Transaction> {\n * const txnHashString = Hex.fromHexInput(txnHash).toString();\n * return await getTransactionByHashInner(txnHashString);\n * }\n * ```\n *\n * This call to `Hex.fromHexInput().toString()` converts the HexInput to a hex string\n * with a leading 0x prefix, regardless of what the input format was.\n *\n * These are some other ways to chain the functions together:\n * - `Hex.fromHexString({ hexInput: \"0x1f\" }).toUint8Array()`\n * - `new Hex([1, 3]).toStringWithoutPrefix()`\n */\nexport class Hex {\n private readonly data: Uint8Array;\n\n /**\n * Create a new Hex instance from a Uint8Array.\n *\n * @param data Uint8Array\n */\n constructor(data: Uint8Array) {\n this.data = data;\n }\n\n // ===\n // Methods for representing an instance of Hex as other types.\n // ===\n\n /**\n * Get the inner hex data. The inner data is already a Uint8Array so no conversion\n * is taking place here, it just returns the inner data.\n *\n * @returns Hex data as Uint8Array\n */\n toUint8Array(): Uint8Array {\n return this.data;\n }\n\n /**\n * Get the hex data as a string without the 0x prefix.\n *\n * @returns Hex string without 0x prefix\n */\n toStringWithoutPrefix(): string {\n return bytesToHex(this.data);\n }\n\n /**\n * Get the hex data as a string with the 0x prefix.\n *\n * @returns Hex string with 0x prefix\n */\n toString(): string {\n return `0x${this.toStringWithoutPrefix()}`;\n }\n\n // ===\n // Methods for creating an instance of Hex from other types.\n // ===\n\n /**\n * Static method to convert a hex string to Hex\n *\n * @param str A hex string, with or without the 0x prefix\n *\n * @returns Hex\n */\n static fromHexString(str: string): Hex {\n let input = str;\n\n if (input.startsWith(\"0x\")) {\n input = input.slice(2);\n }\n\n if (input.length === 0) {\n throw new ParsingError(\n \"Hex string is too short, must be at least 1 char long, excluding the optional leading 0x.\",\n HexInvalidReason.TOO_SHORT,\n );\n }\n\n if (input.length % 2 !== 0) {\n throw new ParsingError(\"Hex string must be an even number of hex characters.\", HexInvalidReason.INVALID_LENGTH);\n }\n\n try {\n return new Hex(hexToBytes(input));\n } catch (error: any) {\n throw new ParsingError(\n `Hex string contains invalid hex characters: ${error?.message}`,\n HexInvalidReason.INVALID_HEX_CHARS,\n );\n }\n }\n\n /**\n * Static method to convert an instance of HexInput to Hex\n *\n * @param hexInput A HexInput (string or Uint8Array)\n *\n * @returns Hex\n */\n static fromHexInput(hexInput: HexInput): Hex {\n if (hexInput instanceof Uint8Array) return new Hex(hexInput);\n return Hex.fromHexString(hexInput);\n }\n\n // ===\n // Methods for checking validity.\n // ===\n\n /**\n * Check if the string is valid hex.\n *\n * @param str A hex string representing byte data.\n *\n * @returns valid = true if the string is valid, false if not. If the string is not\n * valid, invalidReason and invalidReasonMessage will be set explaining why it is\n * invalid.\n */\n static isValid(str: string): ParsingResult<HexInvalidReason> {\n try {\n Hex.fromHexString(str);\n return { valid: true };\n } catch (error: any) {\n return {\n valid: false,\n invalidReason: error?.invalidReason,\n invalidReasonMessage: error?.message,\n };\n }\n }\n\n /**\n * Return whether Hex instances are equal. Hex instances are considered equal if\n * their underlying byte data is identical.\n *\n * @param other The Hex instance to compare to.\n * @returns true if the Hex instances are equal, false if not.\n */\n equals(other: Hex): boolean {\n if (this.data.length !== other.data.length) return false;\n return this.data.every((value, index) => value === other.data[index]);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Uint8, Uint16, Uint32, Uint64, Uint128, Uint256 } from \"../types\";\n\n// Upper bound values for uint8, uint16, uint64 etc. These are all derived as\n// 2^N - 1, where N is the number of bits in the type.\nexport const MAX_U8_NUMBER: Uint8 = 255;\nexport const MAX_U16_NUMBER: Uint16 = 65535;\nexport const MAX_U32_NUMBER: Uint32 = 4294967295;\nexport const MAX_U64_BIG_INT: Uint64 = 18446744073709551615n;\nexport const MAX_U128_BIG_INT: Uint128 = 340282366920938463463374607431768211455n;\nexport const MAX_U256_BIG_INT: Uint256 =\n 115792089237316195423570985008687907853269984665640564039457584007913129639935n;\n","var h=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=(g,b,d,c)=>{for(var a=c>1?void 0:c?i(b,d):b,e=g.length-1,f;e>=0;e--)(f=g[e])&&(a=(c?f(b,d,a):f(a))||a);return c&&a&&h(b,d,a),a};export{j as a};\n//# sourceMappingURL=chunk-FVA2OPG4.mjs.map","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable no-bitwise */\nimport {\n MAX_U128_BIG_INT,\n MAX_U16_NUMBER,\n MAX_U32_NUMBER,\n MAX_U64_BIG_INT,\n MAX_U8_NUMBER,\n MAX_U256_BIG_INT,\n} from \"./consts\";\nimport { Hex } from \"../core/hex\";\nimport { AnyNumber, Uint16, Uint32, Uint8 } from \"../types\";\n\n// This class is intended to be used as a base class for all serializable types.\n// It can be used to facilitate composable serialization of a complex type and\n// in general to serialize a type to its BCS representation.\nexport abstract class Serializable {\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Serializes a `Serializable` value to its BCS representation.\n * This function is the Typescript SDK equivalent of `bcs::to_bytes` in Move.\n * @returns the BCS representation of the Serializable instance as a byte buffer\n */\n bcsToBytes(): Uint8Array {\n const serializer = new Serializer();\n this.serialize(serializer);\n return serializer.toUint8Array();\n }\n\n /**\n * Helper function to get a value's BCS-serialized bytes as a Hex instance.\n * @returns a Hex instance with the BCS-serialized bytes loaded into its underlying Uint8Array\n */\n bcsToHex(): Hex {\n const bcsBytes = this.bcsToBytes();\n return Hex.fromHexInput(bcsBytes);\n }\n}\n\nexport class Serializer {\n private buffer: ArrayBuffer;\n\n private offset: number;\n\n // Constructs a serializer with a buffer of size `length` bytes, 64 bytes by default.\n // `length` must be greater than 0.\n constructor(length: number = 64) {\n if (length <= 0) {\n throw new Error(\"Length needs to be greater than 0\");\n }\n this.buffer = new ArrayBuffer(length);\n this.offset = 0;\n }\n\n private ensureBufferWillHandleSize(bytes: number) {\n while (this.buffer.byteLength < this.offset + bytes) {\n const newBuffer = new ArrayBuffer(this.buffer.byteLength * 2);\n new Uint8Array(newBuffer).set(new Uint8Array(this.buffer));\n this.buffer = newBuffer;\n }\n }\n\n protected appendToBuffer(values: Uint8Array) {\n this.ensureBufferWillHandleSize(values.length);\n new Uint8Array(this.buffer, this.offset).set(values);\n this.offset += values.length;\n }\n\n private serializeWithFunction(\n fn: (byteOffset: number, value: number, littleEndian?: boolean) => void,\n bytesLength: number,\n value: number,\n ) {\n this.ensureBufferWillHandleSize(bytesLength);\n const dv = new DataView(this.buffer, this.offset);\n fn.apply(dv, [0, value, true]);\n this.offset += bytesLength;\n }\n\n /**\n * Serializes a string. UTF8 string is supported.\n *\n * The number of bytes in the string content is serialized first, as a uleb128-encoded u32 integer.\n * Then the string content is serialized as UTF8 encoded bytes.\n *\n * BCS layout for \"string\": string_length | string_content\n * where string_length is a u32 integer encoded as a uleb128 integer, equal to the number of bytes in string_content.\n *\n * @example\n * ```ts\n * const serializer = new Serializer();\n * serializer.serializeStr(\"1234abcd\");\n * assert(serializer.toUint8Array() === new Uint8Array([8, 49, 50, 51, 52, 97, 98, 99, 100]));\n * ```\n */\n serializeStr(value: string) {\n const textEncoder = new TextEncoder();\n this.serializeBytes(textEncoder.encode(value));\n }\n\n /**\n * Serializes an array of bytes.\n *\n * BCS layout for \"bytes\": bytes_length | bytes\n * where bytes_length is a u32 integer encoded as a uleb128 integer, equal to the length of the bytes array.\n */\n serializeBytes(value: Uint8Array) {\n this.serializeU32AsUleb128(value.length);\n this.appendToBuffer(value);\n }\n\n /**\n * Serializes an array of bytes with known length. Therefore, length doesn't need to be\n * serialized to help deserialization.\n *\n * When deserializing, the number of bytes to deserialize needs to be passed in.\n */\n serializeFixedBytes(value: Uint8Array) {\n this.appendToBuffer(value);\n }\n\n /**\n * Serializes a boolean value.\n *\n * BCS layout for \"boolean\": One byte. \"0x01\" for true and \"0x00\" for false.\n */\n serializeBool(value: boolean) {\n ensureBoolean(value);\n const byteValue = value ? 1 : 0;\n this.appendToBuffer(new Uint8Array([byteValue]));\n }\n\n /**\n * Serializes a uint8 number.\n *\n * BCS layout for \"uint8\": One byte. Binary format in little-endian representation.\n */\n @checkNumberRange(0, MAX_U8_NUMBER)\n serializeU8(value: Uint8) {\n this.appendToBuffer(new Uint8Array([value]));\n }\n\n /**\n * Serializes a uint16 number.\n *\n * BCS layout for \"uint16\": Two bytes. Binary format in little-endian representation.\n * @example\n * ```ts\n * const serializer = new Serializer();\n * serializer.serializeU16(4660);\n * assert(serializer.toUint8Array() === new Uint8Array([0x34, 0x12]));\n * ```\n */\n @checkNumberRange(0, MAX_U16_NUMBER)\n serializeU16(value: Uint16) {\n this.serializeWithFunction(DataView.prototype.setUint16, 2, value);\n }\n\n /**\n * Serializes a uint32 number.\n *\n * BCS layout for \"uint32\": Four bytes. Binary format in little-endian representation.\n * @example\n * ```ts\n * const serializer = new Serializer();\n * serializer.serializeU32(305419896);\n * assert(serializer.toUint8Array() === new Uint8Array([0x78, 0x56, 0x34, 0x12]));\n * ```\n */\n @checkNumberRange(0, MAX_U32_NUMBER)\n serializeU32(value: Uint32) {\n this.serializeWithFunction(DataView.prototype.setUint32, 4, value);\n }\n\n /**\n * Serializes a uint64 number.\n *\n * BCS layout for \"uint64\": Eight bytes. Binary format in little-endian representation.\n * @example\n * ```ts\n * const serializer = new Serializer();\n * serializer.serializeU64(1311768467750121216);\n * assert(serializer.toUint8Array() === new Uint8Array([0x00, 0xEF, 0xCD, 0xAB, 0x78, 0x56, 0x34, 0x12]));\n * ```\n */\n @checkNumberRange(BigInt(0), MAX_U64_BIG_INT)\n serializeU64(value: AnyNumber) {\n const low = BigInt(value) & BigInt(MAX_U32_NUMBER);\n const high = BigInt(value) >> BigInt(32);\n\n // write little endian number\n this.serializeU32(Number(low));\n this.serializeU32(Number(high));\n }\n\n /**\n * Serializes a uint128 number.\n *\n * BCS layout for \"uint128\": Sixteen bytes. Binary format in little-endian representation.\n */\n @checkNumberRange(BigInt(0), MAX_U128_BIG_INT)\n serializeU128(value: AnyNumber) {\n const low = BigInt(value) & MAX_U64_BIG_INT;\n const high = BigInt(value) >> BigInt(64);\n\n // write little endian number\n this.serializeU64(low);\n this.serializeU64(high);\n }\n\n /**\n * Serializes a uint256 number.\n *\n * BCS layout for \"uint256\": Sixteen bytes. Binary format in little-endian representation.\n */\n @checkNumberRange(BigInt(0), MAX_U256_BIG_INT)\n serializeU256(value: AnyNumber) {\n const low = BigInt(value) & MAX_U128_BIG_INT;\n const high = BigInt(value) >> BigInt(128);\n\n // write little endian number\n this.serializeU128(low);\n this.serializeU128(high);\n }\n\n /**\n * Serializes a uint32 number with uleb128.\n *\n * BCS uses uleb128 encoding in two cases: (1) lengths of variable-length sequences and (2) tags of enum values\n */\n @checkNumberRange(0, MAX_U32_NUMBER)\n serializeU32AsUleb128(val: Uint32) {\n let value = val;\n const valueArray = [];\n while (value >>> 7 !== 0) {\n valueArray.push((value & 0x7f) | 0x80);\n value >>>= 7;\n }\n valueArray.push(value);\n this.appendToBuffer(new Uint8Array(valueArray));\n }\n\n /**\n * Returns the buffered bytes\n */\n toUint8Array(): Uint8Array {\n return new Uint8Array(this.buffer).slice(0, this.offset);\n }\n\n /**\n * Serializes a `Serializable` value, facilitating composable serialization.\n *\n * @param value The Serializable value to serialize\n *\n * @example\n * // Define the MoveStruct class that implements the Serializable interface\n * class MoveStruct extends Serializable {\n * constructor(\n * public creatorAddress: AccountAddress, // where AccountAddress extends Serializable\n * public collectionName: string,\n * public tokenName: string\n * ) {}\n *\n * serialize(serializer: Serializer): void {\n * serializer.serialize(this.creatorAddress); // Composable serialization of another Serializable object\n * serializer.serializeStr(this.collectionName);\n * serializer.serializeStr(this.tokenName);\n * }\n * }\n *\n * // Construct a MoveStruct\n * const moveStruct = new MoveStruct(new AccountAddress(...), \"MyCollection\", \"TokenA\");\n *\n * // Serialize a string, a u64 number, and a MoveStruct instance.\n * const serializer = new Serializer();\n * serializer.serializeStr(\"ExampleString\");\n * serializer.serializeU64(12345678);\n * serializer.serialize(moveStruct);\n *\n * // Get the bytes from the Serializer instance\n * const serializedBytes = serializer.toUint8Array();\n *\n * @returns the serializer instance\n */\n serialize<T extends Serializable>(value: T): void {\n // NOTE: The `serialize` method called by `value` is defined in `value`'s\n // Serializable interface, not the one defined in this class.\n value.serialize(this);\n }\n\n /**\n * Serializes an array of BCS Serializable values to a serializer instance.\n * Note that this does not return anything. The bytes are added to the serializer instance's byte buffer.\n *\n * @param values The array of BCS Serializable values\n * @example\n * const addresses = new Array<AccountAddress>(\n * AccountAddress.from(\"0x1\"),\n * AccountAddress.from(\"0x2\"),\n * AccountAddress.from(\"0xa\"),\n * AccountAddress.from(\"0xb\"),\n * );\n * const serializer = new Serializer();\n * serializer.serializeVector(addresses);\n * const serializedBytes = serializer.toUint8Array();\n * // serializedBytes is now the BCS-serialized bytes\n * // The equivalent value in Move would be:\n * // `bcs::to_bytes(&vector<address> [@0x1, @0x2, @0xa, @0xb])`;\n */\n serializeVector<T extends Serializable>(values: Array<T>): void {\n this.serializeU32AsUleb128(values.length);\n values.forEach((item) => {\n item.serialize(this);\n });\n }\n}\n\nexport function ensureBoolean(value: unknown): asserts value is boolean {\n if (typeof value !== \"boolean\") {\n throw new Error(`${value} is not a boolean value`);\n }\n}\n\nexport const outOfRangeErrorMessage = (value: AnyNumber, min: AnyNumber, max: AnyNumber) =>\n `${value} is out of range: [${min}, ${max}]`;\n\nexport function validateNumberInRange<T extends AnyNumber>(value: T, minValue: T, maxValue: T) {\n const valueBigInt = BigInt(value);\n if (valueBigInt > BigInt(maxValue) || valueBigInt < BigInt(minValue)) {\n throw new Error(outOfRangeErrorMessage(value, minValue, maxValue));\n }\n}\n\n/**\n * A decorator to ensure the input argument for a function is within a range.\n * @param minValue The input argument must be >= minValue\n * @param maxValue The input argument must be <= maxValue\n */\nfunction checkNumberRange<T extends AnyNumber>(minValue: T, maxValue: T) {\n return (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) => {\n const childFunction = descriptor.value;\n // eslint-disable-next-line no-param-reassign\n descriptor.value = function deco(value: AnyNumber) {\n validateNumberInRange(value, minValue, maxValue);\n return childFunction.apply(this, [value]);\n };\n\n return descriptor;\n };\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nimport { Serializable, Serializer } from \"../bcs/serializer\";\nimport { Deserializer } from \"../bcs/deserializer\";\nimport { ParsingError, ParsingResult } from \"./common\";\nimport { TransactionArgument } from \"../transactions/instances/transactionArgument\";\nimport { HexInput, ScriptTransactionArgumentVariants } from \"../types\";\n\n/**\n * This enum is used to explain why an address was invalid.\n */\nexport enum AddressInvalidReason {\n INCORRECT_NUMBER_OF_BYTES = \"incorrect_number_of_bytes\",\n INVALID_HEX_CHARS = \"invalid_hex_chars\",\n TOO_SHORT = \"too_short\",\n TOO_LONG = \"too_long\",\n LEADING_ZERO_X_REQUIRED = \"leading_zero_x_required\",\n LONG_FORM_REQUIRED_UNLESS_SPECIAL = \"long_form_required_unless_special\",\n INVALID_PADDING_ZEROES = \"INVALID_PADDING_ZEROES\",\n}\n\nexport type AccountAddressInput = HexInput | AccountAddress;\n\n/**\n * NOTE: Only use this class for account addresses. For other hex data, e.g. transaction\n * hashes, use the Hex class.\n *\n * AccountAddress is used for working with account addresses. Account addresses, when\n * represented as a string, generally look like these examples:\n * - 0x1\n * - 0xaa86fe99004361f747f91342ca13c426ca0cccb0c1217677180c9493bad6ef0c\n *\n * Proper formatting and parsing of account addresses is defined by AIP-40.\n * To learn more about the standard, read the AIP here:\n * https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-40.md.\n *\n * The comments in this class make frequent reference to the LONG and SHORT formats,\n * as well as \"special\" addresses. To learn what these refer to see AIP-40.\n */\nexport class AccountAddress extends Serializable implements TransactionArgument {\n /**\n * This is the internal representation of an account address.\n */\n readonly data: Uint8Array;\n\n /**\n * The number of bytes that make up an account address.\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The length of an address string in LONG form without a leading 0x.\n */\n static readonly LONG_STRING_LENGTH: number = 64;\n\n static ZERO: AccountAddress = AccountAddress.from(\"0x0\");\n\n static ONE: AccountAddress = AccountAddress.from(\"0x1\");\n\n static TWO: AccountAddress = AccountAddress.from(\"0x2\");\n\n static THREE: AccountAddress = AccountAddress.from(\"0x3\");\n\n static FOUR: AccountAddress = AccountAddress.from(\"0x4\");\n\n /**\n * Creates an instance of AccountAddress from a Uint8Array.\n *\n * @param args.data A Uint8Array representing an account address.\n */\n constructor(input: Uint8Array) {\n super();\n if (input.length !== AccountAddress.LENGTH) {\n throw new ParsingError(\n \"AccountAddress data should be exactly 32 bytes long\",\n AddressInvalidReason.INCORRECT_NUMBER_OF_BYTES,\n );\n }\n this.data = input;\n }\n\n /**\n * Returns whether an address is special, where special is defined as 0x0 to 0xf\n * inclusive. In other words, the last byte of the address must be < 0b10000 (16)\n * and every other byte must be zero.\n *\n * For more information on how special addresses are defined see AIP-40:\n * https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-40.md.\n *\n * @returns true if the address is special, false if not.\n */\n isSpecial(): boolean {\n return (\n this.data.slice(0, this.data.length - 1).every((byte) => byte === 0) && this.data[this.data.length - 1] < 0b10000\n );\n }\n\n // ===\n // Methods for representing an instance of AccountAddress as other types.\n // ===\n\n /**\n * Return the AccountAddress as a string as per AIP-40.\n * https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-40.md.\n *\n * In short, it means that special addresses are represented in SHORT form, meaning\n * 0x0 through to 0xf inclusive, and every other address is represented in LONG form,\n * meaning 0x + 64 hex characters.\n *\n * @returns AccountAddress as a string conforming to AIP-40.\n */\n toString(): `0x${string}` {\n return `0x${this.toStringWithoutPrefix()}`;\n }\n\n /**\n * NOTE: Prefer to use `toString` where possible.\n *\n * Return the AccountAddress as a string as per AIP-40 but without the leading 0x.\n *\n * Learn more by reading the docstring of `toString`.\n *\n * @returns AccountAddress as a string conforming to AIP-40 but without the leading 0x.\n */\n toStringWithoutPrefix(): string {\n let hex = bytesToHex(this.data);\n if (this.isSpecial()) {\n hex = hex[hex.length - 1];\n }\n return hex;\n }\n\n /**\n * NOTE: Prefer to use `toString` where possible.\n *\n * Whereas toString will format special addresses (as defined by isSpecial) using the\n * SHORT form (no leading 0s), this format the address in the LONG format\n * unconditionally.\n *\n * This means it will be 0x + 64 hex characters.\n *\n * @returns AccountAddress as a string in LONG form.\n */\n toStringLong(): `0x${string}` {\n return `0x${this.toStringLongWithoutPrefix()}`;\n }\n\n /**\n * NOTE: Prefer to use `toString` where possible.\n *\n * Whereas toString will format special addresses (as defined by isSpecial) using the\n * SHORT form (no leading 0s), this function will include leading zeroes. The string\n * will not have a leading zero.\n *\n * This means it will be 64 hex characters without a leading 0x.\n *\n * @returns AccountAddress as a string in LONG form without a leading 0x.\n */\n toStringLongWithoutPrefix(): string {\n return bytesToHex(this.data);\n }\n\n /**\n * Get the inner hex data. The inner data is already a Uint8Array so no conversion\n * is taking place here, it just returns the inner data.\n *\n * @returns Hex data as Uint8Array\n */\n toUint8Array(): Uint8Array {\n return this.data;\n }\n\n /**\n * Serialize the AccountAddress to a Serializer instance's data buffer.\n * @param serializer The serializer to serialize the AccountAddress to.\n * @returns void\n * @example\n * const serializer = new Serializer();\n * const address = AccountAddress.fromString(\"0x1\");\n * address.serialize(serializer);\n * const bytes = serializer.toUint8Array();\n * // `bytes` is now the BCS-serialized address.\n */\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.data);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.Address);\n serializer.serialize(this);\n }\n\n /**\n * Deserialize an AccountAddress from the byte buffer in a Deserializer instance.\n * @param deserializer The deserializer to deserialize the AccountAddress from.\n * @returns An instance of AccountAddress.\n * @example\n * const bytes = hexToBytes(\"0x0102030405060708091011121314151617181920212223242526272829303132\");\n * const deserializer = new Deserializer(bytes);\n * const address = AccountAddress.deserialize(deserializer);\n * // `address` is now an instance of AccountAddress.\n */\n static deserialize(deserializer: Deserializer): AccountAddress {\n const bytes = deserializer.deserializeFixedBytes(AccountAddress.LENGTH);\n return new AccountAddress(bytes);\n }\n\n // ===\n // Methods for creating an instance of AccountAddress from other types.\n // ===\n\n /**\n * NOTE: This function has strict parsing behavior. For relaxed behavior, please use\n * the `fromString` function.\n *\n * Creates an instance of AccountAddress from a hex string.\n *\n * This function allows only the strictest formats defined by AIP-40. In short this\n * means only the following formats are accepted:\n *\n * - LONG\n * - SHORT for special addresses\n *\n * Where:\n * - LONG is defined as 0x + 64 hex characters.\n * - SHORT for special addresses is 0x0 to 0xf inclusive without padding zeroes.\n *\n * This means the following are not accepted:\n * - SHORT for non-special addresses.\n * - Any address without a leading 0x.\n *\n * Learn more about the different address formats by reading AIP-40:\n * https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-40.md.\n *\n * @param input A hex string representing an account address.\n *\n * @returns An instance of AccountAddress.\n */\n static fromStringStrict(input: string): AccountAddress {\n // Assert the string starts with 0x.\n if (!input.startsWith(\"0x\")) {\n throw new ParsingError(\"Hex string must start with a leading 0x.\", AddressInvalidReason.LEADING_ZERO_X_REQUIRED);\n }\n\n const address = AccountAddress.fromString(input);\n\n // Check if the address is in LONG form. If it is not, this is only allowed for\n // special addresses, in which case we check it is in proper SHORT form.\n if (input.length !== AccountAddress.LONG_STRING_LENGTH + 2) {\n if (!address.isSpecial()) {\n throw new ParsingError(\n `The given hex string ${input} is not a special address, it must be represented as 0x + 64 chars.`,\n AddressInvalidReason.LONG_FORM_REQUIRED_UNLESS_SPECIAL,\n );\n } else if (input.length !== 3) {\n // 0x + one hex char is the only valid SHORT form for special addresses.\n throw new ParsingError(\n // eslint-disable-next-line max-len\n `The given hex string ${input} is a special address not in LONG form, it must be 0x0 to 0xf without padding zeroes.`,\n AddressInvalidReason.INVALID_PADDING_ZEROES,\n );\n }\n }\n\n return address;\n }\n\n /**\n * NOTE: This function has relaxed parsing behavior. For strict behavior, please use\n * the `fromStringStrict` function. Where possible use `fromStringStrict` rather than this\n * function, `fromString` is only provided for backwards compatibility.\n *\n * Creates an instance of AccountAddress from a hex string.\n *\n * This function allows all formats defined by AIP-40. In short this means the\n * following formats are accepted:\n *\n * - LONG, with or without leading 0x\n * - SHORT, with or without leading 0x\n *\n * Where:\n * - LONG is 64 hex characters.\n * - SHORT is 1 to 63 hex characters inclusive.\n * - Padding zeroes are allowed, e.g. 0x0123 is valid.\n *\n * Learn more about the different address formats by reading AIP-40:\n * https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-40.md.\n *\n * @param input A hex string representing an account address.\n *\n * @returns An instance of AccountAddress.\n */\n static fromString(input: string): AccountAddress {\n let parsedInput = input;\n // Remove leading 0x for parsing.\n if (input.startsWith(\"0x\")) {\n parsedInput = input.slice(2);\n }\n\n // Ensure the address string is at least 1 character long.\n if (parsedInput.length === 0) {\n throw new ParsingError(\n \"Hex string is too short, must be 1 to 64 chars long, excluding the leading 0x.\",\n AddressInvalidReason.TOO_SHORT,\n );\n }\n\n // Ensure the address string is not longer than 64 characters.\n if (parsedInput.length > 64) {\n throw new ParsingError(\n \"Hex string is too long, must be 1 to 64 chars long, excluding the leading 0x.\",\n AddressInvalidReason.TOO_LONG,\n );\n }\n\n let addressBytes: Uint8Array;\n try {\n // Pad the address with leading zeroes, so it is 64 chars long and then convert\n // the hex string to bytes. Every two characters in a hex string constitutes a\n // single byte. So a 64 length hex string becomes a 32 byte array.\n addressBytes = hexToBytes(parsedInput.padStart(64, \"0\"));\n } catch (error: any) {\n // At this point the only way this can fail is if the hex string contains\n // invalid characters.\n throw new ParsingError(`Hex characters are invalid: ${error?.message}`, AddressInvalidReason.INVALID_HEX_CHARS);\n }\n\n return new AccountAddress(addressBytes);\n }\n\n /**\n * Convenience method for creating an AccountAddress from all known inputs.\n *\n * This handles, Uint8array, string, and AccountAddress itself\n * @param input\n */\n static from(input: AccountAddressInput): AccountAddress {\n if (input instanceof AccountAddress) {\n return input;\n }\n if (input instanceof Uint8Array) {\n return new AccountAddress(input);\n }\n return AccountAddress.fromString(input);\n }\n\n /**\n * Convenience method for creating an AccountAddress from all known inputs.\n *\n * This handles, Uint8array, string, and AccountAddress itself\n * @param input\n */\n static fromStrict(input: AccountAddressInput): AccountAddress {\n if (input instanceof AccountAddress) {\n return input;\n }\n if (input instanceof Uint8Array) {\n return new AccountAddress(input);\n }\n return AccountAddress.fromStringStrict(input);\n }\n\n // ===\n // Methods for checking validity.\n // ===\n\n /**\n * Check if the string is a valid AccountAddress.\n *\n * @param args.input A hex string representing an account address.\n * @param args.strict If true, use strict parsing behavior. If false, use relaxed parsing behavior.\n *\n * @returns valid = true if the string is valid, valid = false if not. If the string\n * is not valid, invalidReason will be set explaining why it is invalid.\n */\n static isValid(args: { input: AccountAddressInput; strict?: boolean }): ParsingResult<AddressInvalidReason> {\n try {\n if (args.strict) {\n AccountAddress.fromStrict(args.input);\n } else {\n AccountAddress.from(args.input);\n }\n return { valid: true };\n } catch (error: any) {\n return {\n valid: false,\n invalidReason: error?.invalidReason,\n invalidReasonMessage: error?.message,\n };\n }\n }\n\n /**\n * Return whether AccountAddresses are equal. AccountAddresses are considered equal\n * if their underlying byte data is identical.\n *\n * @param other The AccountAddress to compare to.\n * @returns true if the AccountAddresses are equal, false if not.\n */\n equals(other: AccountAddress): boolean {\n if (this.data.length !== other.data.length) return false;\n return this.data.every((value, index) => value === other.data[index]);\n }\n}\n","import * as Types from \"./operations\";\n\nimport { GraphQLClient } from \"graphql-request\";\nimport { GraphQLClientRequestHeaders } from \"graphql-request/build/cjs/types\";\nexport const TokenActivitiesFieldsFragmentDoc = `\n fragment TokenActivitiesFields on token_activities_v2 {\n after_value\n before_value\n entry_function_id_str\n event_account_address\n event_index\n from_address\n is_fungible_v2\n property_version_v1\n to_address\n token_amount\n token_data_id\n token_standard\n transaction_timestamp\n transaction_version\n type\n}\n `;\nexport const AnsTokenFragmentFragmentDoc = `\n fragment AnsTokenFragment on current_aptos_names {\n domain\n expiration_timestamp\n registered_address\n subdomain\n token_standard\n is_primary\n owner_address\n}\n `;\nexport const CurrentTokenOwnershipFieldsFragmentDoc = `\n fragment CurrentTokenOwnershipFields on current_token_ownerships_v2 {\n token_standard\n token_properties_mutated_v1\n token_data_id\n table_type_v1\n storage_id\n property_version_v1\n owner_address\n last_transaction_version\n last_transaction_timestamp\n is_soulbound_v2\n is_fungible_v2\n amount\n current_token_data {\n collection_id\n description\n is_fungible_v2\n largest_property_version_v1\n last_transaction_timestamp\n last_transaction_version\n maximum\n supply\n token_data_id\n token_name\n token_properties\n token_standard\n token_uri\n decimals\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n }\n}\n `;\nexport const GetAccountCoinsCount = `\n query getAccountCoinsCount($address: String) {\n current_fungible_asset_balances_aggregate(\n where: {owner_address: {_eq: $address}}\n ) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAccountCoinsData = `\n query getAccountCoinsData($where_condition: current_fungible_asset_balances_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_fungible_asset_balances_order_by!]) {\n current_fungible_asset_balances(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n amount\n asset_type\n is_frozen\n is_primary\n last_transaction_timestamp\n last_transaction_version\n owner_address\n storage_id\n token_standard\n metadata {\n token_standard\n symbol\n supply_aggregator_table_key_v1\n supply_aggregator_table_handle_v1\n project_uri\n name\n last_transaction_version\n last_transaction_timestamp\n icon_uri\n decimals\n creator_address\n asset_type\n }\n }\n}\n `;\nexport const GetAccountCollectionsWithOwnedTokens = `\n query getAccountCollectionsWithOwnedTokens($where_condition: current_collection_ownership_v2_view_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_collection_ownership_v2_view_order_by!]) {\n current_collection_ownership_v2_view(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n mutable_description\n max_supply\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n collection_id\n collection_name\n collection_uri\n creator_address\n distinct_tokens\n last_transaction_version\n owner_address\n single_token_uri\n }\n}\n `;\nexport const GetAccountOwnedObjects = `\n query getAccountOwnedObjects($where_condition: current_objects_bool_exp, $offset: Int, $limit: Int, $order_by: [current_objects_order_by!]) {\n current_objects(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n allow_ungated_transfer\n state_key_hash\n owner_address\n object_address\n last_transaction_version\n last_guid_creation_num\n is_deleted\n }\n}\n `;\nexport const GetAccountOwnedTokens = `\n query getAccountOwnedTokens($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountOwnedTokensByTokenData = `\n query getAccountOwnedTokensByTokenData($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountOwnedTokensFromCollection = `\n query getAccountOwnedTokensFromCollection($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountTokensCount = `\n query getAccountTokensCount($where_condition: current_token_ownerships_v2_bool_exp, $offset: Int, $limit: Int) {\n current_token_ownerships_v2_aggregate(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAccountTransactionsCount = `\n query getAccountTransactionsCount($address: String) {\n account_transactions_aggregate(where: {account_address: {_eq: $address}}) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetChainTopUserTransactions = `\n query getChainTopUserTransactions($limit: Int) {\n user_transactions(limit: $limit, order_by: {version: desc}) {\n version\n }\n}\n `;\nexport const GetCollectionData = `\n query getCollectionData($where_condition: current_collections_v2_bool_exp!) {\n current_collections_v2(where: $where_condition) {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n}\n `;\nexport const GetCurrentFungibleAssetBalances = `\n query getCurrentFungibleAssetBalances($where_condition: current_fungible_asset_balances_bool_exp, $offset: Int, $limit: Int) {\n current_fungible_asset_balances(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n amount\n asset_type\n is_frozen\n is_primary\n last_transaction_timestamp\n last_transaction_version\n owner_address\n storage_id\n token_standard\n }\n}\n `;\nexport const GetDelegatedStakingActivities = `\n query getDelegatedStakingActivities($delegatorAddress: String, $poolAddress: String) {\n delegated_staking_activities(\n where: {delegator_address: {_eq: $delegatorAddress}, pool_address: {_eq: $poolAddress}}\n ) {\n amount\n delegator_address\n event_index\n event_type\n pool_address\n transaction_version\n }\n}\n `;\nexport const GetEvents = `\n query getEvents($where_condition: events_bool_exp, $offset: Int, $limit: Int, $order_by: [events_order_by!]) {\n events(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n account_address\n creation_number\n data\n event_index\n sequence_number\n transaction_block_height\n transaction_version\n type\n indexed_type\n }\n}\n `;\nexport const GetFungibleAssetActivities = `\n query getFungibleAssetActivities($where_condition: fungible_asset_activities_bool_exp, $offset: Int, $limit: Int) {\n fungible_asset_activities(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n amount\n asset_type\n block_height\n entry_function_id_str\n event_index\n gas_fee_payer_address\n is_frozen\n is_gas_fee\n is_transaction_success\n owner_address\n storage_id\n storage_refund_amount\n token_standard\n transaction_timestamp\n transaction_version\n type\n }\n}\n `;\nexport const GetFungibleAssetMetadata = `\n query getFungibleAssetMetadata($where_condition: fungible_asset_metadata_bool_exp, $offset: Int, $limit: Int) {\n fungible_asset_metadata(where: $where_condition, offset: $offset, limit: $limit) {\n icon_uri\n project_uri\n supply_aggregator_table_handle_v1\n supply_aggregator_table_key_v1\n creator_address\n asset_type\n decimals\n last_transaction_timestamp\n last_transaction_version\n name\n symbol\n token_standard\n }\n}\n `;\nexport const GetNames = `\n query getNames($offset: Int, $limit: Int, $where_condition: current_aptos_names_bool_exp, $order_by: [current_aptos_names_order_by!]) {\n current_aptos_names(\n limit: $limit\n where: $where_condition\n order_by: $order_by\n offset: $offset\n ) {\n ...AnsTokenFragment\n }\n}\n ${AnsTokenFragmentFragmentDoc}`;\nexport const GetNumberOfDelegators = `\n query getNumberOfDelegators($where_condition: num_active_delegator_per_pool_bool_exp, $order_by: [num_active_delegator_per_pool_order_by!]) {\n num_active_delegator_per_pool(where: $where_condition, order_by: $order_by) {\n num_active_delegator\n pool_address\n }\n}\n `;\nexport const GetProcessorStatus = `\n query getProcessorStatus($where_condition: processor_status_bool_exp) {\n processor_status(where: $where_condition) {\n last_success_version\n processor\n last_updated\n }\n}\n `;\nexport const GetTokenActivity = `\n query getTokenActivity($where_condition: token_activities_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [token_activities_v2_order_by!]) {\n token_activities_v2(\n where: $where_condition\n order_by: $order_by\n offset: $offset\n limit: $limit\n ) {\n ...TokenActivitiesFields\n }\n}\n ${TokenActivitiesFieldsFragmentDoc}`;\nexport const GetCurrentTokenOwnership = `\n query getCurrentTokenOwnership($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetTokenData = `\n query getTokenData($where_condition: current_token_datas_v2_bool_exp, $offset: Int, $limit: Int, $order_by: [current_token_datas_v2_order_by!]) {\n current_token_datas_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n collection_id\n description\n is_fungible_v2\n largest_property_version_v1\n last_transaction_timestamp\n last_transaction_version\n maximum\n supply\n token_data_id\n token_name\n token_properties\n token_standard\n token_uri\n decimals\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n }\n}\n `;\n\nexport type SdkFunctionWrapper = <T>(\n action: (requestHeaders?: Record<string, string>) => Promise<T>,\n operationName: string,\n operationType?: string,\n) => Promise<T>;\n\nconst defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationType) => action();\n\nexport function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {\n return {\n getAccountCoinsCount(\n variables?: Types.GetAccountCoinsCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCoinsCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCoinsCountQuery>(GetAccountCoinsCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountCoinsCount\",\n \"query\",\n );\n },\n getAccountCoinsData(\n variables: Types.GetAccountCoinsDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCoinsDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCoinsDataQuery>(GetAccountCoinsData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountCoinsData\",\n \"query\",\n );\n },\n getAccountCollectionsWithOwnedTokens(\n variables: Types.GetAccountCollectionsWithOwnedTokensQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCollectionsWithOwnedTokensQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCollectionsWithOwnedTokensQuery>(\n GetAccountCollectionsWithOwnedTokens,\n variables,\n { ...requestHeaders, ...wrappedRequestHeaders },\n ),\n \"getAccountCollectionsWithOwnedTokens\",\n \"query\",\n );\n },\n getAccountOwnedObjects(\n variables?: Types.GetAccountOwnedObjectsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedObjectsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedObjectsQuery>(GetAccountOwnedObjects, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedObjects\",\n \"query\",\n );\n },\n getAccountOwnedTokens(\n variables: Types.GetAccountOwnedTokensQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensQuery>(GetAccountOwnedTokens, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedTokens\",\n \"query\",\n );\n },\n getAccountOwnedTokensByTokenData(\n variables: Types.GetAccountOwnedTokensByTokenDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensByTokenDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensByTokenDataQuery>(GetAccountOwnedTokensByTokenData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedTokensByTokenData\",\n \"query\",\n );\n },\n getAccountOwnedTokensFromCollection(\n variables: Types.GetAccountOwnedTokensFromCollectionQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensFromCollectionQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensFromCollectionQuery>(\n GetAccountOwnedTokensFromCollection,\n variables,\n { ...requestHeaders, ...wrappedRequestHeaders },\n ),\n \"getAccountOwnedTokensFromCollection\",\n \"query\",\n );\n },\n getAccountTokensCount(\n variables?: Types.GetAccountTokensCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountTokensCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountTokensCountQuery>(GetAccountTokensCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountTokensCount\",\n \"query\",\n );\n },\n getAccountTransactionsCount(\n variables?: Types.GetAccountTransactionsCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountTransactionsCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountTransactionsCountQuery>(GetAccountTransactionsCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountTransactionsCount\",\n \"query\",\n );\n },\n getChainTopUserTransactions(\n variables?: Types.GetChainTopUserTransactionsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetChainTopUserTransactionsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetChainTopUserTransactionsQuery>(GetChainTopUserTransactions, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getChainTopUserTransactions\",\n \"query\",\n );\n },\n getCollectionData(\n variables: Types.GetCollectionDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCollectionDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCollectionDataQuery>(GetCollectionData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCollectionData\",\n \"query\",\n );\n },\n getCurrentFungibleAssetBalances(\n variables?: Types.GetCurrentFungibleAssetBalancesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCurrentFungibleAssetBalancesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCurrentFungibleAssetBalancesQuery>(GetCurrentFungibleAssetBalances, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCurrentFungibleAssetBalances\",\n \"query\",\n );\n },\n getDelegatedStakingActivities(\n variables?: Types.GetDelegatedStakingActivitiesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetDelegatedStakingActivitiesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetDelegatedStakingActivitiesQuery>(GetDelegatedStakingActivities, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getDelegatedStakingActivities\",\n \"query\",\n );\n },\n getEvents(\n variables?: Types.GetEventsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetEventsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetEventsQuery>(GetEvents, variables, { ...requestHeaders, ...wrappedRequestHeaders }),\n \"getEvents\",\n \"query\",\n );\n },\n getFungibleAssetActivities(\n variables?: Types.GetFungibleAssetActivitiesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetFungibleAssetActivitiesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetFungibleAssetActivitiesQuery>(GetFungibleAssetActivities, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getFungibleAssetActivities\",\n \"query\",\n );\n },\n getFungibleAssetMetadata(\n variables?: Types.GetFungibleAssetMetadataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetFungibleAssetMetadataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetFungibleAssetMetadataQuery>(GetFungibleAssetMetadata, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getFungibleAssetMetadata\",\n \"query\",\n );\n },\n getNames(\n variables?: Types.GetNamesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetNamesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetNamesQuery>(GetNames, variables, { ...requestHeaders, ...wrappedRequestHeaders }),\n \"getNames\",\n \"query\",\n );\n },\n getNumberOfDelegators(\n variables?: Types.GetNumberOfDelegatorsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetNumberOfDelegatorsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetNumberOfDelegatorsQuery>(GetNumberOfDelegators, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getNumberOfDelegators\",\n \"query\",\n );\n },\n getProcessorStatus(\n variables?: Types.GetProcessorStatusQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetProcessorStatusQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetProcessorStatusQuery>(GetProcessorStatus, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getProcessorStatus\",\n \"query\",\n );\n },\n getTokenActivity(\n variables: Types.GetTokenActivityQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTokenActivityQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTokenActivityQuery>(GetTokenActivity, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTokenActivity\",\n \"query\",\n );\n },\n getCurrentTokenOwnership(\n variables: Types.GetCurrentTokenOwnershipQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCurrentTokenOwnershipQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCurrentTokenOwnershipQuery>(GetCurrentTokenOwnership, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCurrentTokenOwnership\",\n \"query\",\n );\n },\n getTokenData(\n variables?: Types.GetTokenDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTokenDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTokenDataQuery>(GetTokenData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTokenData\",\n \"query\",\n );\n },\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosRequest } from \"../types\";\n\n/**\n * The API response type\n *\n * @param status - the response status. i.e. 200\n * @param statusText - the response message\n * @param data the response data\n * @param url the url the request was made to\n * @param headers the response headers\n * @param config (optional) - the request object\n * @param request (optional) - the request object\n */\nexport interface AptosResponse<Req, Res> {\n status: number;\n statusText: string;\n data: Res;\n url: string;\n headers: any;\n config?: any;\n request?: Req;\n}\n\n/**\n * The type returned from an API error\n *\n * @param name - the error name \"AptosApiError\"\n * @param url the url the request was made to\n * @param status - the response status. i.e. 400\n * @param statusText - the response message\n * @param data the response data\n * @param request - the AptosRequest\n */\nexport class AptosApiError extends Error {\n readonly url: string;\n\n readonly status: number;\n\n readonly statusText: string;\n\n readonly data: any;\n\n readonly request: AptosRequest;\n\n constructor(request: AptosRequest, response: AptosResponse<any, any>, message: string) {\n super(message);\n\n this.name = \"AptosApiError\";\n this.url = response.url;\n this.status = response.status;\n this.statusText = response.statusText;\n this.data = response.data;\n this.request = request;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * The current version of the SDK\n *\n * hardcoded for now, we would want to have it injected dynamically\n */\nexport const VERSION = \"1.14.0\";\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { AptosApiError, AptosResponse } from \"./types\";\nimport { VERSION } from \"../version\";\nimport { AnyNumber, AptosRequest, Client, ClientRequest, ClientResponse, MimeType } from \"../types\";\nimport { AptosApiType } from \"../utils\";\n\n/**\n * Meaningful errors map\n */\nconst errors: Record<number, string> = {\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 429: \"Too Many Requests\",\n 500: \"Internal Server Error\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n};\n\n/**\n * Given a url and method, sends the request with axios and\n * returns the response.\n */\nexport async function request<Req, Res>(options: ClientRequest<Req>, client: Client): Promise<ClientResponse<Res>> {\n const { url, method, body, contentType, params, overrides, originMethod } = options;\n const headers: Record<string, string | AnyNumber | boolean | undefined> = {\n ...overrides?.HEADERS,\n \"x-aptos-client\": `aptos-typescript-sdk/${VERSION}`,\n \"content-type\": contentType ?? MimeType.JSON,\n \"x-aptos-typescript-sdk-origin-method\": originMethod,\n };\n\n if (overrides?.AUTH_TOKEN) {\n headers.Authorization = `Bearer ${overrides?.AUTH_TOKEN}`;\n }\n if (overrides?.API_KEY) {\n headers.Authorization = `Bearer ${overrides?.API_KEY}`;\n }\n\n /*\n * make a call using the @aptos-labs/aptos-client package\n * {@link https://www.npmjs.com/package/@aptos-labs/aptos-client}\n */\n return client.provider<Req, Res>({\n url,\n method,\n body,\n params,\n headers,\n overrides,\n });\n}\n\n/**\n * The main function to use when doing an API request.\n *\n * @param options AptosRequest\n * @param aptosConfig The config information for the SDK client instance\n * @returns the response or AptosApiError\n */\nexport async function aptosRequest<Req extends {}, Res extends {}>(\n options: AptosRequest,\n aptosConfig: AptosConfig,\n apiType: AptosApiType,\n): Promise<AptosResponse<Req, Res>> {\n const { url, path } = options;\n const fullUrl = path ? `${url}/${path}` : url;\n const response = await request<Req, Res>({ ...options, url: fullUrl }, aptosConfig.client);\n\n const result: AptosResponse<Req, Res> = {\n status: response.status,\n statusText: response.statusText!,\n data: response.data,\n headers: response.headers,\n config: response.config,\n request: response.request,\n url: fullUrl,\n };\n\n // Handle case for `Unauthorized` error (i.e API_KEY error)\n if (result.status === 401) {\n throw new AptosApiError(options, result, `Error: ${result.data}`);\n }\n\n // to support both fullnode and indexer responses,\n // check if it is an indexer query, and adjust response.data\n if (apiType === AptosApiType.INDEXER) {\n const indexerResponse = result.data as any;\n // Handle Indexer general errors\n if (indexerResponse.errors) {\n throw new AptosApiError(\n options,\n result,\n `Indexer error: ${indexerResponse.errors[0].message}` ??\n `Indexer unhandled Error ${response.status} : ${response.statusText}`,\n );\n }\n result.data = indexerResponse.data as Res;\n }\n\n if (result.status >= 200 && result.status < 300) {\n return result;\n }\n\n let errorMessage: string;\n\n if (result && result.data && \"message\" in result.data && \"error_code\" in result.data) {\n errorMessage = JSON.stringify(result.data);\n } else if (result.status in errors) {\n // If it's not an API type, it must come form infra, these are prehandled\n errorMessage = errors[result.status];\n } else {\n // Everything else is unhandled\n errorMessage = `Unhandled Error ${result.status} : ${result.statusText}`;\n }\n\n // We have to explicitly check for all request types, because if the error is a non-indexer error, but\n // comes from an indexer request (e.g. 404), we'll need to mention it appropriately\n throw new AptosApiError(options, result, `${apiType} error: ${errorMessage}`);\n}\n","import { AptosConfig } from \"../api/aptosConfig\";\nimport { aptosRequest } from \"./core\";\nimport { AptosResponse } from \"./types\";\nimport { AnyNumber, ClientConfig, MimeType } from \"../types\";\nimport { AptosApiType } from \"../utils/const\";\n\nexport type GetRequestOptions = {\n /**\n * The config for the API client\n */\n aptosConfig: AptosConfig;\n /**\n * The type of API endpoint to call e.g. fullnode, indexer, etc\n */\n type: AptosApiType;\n /**\n * The name of the API method\n */\n originMethod: string;\n /**\n * The URL path to the API method\n */\n path: string;\n /**\n * The content type of the request body\n */\n contentType?: MimeType;\n /**\n * The accepted content type of the response of the API\n */\n acceptType?: MimeType;\n /**\n * The query parameters for the request\n */\n params?: Record<string, string | AnyNumber | boolean | undefined>;\n /**\n * Specific client overrides for this request to override aptosConfig\n */\n overrides?: ClientConfig;\n};\n\nexport type GetAptosRequestOptions = Omit<GetRequestOptions, \"type\">;\n\n/**\n * Main function to do a Get request\n *\n * @param options GetRequestOptions\n * @returns\n */\nexport async function get<Req extends {}, Res extends {}>(\n options: GetRequestOptions,\n): Promise<AptosResponse<Req, Res>> {\n const { aptosConfig, overrides, params, contentType, acceptType, path, originMethod, type } = options;\n const url = aptosConfig.getRequestUrl(type);\n\n return aptosRequest<Req, Res>(\n {\n url,\n method: \"GET\",\n originMethod,\n path,\n contentType,\n acceptType,\n params,\n overrides: {\n ...aptosConfig.clientConfig,\n ...overrides,\n },\n },\n aptosConfig,\n options.type,\n );\n}\n\nexport async function getAptosFullNode<Req extends {}, Res extends {}>(\n options: GetAptosRequestOptions,\n): Promise<AptosResponse<Req, Res>> {\n const { aptosConfig } = options;\n\n return get<Req, Res>({\n ...options,\n type: AptosApiType.FULLNODE,\n overrides: {\n ...aptosConfig.clientConfig,\n ...aptosConfig.fullnodeConfig,\n ...options.overrides,\n HEADERS: { ...aptosConfig.clientConfig?.HEADERS, ...aptosConfig.fullnodeConfig?.HEADERS },\n },\n });\n}\n\n/// This function is a helper for paginating using a function wrapping an API\nexport async function paginateWithCursor<Req extends Record<string, any>, Res extends Array<{}>>(\n options: GetAptosRequestOptions,\n): Promise<Res> {\n const out: any[] = [];\n let cursor: string | undefined;\n const requestParams = options.params as { start?: string; limit?: number };\n do {\n // eslint-disable-next-line no-await-in-loop\n const response = await get<Req, Res>({\n type: AptosApiType.FULLNODE,\n aptosConfig: options.aptosConfig,\n originMethod: options.originMethod,\n path: options.path,\n params: requestParams,\n overrides: options.overrides,\n });\n /**\n * the cursor is a \"state key\" from the API perspective. Client\n * should not need to \"care\" what it represents but just use it\n * to query the next chunk of data.\n */\n cursor = response.headers[\"x-aptos-cursor\"];\n // Now that we have the cursor (if any), we remove the headers before\n // adding these to the output of this function.\n delete response.headers;\n out.push(...response.data);\n requestParams.start = cursor;\n } while (cursor !== null && cursor !== undefined);\n return out as Res;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { aptosRequest } from \"./core\";\nimport { AptosResponse } from \"./types\";\nimport { AnyNumber, ClientConfig, MimeType } from \"../types\";\nimport { AptosApiType } from \"../utils/const\";\n\nexport type PostRequestOptions = {\n /**\n * The config for the API client\n */\n aptosConfig: AptosConfig;\n /**\n * The type of API endpoint to call e.g. fullnode, indexer, etc\n */\n type: AptosApiType;\n /**\n * The name of the API method\n */\n originMethod: string;\n /**\n * The URL path to the API method\n */\n path: string;\n /**\n * The content type of the request body\n */\n contentType?: MimeType;\n /**\n * The accepted content type of the response of the API\n */\n acceptType?: MimeType;\n /**\n * The query parameters for the request\n */\n params?: Record<string, string | AnyNumber | boolean | undefined>;\n /**\n * The body of the request, should match the content type of the request\n */\n body?: any;\n /**\n * Specific client overrides for this request to override aptosConfig\n */\n overrides?: ClientConfig;\n};\n\nexport type PostAptosRequestOptions = Omit<PostRequestOptions, \"type\">;\n\n/**\n * Main function to do a Post request\n *\n * @param options PostRequestOptions\n * @returns\n */\nexport async function post<Req extends {}, Res extends {}>(\n options: PostRequestOptions,\n): Promise<AptosResponse<Req, Res>> {\n const { type, originMethod, path, body, acceptType, contentType, params, aptosConfig, overrides } = options;\n const url = aptosConfig.getRequestUrl(type);\n\n return aptosRequest<Req, Res>(\n {\n url,\n method: \"POST\",\n originMethod,\n path,\n body,\n contentType,\n acceptType,\n params,\n overrides,\n },\n aptosConfig,\n options.type,\n );\n}\n\nexport async function postAptosFullNode<Req extends {}, Res extends {}>(\n options: PostAptosRequestOptions,\n): Promise<AptosResponse<Req, Res>> {\n const { aptosConfig } = options;\n\n return post<Req, Res>({\n ...options,\n type: AptosApiType.FULLNODE,\n overrides: {\n ...aptosConfig.clientConfig,\n ...aptosConfig.fullnodeConfig,\n ...options.overrides,\n HEADERS: { ...aptosConfig.clientConfig?.HEADERS, ...aptosConfig.fullnodeConfig?.HEADERS },\n },\n });\n}\n\nexport async function postAptosIndexer<Req extends {}, Res extends {}>(\n options: PostAptosRequestOptions,\n): Promise<AptosResponse<Req, Res>> {\n const { aptosConfig } = options;\n\n return post<Req, Res>({\n ...options,\n type: AptosApiType.INDEXER,\n overrides: {\n ...aptosConfig.clientConfig,\n ...aptosConfig.indexerConfig,\n ...options.overrides,\n HEADERS: { ...aptosConfig.clientConfig?.HEADERS, ...aptosConfig.indexerConfig?.HEADERS },\n },\n });\n}\n\nexport async function postAptosFaucet<Req extends {}, Res extends {}>(\n options: PostAptosRequestOptions,\n): Promise<AptosResponse<Req, Res>> {\n const { aptosConfig } = options;\n // Faucet does not support API_KEY\n // Create a new object with the desired modification\n const modifiedAptosConfig = {\n ...aptosConfig,\n clientConfig: { ...aptosConfig.clientConfig },\n };\n // Delete API_KEY config\n delete modifiedAptosConfig?.clientConfig?.API_KEY;\n\n return post<Req, Res>({\n ...options,\n type: AptosApiType.FAUCET,\n overrides: {\n ...modifiedAptosConfig.clientConfig,\n ...modifiedAptosConfig.faucetConfig,\n ...options.overrides,\n HEADERS: { ...modifiedAptosConfig.clientConfig?.HEADERS, ...modifiedAptosConfig.faucetConfig?.HEADERS },\n },\n });\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/general}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * general namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { getAptosFullNode, postAptosFullNode, postAptosIndexer } from \"../client\";\nimport {\n AnyNumber,\n Block,\n GetChainTopUserTransactionsResponse,\n GetProcessorStatusResponse,\n GraphqlQuery,\n LedgerInfo,\n LedgerVersionArg,\n TableItemRequest,\n} from \"../types\";\nimport { GetChainTopUserTransactionsQuery, GetProcessorStatusQuery } from \"../types/generated/operations\";\nimport { GetChainTopUserTransactions, GetProcessorStatus } from \"../types/generated/queries\";\nimport { ProcessorType } from \"../utils/const\";\n\nexport async function getLedgerInfo(args: { aptosConfig: AptosConfig }): Promise<LedgerInfo> {\n const { aptosConfig } = args;\n const { data } = await getAptosFullNode<{}, LedgerInfo>({\n aptosConfig,\n originMethod: \"getLedgerInfo\",\n path: \"\",\n });\n return data;\n}\n\nexport async function getBlockByVersion(args: {\n aptosConfig: AptosConfig;\n ledgerVersion: AnyNumber;\n options?: { withTransactions?: boolean };\n}): Promise<Block> {\n const { aptosConfig, ledgerVersion, options } = args;\n const { data } = await getAptosFullNode<{}, Block>({\n aptosConfig,\n originMethod: \"getBlockByVersion\",\n path: `blocks/by_version/${ledgerVersion}`,\n params: { with_transactions: options?.withTransactions },\n });\n return data;\n}\n\nexport async function getBlockByHeight(args: {\n aptosConfig: AptosConfig;\n blockHeight: AnyNumber;\n options?: { withTransactions?: boolean };\n}): Promise<Block> {\n const { aptosConfig, blockHeight, options } = args;\n const { data } = await getAptosFullNode<{}, Block>({\n aptosConfig,\n originMethod: \"getBlockByHeight\",\n path: `blocks/by_height/${blockHeight}`,\n params: { with_transactions: options?.withTransactions },\n });\n return data;\n}\n\nexport async function getTableItem<T>(args: {\n aptosConfig: AptosConfig;\n handle: string;\n data: TableItemRequest;\n options?: LedgerVersionArg;\n}): Promise<T> {\n const { aptosConfig, handle, data, options } = args;\n const response = await postAptosFullNode<TableItemRequest, any>({\n aptosConfig,\n originMethod: \"getTableItem\",\n path: `tables/${handle}/item`,\n params: { ledger_version: options?.ledgerVersion },\n body: data,\n });\n return response.data as T;\n}\n\nexport async function getChainTopUserTransactions(args: {\n aptosConfig: AptosConfig;\n limit: number;\n}): Promise<GetChainTopUserTransactionsResponse> {\n const { aptosConfig, limit } = args;\n const graphqlQuery = {\n query: GetChainTopUserTransactions,\n variables: { limit },\n };\n\n const data = await queryIndexer<GetChainTopUserTransactionsQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getChainTopUserTransactions\",\n });\n\n return data.user_transactions;\n}\n\nexport async function queryIndexer<T extends {}>(args: {\n aptosConfig: AptosConfig;\n query: GraphqlQuery;\n originMethod?: string;\n}): Promise<T> {\n const { aptosConfig, query, originMethod } = args;\n const { data } = await postAptosIndexer<GraphqlQuery, T>({\n aptosConfig,\n originMethod: originMethod ?? \"queryIndexer\",\n path: \"\",\n body: query,\n overrides: { WITH_CREDENTIALS: false },\n });\n return data;\n}\n\nexport async function getProcessorStatuses(args: { aptosConfig: AptosConfig }): Promise<GetProcessorStatusResponse> {\n const { aptosConfig } = args;\n\n const graphqlQuery = {\n query: GetProcessorStatus,\n };\n\n const data = await queryIndexer<GetProcessorStatusQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getProcessorStatuses\",\n });\n\n return data.processor_status;\n}\n\nexport async function getIndexerLastSuccessVersion(args: { aptosConfig: AptosConfig }): Promise<bigint> {\n const response = await getProcessorStatuses({ aptosConfig: args.aptosConfig });\n return BigInt(response[0].last_success_version);\n}\n\nexport async function getProcessorStatus(args: {\n aptosConfig: AptosConfig;\n processorType: ProcessorType;\n}): Promise<GetProcessorStatusResponse[0]> {\n const { aptosConfig, processorType } = args;\n\n const whereCondition: { processor: { _eq: string } } = {\n processor: { _eq: processorType },\n };\n\n const graphqlQuery = {\n query: GetProcessorStatus,\n variables: {\n where_condition: whereCondition,\n },\n };\n\n const data = await queryIndexer<GetProcessorStatusQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getProcessorStatus\",\n });\n\n return data.processor_status[0];\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/staking}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * faucet namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { AccountAddress, AccountAddressInput } from \"../core\";\nimport { GetDelegatedStakingActivitiesResponse, GetNumberOfDelegatorsResponse, OrderByArg } from \"../types\";\nimport { GetDelegatedStakingActivitiesQuery, GetNumberOfDelegatorsQuery } from \"../types/generated/operations\";\nimport { GetDelegatedStakingActivities, GetNumberOfDelegators } from \"../types/generated/queries\";\nimport { queryIndexer } from \"./general\";\n\nexport async function getNumberOfDelegators(args: {\n aptosConfig: AptosConfig;\n poolAddress: AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, poolAddress } = args;\n const address = AccountAddress.from(poolAddress).toStringLong();\n const query = {\n query: GetNumberOfDelegators,\n variables: { where_condition: { pool_address: { _eq: address } } },\n };\n const data = await queryIndexer<GetNumberOfDelegatorsQuery>({ aptosConfig, query });\n\n // commonjs (aka cjs) doesnt handle Nullish Coalescing for some reason\n // might be because of how ts infer the graphql generated scheme type\n return data.num_active_delegator_per_pool[0] ? data.num_active_delegator_per_pool[0].num_active_delegator : 0;\n}\n\nexport async function getNumberOfDelegatorsForAllPools(args: {\n aptosConfig: AptosConfig;\n options?: OrderByArg<GetNumberOfDelegatorsResponse[0]>;\n}): Promise<GetNumberOfDelegatorsResponse> {\n const { aptosConfig, options } = args;\n const query = {\n query: GetNumberOfDelegators,\n variables: { order_by: options?.orderBy },\n };\n const data = await queryIndexer<GetNumberOfDelegatorsQuery>({\n aptosConfig,\n query,\n });\n return data.num_active_delegator_per_pool;\n}\n\nexport async function getDelegatedStakingActivities(args: {\n aptosConfig: AptosConfig;\n delegatorAddress: AccountAddressInput;\n poolAddress: AccountAddressInput;\n}): Promise<GetDelegatedStakingActivitiesResponse> {\n const { aptosConfig, delegatorAddress, poolAddress } = args;\n const query = {\n query: GetDelegatedStakingActivities,\n variables: {\n delegatorAddress: AccountAddress.from(delegatorAddress).toStringLong(),\n poolAddress: AccountAddress.from(poolAddress).toStringLong(),\n },\n };\n const data = await queryIndexer<GetDelegatedStakingActivitiesQuery>({ aptosConfig, query });\n return data.delegated_staking_activities;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Sleep the current thread for the given amount of time\n * @param timeMs time in milliseconds to sleep\n */\nexport async function sleep(timeMs: number): Promise<null> {\n return new Promise((resolve) => {\n setTimeout(resolve, timeMs);\n });\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * The global cache Map shared across all functions. Must keep care to ensure that the\n * cache keys are unique across all functions.\n */\nconst cache = new Map<string, { value: any; timestamp: number }>();\n\n/**\n * A memoize high order function to cache async function response\n *\n * @param func An async function to cache the result of\n * @param key The provided cache key\n * @param ttlMs time-to-live in milliseconds for cached data\n * @returns the cached or latest result\n */\nexport function memoizeAsync<T>(\n func: (...args: any[]) => Promise<T>,\n key: string,\n ttlMs?: number,\n): (...args: any[]) => Promise<T> {\n return async (...args: any[]) => {\n // Check if the cached result exists and is within TTL\n if (cache.has(key)) {\n const { value, timestamp } = cache.get(key)!;\n if (ttlMs === undefined || Date.now() - timestamp <= ttlMs) {\n return value;\n }\n }\n\n // If not cached or TTL expired, compute the result\n const result = await func(...args);\n\n // Cache the result with a timestamp\n cache.set(key, { value: result, timestamp: Date.now() });\n\n return result;\n };\n}\n\n/**\n * A memoize high order function to cache function response\n *\n * @param func A function to cache the result of\n * @param key The provided cache key\n * @param ttlMs time-to-live in milliseconds for cached data\n * @returns the cached or latest result\n */\nexport function memoize<T>(func: (...args: any[]) => T, key: string, ttlMs?: number): (...args: any[]) => T {\n return (...args: any[]) => {\n // Check if the cached result exists and is within TTL\n if (cache.has(key)) {\n const { value, timestamp } = cache.get(key)!;\n if (ttlMs === undefined || Date.now() - timestamp <= ttlMs) {\n return value;\n }\n }\n\n // If not cached or TTL expired, compute the result\n const result = func(...args);\n\n // Cache the result with a timestamp\n cache.set(key, { value: result, timestamp: Date.now() });\n\n return result;\n };\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Type of API endpoint for request routing\n */\nexport enum AptosApiType {\n FULLNODE = \"Fullnode\",\n INDEXER = \"Indexer\",\n FAUCET = \"Faucet\",\n}\n\n/**\n * The default max gas amount when none is given.\n *\n * This is the maximum number of gas units that will be used by a transaction before being rejected.\n *\n * Note that max gas amount varies based on the transaction. A larger transaction will go over this\n * default gas amount, and the value will need to be changed for the specific transaction.\n */\nexport const DEFAULT_MAX_GAS_AMOUNT = 200000;\n\n/**\n * The default transaction expiration seconds from now.\n *\n * This time is how long until the blockchain nodes will reject the transaction.\n *\n * Note that the transaction expiration time varies based on network connection and network load. It may need to be\n * increased for the transaction to be processed.\n */\nexport const DEFAULT_TXN_EXP_SEC_FROM_NOW = 20;\n\n/**\n * The default number of seconds to wait for a transaction to be processed.\n *\n * This time is the amount of time that the SDK will wait for a transaction to be processed when waiting for\n * the results of the transaction. It may take longer based on network connection and network load.\n */\nexport const DEFAULT_TXN_TIMEOUT_SEC = 20;\n\n/**\n * The default gas currency for the network.\n */\nexport const APTOS_COIN = \"0x1::aptos_coin::AptosCoin\";\n\nexport const RAW_TRANSACTION_SALT = \"APTOS::RawTransaction\";\nexport const RAW_TRANSACTION_WITH_DATA_SALT = \"APTOS::RawTransactionWithData\";\n\n/**\n * The list of supported Processor types for our indexer api.\n *\n * These can be found from the processor_status table in the indexer database.\n * {@link https://cloud.hasura.io/public/graphiql?endpoint=https://api.mainnet.aptoslabs.com/v1/graphql}\n */\nexport enum ProcessorType {\n ACCOUNT_TRANSACTION_PROCESSOR = \"account_transactions_processor\",\n DEFAULT = \"default_processor\",\n EVENTS_PROCESSOR = \"events_processor\",\n // Fungible asset processor also handles coins\n FUNGIBLE_ASSET_PROCESSOR = \"fungible_asset_processor\",\n STAKE_PROCESSOR = \"stake_processor\",\n // Token V2 processor replaces Token processor (not only for digital assets)\n TOKEN_V2_PROCESSOR = \"token_v2_processor\",\n USER_TRANSACTION_PROCESSOR = \"user_transaction_processor\",\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/transaction}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * transaction namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { AptosApiError, getAptosFullNode, paginateWithCursor } from \"../client\";\nimport {\n TransactionResponseType,\n type AnyNumber,\n type GasEstimation,\n type HexInput,\n type PaginationArgs,\n type TransactionResponse,\n WaitForTransactionOptions,\n CommittedTransactionResponse,\n} from \"../types\";\nimport { DEFAULT_TXN_TIMEOUT_SEC, ProcessorType } from \"../utils/const\";\nimport { sleep } from \"../utils/helpers\";\nimport { memoizeAsync } from \"../utils/memoize\";\nimport { getIndexerLastSuccessVersion, getProcessorStatus } from \"./general\";\n\nexport async function getTransactions(args: {\n aptosConfig: AptosConfig;\n options?: PaginationArgs;\n}): Promise<TransactionResponse[]> {\n const { aptosConfig, options } = args;\n return paginateWithCursor<{}, TransactionResponse[]>({\n aptosConfig,\n originMethod: \"getTransactions\",\n path: \"transactions\",\n params: { start: options?.offset, limit: options?.limit },\n });\n}\n\nexport async function getGasPriceEstimation(args: { aptosConfig: AptosConfig }) {\n const { aptosConfig } = args;\n\n return memoizeAsync(\n async () => {\n const { data } = await getAptosFullNode<{}, GasEstimation>({\n aptosConfig,\n originMethod: \"getGasPriceEstimation\",\n path: \"estimate_gas_price\",\n });\n return data;\n },\n `gas-price-${aptosConfig.network}`,\n 1000 * 60 * 5, // 5 minutes\n )();\n}\n\nexport async function getTransactionByVersion(args: {\n aptosConfig: AptosConfig;\n ledgerVersion: AnyNumber;\n}): Promise<TransactionResponse> {\n const { aptosConfig, ledgerVersion } = args;\n const { data } = await getAptosFullNode<{}, TransactionResponse>({\n aptosConfig,\n originMethod: \"getTransactionByVersion\",\n path: `transactions/by_version/${ledgerVersion}`,\n });\n return data;\n}\n\nexport async function getTransactionByHash(args: {\n aptosConfig: AptosConfig;\n transactionHash: HexInput;\n}): Promise<TransactionResponse> {\n const { aptosConfig, transactionHash } = args;\n const { data } = await getAptosFullNode<{}, TransactionResponse>({\n aptosConfig,\n path: `transactions/by_hash/${transactionHash}`,\n originMethod: \"getTransactionByHash\",\n });\n return data;\n}\n\nexport async function isTransactionPending(args: {\n aptosConfig: AptosConfig;\n transactionHash: HexInput;\n}): Promise<boolean> {\n const { aptosConfig, transactionHash } = args;\n try {\n const transaction = await getTransactionByHash({ aptosConfig, transactionHash });\n return transaction.type === TransactionResponseType.Pending;\n } catch (e: any) {\n if (e?.status === 404) {\n return true;\n }\n throw e;\n }\n}\n\nexport async function longWaitForTransaction(args: {\n aptosConfig: AptosConfig;\n transactionHash: HexInput;\n}): Promise<TransactionResponse> {\n const { aptosConfig, transactionHash } = args;\n const { data } = await getAptosFullNode<{}, TransactionResponse>({\n aptosConfig,\n path: `transactions/wait_by_hash/${transactionHash}`,\n originMethod: \"longWaitForTransaction\",\n });\n return data;\n}\n\nexport async function waitForTransaction(args: {\n aptosConfig: AptosConfig;\n transactionHash: HexInput;\n options?: WaitForTransactionOptions;\n}): Promise<CommittedTransactionResponse> {\n const { aptosConfig, transactionHash, options } = args;\n const timeoutSecs = options?.timeoutSecs ?? DEFAULT_TXN_TIMEOUT_SEC;\n const checkSuccess = options?.checkSuccess ?? true;\n\n let isPending = true;\n let timeElapsed = 0;\n let lastTxn: TransactionResponse | undefined;\n let lastError: AptosApiError | undefined;\n let backoffIntervalMs = 200;\n const backoffMultiplier = 1.5;\n\n function handleAPIError(e: any) {\n // In short, this means we will retry if it was an AptosApiError and the code was 404 or 5xx.\n const isAptosApiError = e instanceof AptosApiError;\n if (!isAptosApiError) {\n throw e; // This would be unexpected\n }\n lastError = e;\n const isRequestError = e.status !== 404 && e.status >= 400 && e.status < 500;\n if (isRequestError) {\n throw e;\n }\n }\n\n // check to see if the txn is already on the blockchain\n try {\n lastTxn = await getTransactionByHash({ aptosConfig, transactionHash });\n isPending = lastTxn.type === TransactionResponseType.Pending;\n } catch (e) {\n handleAPIError(e);\n }\n\n // If the transaction is pending, we do a long wait once to avoid polling\n if (isPending) {\n const startTime = Date.now();\n try {\n lastTxn = await longWaitForTransaction({ aptosConfig, transactionHash });\n isPending = lastTxn.type === TransactionResponseType.Pending;\n } catch (e) {\n handleAPIError(e);\n }\n timeElapsed = (Date.now() - startTime) / 1000;\n }\n\n // Now we do polling to see if the transaction is still pending\n while (isPending) {\n if (timeElapsed >= timeoutSecs) {\n break;\n }\n try {\n // eslint-disable-next-line no-await-in-loop\n lastTxn = await getTransactionByHash({ aptosConfig, transactionHash });\n\n isPending = lastTxn.type === TransactionResponseType.Pending;\n\n if (!isPending) {\n break;\n }\n } catch (e) {\n handleAPIError(e);\n }\n // eslint-disable-next-line no-await-in-loop\n await sleep(backoffIntervalMs);\n timeElapsed += backoffIntervalMs / 1000; // Convert to seconds\n backoffIntervalMs *= backoffMultiplier;\n }\n\n // There is a chance that lastTxn is still undefined. Let's throw the last error otherwise a WaitForTransactionError\n if (lastTxn === undefined) {\n if (lastError) {\n throw lastError;\n } else {\n throw new WaitForTransactionError(\n `Fetching transaction ${transactionHash} failed and timed out after ${timeoutSecs} seconds`,\n lastTxn,\n );\n }\n }\n\n if (lastTxn.type === TransactionResponseType.Pending) {\n throw new WaitForTransactionError(\n `Transaction ${transactionHash} timed out in pending state after ${timeoutSecs} seconds`,\n lastTxn,\n );\n }\n if (!checkSuccess) {\n return lastTxn;\n }\n if (!lastTxn.success) {\n throw new FailedTransactionError(\n `Transaction ${transactionHash} failed with an error: ${lastTxn.vm_status}`,\n lastTxn,\n );\n }\n\n return lastTxn;\n}\n\n/**\n * Waits for the indexer to sync up to the ledgerVersion. Timeout is 3 seconds.\n */\nexport async function waitForIndexer(args: {\n aptosConfig: AptosConfig;\n minimumLedgerVersion: AnyNumber;\n processorType?: ProcessorType;\n}): Promise<void> {\n const { aptosConfig, processorType } = args;\n const minimumLedgerVersion = BigInt(args.minimumLedgerVersion);\n const timeoutMilliseconds = 3000; // 3 seconds\n const startTime = new Date().getTime();\n let indexerVersion = BigInt(-1);\n\n while (indexerVersion < minimumLedgerVersion) {\n // check for timeout\n if (new Date().getTime() - startTime > timeoutMilliseconds) {\n throw new Error(\"waitForLastSuccessIndexerVersionSync timeout\");\n }\n\n if (processorType === undefined) {\n // Get the last success version from all processor\n // eslint-disable-next-line no-await-in-loop\n indexerVersion = await getIndexerLastSuccessVersion({ aptosConfig });\n } else {\n // Get the last success version from the specific processor\n // eslint-disable-next-line no-await-in-loop\n const processor = await getProcessorStatus({ aptosConfig, processorType });\n indexerVersion = processor.last_success_version;\n }\n\n if (indexerVersion >= minimumLedgerVersion) {\n // break out immediately if we are synced\n break;\n }\n\n // eslint-disable-next-line no-await-in-loop\n await sleep(200);\n }\n}\n\n/**\n * This error is used by `waitForTransaction` when waiting for a\n * transaction to time out or when the transaction response is undefined\n */\nexport class WaitForTransactionError extends Error {\n public readonly lastSubmittedTransaction: TransactionResponse | undefined;\n\n constructor(message: string, lastSubmittedTransaction: TransactionResponse | undefined) {\n super(message);\n this.lastSubmittedTransaction = lastSubmittedTransaction;\n }\n}\n\n/**\n * This error is used by `waitForTransaction` if `checkSuccess` is true.\n * See that function for more information.\n */\nexport class FailedTransactionError extends Error {\n public readonly transaction: TransactionResponse;\n\n constructor(message: string, transaction: TransactionResponse) {\n super(message);\n this.transaction = transaction;\n }\n}\n","import { waitForIndexer } from \"../internal/transaction\";\nimport { ProcessorType } from \"../utils\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { AnyNumber } from \"../types\";\n\n/**\n * Utility function to handle optional waiting on indexer for APIs\n *\n * This is purposely placed here to not expose this internal function.\n * @param args\n */\nexport async function waitForIndexerOnVersion(args: {\n config: AptosConfig;\n minimumLedgerVersion?: AnyNumber;\n processorType: ProcessorType;\n}) {\n if (args.minimumLedgerVersion !== undefined) {\n await waitForIndexer({\n aptosConfig: args.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: args.processorType,\n });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n getDelegatedStakingActivities,\n getNumberOfDelegators,\n getNumberOfDelegatorsForAllPools,\n} from \"../internal/staking\";\nimport { AnyNumber, GetDelegatedStakingActivitiesResponse, GetNumberOfDelegatorsResponse, OrderByArg } from \"../types\";\nimport { AccountAddressInput } from \"../core\";\nimport { ProcessorType } from \"../utils/const\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexerOnVersion } from \"./utils\";\n\n/**\n * A class to query all `Staking` related queries on Aptos.\n */\nexport class Staking {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries current number of delegators in a pool. Throws an error if the pool is not found.\n *\n * @example\n * const delegators = await aptos.getNumberOfDelegators({poolAddress:\"0x123\"})\n *\n * @param args.poolAddress Pool address\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns The number of delegators for the given pool\n */\n async getNumberOfDelegators(args: {\n poolAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.STAKE_PROCESSOR,\n });\n return getNumberOfDelegators({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries current number of delegators in a pool. Throws an error if the pool is not found.\n *\n * @example\n * const delegators = await aptos.getNumberOfDelegatorsForAllPools()\n *\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns GetNumberOfDelegatorsForAllPoolsResponse response type\n */\n async getNumberOfDelegatorsForAllPools(args?: {\n minimumLedgerVersion?: AnyNumber;\n options?: OrderByArg<GetNumberOfDelegatorsResponse[0]>;\n }): Promise<GetNumberOfDelegatorsResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.STAKE_PROCESSOR,\n });\n return getNumberOfDelegatorsForAllPools({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries delegated staking activities\n *\n * @example\n * const delegators = await aptos.getDelegatedStakingActivities({delegatorAddress:\"0x123\",poolAddress:\"0x456\"})\n *\n * @param args.delegatorAddress Delegator address\n * @param args.poolAddress Pool address\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns GetDelegatedStakingActivitiesResponse response type\n */\n async getDelegatedStakingActivities(args: {\n delegatorAddress: AccountAddressInput;\n poolAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetDelegatedStakingActivitiesResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.STAKE_PROCESSOR,\n });\n return getDelegatedStakingActivities({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\n\n/**\n * Representation of an Identifier that can serialized and deserialized.\n * We use Identifier to represent the module \"name\" in \"ModuleId\" and\n * the \"function name\" in \"EntryFunction\"\n */\nexport class Identifier extends Serializable {\n public identifier: string;\n\n constructor(identifier: string) {\n super();\n this.identifier = identifier;\n }\n\n public serialize(serializer: Serializer): void {\n serializer.serializeStr(this.identifier);\n }\n\n static deserialize(deserializer: Deserializer): Identifier {\n const identifier = deserializer.deserializeStr();\n return new Identifier(identifier);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable max-classes-per-file */\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { AccountAddress } from \"../../core\";\nimport { Identifier } from \"../instances/identifier\";\nimport { TypeTagVariants } from \"../../types\";\n\nexport abstract class TypeTag extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n static deserialize(deserializer: Deserializer): TypeTag {\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TypeTagVariants.Bool:\n return TypeTagBool.load(deserializer);\n case TypeTagVariants.U8:\n return TypeTagU8.load(deserializer);\n case TypeTagVariants.U64:\n return TypeTagU64.load(deserializer);\n case TypeTagVariants.U128:\n return TypeTagU128.load(deserializer);\n case TypeTagVariants.Address:\n return TypeTagAddress.load(deserializer);\n case TypeTagVariants.Signer:\n return TypeTagSigner.load(deserializer);\n case TypeTagVariants.Vector:\n return TypeTagVector.load(deserializer);\n case TypeTagVariants.Struct:\n return TypeTagStruct.load(deserializer);\n case TypeTagVariants.U16:\n return TypeTagU16.load(deserializer);\n case TypeTagVariants.U32:\n return TypeTagU32.load(deserializer);\n case TypeTagVariants.U256:\n return TypeTagU256.load(deserializer);\n case TypeTagVariants.Generic:\n // This is only used for ABI representation, and cannot actually be used as a type.\n return TypeTagGeneric.load(deserializer);\n default:\n throw new Error(`Unknown variant index for TypeTag: ${index}`);\n }\n }\n\n abstract toString(): string;\n\n isBool(): this is TypeTagBool {\n return this instanceof TypeTagBool;\n }\n\n isAddress(): this is TypeTagAddress {\n return this instanceof TypeTagAddress;\n }\n\n isGeneric(): this is TypeTagGeneric {\n return this instanceof TypeTagGeneric;\n }\n\n isSigner(): this is TypeTagSigner {\n return this instanceof TypeTagSigner;\n }\n\n isVector(): this is TypeTagVector {\n return this instanceof TypeTagVector;\n }\n\n isStruct(): this is TypeTagStruct {\n return this instanceof TypeTagStruct;\n }\n\n isU8(): this is TypeTagU8 {\n return this instanceof TypeTagU8;\n }\n\n isU16(): this is TypeTagU16 {\n return this instanceof TypeTagU16;\n }\n\n isU32(): this is TypeTagU32 {\n return this instanceof TypeTagU32;\n }\n\n isU64(): this is TypeTagU64 {\n return this instanceof TypeTagU64;\n }\n\n isU128(): this is TypeTagU128 {\n return this instanceof TypeTagU128;\n }\n\n isU256(): this is TypeTagU256 {\n return this instanceof TypeTagU256;\n }\n}\n\nexport class TypeTagBool extends TypeTag {\n toString(): string {\n return \"bool\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Bool);\n }\n\n static load(_deserializer: Deserializer): TypeTagBool {\n return new TypeTagBool();\n }\n}\n\nexport class TypeTagU8 extends TypeTag {\n toString(): string {\n return \"u8\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.U8);\n }\n\n static load(_deserializer: Deserializer): TypeTagU8 {\n return new TypeTagU8();\n }\n}\n\nexport class TypeTagU16 extends TypeTag {\n toString(): string {\n return \"u16\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.U16);\n }\n\n static load(_deserializer: Deserializer): TypeTagU16 {\n return new TypeTagU16();\n }\n}\n\nexport class TypeTagU32 extends TypeTag {\n toString(): string {\n return \"u32\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.U32);\n }\n\n static load(_deserializer: Deserializer): TypeTagU32 {\n return new TypeTagU32();\n }\n}\n\nexport class TypeTagU64 extends TypeTag {\n toString(): string {\n return \"u64\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.U64);\n }\n\n static load(_deserializer: Deserializer): TypeTagU64 {\n return new TypeTagU64();\n }\n}\n\nexport class TypeTagU128 extends TypeTag {\n toString(): string {\n return \"u128\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.U128);\n }\n\n static load(_deserializer: Deserializer): TypeTagU128 {\n return new TypeTagU128();\n }\n}\n\nexport class TypeTagU256 extends TypeTag {\n toString(): string {\n return \"u256\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.U256);\n }\n\n static load(_deserializer: Deserializer): TypeTagU256 {\n return new TypeTagU256();\n }\n}\n\nexport class TypeTagAddress extends TypeTag {\n toString(): string {\n return \"address\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Address);\n }\n\n static load(_deserializer: Deserializer): TypeTagAddress {\n return new TypeTagAddress();\n }\n}\n\nexport class TypeTagSigner extends TypeTag {\n toString(): string {\n return \"signer\";\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Signer);\n }\n\n static load(_deserializer: Deserializer): TypeTagSigner {\n return new TypeTagSigner();\n }\n}\n\nexport class TypeTagReference extends TypeTag {\n toString(): `&${string}` {\n return `&${this.value.toString()}`;\n }\n\n constructor(public readonly value: TypeTag) {\n super();\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Reference);\n }\n\n static load(deserializer: Deserializer): TypeTagReference {\n const value = TypeTag.deserialize(deserializer);\n return new TypeTagReference(value);\n }\n}\n\n/**\n * Generics are used for type parameters in entry functions. However,\n * they are not actually serialized into a real type, so they cannot be\n * used as a type directly.\n */\nexport class TypeTagGeneric extends TypeTag {\n toString(): `T${number}` {\n return `T${this.value}`;\n }\n\n constructor(public readonly value: number) {\n super();\n if (value < 0) throw new Error(\"Generic type parameter index cannot be negative\");\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Generic);\n serializer.serializeU32(this.value);\n }\n\n static load(deserializer: Deserializer): TypeTagGeneric {\n const value = deserializer.deserializeU32();\n return new TypeTagGeneric(value);\n }\n}\n\nexport class TypeTagVector extends TypeTag {\n toString(): `vector<${string}>` {\n return `vector<${this.value.toString()}>`;\n }\n\n constructor(public readonly value: TypeTag) {\n super();\n }\n\n static u8(): TypeTagVector {\n return new TypeTagVector(new TypeTagU8());\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Vector);\n this.value.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TypeTagVector {\n const value = TypeTag.deserialize(deserializer);\n return new TypeTagVector(value);\n }\n}\n\nexport class TypeTagStruct extends TypeTag {\n toString(): `0x${string}::${string}::${string}` {\n // Collect type args and add it if there are any\n let typePredicate = \"\";\n if (this.value.typeArgs.length > 0) {\n typePredicate = `<${this.value.typeArgs.map((typeArg) => typeArg.toString()).join(\", \")}>`;\n }\n\n return `${this.value.address.toString()}::${this.value.moduleName.identifier}::${\n this.value.name.identifier\n }${typePredicate}`;\n }\n\n constructor(public readonly value: StructTag) {\n super();\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Struct);\n this.value.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TypeTagStruct {\n const value = StructTag.deserialize(deserializer);\n return new TypeTagStruct(value);\n }\n\n isTypeTag(address: AccountAddress, moduleName: string, structName: string): boolean {\n return (\n this.value.moduleName.identifier === moduleName &&\n this.value.name.identifier === structName &&\n this.value.address.equals(address)\n );\n }\n\n isString(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"string\", \"String\");\n }\n\n isOption(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"option\", \"Option\");\n }\n\n isObject(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"object\", \"Object\");\n }\n}\n\nexport class StructTag extends Serializable {\n public readonly address: AccountAddress;\n\n public readonly moduleName: Identifier;\n\n public readonly name: Identifier;\n\n public readonly typeArgs: Array<TypeTag>;\n\n constructor(address: AccountAddress, module_name: Identifier, name: Identifier, type_args: Array<TypeTag>) {\n super();\n this.address = address;\n this.moduleName = module_name;\n this.name = name;\n this.typeArgs = type_args;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serialize(this.address);\n serializer.serialize(this.moduleName);\n serializer.serialize(this.name);\n serializer.serializeVector(this.typeArgs);\n }\n\n static deserialize(deserializer: Deserializer): StructTag {\n const address = AccountAddress.deserialize(deserializer);\n const moduleName = Identifier.deserialize(deserializer);\n const name = Identifier.deserialize(deserializer);\n const typeArgs = deserializer.deserializeVector(TypeTag);\n return new StructTag(address, moduleName, name, typeArgs);\n }\n}\n\nexport function aptosCoinStructTag(): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"aptos_coin\"), new Identifier(\"AptosCoin\"), []);\n}\n\nexport function stringStructTag(): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"string\"), new Identifier(\"String\"), []);\n}\n\nexport function optionStructTag(typeArg: TypeTag): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"option\"), new Identifier(\"Option\"), [typeArg]);\n}\n\nexport function objectStructTag(typeArg: TypeTag): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"object\"), new Identifier(\"Object\"), [typeArg]);\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n StructTag,\n TypeTag,\n TypeTagAddress,\n TypeTagBool,\n TypeTagGeneric,\n TypeTagReference,\n TypeTagSigner,\n TypeTagStruct,\n TypeTagU128,\n TypeTagU16,\n TypeTagU256,\n TypeTagU32,\n TypeTagU64,\n TypeTagU8,\n TypeTagVector,\n} from \".\";\nimport { AccountAddress } from \"../../core\";\nimport { Identifier } from \"../instances/identifier\";\n\nfunction isValidIdentifier(str: string) {\n return !!str.match(/^[_a-zA-Z0-9]+$/);\n}\n\nfunction isValidWhitespaceCharacter(char: string) {\n return !!char.match(/\\s/);\n}\n\nfunction isGeneric(str: string) {\n return !!str.match(/^T[0-9]+$/);\n}\n\nfunction consumeWhitespace(tagStr: string, pos: number) {\n let i = pos;\n for (; i < tagStr.length; i += 1) {\n const innerChar = tagStr[i];\n\n if (!isValidWhitespaceCharacter(innerChar)) {\n // If it's not colons, and it's an invalid character, we will stop here\n break;\n }\n }\n return i;\n}\n\ntype TypeTagState = {\n savedExpectedTypes: number;\n savedStr: string;\n savedTypes: Array<TypeTag>;\n};\n\nexport enum TypeTagParserErrorType {\n InvalidTypeTag = \"unknown type\",\n UnexpectedGenericType = \"unexpected generic type\",\n UnexpectedTypeArgumentClose = \"unexpected '>'\",\n UnexpectedWhitespaceCharacter = \"unexpected whitespace character\",\n UnexpectedComma = \"unexpected ','\",\n TypeArgumentCountMismatch = \"type argument count doesn't match expected amount\",\n MissingTypeArgumentClose = \"no matching '>' for '<'\",\n UnexpectedPrimitiveTypeArguments = \"primitive types not expected to have type arguments\",\n UnexpectedVectorTypeArgumentCount = \"vector type expected to have exactly one type argument\",\n UnexpectedStructFormat = \"unexpected struct format, must be of the form 0xaddress::module_name::struct_name\",\n InvalidModuleNameCharacter = \"module name must only contain alphanumeric or '_' characters\",\n InvalidStructNameCharacter = \"struct name must only contain alphanumeric or '_' characters\",\n}\n\nexport class TypeTagParserError extends Error {\n constructor(typeTagStr: string, invalidReason: TypeTagParserErrorType) {\n super(`Failed to parse typeTag '${typeTagStr}', ${invalidReason}`);\n }\n}\n\n/**\n * All types are made of a few parts they're either:\n * 1. A simple type e.g. u8\n * 2. A standalone struct e.g. 0x1::account::Account\n * 3. A nested struct e.g. 0x1::coin::Coin<0x1234::coin::MyCoin>\n *\n * There are a few more special cases that need to be handled, however.\n * 1. Multiple generics e.g 0x1::pair::Pair<u8, u16>\n * 2. Spacing in the generics e.g. 0x1::pair::Pair< u8 , u16>\n * 3. Nested generics of different depths e.g. 0x1::pair::Pair<0x1::coin::Coin<0x1234::coin::MyCoin>, u8>\n * 4. Generics for types in ABIs are filled in with placeholders e.g T1, T2, T3\n */\nexport function parseTypeTag(typeStr: string, options?: { allowGenerics?: boolean }) {\n const allowGenerics = options?.allowGenerics ?? false;\n\n const saved: Array<TypeTagState> = [];\n // This represents the internal types for a type tag e.g. '0x1::coin::Coin<innerTypes>'\n let innerTypes: Array<TypeTag> = [];\n // This represents the current parsed types in a comma list e.g. 'u8, u8'\n let curTypes: Array<TypeTag> = [];\n // This represents the current character index\n let cur: number = 0;\n // This represents the current working string as a type or struct name\n let currentStr: string = \"\";\n let expectedTypes: number = 1;\n\n // Iterate through each character, and handle the border conditions\n while (cur < typeStr.length) {\n const char = typeStr[cur];\n\n if (char === \"<\") {\n // Start of a type argument, push current state onto a stack\n saved.push({\n savedExpectedTypes: expectedTypes,\n savedStr: currentStr,\n savedTypes: curTypes,\n });\n\n // Clear current state\n currentStr = \"\";\n curTypes = [];\n expectedTypes = 1;\n } else if (char === \">\") {\n // Process last type, if there is no type string, then don't parse it\n if (currentStr !== \"\") {\n const newType = parseTypeTagInner(currentStr, innerTypes, allowGenerics);\n curTypes.push(newType);\n }\n\n // Pop off stack outer type, if there's nothing left, there were too many '>'\n const savedPop = saved.pop();\n if (savedPop === undefined) {\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.UnexpectedTypeArgumentClose);\n }\n\n // If the expected types don't match the number of commas, then we also fail\n if (expectedTypes !== curTypes.length) {\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.TypeArgumentCountMismatch);\n }\n\n // Add in the new created type, shifting the current types to the inner types\n const { savedStr, savedTypes, savedExpectedTypes } = savedPop;\n innerTypes = curTypes;\n curTypes = savedTypes;\n currentStr = savedStr;\n expectedTypes = savedExpectedTypes;\n } else if (char === \",\") {\n // Comma means we need to start parsing a new tag, push the previous one to the curTypes\n // Process last type, if there is no type string, then don't parse it\n if (currentStr.length !== 0) {\n const newType = parseTypeTagInner(currentStr, innerTypes, allowGenerics);\n\n // parse type tag and push it on the types\n innerTypes = [];\n curTypes.push(newType);\n currentStr = \"\";\n expectedTypes += 1;\n }\n } else if (isValidWhitespaceCharacter(char)) {\n // This means we should save what we have and everything else should skip until the next\n let parsedTypeTag = false;\n if (currentStr.length !== 0) {\n const newType = parseTypeTagInner(currentStr, innerTypes, allowGenerics);\n\n // parse type tag and push it on the types\n innerTypes = [];\n curTypes.push(newType);\n currentStr = \"\";\n parsedTypeTag = true;\n }\n\n // Skip ahead on any more whitespace\n cur = consumeWhitespace(typeStr, cur);\n\n // The next space MUST be a comma, or a closing > if there was something parsed before\n // e.g. `u8 u8` is invalid but `u8, u8` is valid\n const nextChar = typeStr[cur];\n if (cur < typeStr.length && parsedTypeTag && nextChar !== \",\" && nextChar !== \">\") {\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.UnexpectedWhitespaceCharacter);\n }\n\n // eslint-disable-next-line no-continue\n continue;\n } else {\n // Any other characters just append to the current string\n currentStr += char;\n }\n\n cur += 1;\n }\n\n // This prevents a missing '>' on type arguments\n if (saved.length > 0) {\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.MissingTypeArgumentClose);\n }\n\n // This prevents 'u8, u8' as an input\n switch (curTypes.length) {\n case 0:\n return parseTypeTagInner(currentStr, innerTypes, allowGenerics);\n case 1:\n if (currentStr === \"\") {\n return curTypes[0];\n }\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.UnexpectedComma);\n default:\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.UnexpectedWhitespaceCharacter);\n }\n}\n\n/**\n * Parses a type tag with internal types associated\n * @param str\n * @param types\n */\nfunction parseTypeTagInner(str: string, types: Array<TypeTag>, allowGenerics: boolean): TypeTag {\n // TODO: Parse references to any item not just signer\n switch (str) {\n case \"&signer\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagReference(new TypeTagSigner());\n case \"signer\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagSigner();\n case \"bool\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagBool();\n case \"address\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagAddress();\n case \"u8\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagU8();\n case \"u16\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagU16();\n case \"u32\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagU32();\n case \"u64\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagU64();\n case \"u128\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagU128();\n case \"u256\":\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n return new TypeTagU256();\n case \"vector\":\n if (types.length !== 1) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedVectorTypeArgumentCount);\n }\n return new TypeTagVector(types[0]);\n default:\n if (isGeneric(str)) {\n if (allowGenerics) {\n return new TypeTagGeneric(Number(str.split(\"T\")[1]));\n }\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedGenericType);\n }\n\n // If the value doesn't contain a colon, then we'll assume it isn't trying to be a struct\n if (!str.match(/:/)) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.InvalidTypeTag);\n }\n\n // Parse for a struct tag\n // eslint-disable-next-line no-case-declarations\n const structParts = str.split(\"::\");\n if (structParts.length !== 3) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedStructFormat);\n }\n\n // Validate identifier characters\n if (!isValidIdentifier(structParts[1])) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.InvalidModuleNameCharacter);\n }\n if (!isValidIdentifier(structParts[2])) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.InvalidStructNameCharacter);\n }\n\n return new TypeTagStruct(\n new StructTag(\n AccountAddress.fromString(structParts[0]),\n new Identifier(structParts[1]),\n new Identifier(structParts[2]),\n types,\n ),\n );\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n MAX_U128_BIG_INT,\n MAX_U16_NUMBER,\n MAX_U32_NUMBER,\n MAX_U64_BIG_INT,\n MAX_U8_NUMBER,\n MAX_U256_BIG_INT,\n} from \"../consts\";\nimport { Deserializer } from \"../deserializer\";\nimport { Serializable, Serializer, ensureBoolean, validateNumberInRange } from \"../serializer\";\nimport { TransactionArgument } from \"../../transactions/instances/transactionArgument\";\nimport { AnyNumber, Uint16, Uint32, Uint8, ScriptTransactionArgumentVariants } from \"../../types\";\n\nexport class Bool extends Serializable implements TransactionArgument {\n public readonly value: boolean;\n\n constructor(value: boolean) {\n super();\n ensureBoolean(value);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeBool(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.Bool);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): Bool {\n return new Bool(deserializer.deserializeBool());\n }\n}\n\nexport class U8 extends Serializable implements TransactionArgument {\n public readonly value: Uint8;\n\n constructor(value: Uint8) {\n super();\n validateNumberInRange(value, 0, MAX_U8_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU8(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U8);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U8 {\n return new U8(deserializer.deserializeU8());\n }\n}\n\nexport class U16 extends Serializable implements TransactionArgument {\n public readonly value: Uint16;\n\n constructor(value: Uint16) {\n super();\n validateNumberInRange(value, 0, MAX_U16_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU16(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U16);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U16 {\n return new U16(deserializer.deserializeU16());\n }\n}\n\nexport class U32 extends Serializable implements TransactionArgument {\n public readonly value: Uint32;\n\n constructor(value: Uint32) {\n super();\n validateNumberInRange(value, 0, MAX_U32_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U32);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U32 {\n return new U32(deserializer.deserializeU32());\n }\n}\n\nexport class U64 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U64_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU64(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U64);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U64 {\n return new U64(deserializer.deserializeU64());\n }\n}\n\nexport class U128 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U128_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU128(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U128);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U128 {\n return new U128(deserializer.deserializeU128());\n }\n}\n\nexport class U256 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U256_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU256(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U256);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U256 {\n return new U256(deserializer.deserializeU256());\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Bool, U128, U16, U256, U32, U64, U8 } from \"./movePrimitives\";\nimport { Serializable, Serializer } from \"../serializer\";\nimport { Deserializable, Deserializer } from \"../deserializer\";\nimport { AnyNumber, HexInput, ScriptTransactionArgumentVariants } from \"../../types\";\nimport { Hex } from \"../../core/hex\";\nimport { EntryFunctionArgument, TransactionArgument } from \"../../transactions/instances/transactionArgument\";\n\n/**\n * This class is the Aptos Typescript SDK representation of a Move `vector<T>`,\n * where `T` represents either a primitive type (`bool`, `u8`, `u64`, ...)\n * or a BCS-serializable struct itself.\n *\n * It is a BCS-serializable, array-like type that contains an array of values of type `T`,\n * where `T` is a class that implements `Serializable`.\n *\n * The purpose of this class is to facilitate easy construction of BCS-serializable\n * Move `vector<T>` types.\n *\n * @example\n * // in Move: `vector<u8> [1, 2, 3, 4];`\n * const vecOfU8s = new MoveVector<U8>([new U8(1), new U8(2), new U8(3), new U8(4)]);\n * // in Move: `std::bcs::to_bytes(vector<u8> [1, 2, 3, 4]);`\n * const bcsBytes = vecOfU8s.toUint8Array();\n *\n * // vector<vector<u8>> [ vector<u8> [1], vector<u8> [1, 2, 3, 4], vector<u8> [5, 6, 7, 8] ];\n * const vecOfVecs = new MoveVector<MoveVector<U8>>([\n * new MoveVector<U8>([new U8(1)]),\n * MoveVector.U8([1, 2, 3, 4]),\n * MoveVector.U8([5, 6, 7, 8]),\n * ]);\n *\n * // vector<Option<u8>> [ std::option::some<u8>(1), std::option::some<u8>(2) ];\n * const vecOfOptionU8s = new MoveVector<MoveOption<U8>>([\n * MoveOption.U8(1),\n * MoveOption.U8(2),\n * ]);\n *\n * // vector<MoveString> [ std::string::utf8(b\"hello\"), std::string::utf8(b\"world\") ];\n * const vecOfStrings = new MoveVector([new MoveString(\"hello\"), new MoveString(\"world\")]);\n * const vecOfStrings2 = MoveVector.MoveString([\"hello\", \"world\"]);\n *\n * @params\n * values: an Array<T> of values where T is a class that implements Serializable\n * @returns a `MoveVector<T>` with the values `values`\n */\nexport class MoveVector<T extends Serializable & EntryFunctionArgument>\n extends Serializable\n implements TransactionArgument\n{\n public values: Array<T>;\n\n constructor(values: Array<T>) {\n super();\n this.values = values;\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * NOTE: This function will only work when the inner values in the `MoveVector` are `U8`s.\n * @param serializer\n */\n serializeForScriptFunction(serializer: Serializer): void {\n // runtime check to ensure that you can't serialize anything other than vector<u8>\n const isU8 = this.values[0] instanceof U8;\n // if the inner array is length 0, we can't check the type because it has no instance, so we assume it's a u8\n // it may not be, but we don't care because regardless of a vector's type,\n // a zero-length vector is serialized to a single byte value: 0\n if (!isU8 && this.values[0] !== undefined) {\n throw new Error(\"Script function arguments only accept u8 vectors\");\n }\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U8Vector);\n serializer.serialize(this);\n }\n\n /**\n * Factory method to generate a MoveVector of U8s from an array of numbers.\n *\n * @example\n * const v = MoveVector.U8([1, 2, 3, 4]);\n * @params values: an array of `numbers` to convert to U8s\n * @returns a `MoveVector<U8>`\n */\n static U8(values: Array<number> | HexInput): MoveVector<U8> {\n let numbers: Array<number>;\n\n if (Array.isArray(values) && typeof values[0] === \"number\") {\n numbers = values;\n } else if (typeof values === \"string\") {\n const hex = Hex.fromHexInput(values);\n numbers = Array.from(hex.toUint8Array());\n } else if (values instanceof Uint8Array) {\n numbers = Array.from(values);\n } else {\n throw new Error(\"Invalid input type\");\n }\n\n return new MoveVector<U8>(numbers.map((v) => new U8(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of U16s from an array of numbers.\n *\n * @example\n * const v = MoveVector.U16([1, 2, 3, 4]);\n * @params values: an array of `numbers` to convert to U16s\n * @returns a `MoveVector<U16>`\n */\n static U16(values: Array<number>): MoveVector<U16> {\n return new MoveVector<U16>(values.map((v) => new U16(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of U32s from an array of numbers.\n *\n * @example\n * const v = MoveVector.U32([1, 2, 3, 4]);\n * @params values: an array of `numbers` to convert to U32s\n * @returns a `MoveVector<U32>`\n */\n static U32(values: Array<number>): MoveVector<U32> {\n return new MoveVector<U32>(values.map((v) => new U32(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of U64s from an array of numbers or bigints.\n *\n * @example\n * const v = MoveVector.U64([1, 2, 3, 4]);\n * @params values: an array of numbers of type `number | bigint` to convert to U64s\n * @returns a `MoveVector<U64>`\n */\n static U64(values: Array<AnyNumber>): MoveVector<U64> {\n return new MoveVector<U64>(values.map((v) => new U64(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of U128s from an array of numbers or bigints.\n *\n * @example\n * const v = MoveVector.U128([1, 2, 3, 4]);\n * @params values: an array of numbers of type `number | bigint` to convert to U128s\n * @returns a `MoveVector<U128>`\n */\n static U128(values: Array<AnyNumber>): MoveVector<U128> {\n return new MoveVector<U128>(values.map((v) => new U128(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of U256s from an array of numbers or bigints.\n *\n * @example\n * const v = MoveVector.U256([1, 2, 3, 4]);\n * @params values: an array of numbers of type `number | bigint` to convert to U256s\n * @returns a `MoveVector<U256>`\n */\n static U256(values: Array<AnyNumber>): MoveVector<U256> {\n return new MoveVector<U256>(values.map((v) => new U256(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of Bools from an array of booleans.\n *\n * @example\n * const v = MoveVector.Bool([true, false, true, false]);\n * @params values: an array of `bools` to convert to Bools\n * @returns a `MoveVector<Bool>`\n */\n static Bool(values: Array<boolean>): MoveVector<Bool> {\n return new MoveVector<Bool>(values.map((v) => new Bool(v)));\n }\n\n /**\n * Factory method to generate a MoveVector of MoveStrings from an array of strings.\n *\n * @example\n * const v = MoveVector.MoveString([\"hello\", \"world\"]);\n * @params values: an array of `strings` to convert to MoveStrings\n * @returns a `MoveVector<MoveString>`\n */\n static MoveString(values: Array<string>): MoveVector<MoveString> {\n return new MoveVector<MoveString>(values.map((v) => new MoveString(v)));\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeVector(this.values);\n }\n\n /**\n * Deserialize a MoveVector of type T, specifically where T is a Serializable and Deserializable type.\n *\n * NOTE: This only works with a depth of one. Generics will not work.\n *\n * NOTE: This will not work with types that aren't of the Serializable class.\n *\n * If you're looking for a more flexible deserialization function, you can use the deserializeVector function\n * in the Deserializer class.\n *\n * @example\n * const vec = MoveVector.deserialize(deserializer, U64);\n * @params deserializer: the Deserializer instance to use, with bytes loaded into it already.\n * cls: the class to typecast the input values to, must be a Serializable and Deserializable type.\n * @returns a MoveVector of the corresponding class T\n * *\n */\n static deserialize<T extends Serializable & EntryFunctionArgument>(\n deserializer: Deserializer,\n cls: Deserializable<T>,\n ): MoveVector<T> {\n const length = deserializer.deserializeUleb128AsU32();\n const values = new Array<T>();\n for (let i = 0; i < length; i += 1) {\n values.push(cls.deserialize(deserializer));\n }\n return new MoveVector(values);\n }\n}\n\nexport class MoveString extends Serializable implements TransactionArgument {\n public value: string;\n\n constructor(value: string) {\n super();\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeStr(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n // Serialize the string as a fixed byte string, i.e., without the length prefix\n const fixedStringBytes = this.bcsToBytes().slice(1);\n // Put those bytes into a vector<u8> and serialize it as a script function argument\n const vectorU8 = MoveVector.U8(fixedStringBytes);\n vectorU8.serializeForScriptFunction(serializer);\n }\n\n static deserialize(deserializer: Deserializer): MoveString {\n return new MoveString(deserializer.deserializeStr());\n }\n}\n\nexport class MoveOption<T extends Serializable & EntryFunctionArgument>\n extends Serializable\n implements EntryFunctionArgument\n{\n private vec: MoveVector<T>;\n\n public readonly value?: T;\n\n constructor(value?: T | null) {\n super();\n if (typeof value !== \"undefined\" && value !== null) {\n this.vec = new MoveVector([value]);\n } else {\n this.vec = new MoveVector([]);\n }\n\n [this.value] = this.vec.values;\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * Retrieves the inner value of the MoveOption.\n *\n * This method is inspired by Rust's `Option<T>.unwrap()`.\n * In Rust, attempting to unwrap a `None` value results in a panic.\n *\n * Similarly, this method will throw an error if the value is not present.\n *\n * @example\n * const option = new MoveOption<Bool>(new Bool(true));\n * const value = option.unwrap(); // Returns the Bool instance\n *\n * @throws {Error} Throws an error if the MoveOption does not contain a value.\n *\n * @returns {T} The contained value if present.\n */\n unwrap(): T {\n if (!this.isSome()) {\n throw new Error(\"Called unwrap on a MoveOption with no value\");\n } else {\n return this.vec.values[0];\n }\n }\n\n // Check if the MoveOption has a value.\n isSome(): boolean {\n return this.vec.values.length === 1;\n }\n\n serialize(serializer: Serializer): void {\n // serialize 0 or 1\n // if 1, serialize the value\n this.vec.serialize(serializer);\n }\n\n /**\n * Factory method to generate a MoveOption<U8> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U8(1).isSome() === true;\n * MoveOption.U8().isSome() === false;\n * MoveOption.U8(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U8> with an inner value `value`\n */\n static U8(value?: number | null): MoveOption<U8> {\n return new MoveOption<U8>(value !== null && value !== undefined ? new U8(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U16> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U16(1).isSome() === true;\n * MoveOption.U16().isSome() === false;\n * MoveOption.U16(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U16> with an inner value `value`\n */\n static U16(value?: number | null): MoveOption<U16> {\n return new MoveOption<U16>(value !== null && value !== undefined ? new U16(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U32> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U32(1).isSome() === true;\n * MoveOption.U32().isSome() === false;\n * MoveOption.U32(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U32> with an inner value `value`\n */\n static U32(value?: number | null): MoveOption<U32> {\n return new MoveOption<U32>(value !== null && value !== undefined ? new U32(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U64> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U64(1).isSome() === true;\n * MoveOption.U64().isSome() === false;\n * MoveOption.U64(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U64> with an inner value `value`\n */\n static U64(value?: AnyNumber | null): MoveOption<U64> {\n return new MoveOption<U64>(value !== null && value !== undefined ? new U64(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U128> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U128(1).isSome() === true;\n * MoveOption.U128().isSome() === false;\n * MoveOption.U128(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U128> with an inner value `value`\n */\n static U128(value?: AnyNumber | null): MoveOption<U128> {\n return new MoveOption<U128>(value !== null && value !== undefined ? new U128(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U256> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U256(1).isSome() === true;\n * MoveOption.U256().isSome() === false;\n * MoveOption.U256(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U256> with an inner value `value`\n */\n static U256(value?: AnyNumber | null): MoveOption<U256> {\n return new MoveOption<U256>(value !== null && value !== undefined ? new U256(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<Bool> from a `boolean` or `undefined`.\n *\n * @example\n * MoveOption.Bool(true).isSome() === true;\n * MoveOption.Bool().isSome() === false;\n * MoveOption.Bool(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<Bool> with an inner value `value`\n */\n static Bool(value?: boolean | null): MoveOption<Bool> {\n return new MoveOption<Bool>(value !== null && value !== undefined ? new Bool(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<MoveString> from a `string` or `undefined`.\n *\n * @example\n * MoveOption.MoveString(\"hello\").isSome() === true;\n * MoveOption.MoveString(\"\").isSome() === true;\n * MoveOption.MoveString().isSome() === false;\n * MoveOption.MoveString(undefined).isSome() === false;\n * @params value: the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<MoveString> with an inner value `value`\n */\n static MoveString(value?: string | null): MoveOption<MoveString> {\n return new MoveOption<MoveString>(value !== null && value !== undefined ? new MoveString(value) : undefined);\n }\n\n static deserialize<U extends Serializable & EntryFunctionArgument>(\n deserializer: Deserializer,\n cls: Deserializable<U>,\n ): MoveOption<U> {\n const vector = MoveVector.deserialize(deserializer, cls);\n return new MoveOption(vector.values[0]);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../serializer\";\nimport { Deserializer } from \"../deserializer\";\nimport { HexInput } from \"../../types\";\nimport { Hex } from \"../../core/hex\";\nimport { TransactionArgument } from \"../../transactions/instances/transactionArgument\";\n\n/**\n * This class exists to represent a contiguous sequence of already serialized BCS-bytes.\n *\n * It differs from most other Serializable classes in that its internal byte buffer is serialized to BCS\n * bytes exactly as-is, without prepending the length of the bytes.\n *\n * If you want to write your own serialization function and pass the bytes as a transaction argument,\n * you should use this class.\n *\n * This class is also more generally used to represent type-agnostic BCS bytes as a vector<u8>.\n *\n * An example of this is the bytes resulting from entry function arguments that have been serialized\n * for an entry function.\n *\n * @example\n * const yourCustomSerializedBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);\n * const fixedBytes = new FixedBytes(yourCustomSerializedBytes);\n * const payload = await generateTransactionPayload({\n * function: \"0xbeefcafe::your_module::your_function_that_requires_custom_serialization\",\n * functionArguments: [yourCustomBytes],\n * });\n *\n * For example, if you store each of the 32 bytes for an address as a U8 in a MoveVector<U8>, when you\n * serialize that MoveVector<U8>, it will be serialized to 33 bytes. If you solely want to pass around\n * the 32 bytes as a Serializable class that *does not* prepend the length to the BCS-serialized representation,\n * use this class.\n *\n * @params value: HexInput representing a sequence of Uint8 bytes\n * @returns a Serializable FixedBytes instance, which when serialized, does not prepend the length of the bytes\n * @see EntryFunctionBytes\n */\nexport class FixedBytes extends Serializable implements TransactionArgument {\n public value: Uint8Array;\n\n constructor(value: HexInput) {\n super();\n this.value = Hex.fromHexInput(value).toUint8Array();\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n serializer.serialize(this);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer, length: number): FixedBytes {\n const bytes = deserializer.deserializeFixedBytes(length);\n return new FixedBytes(bytes);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n EntryFunctionArgumentTypes,\n InputGenerateTransactionPayloadData,\n InputGenerateTransactionPayloadDataWithRemoteABI,\n InputScriptData,\n SimpleEntryFunctionArgumentTypes,\n} from \"../types\";\nimport { Bool, FixedBytes, MoveOption, MoveString, MoveVector, U128, U16, U256, U32, U64, U8 } from \"../../bcs\";\nimport { AccountAddress } from \"../../core\";\nimport { MoveFunction, MoveFunctionId } from \"../../types\";\n\nexport function isBool(arg: SimpleEntryFunctionArgumentTypes): arg is boolean {\n return typeof arg === \"boolean\";\n}\n\nexport function isString(arg: any): arg is string {\n return typeof arg === \"string\";\n}\n\nexport function isNumber(arg: SimpleEntryFunctionArgumentTypes): arg is number {\n return typeof arg === \"number\";\n}\n\nexport function isLargeNumber(arg: SimpleEntryFunctionArgumentTypes): arg is number | bigint | string {\n return typeof arg === \"number\" || typeof arg === \"bigint\" || typeof arg === \"string\";\n}\n\nexport function isNull(arg: SimpleEntryFunctionArgumentTypes): arg is null | undefined {\n return arg === null || arg === undefined;\n}\n\nexport function isEncodedEntryFunctionArgument(\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n): arg is EntryFunctionArgumentTypes {\n return (\n isBcsBool(arg) ||\n isBcsU8(arg) ||\n isBcsU16(arg) ||\n isBcsU32(arg) ||\n isBcsU64(arg) ||\n isBcsU128(arg) ||\n isBcsU256(arg) ||\n isBcsAddress(arg) ||\n isBcsString(arg) ||\n isBcsFixedBytes(arg) ||\n arg instanceof MoveVector ||\n arg instanceof MoveOption\n );\n}\n\nexport function isBcsBool(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is Bool {\n return arg instanceof Bool;\n}\n\nexport function isBcsAddress(\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n): arg is AccountAddress {\n return arg instanceof AccountAddress;\n}\n\nexport function isBcsString(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is MoveString {\n return arg instanceof MoveString;\n}\n\nexport function isBcsFixedBytes(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is FixedBytes {\n return arg instanceof FixedBytes;\n}\n\nexport function isBcsU8(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U8 {\n return arg instanceof U8;\n}\n\nexport function isBcsU16(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U16 {\n return arg instanceof U16;\n}\n\nexport function isBcsU32(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U32 {\n return arg instanceof U32;\n}\n\nexport function isBcsU64(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U64 {\n return arg instanceof U64;\n}\n\nexport function isBcsU128(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U128 {\n return arg instanceof U128;\n}\n\nexport function isBcsU256(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U256 {\n return arg instanceof U256;\n}\n\nexport function isScriptDataInput(\n arg: InputGenerateTransactionPayloadDataWithRemoteABI | InputGenerateTransactionPayloadData,\n): arg is InputScriptData {\n return \"bytecode\" in arg;\n}\n\nexport function throwTypeMismatch(expectedType: string, position: number) {\n throw new Error(`Type mismatch for argument ${position}, expected '${expectedType}'`);\n}\n\n/**\n * Finds first non-signer arg.\n *\n * A function is often defined with a `signer` or `&signer` arguments at the start, which are filled in\n * by signatures, and not by the caller.\n * @param functionAbi\n */\nexport function findFirstNonSignerArg(functionAbi: MoveFunction): number {\n const index = functionAbi.params.findIndex((param) => param !== \"signer\" && param !== \"&signer\");\n if (index < 0) {\n return functionAbi.params.length;\n }\n return index;\n}\n\nexport function getFunctionParts(functionArg: MoveFunctionId) {\n const funcNameParts = functionArg.split(\"::\");\n if (funcNameParts.length !== 3) {\n throw new Error(`Invalid function ${functionArg}`);\n }\n const moduleAddress = funcNameParts[0];\n const moduleName = funcNameParts[1];\n const functionName = funcNameParts[2];\n return { moduleAddress, moduleName, functionName };\n}\n","import { Serializable } from \"../../bcs\";\nimport { Hex } from \"../hex\";\n\n/**\n * An abstract representation of a crypto signature,\n * associated to a specific signature scheme e.g. Ed25519 or Secp256k1\n *\n * This is the product of signing a message directly from a PrivateKey\n * and can be verified against a CryptoPublicKey.\n */\nexport abstract class Signature extends Serializable {\n /**\n * Get the raw signature bytes\n */\n abstract toUint8Array(): Uint8Array;\n\n /**\n * Get the signature as a hex string with a 0x prefix e.g. 0x123456...\n */\n toString(): string {\n const bytes = this.toUint8Array();\n return Hex.fromHexInput(bytes).toString();\n }\n}\n\n/**\n * An abstract representation of an account signature,\n * associated to a specific authentication scheme e.g. Ed25519 or SingleKey\n *\n * This is the product of signing a message through an account,\n * and can be verified against an AccountPublicKey.\n */\n// export abstract class AccountSignature extends Serializable {\n// /**\n// * Get the raw signature bytes\n// */\n// abstract toUint8Array(): Uint8Array;\n//\n// /**\n// * Get the signature as a hex string with a 0x prefix e.g. 0x123456...\n// */\n// toString(): string {\n// const bytes = this.toUint8Array();\n// return Hex.fromHexInput(bytes).toString();\n// }\n// }\n","import { HexInput } from \"../../types\";\nimport { Hex } from \"../hex\";\n\n/**\n * Helper function to convert a message to sign or to verify to a valid message input\n *\n * @param message a message as a string or Uint8Array\n *\n * @returns a valid HexInput - string or Uint8Array\n */\nexport const convertSigningMessage = (message: HexInput): HexInput => {\n // if message is of type string, verify it is a valid Hex string\n if (typeof message === \"string\") {\n const isValid = Hex.isValid(message);\n // If message is not a valid Hex string, convert it into a Buffer\n if (!isValid.valid) {\n return Buffer.from(message, \"utf8\");\n }\n // If message is a valid Hex string, return it\n return message;\n }\n // message is a Uint8Array\n return message;\n};\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha512 } from \"@noble/hashes/sha512\";\nimport * as bip39 from \"@scure/bip39\";\n\nexport type DerivedKeys = {\n key: Uint8Array;\n chainCode: Uint8Array;\n};\n\n/**\n * Aptos derive path is 637\n */\nexport const APTOS_HARDENED_REGEX = /^m\\/44'\\/637'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'?$/;\nexport const APTOS_BIP44_REGEX = /^m\\/44'\\/637'\\/[0-9]+'\\/[0-9]+\\/[0-9]+$/;\n\n/**\n * A list of supported key types and associated seeds\n */\nexport enum KeyType {\n ED25519 = \"ed25519 seed\",\n}\n\nexport const HARDENED_OFFSET = 0x80000000;\n\n/**\n * Aptos derive path is 637\n *\n * Parse and validate a path that is compliant to BIP-44 in form m/44'/637'/{account_index}'/{change_index}/{address_index}\n * for Secp256k1\n *\n * Note that for secp256k1, last two components must be non-hardened.\n *\n * @param path path string (e.g. `m/44'/637'/0'/0/0`).\n */\nexport function isValidBIP44Path(path: string): boolean {\n return APTOS_BIP44_REGEX.test(path);\n}\n\n/**\n * Aptos derive path is 637\n *\n * Parse and validate a path that is compliant to SLIP-0010 and BIP-44\n * in form m/44'/637'/{account_index}'/{change_index}'/{address_index}'.\n * See SLIP-0010 {@link https://github.com/satoshilabs/slips/blob/master/slip-0044.md}\n * See BIP-44 {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}\n *\n * Note that for Ed25519, all components must be hardened.\n * This is because non-hardened [PK] derivation would not work due to Ed25519's lack of a key homomorphism.\n * Specifically, you cannot derive the PK associated with derivation path a/b/c given the PK of a/b.\n * This is because the PK in Ed25519 is, more or less, computed as 𝑔𝐻(𝑠𝑘),\n * with the hash function breaking the homomorphism.\n *\n * @param path path string (e.g. `m/44'/637'/0'/0'/0'`).\n */\nexport function isValidHardenedPath(path: string): boolean {\n return APTOS_HARDENED_REGEX.test(path);\n}\n\nexport const deriveKey = (hashSeed: Uint8Array | string, data: Uint8Array | string): DerivedKeys => {\n const digest = hmac.create(sha512, hashSeed).update(data).digest();\n return {\n key: digest.slice(0, 32),\n chainCode: digest.slice(32),\n };\n};\n\n/**\n * Derive a child key from the private key\n * @param key\n * @param chainCode\n * @param index\n * @constructor\n */\nexport const CKDPriv = ({ key, chainCode }: DerivedKeys, index: number): DerivedKeys => {\n const buffer = new ArrayBuffer(4);\n new DataView(buffer).setUint32(0, index);\n const indexBytes = new Uint8Array(buffer);\n const zero = new Uint8Array([0]);\n const data = new Uint8Array([...zero, ...key, ...indexBytes]);\n return deriveKey(chainCode, data);\n};\n\nconst removeApostrophes = (val: string): string => val.replace(\"'\", \"\");\n\n/**\n * Splits derive path into segments\n * @param path\n */\nexport const splitPath = (path: string): Array<string> => path.split(\"/\").slice(1).map(removeApostrophes);\n\n/**\n * Normalizes the mnemonic by removing extra whitespace and making it lowercase\n * @param mnemonic the mnemonic seed phrase\n */\nexport const mnemonicToSeed = (mnemonic: string): Uint8Array => {\n const normalizedMnemonic = mnemonic\n .trim()\n .split(/\\s+/)\n .map((part) => part.toLowerCase())\n .join(\" \");\n return bip39.mnemonicToSeedSync(normalizedMnemonic);\n};\n","/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { bytes as assertBytes, number as assertNumber } from '@noble/hashes/_assert';\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError(`Invalid mnemonic type: ${typeof str}`);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction assertEntropy(entropy) {\n assertBytes(entropy, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n assertNumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error(`Wordlist: non-string element: ${i}`);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n assertEntropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n assertEntropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst salt = (passphrase) => nfkd(`mnemonic${passphrase}`);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 });\n}\n","import { Serializable } from \"../../bcs\";\nimport { HexInput } from \"../../types\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Hex } from \"../hex\";\nimport { Signature } from \"./signature\";\n\n/**\n * Arguments for verifying a signature\n */\nexport interface VerifySignatureArgs {\n message: HexInput;\n signature: Signature;\n}\n\n/**\n * An abstract representation of a public key.\n *\n * Provides a common interface for verifying any signature.\n */\nexport abstract class PublicKey extends Serializable {\n /**\n * Verifies that the private key associated with this public key signed the message with the given signature.\n * @param args.message The message that was signed\n * @param args.signature The signature to verify\n */\n abstract verifySignature(args: VerifySignatureArgs): boolean;\n\n /**\n * Get the raw public key bytes\n */\n abstract toUint8Array(): Uint8Array;\n\n /**\n * Get the public key as a hex string with a 0x prefix e.g. 0x123456...\n */\n toString(): string {\n const bytes = this.toUint8Array();\n return Hex.fromHexInput(bytes).toString();\n }\n}\n\n/**\n * An abstract representation of an account public key.\n *\n * Provides a common interface for deriving an authentication key.\n */\nexport abstract class AccountPublicKey extends PublicKey {\n /**\n * Get the authentication key associated with this public key\n */\n abstract authKey(): AuthenticationKey;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { sha3_256 as sha3Hash } from \"@noble/hashes/sha3\";\nimport { AccountAddress } from \"./accountAddress\";\nimport type { AccountPublicKey } from \"./crypto\";\nimport { Hex } from \"./hex\";\nimport { AuthenticationKeyScheme, HexInput } from \"../types\";\nimport { Serializable, Serializer } from \"../bcs/serializer\";\nimport { Deserializer } from \"../bcs/deserializer\";\n\n/**\n * Each account stores an authentication key. Authentication key enables account owners to rotate\n * their private key(s) associated with the account without changing the address that hosts their account.\n * @see {@link https://aptos.dev/concepts/accounts | Account Basics}\n *\n * Account addresses can be derived from AuthenticationKey\n */\nexport class AuthenticationKey extends Serializable {\n /**\n * An authentication key is always a SHA3-256 hash of data, and is always 32 bytes.\n *\n * The data to hash depends on the underlying public key type and the derivation scheme.\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The raw bytes of the authentication key.\n */\n public readonly data: Hex;\n\n constructor(args: { data: HexInput }) {\n super();\n const { data } = args;\n const hex = Hex.fromHexInput(data);\n if (hex.toUint8Array().length !== AuthenticationKey.LENGTH) {\n throw new Error(`Authentication Key length should be ${AuthenticationKey.LENGTH}`);\n }\n this.data = hex;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.data.toUint8Array());\n }\n\n /**\n * Deserialize an AuthenticationKey from the byte buffer in a Deserializer instance.\n * @param deserializer The deserializer to deserialize the AuthenticationKey from.\n * @returns An instance of AuthenticationKey.\n */\n static deserialize(deserializer: Deserializer): AuthenticationKey {\n const bytes = deserializer.deserializeFixedBytes(AuthenticationKey.LENGTH);\n return new AuthenticationKey({ data: bytes });\n }\n\n toString(): string {\n return this.data.toString();\n }\n\n toUint8Array(): Uint8Array {\n return this.data.toUint8Array();\n }\n\n static fromSchemeAndBytes(args: { scheme: AuthenticationKeyScheme; input: HexInput }): AuthenticationKey {\n const { scheme, input } = args;\n const inputBytes = Hex.fromHexInput(input).toUint8Array();\n const hashInput = new Uint8Array([...inputBytes, scheme]);\n const hash = sha3Hash.create();\n hash.update(hashInput);\n const hashDigest = hash.digest();\n return new AuthenticationKey({ data: hashDigest });\n }\n\n /**\n * @deprecated Use `fromPublicKey` instead\n * Derives an AuthenticationKey from the public key seed bytes and an explicit derivation scheme.\n *\n * This facilitates targeting a specific scheme for deriving an authentication key from a public key.\n *\n * @param args - the public key and scheme to use for the derivation\n */\n public static fromPublicKeyAndScheme(args: { publicKey: AccountPublicKey; scheme: AuthenticationKeyScheme }) {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Converts a PublicKey(s) to an AuthenticationKey, using the derivation scheme inferred from the\n * instance of the PublicKey type passed in.\n *\n * @param args.publicKey\n * @returns AuthenticationKey\n */\n static fromPublicKey(args: { publicKey: AccountPublicKey }): AuthenticationKey {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Derives an account address from an AuthenticationKey. Since an AccountAddress is also 32 bytes,\n * the AuthenticationKey bytes are directly translated to an AccountAddress.\n *\n * @returns AccountAddress\n */\n derivedAddress(): AccountAddress {\n return new AccountAddress(this.data.toUint8Array());\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Hex } from \"../hex\";\nimport { HexInput, SigningScheme as AuthenticationKeyScheme } from \"../../types\";\nimport { CKDPriv, deriveKey, HARDENED_OFFSET, isValidHardenedPath, mnemonicToSeed, splitPath } from \"./hdKey\";\nimport { PrivateKey } from \"./privateKey\";\nimport { AccountPublicKey, VerifySignatureArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { convertSigningMessage } from \"./utils\";\n\n/**\n * L is the value that greater than or equal to will produce a non-canonical signature, and must be rejected\n */\nconst L: number[] = [\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\n];\n\n/**\n * Represents the public key of an Ed25519 key pair.\n *\n * Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports\n * `Legacy` and `Unified` authentication keys.\n *\n * Ed25519 scheme is represented in the SDK as `Legacy authentication key` and also\n * as `AnyPublicKey` that represents any `Unified authentication key`\n */\nexport class Ed25519PublicKey extends AccountPublicKey {\n /**\n * Length of an Ed25519 public key\n */\n static readonly LENGTH: number = 32;\n\n /**\n * Bytes of the public key\n * @private\n */\n private readonly key: Hex;\n\n /**\n * Create a new PublicKey instance from a Uint8Array or String.\n *\n * @param hexInput A HexInput (string or Uint8Array)\n */\n constructor(hexInput: HexInput) {\n super();\n\n const hex = Hex.fromHexInput(hexInput);\n if (hex.toUint8Array().length !== Ed25519PublicKey.LENGTH) {\n throw new Error(`PublicKey length should be ${Ed25519PublicKey.LENGTH}`);\n }\n this.key = hex;\n }\n\n // region AccountPublicKey\n\n /**\n * Verifies a signed data with a public key\n * @param args.message a signed message as a Hex string or Uint8Array\n * @param args.signature the signature of the message\n */\n verifySignature(args: VerifySignatureArgs): boolean {\n const { message, signature } = args;\n if (!(signature instanceof Ed25519Signature)) {\n return false;\n }\n const messageToVerify = convertSigningMessage(message);\n const messageBytes = Hex.fromHexInput(messageToVerify).toUint8Array();\n const signatureBytes = signature.toUint8Array();\n const publicKeyBytes = this.key.toUint8Array();\n // Also verify malleability\n if (!signature.isCanonicalSignature()) {\n return false;\n }\n\n return ed25519.verify(signatureBytes, messageBytes, publicKeyBytes);\n }\n\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.Ed25519,\n input: this.toUint8Array(),\n });\n }\n\n /**\n * Get the public key in bytes (Uint8Array).\n *\n * @returns Uint8Array representation of the public key\n */\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.key.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Ed25519PublicKey {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519PublicKey(bytes);\n }\n\n // endregion\n\n /**\n * @deprecated use `instanceof Ed25519PublicKey` instead.\n */\n static isPublicKey(publicKey: AccountPublicKey): publicKey is Ed25519PublicKey {\n return publicKey instanceof Ed25519PublicKey;\n }\n}\n\n/**\n * Represents the private key of an Ed25519 key pair.\n */\nexport class Ed25519PrivateKey extends Serializable implements PrivateKey {\n /**\n * Length of an Ed25519 private key\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The Ed25519 key seed to use for BIP-32 compatibility\n * See more {@link https://github.com/satoshilabs/slips/blob/master/slip-0010.md}\n */\n static readonly SLIP_0010_SEED = \"ed25519 seed\";\n\n /**\n * The Ed25519 signing key\n * @private\n */\n private readonly signingKey: Hex;\n\n // region Constructors\n\n /**\n * Create a new PrivateKey instance from a Uint8Array or String.\n *\n * @param hexInput HexInput (string or Uint8Array)\n */\n constructor(hexInput: HexInput) {\n super();\n\n const privateKeyHex = Hex.fromHexInput(hexInput);\n if (privateKeyHex.toUint8Array().length !== Ed25519PrivateKey.LENGTH) {\n throw new Error(`PrivateKey length should be ${Ed25519PrivateKey.LENGTH}`);\n }\n\n // Create keyPair from Private key in Uint8Array format\n this.signingKey = privateKeyHex;\n }\n\n /**\n * Generate a new random private key.\n *\n * @returns Ed25519PrivateKey\n */\n static generate(): Ed25519PrivateKey {\n const keyPair = ed25519.utils.randomPrivateKey();\n return new Ed25519PrivateKey(keyPair);\n }\n\n /**\n * Derives a private key from a mnemonic seed phrase.\n *\n * To derive multiple keys from the same phrase, change the path\n *\n * IMPORTANT: Ed25519 supports hardened derivation only (since it lacks a key homomorphism,\n * so non-hardened derivation cannot work)\n *\n * @param path the BIP44 path\n * @param mnemonics the mnemonic seed phrase\n */\n static fromDerivationPath(path: string, mnemonics: string): Ed25519PrivateKey {\n if (!isValidHardenedPath(path)) {\n throw new Error(`Invalid derivation path ${path}`);\n }\n return Ed25519PrivateKey.fromDerivationPathInner(path, mnemonicToSeed(mnemonics));\n }\n\n /**\n * A private inner function so we can separate from the main fromDerivationPath() method\n * to add tests to verify we create the keys correctly.\n *\n * @param path the BIP44 path\n * @param seed the seed phrase created by the mnemonics\n * @param offset the offset used for key derivation, defaults to 0x80000000\n * @returns\n */\n private static fromDerivationPathInner(path: string, seed: Uint8Array, offset = HARDENED_OFFSET): Ed25519PrivateKey {\n const { key, chainCode } = deriveKey(Ed25519PrivateKey.SLIP_0010_SEED, seed);\n\n const segments = splitPath(path).map((el) => parseInt(el, 10));\n\n // Derive the child key based on the path\n const { key: privateKey } = segments.reduce((parentKeys, segment) => CKDPriv(parentKeys, segment + offset), {\n key,\n chainCode,\n });\n return new Ed25519PrivateKey(privateKey);\n }\n\n // endregion\n\n // region PrivateKey\n\n /**\n * Derive the Ed25519PublicKey for this private key.\n *\n * @returns Ed25519PublicKey\n */\n publicKey(): Ed25519PublicKey {\n const bytes = ed25519.getPublicKey(this.signingKey.toUint8Array());\n return new Ed25519PublicKey(bytes);\n }\n\n /**\n * Sign the given message with the private key.\n *\n * @param message a message as a string or Uint8Array\n * @returns Signature\n */\n sign(message: HexInput): Ed25519Signature {\n const messageToSign = convertSigningMessage(message);\n const messageBytes = Hex.fromHexInput(messageToSign).toUint8Array();\n const signatureBytes = ed25519.sign(messageBytes, this.signingKey.toUint8Array());\n return new Ed25519Signature(signatureBytes);\n }\n\n /**\n * Get the private key in bytes (Uint8Array).\n *\n * @returns Uint8Array representation of the private key\n */\n toUint8Array(): Uint8Array {\n return this.signingKey.toUint8Array();\n }\n\n /**\n * Get the private key as a hex string with the 0x prefix.\n *\n * @returns string representation of the private key\n */\n toString(): string {\n return this.signingKey.toString();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Ed25519PrivateKey {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519PrivateKey(bytes);\n }\n\n // endregion\n\n /**\n * @deprecated use `instanceof Ed25519PrivateKey` instead.\n */\n static isPrivateKey(privateKey: PrivateKey): privateKey is Ed25519PrivateKey {\n return privateKey instanceof Ed25519PrivateKey;\n }\n}\n\n/**\n * A signature of a message signed using an Ed25519 private key\n */\nexport class Ed25519Signature extends Signature {\n /**\n * Length of an Ed25519 signature\n */\n static readonly LENGTH = 64;\n\n /**\n * The signature bytes\n * @private\n */\n private readonly data: Hex;\n\n // region Constructors\n\n constructor(hexInput: HexInput) {\n super();\n const data = Hex.fromHexInput(hexInput);\n if (data.toUint8Array().length !== Ed25519Signature.LENGTH) {\n throw new Error(`Signature length should be ${Ed25519Signature.LENGTH}`);\n }\n this.data = data;\n }\n\n // endregion\n\n // region Signature\n\n toUint8Array(): Uint8Array {\n return this.data.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.data.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Ed25519Signature {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519Signature(bytes);\n }\n\n /**\n * Checks if an ED25519 signature is non-canonical.\n *\n * Comes from Aptos Core\n * https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-crypto/src/ed25519/ed25519_sigs.rs#L47-L85\n */\n isCanonicalSignature(): boolean {\n const s = this.toUint8Array().slice(32);\n\n for (let i = s.length - 1; i >= 0; i -= 1) {\n if (s[i] < L[i]) {\n return true;\n }\n if (s[i] > L[i]) {\n return false;\n }\n }\n // As this stage S == L which implies a non-canonical S.\n return false;\n }\n\n // endregion\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Deserializer, Serializer } from \"../../bcs\";\nimport { SigningScheme as AuthenticationKeyScheme } from \"../../types\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"./ed25519\";\nimport { AccountPublicKey, VerifySignatureArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\n\n/**\n * Represents the public key of a K-of-N Ed25519 multi-sig transaction.\n */\nexport class MultiEd25519PublicKey extends AccountPublicKey {\n /**\n * Maximum number of public keys supported\n */\n static readonly MAX_KEYS = 32;\n\n /**\n * Minimum number of public keys needed\n */\n static readonly MIN_KEYS = 2;\n\n /**\n * Minimum threshold for the number of valid signatures required\n */\n static readonly MIN_THRESHOLD = 1;\n\n /**\n * List of Ed25519 public keys for this LegacyMultiEd25519PublicKey\n */\n public readonly publicKeys: Ed25519PublicKey[];\n\n /**\n * The minimum number of valid signatures required, for the number of public keys specified\n */\n public readonly threshold: number;\n\n /**\n * Public key for a K-of-N multi-sig transaction. A K-of-N multi-sig transaction means that for such a\n * transaction to be executed, at least K out of the N authorized signers have signed the transaction\n * and passed the check conducted by the chain.\n *\n * @see {@link\n * https://aptos.dev/integration/creating-a-signed-transaction/ | Creating a Signed Transaction}\n *\n * @param args.publicKeys A list of public keys\n * @param args.threshold At least \"threshold\" signatures must be valid\n */\n constructor(args: { publicKeys: Ed25519PublicKey[]; threshold: number }) {\n super();\n const { publicKeys, threshold } = args;\n\n // Validate number of public keys\n if (publicKeys.length > MultiEd25519PublicKey.MAX_KEYS || publicKeys.length < MultiEd25519PublicKey.MIN_KEYS) {\n throw new Error(\n `Must have between ${MultiEd25519PublicKey.MIN_KEYS} and ` +\n `${MultiEd25519PublicKey.MAX_KEYS} public keys, inclusive`,\n );\n }\n\n // Validate threshold: must be between 1 and the number of public keys, inclusive\n if (threshold < MultiEd25519PublicKey.MIN_THRESHOLD || threshold > publicKeys.length) {\n throw new Error(\n `Threshold must be between ${MultiEd25519PublicKey.MIN_THRESHOLD} and ${publicKeys.length}, inclusive`,\n );\n }\n\n this.publicKeys = publicKeys;\n this.threshold = threshold;\n }\n\n // region AccountPublicKey\n\n verifySignature(args: VerifySignatureArgs): boolean {\n const { message, signature } = args;\n if (!(signature instanceof MultiEd25519Signature)) {\n return false;\n }\n\n const indices: number[] = [];\n for (let i = 0; i < 4; i += 1) {\n for (let j = 0; j < 8; j += 1) {\n // eslint-disable-next-line no-bitwise\n const bitIsSet = (signature.bitmap[i] & (1 << (7 - j))) !== 0;\n if (bitIsSet) {\n const index = i * 8 + j;\n indices.push(index);\n }\n }\n }\n\n if (indices.length !== signature.signatures.length) {\n throw new Error(\"Bitmap and signatures length mismatch\");\n }\n\n if (indices.length < this.threshold) {\n throw new Error(\"Not enough signatures\");\n }\n\n for (let i = 0; i < indices.length; i += 1) {\n const publicKey = this.publicKeys[indices[i]];\n if (!publicKey.verifySignature({ message, signature: signature.signatures[i] })) {\n return false;\n }\n }\n return true;\n }\n\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.MultiEd25519,\n input: this.toUint8Array(),\n });\n }\n\n /**\n * Converts a PublicKeys into Uint8Array (bytes) with: bytes = p1_bytes | ... | pn_bytes | threshold\n */\n toUint8Array(): Uint8Array {\n const bytes = new Uint8Array(this.publicKeys.length * Ed25519PublicKey.LENGTH + 1);\n this.publicKeys.forEach((k: Ed25519PublicKey, i: number) => {\n bytes.set(k.toUint8Array(), i * Ed25519PublicKey.LENGTH);\n });\n\n bytes[this.publicKeys.length * Ed25519PublicKey.LENGTH] = this.threshold;\n\n return bytes;\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): MultiEd25519PublicKey {\n const bytes = deserializer.deserializeBytes();\n const threshold = bytes[bytes.length - 1];\n\n const keys: Ed25519PublicKey[] = [];\n\n for (let i = 0; i < bytes.length - 1; i += Ed25519PublicKey.LENGTH) {\n const begin = i;\n keys.push(new Ed25519PublicKey(bytes.subarray(begin, begin + Ed25519PublicKey.LENGTH)));\n }\n return new MultiEd25519PublicKey({ publicKeys: keys, threshold });\n }\n\n // endregion\n}\n\n/**\n * Represents the signature of a K-of-N Ed25519 multi-sig transaction.\n */\nexport class MultiEd25519Signature extends Signature {\n /**\n * Maximum number of Ed25519 signatures supported\n */\n static MAX_SIGNATURES_SUPPORTED = 32;\n\n /**\n * Number of bytes in the bitmap representing who signed the transaction (32-bits)\n */\n static BITMAP_LEN: number = 4;\n\n /**\n * The list of underlying Ed25519 signatures\n */\n public readonly signatures: Ed25519Signature[];\n\n /**\n * 32-bit Bitmap representing who signed the transaction\n *\n * This is represented where each public key can be masked to determine whether the message was signed by that key.\n */\n public readonly bitmap: Uint8Array;\n\n /**\n * Signature for a K-of-N multi-sig transaction.\n *\n * @see {@link\n * https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}\n *\n * @param args.signatures A list of signatures\n * @param args.bitmap 4 bytes, at most 32 signatures are supported. If Nth bit value is `1`, the Nth\n * signature should be provided in `signatures`. Bits are read from left to right.\n * Alternatively, you can specify an array of bitmap positions.\n * Valid position should range between 0 and 31.\n * @see MultiEd25519Signature.createBitmap\n */\n constructor(args: { signatures: Ed25519Signature[]; bitmap: Uint8Array | number[] }) {\n super();\n const { signatures, bitmap } = args;\n\n if (signatures.length > MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED) {\n throw new Error(\n `The number of signatures cannot be greater than ${MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED}`,\n );\n }\n this.signatures = signatures;\n\n if (!(bitmap instanceof Uint8Array)) {\n this.bitmap = MultiEd25519Signature.createBitmap({ bits: bitmap });\n } else if (bitmap.length !== MultiEd25519Signature.BITMAP_LEN) {\n throw new Error(`\"bitmap\" length should be ${MultiEd25519Signature.BITMAP_LEN}`);\n } else {\n this.bitmap = bitmap;\n }\n }\n\n // region AccountSignature\n\n /**\n * Converts a MultiSignature into Uint8Array (bytes) with `bytes = s1_bytes | ... | sn_bytes | bitmap`\n */\n toUint8Array(): Uint8Array {\n const bytes = new Uint8Array(this.signatures.length * Ed25519Signature.LENGTH + MultiEd25519Signature.BITMAP_LEN);\n this.signatures.forEach((k: Ed25519Signature, i: number) => {\n bytes.set(k.toUint8Array(), i * Ed25519Signature.LENGTH);\n });\n\n bytes.set(this.bitmap, this.signatures.length * Ed25519Signature.LENGTH);\n\n return bytes;\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): MultiEd25519Signature {\n const bytes = deserializer.deserializeBytes();\n const bitmap = bytes.subarray(bytes.length - 4);\n\n const signatures: Ed25519Signature[] = [];\n\n for (let i = 0; i < bytes.length - bitmap.length; i += Ed25519Signature.LENGTH) {\n const begin = i;\n signatures.push(new Ed25519Signature(bytes.subarray(begin, begin + Ed25519Signature.LENGTH)));\n }\n return new MultiEd25519Signature({ signatures, bitmap });\n }\n\n // endregion\n\n /**\n * Helper method to create a bitmap out of the specified bit positions\n * @param args.bits The bitmap positions that should be set. A position starts at index 0.\n * Valid position should range between 0 and 31.\n * @example\n * Here's an example of valid `bits`\n * ```\n * [0, 2, 31]\n * ```\n * `[0, 2, 31]` means the 1st, 3rd and 32nd bits should be set in the bitmap.\n * The result bitmap should be 0b1010000000000000000000000000001\n *\n * @returns bitmap that is 32bit long\n */\n static createBitmap(args: { bits: number[] }): Uint8Array {\n const { bits } = args;\n // Bits are read from left to right. e.g. 0b10000000 represents the first bit is set in one byte.\n // The decimal value of 0b10000000 is 128.\n const firstBitInByte = 128;\n const bitmap = new Uint8Array([0, 0, 0, 0]);\n\n // Check if duplicates exist in bits\n const dupCheckSet = new Set();\n\n bits.forEach((bit: number, index) => {\n if (bit >= MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED) {\n throw new Error(`Cannot have a signature larger than ${MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED - 1}.`);\n }\n\n if (dupCheckSet.has(bit)) {\n throw new Error(\"Duplicate bits detected.\");\n }\n\n if (index > 0 && bit <= bits[index - 1]) {\n throw new Error(\"The bits need to be sorted in ascending order.\");\n }\n\n dupCheckSet.add(bit);\n\n const byteOffset = Math.floor(bit / 8);\n\n let byte = bitmap[byteOffset];\n\n // eslint-disable-next-line no-bitwise\n byte |= firstBitInByte >> bit % 8;\n\n bitmap[byteOffset] = byte;\n });\n\n return bitmap;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { sha3_256 } from \"@noble/hashes/sha3\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Serializable, Deserializer, Serializer } from \"../../bcs\";\nimport { Hex } from \"../hex\";\nimport { HexInput } from \"../../types\";\nimport { isValidBIP44Path, mnemonicToSeed } from \"./hdKey\";\nimport { PrivateKey } from \"./privateKey\";\nimport { PublicKey, VerifySignatureArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { convertSigningMessage } from \"./utils\";\n\n/**\n * Represents the Secp256k1 ecdsa public key\n *\n * Secp256k1 authentication key is represented in the SDK as `AnyPublicKey`.\n */\nexport class Secp256k1PublicKey extends PublicKey {\n // Secp256k1 ecdsa public keys contain a prefix indicating compression and two 32-byte coordinates.\n static readonly LENGTH: number = 65;\n\n // Hex value of the public key\n private readonly key: Hex;\n\n /**\n * Create a new PublicKey instance from a Uint8Array or String.\n *\n * @param hexInput A HexInput (string or Uint8Array)\n */\n constructor(hexInput: HexInput) {\n super();\n\n const hex = Hex.fromHexInput(hexInput);\n if (hex.toUint8Array().length !== Secp256k1PublicKey.LENGTH) {\n throw new Error(`PublicKey length should be ${Secp256k1PublicKey.LENGTH}`);\n }\n this.key = hex;\n }\n\n // region PublicKey\n /**\n * Verifies a Secp256k1 signature against the public key\n *\n * Note signatures are validated to be canonical as a malleability check\n */\n verifySignature(args: VerifySignatureArgs): boolean {\n const { message, signature } = args;\n if (!(signature instanceof Secp256k1Signature)) {\n return false;\n }\n const messageToVerify = convertSigningMessage(message);\n const messageBytes = Hex.fromHexInput(messageToVerify).toUint8Array();\n const messageSha3Bytes = sha3_256(messageBytes);\n const signatureBytes = signature.toUint8Array();\n return secp256k1.verify(signatureBytes, messageSha3Bytes, this.key.toUint8Array(), { lowS: true });\n }\n\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.key.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Secp256k1PublicKey {\n const bytes = deserializer.deserializeBytes();\n return new Secp256k1PublicKey(bytes);\n }\n\n // endregion\n\n /**\n * @deprecated use `instanceof Secp256k1PublicKey` instead\n * @param publicKey\n */\n static isPublicKey(publicKey: PublicKey): publicKey is Secp256k1PublicKey {\n return publicKey instanceof Secp256k1PublicKey;\n }\n}\n\n/**\n * A Secp256k1 ecdsa private key\n */\nexport class Secp256k1PrivateKey extends Serializable implements PrivateKey {\n /**\n * Length of Secp256k1 ecdsa private key\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The private key bytes\n * @private\n */\n private readonly key: Hex;\n\n // region Constructors\n\n /**\n * Create a new PrivateKey instance from a Uint8Array or String.\n *\n * @param hexInput A HexInput (string or Uint8Array)\n */\n constructor(hexInput: HexInput) {\n super();\n\n const privateKeyHex = Hex.fromHexInput(hexInput);\n if (privateKeyHex.toUint8Array().length !== Secp256k1PrivateKey.LENGTH) {\n throw new Error(`PrivateKey length should be ${Secp256k1PrivateKey.LENGTH}`);\n }\n\n this.key = privateKeyHex;\n }\n\n /**\n * Generate a new random private key.\n *\n * @returns Secp256k1PrivateKey\n */\n static generate(): Secp256k1PrivateKey {\n const hexInput = secp256k1.utils.randomPrivateKey();\n return new Secp256k1PrivateKey(hexInput);\n }\n\n /**\n * Derives a private key from a mnemonic seed phrase.\n *\n * @param path the BIP44 path\n * @param mnemonics the mnemonic seed phrase\n *\n * @returns The generated key\n */\n static fromDerivationPath(path: string, mnemonics: string): Secp256k1PrivateKey {\n if (!isValidBIP44Path(path)) {\n throw new Error(`Invalid derivation path ${path}`);\n }\n return Secp256k1PrivateKey.fromDerivationPathInner(path, mnemonicToSeed(mnemonics));\n }\n\n /**\n * A private inner function so we can separate from the main fromDerivationPath() method\n * to add tests to verify we create the keys correctly.\n *\n * @param path the BIP44 path\n * @param seed the seed phrase created by the mnemonics\n *\n * @returns The generated key\n */\n private static fromDerivationPathInner(path: string, seed: Uint8Array): Secp256k1PrivateKey {\n const { privateKey } = HDKey.fromMasterSeed(seed).derive(path);\n // library returns privateKey as Uint8Array | null\n if (privateKey === null) {\n throw new Error(\"Invalid key\");\n }\n\n return new Secp256k1PrivateKey(privateKey);\n }\n\n // endregion\n\n // region PrivateKey\n\n /**\n * Sign the given message with the private key.\n *\n * Note: signatures are canonical, and non-malleable\n *\n * @param message a message as a string or Uint8Array\n * @returns Signature\n */\n sign(message: HexInput): Secp256k1Signature {\n const messageToSign = convertSigningMessage(message);\n const messageBytes = Hex.fromHexInput(messageToSign);\n const messageHashBytes = sha3_256(messageBytes.toUint8Array());\n const signature = secp256k1.sign(messageHashBytes, this.key.toUint8Array(), { lowS: true });\n return new Secp256k1Signature(signature.toCompactRawBytes());\n }\n\n /**\n * Derive the Secp256k1PublicKey from this private key.\n *\n * @returns Secp256k1PublicKey\n */\n publicKey(): Secp256k1PublicKey {\n const bytes = secp256k1.getPublicKey(this.key.toUint8Array(), false);\n return new Secp256k1PublicKey(bytes);\n }\n\n /**\n * Get the private key in bytes (Uint8Array).\n *\n * @returns\n */\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n /**\n * Get the private key as a hex string with the 0x prefix.\n *\n * @returns string representation of the private key\n */\n toString(): string {\n return this.key.toString();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Secp256k1PrivateKey {\n const bytes = deserializer.deserializeBytes();\n return new Secp256k1PrivateKey(bytes);\n }\n\n // endregion\n\n /**\n * @deprecated use `instanceof Secp256k1PrivateKey` instead\n */\n static isPrivateKey(privateKey: PrivateKey): privateKey is Secp256k1PrivateKey {\n return privateKey instanceof Secp256k1PrivateKey;\n }\n}\n\n/**\n * A signature of a message signed using a Secp256k1 ecdsa private key\n */\nexport class Secp256k1Signature extends Signature {\n /**\n * Secp256k1 ecdsa signatures are 256-bit.\n */\n static readonly LENGTH = 64;\n\n /**\n * The signature bytes\n * @private\n */\n private readonly data: Hex;\n\n // region Constructors\n\n /**\n * Create a new Signature instance from a Uint8Array or String.\n *\n * @param hexInput A HexInput (string or Uint8Array)\n */\n constructor(hexInput: HexInput) {\n super();\n const data = Hex.fromHexInput(hexInput);\n if (data.toUint8Array().length !== Secp256k1Signature.LENGTH) {\n throw new Error(\n `Signature length should be ${Secp256k1Signature.LENGTH}, received ${data.toUint8Array().length}`,\n );\n }\n this.data = data;\n }\n\n // endregion\n\n // region Signature\n\n toUint8Array(): Uint8Array {\n return this.data.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.data.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Secp256k1Signature {\n const hex = deserializer.deserializeBytes();\n return new Secp256k1Signature(hex);\n }\n\n // endregion\n}\n","/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { bytes as assertBytes } from '@noble/hashes/_assert';\nimport { bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { mod } from '@noble/curves/abstract/modular';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.ProjectivePoint;\nconst base58check = createBase58check(sha256);\n\nfunction bytesToNumber(bytes: Uint8Array): bigint {\n return BigInt(`0x${bytesToHex(bytes)}`);\n}\n\nfunction numberToBytes(num: bigint): Uint8Array {\n return hexToBytes(num.toString(16).padStart(64, '0'));\n}\n\nconst MASTER_SECRET = utf8ToBytes('Bitcoin seed');\n// Bitcoin hardcoded by default\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number) => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array | bigint;\n}\n\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this.privKeyBytes || null;\n }\n get publicKey(): Uint8Array | null {\n return this.pubKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this.privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this.pubKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this.pubKey));\n }\n\n public static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n assertBytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n `HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n return new HDKey({\n versions,\n chainCode: I.slice(32),\n privateKey: I.slice(0, 32),\n });\n }\n\n public static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n public readonly versions: Versions;\n public readonly depth: number = 0;\n public readonly index: number = 0;\n public readonly chainCode: Uint8Array | null = null;\n public readonly parentFingerprint: number = 0;\n private privKey?: bigint;\n private privKeyBytes?: Uint8Array;\n private pubKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidPrivateKey(opt.privateKey)) {\n throw new Error('Invalid private key');\n }\n this.privKey =\n typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey);\n this.privKeyBytes = numberToBytes(this.privKey);\n this.pubKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this.pubKey);\n }\n\n public derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string') {\n throw new Error(`Invalid child index: ${c}`);\n }\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n public deriveChild(index: number): HDKey {\n if (!this.pubKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this.privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(new Uint8Array([0]), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this.pubKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = bytesToNumber(I.slice(0, 32));\n const chainCode = I.slice(32);\n if (!secp.utils.isValidPrivateKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n try {\n // Private parent key -> private child key\n if (this.privateKey) {\n const added = mod(this.privKey! + childTweak, secp.CURVE.n);\n if (!secp.utils.isValidPrivateKey(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = added;\n } else {\n const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toRawBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n public sign(hash: Uint8Array): Uint8Array {\n if (!this.privateKey) {\n throw new Error('No privateKey set!');\n }\n assertBytes(hash, 32);\n return secp.sign(hash, this.privKey!).toCompactRawBytes();\n }\n\n public verify(hash: Uint8Array, signature: Uint8Array): boolean {\n assertBytes(hash, 32);\n assertBytes(signature, 64);\n if (!this.publicKey) {\n throw new Error('No publicKey set!');\n }\n let sig;\n try {\n sig = secp.Signature.fromCompact(signature);\n } catch (error) {\n return false;\n }\n return secp.verify(sig, hash, this.publicKey);\n }\n\n public wipePrivateData(): this {\n this.privKey = undefined;\n if (this.privKeyBytes) {\n this.privKeyBytes.fill(0);\n this.privKeyBytes = undefined;\n }\n return this;\n }\n public toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n assertBytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n","import { Deserializer, Serializer } from \"../../bcs\";\nimport { AnyPublicKeyVariant, AnySignatureVariant, SigningScheme as AuthenticationKeyScheme } from \"../../types\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"./ed25519\";\nimport { AccountPublicKey, PublicKey, VerifySignatureArgs } from \"./publicKey\";\nimport { Secp256k1PublicKey, Secp256k1Signature } from \"./secp256k1\";\nimport { Signature } from \"./signature\";\n\n/**\n * Represents any public key supported by Aptos.\n *\n * Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports\n * `Legacy` and `Unified` authentication keys.\n *\n * Any unified authentication key is represented in the SDK as `AnyPublicKey`.\n */\nexport class AnyPublicKey extends AccountPublicKey {\n /**\n * Reference to the inner public key\n */\n public readonly publicKey: PublicKey;\n\n /**\n * Index of the underlying enum variant\n */\n public readonly variant: AnyPublicKeyVariant;\n\n // region Constructors\n\n constructor(publicKey: PublicKey) {\n super();\n this.publicKey = publicKey;\n if (publicKey instanceof Ed25519PublicKey) {\n this.variant = AnyPublicKeyVariant.Ed25519;\n } else if (publicKey instanceof Secp256k1PublicKey) {\n this.variant = AnyPublicKeyVariant.Secp256k1;\n } else {\n throw new Error(\"Unsupported public key type\");\n }\n }\n\n // endregion\n\n // region AccountPublicKey\n\n verifySignature(args: VerifySignatureArgs): boolean {\n const { message, signature } = args;\n if (!(signature instanceof AnySignature)) {\n return false;\n }\n\n return this.publicKey.verifySignature({\n message,\n signature: signature.signature,\n });\n }\n\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.SingleKey,\n input: this.toUint8Array(),\n });\n }\n\n toUint8Array() {\n return this.bcsToBytes();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.variant);\n this.publicKey.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): AnyPublicKey {\n const variantIndex = deserializer.deserializeUleb128AsU32();\n let publicKey: PublicKey;\n switch (variantIndex) {\n case AnyPublicKeyVariant.Ed25519:\n publicKey = Ed25519PublicKey.deserialize(deserializer);\n break;\n case AnyPublicKeyVariant.Secp256k1:\n publicKey = Secp256k1PublicKey.deserialize(deserializer);\n break;\n default:\n throw new Error(`Unknown variant index for AnyPublicKey: ${variantIndex}`);\n }\n return new AnyPublicKey(publicKey);\n }\n\n // endregion\n\n /**\n * @deprecated use `instanceof AnyPublicKey` instead.\n */\n static isPublicKey(publicKey: AccountPublicKey): publicKey is AnyPublicKey {\n return publicKey instanceof AnyPublicKey;\n }\n\n /**\n * @deprecated use `publicKey instanceof Ed25519PublicKey` instead.\n */\n isEd25519(): boolean {\n return this.publicKey instanceof Ed25519PublicKey;\n }\n\n /**\n * @deprecated use `publicKey instanceof Secp256k1PublicKey` instead.\n */\n isSecp256k1PublicKey(): boolean {\n return this.publicKey instanceof Secp256k1PublicKey;\n }\n}\n\n/**\n * Instance of signature that uses the SingleKey authentication scheme.\n * This signature can only be generated by a `SingleKeySigner`, since it uses the\n * same authentication scheme.\n */\nexport class AnySignature extends Signature {\n public readonly signature: Signature;\n\n /**\n * Index of the underlying enum variant\n */\n private readonly variant: AnySignatureVariant;\n\n // region Constructors\n\n constructor(signature: Signature) {\n super();\n this.signature = signature;\n\n if (signature instanceof Ed25519Signature) {\n this.variant = AnySignatureVariant.Ed25519;\n } else if (signature instanceof Secp256k1Signature) {\n this.variant = AnySignatureVariant.Secp256k1;\n } else {\n throw new Error(\"Unsupported signature type\");\n }\n }\n\n // endregion\n\n // region AccountSignature\n\n toUint8Array() {\n return this.bcsToBytes();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.variant);\n this.signature.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): AnySignature {\n const variantIndex = deserializer.deserializeUleb128AsU32();\n let signature: Signature;\n switch (variantIndex) {\n case AnySignatureVariant.Ed25519:\n signature = Ed25519Signature.deserialize(deserializer);\n break;\n case AnySignatureVariant.Secp256k1:\n signature = Secp256k1Signature.deserialize(deserializer);\n break;\n default:\n throw new Error(`Unknown variant index for AnySignature: ${variantIndex}`);\n }\n return new AnySignature(signature);\n }\n\n // endregion\n}\n","import { SigningScheme as AuthenticationKeyScheme } from \"../../types\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializer } from \"../../bcs/serializer\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { AccountPublicKey, PublicKey, VerifySignatureArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { AnyPublicKey, AnySignature } from \"./singleKey\";\n\n/* eslint-disable no-bitwise */\n\nfunction bitCount(byte: number) {\n let n = byte;\n n -= (n >> 1) & 0x55555555;\n n = (n & 0x33333333) + ((n >> 2) & 0x33333333);\n return (((n + (n >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24;\n}\n\n/* eslint-enable no-bitwise */\n\n/**\n * Represents the public key of a multi-agent account.\n *\n * The public keys of each individual agent can be any type of public key supported by Aptos.\n * Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports\n * `Legacy` and `Unified` authentication keys.\n */\nexport class MultiKey extends AccountPublicKey {\n /**\n * List of any public keys\n */\n public readonly publicKeys: AnyPublicKey[];\n\n /**\n * The minimum number of valid signatures required, for the number of public keys specified\n */\n public readonly signaturesRequired: number;\n\n // region Constructors\n\n constructor(args: { publicKeys: Array<PublicKey>; signaturesRequired: number }) {\n super();\n const { publicKeys, signaturesRequired } = args;\n\n // Validate number of public keys is greater than signature required\n if (signaturesRequired < 1) {\n throw new Error(\"The number of required signatures needs to be greater than 0\");\n }\n\n // Validate number of public keys is greater than signature required\n if (publicKeys.length < signaturesRequired) {\n throw new Error(\n `Provided ${publicKeys.length} public keys is smaller than the ${signaturesRequired} required signatures`,\n );\n }\n\n // Make sure that all keys are normalized to the SingleKey authentication scheme\n this.publicKeys = publicKeys.map((publicKey) =>\n publicKey instanceof AnyPublicKey ? publicKey : new AnyPublicKey(publicKey),\n );\n\n this.signaturesRequired = signaturesRequired;\n }\n\n // endregion\n\n // region AccountPublicKey\n\n // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars\n verifySignature(args: VerifySignatureArgs): boolean {\n throw new Error(\"not implemented\");\n }\n\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.MultiKey,\n input: this.toUint8Array(),\n });\n }\n\n toUint8Array(): Uint8Array {\n return this.bcsToBytes();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeVector(this.publicKeys);\n serializer.serializeU8(this.signaturesRequired);\n }\n\n static deserialize(deserializer: Deserializer): MultiKey {\n const keys = deserializer.deserializeVector(AnyPublicKey);\n const signaturesRequired = deserializer.deserializeU8();\n\n return new MultiKey({ publicKeys: keys, signaturesRequired });\n }\n\n // endregion\n\n /**\n * Create a bitmap that holds the mapping from the original public keys\n * to the signatures passed in\n *\n * @param args.bits array of the index mapping to the matching public keys\n * @returns Uint8array bit map\n */\n createBitmap(args: { bits: number[] }): Uint8Array {\n const { bits } = args;\n // Bits are read from left to right. e.g. 0b10000000 represents the first bit is set in one byte.\n // The decimal value of 0b10000000 is 128.\n const firstBitInByte = 128;\n const bitmap = new Uint8Array([0, 0, 0, 0]);\n\n // Check if duplicates exist in bits\n const dupCheckSet = new Set();\n\n bits.forEach((bit: number, idx: number) => {\n if (idx + 1 > this.publicKeys.length) {\n throw new Error(`Signature index ${idx + 1} is out of public keys range, ${this.publicKeys.length}.`);\n }\n\n if (dupCheckSet.has(bit)) {\n throw new Error(`Duplicate bit ${bit} detected.`);\n }\n\n dupCheckSet.add(bit);\n\n const byteOffset = Math.floor(bit / 8);\n\n let byte = bitmap[byteOffset];\n\n // eslint-disable-next-line no-bitwise\n byte |= firstBitInByte >> bit % 8;\n\n bitmap[byteOffset] = byte;\n });\n\n return bitmap;\n }\n}\n\nexport class MultiKeySignature extends Signature {\n /**\n * Number of bytes in the bitmap representing who signed the transaction (32-bits)\n */\n static BITMAP_LEN: number = 4;\n\n /**\n * Maximum number of Ed25519 signatures supported\n */\n static MAX_SIGNATURES_SUPPORTED = MultiKeySignature.BITMAP_LEN * 8;\n\n /**\n * The list of underlying Ed25519 signatures\n */\n public readonly signatures: AnySignature[];\n\n /**\n * 32-bit Bitmap representing who signed the transaction\n *\n * This is represented where each public key can be masked to determine whether the message was signed by that key.\n */\n public readonly bitmap: Uint8Array;\n\n /**\n * Signature for a K-of-N multi-sig transaction.\n *\n * @see {@link\n * https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}\n *\n * @param args.signatures A list of signatures\n * @param args.bitmap 4 bytes, at most 32 signatures are supported. If Nth bit value is `1`, the Nth\n * signature should be provided in `signatures`. Bits are read from left to right\n */\n constructor(args: { signatures: Array<Signature | AnySignature>; bitmap: Uint8Array | number[] }) {\n super();\n const { signatures, bitmap } = args;\n\n if (signatures.length > MultiKeySignature.MAX_SIGNATURES_SUPPORTED) {\n throw new Error(`The number of signatures cannot be greater than ${MultiKeySignature.MAX_SIGNATURES_SUPPORTED}`);\n }\n\n // Make sure that all signatures are normalized to the SingleKey authentication scheme\n this.signatures = signatures.map((signature) =>\n signature instanceof AnySignature ? signature : new AnySignature(signature),\n );\n\n if (!(bitmap instanceof Uint8Array)) {\n this.bitmap = MultiKeySignature.createBitmap({ bits: bitmap });\n } else if (bitmap.length !== MultiKeySignature.BITMAP_LEN) {\n throw new Error(`\"bitmap\" length should be ${MultiKeySignature.BITMAP_LEN}`);\n } else {\n this.bitmap = bitmap;\n }\n\n const nSignatures = this.bitmap.reduce((acc, byte) => acc + bitCount(byte), 0);\n if (nSignatures !== this.signatures.length) {\n throw new Error(`Expecting ${nSignatures} signatures from the bitmap, but got ${this.signatures.length}`);\n }\n }\n\n /**\n * Helper method to create a bitmap out of the specified bit positions\n * @param args.bits The bitmap positions that should be set. A position starts at index 0.\n * Valid position should range between 0 and 31.\n * @example\n * Here's an example of valid `bits`\n * ```\n * [0, 2, 31]\n * ```\n * `[0, 2, 31]` means the 1st, 3rd and 32nd bits should be set in the bitmap.\n * The result bitmap should be 0b1010000000000000000000000000001\n *\n * @returns bitmap that is 32bit long\n */\n static createBitmap(args: { bits: number[] }): Uint8Array {\n const { bits } = args;\n // Bits are read from left to right. e.g. 0b10000000 represents the first bit is set in one byte.\n // The decimal value of 0b10000000 is 128.\n const firstBitInByte = 128;\n const bitmap = new Uint8Array([0, 0, 0, 0]);\n\n // Check if duplicates exist in bits\n const dupCheckSet = new Set();\n\n bits.forEach((bit: number) => {\n if (bit >= MultiKeySignature.MAX_SIGNATURES_SUPPORTED) {\n throw new Error(`Cannot have a signature larger than ${MultiKeySignature.MAX_SIGNATURES_SUPPORTED - 1}.`);\n }\n\n if (dupCheckSet.has(bit)) {\n throw new Error(\"Duplicate bits detected.\");\n }\n\n dupCheckSet.add(bit);\n\n const byteOffset = Math.floor(bit / 8);\n\n let byte = bitmap[byteOffset];\n\n // eslint-disable-next-line no-bitwise\n byte |= firstBitInByte >> bit % 8;\n\n bitmap[byteOffset] = byte;\n });\n\n return bitmap;\n }\n\n // region Signature\n\n toUint8Array(): Uint8Array {\n return this.bcsToBytes();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n // Note: we should not need to serialize the vector length, as it can be derived from the bitmap\n serializer.serializeVector(this.signatures);\n serializer.serializeBytes(this.bitmap);\n }\n\n static deserialize(deserializer: Deserializer): MultiKeySignature {\n const bitmap = deserializer.deserializeBytes();\n const nSignatures = bitmap.reduce((acc, byte) => acc + bitCount(byte), 0);\n const signatures: AnySignature[] = [];\n for (let i = 0; i < nSignatures; i += 1) {\n const signature = AnySignature.deserialize(deserializer);\n signatures.push(signature);\n }\n return new MultiKeySignature({ signatures, bitmap });\n }\n\n // endregion\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { Serializer, Deserializer, Serializable } from \"../../bcs\";\nimport { AnyPublicKey, AnySignature } from \"../../core/crypto\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"../../core/crypto/ed25519\";\nimport { MultiEd25519PublicKey, MultiEd25519Signature } from \"../../core/crypto/multiEd25519\";\nimport { MultiKey } from \"../../core/crypto/multiKey\";\nimport { AccountAuthenticatorVariant } from \"../../types\";\n\nexport abstract class AccountAuthenticator extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n static deserialize(deserializer: Deserializer): AccountAuthenticator {\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case AccountAuthenticatorVariant.Ed25519:\n return AccountAuthenticatorEd25519.load(deserializer);\n case AccountAuthenticatorVariant.MultiEd25519:\n return AccountAuthenticatorMultiEd25519.load(deserializer);\n case AccountAuthenticatorVariant.SingleKey:\n return AccountAuthenticatorSingleKey.load(deserializer);\n case AccountAuthenticatorVariant.MultiKey:\n return AccountAuthenticatorMultiKey.load(deserializer);\n default:\n throw new Error(`Unknown variant index for AccountAuthenticator: ${index}`);\n }\n }\n\n isEd25519(): this is AccountAuthenticatorEd25519 {\n return this instanceof AccountAuthenticatorEd25519;\n }\n\n isMultiEd25519(): this is AccountAuthenticatorMultiEd25519 {\n return this instanceof AccountAuthenticatorMultiEd25519;\n }\n\n isSingleKey(): this is AccountAuthenticatorSingleKey {\n return this instanceof AccountAuthenticatorSingleKey;\n }\n\n isMultiKey(): this is AccountAuthenticatorMultiKey {\n return this instanceof AccountAuthenticatorMultiKey;\n }\n}\n\n/**\n * Transaction authenticator Ed25519 for a multi signer transaction\n *\n * @param public_key Account's Ed25519 public key.\n * @param signature Account's Ed25519 signature\n *\n */\nexport class AccountAuthenticatorEd25519 extends AccountAuthenticator {\n public readonly public_key: Ed25519PublicKey;\n\n public readonly signature: Ed25519Signature;\n\n constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.Ed25519);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorEd25519 {\n const public_key = Ed25519PublicKey.deserialize(deserializer);\n const signature = Ed25519Signature.deserialize(deserializer);\n return new AccountAuthenticatorEd25519(public_key, signature);\n }\n}\n\n/**\n * Transaction authenticator Multi Ed25519 for a multi signers transaction\n *\n * @param public_key Account's MultiEd25519 public key.\n * @param signature Account's MultiEd25519 signature\n *\n */\nexport class AccountAuthenticatorMultiEd25519 extends AccountAuthenticator {\n public readonly public_key: MultiEd25519PublicKey;\n\n public readonly signature: MultiEd25519Signature;\n\n constructor(public_key: MultiEd25519PublicKey, signature: MultiEd25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.MultiEd25519);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorMultiEd25519 {\n const public_key = MultiEd25519PublicKey.deserialize(deserializer);\n const signature = MultiEd25519Signature.deserialize(deserializer);\n return new AccountAuthenticatorMultiEd25519(public_key, signature);\n }\n}\n\n/**\n * AccountAuthenticatorSingleKey for a single signer\n *\n * @param public_key AnyPublicKey\n * @param signature AnySignature\n *\n */\nexport class AccountAuthenticatorSingleKey extends AccountAuthenticator {\n public readonly public_key: AnyPublicKey;\n\n public readonly signature: AnySignature;\n\n constructor(public_key: AnyPublicKey, signature: AnySignature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.SingleKey);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorSingleKey {\n const public_key = AnyPublicKey.deserialize(deserializer);\n const signature = AnySignature.deserialize(deserializer);\n return new AccountAuthenticatorSingleKey(public_key, signature);\n }\n}\n\n/**\n * AccountAuthenticatorMultiKey for a multi signer\n *\n * @param public_keys MultiKey\n * @param signatures Signature\n *\n */\nexport class AccountAuthenticatorMultiKey extends AccountAuthenticator {\n public readonly public_keys: MultiKey;\n\n public readonly signatures: Array<AnySignature>;\n\n public readonly signatures_bitmap: Uint8Array;\n\n constructor(public_keys: MultiKey, signatures: Array<AnySignature>, signatures_bitmap: Uint8Array) {\n super();\n this.public_keys = public_keys;\n this.signatures = signatures;\n this.signatures_bitmap = signatures_bitmap;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.MultiKey);\n this.public_keys.serialize(serializer);\n serializer.serializeVector<AnySignature>(this.signatures);\n serializer.serializeBytes(this.signatures_bitmap);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorMultiKey {\n const public_keys = MultiKey.deserialize(deserializer);\n const signatures = deserializer.deserializeVector(AnySignature);\n const signatures_bitmap = deserializer.deserializeBytes();\n return new AccountAuthenticatorMultiKey(public_keys, signatures, signatures_bitmap);\n }\n}\n","import { AccountAuthenticatorEd25519 } from \"../../transactions/authenticator/account\";\nimport { HexInput, SigningScheme } from \"../../types\";\nimport { AccountAddress, AccountAddressInput } from \"../accountAddress\";\nimport { Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature } from \"../crypto\";\nimport type { Account } from \"./Account\";\n\nexport interface Ed25519SignerConstructorArgs {\n privateKey: Ed25519PrivateKey;\n address?: AccountAddressInput;\n}\n\nexport interface Ed25519SignerFromDerivationPathArgs {\n path: string;\n mnemonic: string;\n}\n\nexport interface VerifyEd25519SignatureArgs {\n message: HexInput;\n signature: Ed25519Signature;\n}\n\n/**\n * Signer implementation for the Ed25519 authentication scheme.\n * This extends an {@link Ed25519Account} by adding signing capabilities through an {@link Ed25519PrivateKey}.\n *\n * Note: Generating a signer instance does not create the account on-chain.\n */\nexport class Ed25519Account implements Account {\n /**\n * Private key associated with the account\n */\n readonly privateKey: Ed25519PrivateKey;\n\n readonly publicKey: Ed25519PublicKey;\n\n readonly accountAddress: AccountAddress;\n\n readonly signingScheme = SigningScheme.Ed25519;\n\n // region Constructors\n\n constructor(args: Ed25519SignerConstructorArgs) {\n const { privateKey, address } = args;\n this.privateKey = privateKey;\n this.publicKey = privateKey.publicKey();\n this.accountAddress = address ? AccountAddress.from(address) : this.publicKey.authKey().derivedAddress();\n }\n\n /**\n * Derives a signer from a randomly generated private key\n */\n static generate() {\n const privateKey = Ed25519PrivateKey.generate();\n return new Ed25519Account({ privateKey });\n }\n\n /**\n * Derives an account with bip44 path and mnemonics\n *\n * @param args.path the BIP44 derive hardened path e.g. m/44'/637'/0'/0'/0'\n * Detailed description: {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}\n * @param args.mnemonic the mnemonic seed phrase of the account\n */\n static fromDerivationPath(args: Ed25519SignerFromDerivationPathArgs) {\n const { path, mnemonic } = args;\n const privateKey = Ed25519PrivateKey.fromDerivationPath(path, mnemonic);\n return new Ed25519Account({ privateKey });\n }\n\n // endregion\n\n // region Account\n\n verifySignature(args: VerifyEd25519SignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n signWithAuthenticator(message: HexInput) {\n const signature = this.privateKey.sign(message);\n return new AccountAuthenticatorEd25519(this.publicKey, signature);\n }\n\n sign(message: HexInput) {\n return this.signWithAuthenticator(message).signature;\n }\n\n // endregion\n}\n","import { AccountAuthenticatorSingleKey } from \"../../transactions/authenticator/account\";\nimport { type HexInput, SigningScheme, SigningSchemeInput } from \"../../types\";\nimport { AccountAddress, AccountAddressInput } from \"../accountAddress\";\nimport { AnyPublicKey, AnySignature, Ed25519PrivateKey, PrivateKey, Secp256k1PrivateKey } from \"../crypto\";\nimport type { Account } from \"./Account\";\n\nexport interface SingleKeySignerConstructorArgs {\n privateKey: PrivateKey;\n address?: AccountAddressInput;\n}\n\nexport interface SingleKeySignerGenerateArgs {\n scheme?: SigningSchemeInput;\n}\n\nexport type SingleKeySignerFromDerivationPathArgs = SingleKeySignerGenerateArgs & {\n path: string;\n mnemonic: string;\n};\n\nexport interface VerifySingleKeySignatureArgs {\n message: HexInput;\n signature: AnySignature;\n}\n\n/**\n * Signer implementation for the SingleKey authentication scheme.\n * This extends a SingleKeyAccount by adding signing capabilities through a valid private key.\n * Currently, the only supported signature schemes are Ed25519 and Secp256k1.\n *\n * Note: Generating a signer instance does not create the account on-chain.\n */\nexport class SingleKeyAccount implements Account {\n /**\n * Private key associated with the account\n */\n readonly privateKey: PrivateKey;\n\n readonly publicKey: AnyPublicKey;\n\n readonly accountAddress: AccountAddress;\n\n readonly signingScheme = SigningScheme.SingleKey;\n\n // region Constructors\n\n constructor(args: SingleKeySignerConstructorArgs) {\n const { privateKey, address } = args;\n this.privateKey = privateKey;\n this.publicKey = new AnyPublicKey(privateKey.publicKey());\n this.accountAddress = address ? AccountAddress.from(address) : this.publicKey.authKey().derivedAddress();\n }\n\n /**\n * Derives an account from a randomly generated private key.\n * Default generation is using an Ed25519 key\n * @returns Account with the given signature scheme\n */\n static generate(args: SingleKeySignerGenerateArgs = {}) {\n const { scheme = SigningSchemeInput.Ed25519 } = args;\n let privateKey: PrivateKey;\n switch (scheme) {\n case SigningSchemeInput.Ed25519:\n privateKey = Ed25519PrivateKey.generate();\n break;\n case SigningSchemeInput.Secp256k1Ecdsa:\n privateKey = Secp256k1PrivateKey.generate();\n break;\n default:\n throw new Error(`Unsupported signature scheme ${scheme}`);\n }\n return new SingleKeyAccount({ privateKey });\n }\n\n /**\n * Derives an account with bip44 path and mnemonics,\n * Default to using an Ed25519 signature scheme.\n *\n * @param args.scheme The signature scheme to derive the private key with\n * @param args.path the BIP44 derive hardened path (e.g. m/44'/637'/0'/0'/0') for Ed25519,\n * or non-hardened path (e.g. m/44'/637'/0'/0/0) for secp256k1\n * Detailed description: {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}\n * @param args.mnemonic the mnemonic seed phrase of the account\n */\n static fromDerivationPath(args: SingleKeySignerFromDerivationPathArgs) {\n const { scheme = SigningSchemeInput.Ed25519, path, mnemonic } = args;\n let privateKey: PrivateKey;\n switch (scheme) {\n case SigningSchemeInput.Ed25519:\n privateKey = Ed25519PrivateKey.fromDerivationPath(path, mnemonic);\n break;\n case SigningSchemeInput.Secp256k1Ecdsa:\n privateKey = Secp256k1PrivateKey.fromDerivationPath(path, mnemonic);\n break;\n default:\n throw new Error(`Unsupported signature scheme ${scheme}`);\n }\n return new SingleKeyAccount({ privateKey });\n }\n\n // endregion\n\n // region Account\n\n verifySignature(args: VerifySingleKeySignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n signWithAuthenticator(message: HexInput) {\n const innerSignature = this.privateKey.sign(message);\n const signature = new AnySignature(innerSignature);\n return new AccountAuthenticatorSingleKey(this.publicKey, signature);\n }\n\n sign(message: HexInput) {\n return this.signWithAuthenticator(message).signature;\n }\n\n // endregion\n}\n","import type { AccountAuthenticator } from \"../../transactions/authenticator/account\";\nimport { HexInput, SigningScheme, SigningSchemeInput } from \"../../types\";\nimport type { AccountAddress, AccountAddressInput } from \"../accountAddress\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { AccountPublicKey, Ed25519PrivateKey, PrivateKey, Signature, VerifySignatureArgs } from \"../crypto\";\nimport { Ed25519Account } from \"./Ed25519Account\";\nimport { SingleKeyAccount } from \"./SingleKeyAccount\";\n\n/**\n * Arguments for creating an `Ed25519Account` from an `Ed25519PrivateKey`.\n * This is the default input type when passing an `Ed25519PrivateKey`.\n * In order to use the SingleKey authentication scheme, `legacy` needs to be explicitly set to false.\n */\nexport interface CreateEd25519AccountFromPrivateKeyArgs {\n privateKey: Ed25519PrivateKey;\n address?: AccountAddressInput;\n legacy?: true;\n}\n\n/**\n * Arguments for creating an `SingleKeyAccount` from an `Ed25519PrivateKey`.\n * The `legacy` argument needs to be explicitly set to false in order to\n * use the `SingleKey` authentication scheme.\n */\nexport interface CreateEd25519SingleKeyAccountFromPrivateKeyArgs {\n privateKey: Ed25519PrivateKey;\n address?: AccountAddressInput;\n legacy: false;\n}\n\n/**\n * Arguments for creating an `SingleKeyAccount` from any supported private key\n * that is not an `Ed25519PrivateKey`.\n * The `legacy` argument defaults to false and cannot be explicitly set to true.\n */\nexport interface CreateSingleKeyAccountFromPrivateKeyArgs {\n privateKey: Exclude<PrivateKey, Ed25519PrivateKey>;\n address?: AccountAddressInput;\n legacy?: false;\n}\n\n/**\n * Arguments for creating an opaque `Account` from any supported private key.\n * This is used when the private key type is not known at compilation time.\n */\nexport interface CreateAccountFromPrivateKeyArgs {\n privateKey: PrivateKey;\n address?: AccountAddressInput;\n legacy?: boolean;\n}\n\n/**\n * Arguments for generating an `Ed25519Account`.\n * This is the input type used by default.\n */\nexport interface GenerateEd25519AccountArgs {\n scheme?: SigningSchemeInput.Ed25519;\n legacy?: true;\n}\n\n/**\n * Arguments for generating an `SingleKeyAccount` with ah underlying `Ed25519PrivateKey`.\n * The `legacy` argument needs to be explicitly set to false,\n * otherwise an `Ed25519Account` will be returned instead.\n */\nexport interface GenerateEd25519SingleKeyAccountArgs {\n scheme?: SigningSchemeInput.Ed25519;\n legacy: false;\n}\n\n/**\n * Arguments for generating an `SingleKeyAccount` with any supported private key\n * that is not an `Ed25519PrivateKey`.\n * The `legacy` argument defaults to false and cannot be explicitly set to true.\n */\nexport interface GenerateSingleKeyAccountArgs {\n scheme: Exclude<SigningSchemeInput, SigningSchemeInput.Ed25519>;\n legacy?: false;\n}\n\n/**\n * Arguments for generating an opaque `Account`.\n * This is used when the input signature scheme is not known at compilation time.\n */\nexport interface GenerateAccountArgs {\n scheme?: SigningSchemeInput;\n legacy?: boolean;\n}\n\n/**\n * Arguments for deriving a private key from a mnemonic phrase and a BIP44 path.\n */\nexport interface PrivateKeyFromDerivationPathArgs {\n path: string;\n mnemonic: string;\n}\n\n/**\n * Interface for a generic Aptos account.\n *\n * The interface is defined as abstract class to provide a single entrypoint for account generation,\n * either through `Account.generate()` or `Account.fromDerivationPath`.\n * Despite this being an abstract class, it should be treated as an interface and enforced using\n * the `implements` keyword.\n *\n * Note: Generating an account instance does not create the account on-chain.\n */\nexport abstract class Account {\n /**\n * Private key associated with the account.\n * Note: this will be removed in the next major release,\n * as not all accounts have a private key.\n */\n abstract readonly privateKey: PrivateKey;\n\n /**\n * Public key associated with the account\n */\n abstract readonly publicKey: AccountPublicKey;\n\n /**\n * Account address associated with the account\n */\n abstract readonly accountAddress: AccountAddress;\n\n /**\n * Signing scheme used to sign transactions\n */\n abstract signingScheme: SigningScheme;\n\n /**\n * Derives an account from a randomly generated private key.\n * @param args.scheme The signature scheme to use, to generate the private key\n * @param args.legacy Whether to use a legacy authentication scheme, when applicable\n * @returns An account compatible with the provided signature scheme\n */\n static generate(args?: GenerateEd25519AccountArgs): Ed25519Account;\n static generate(args: GenerateEd25519SingleKeyAccountArgs): SingleKeyAccount;\n static generate(args: GenerateSingleKeyAccountArgs): SingleKeyAccount;\n static generate(args: GenerateAccountArgs): Account;\n static generate(args: GenerateAccountArgs = {}) {\n const { scheme = SigningSchemeInput.Ed25519, legacy = true } = args;\n if (scheme === SigningSchemeInput.Ed25519 && legacy) {\n return Ed25519Account.generate();\n }\n return SingleKeyAccount.generate({ scheme });\n }\n\n /**\n * Creates an account from the provided private key.\n *\n * @param args.privateKey a valid private key\n * @param args.address the account's address. If not provided, it will be derived from the public key.\n * @param args.legacy Whether to use a legacy authentication scheme, when applicable\n */\n static fromPrivateKey(args: CreateEd25519AccountFromPrivateKeyArgs): Ed25519Account;\n static fromPrivateKey(args: CreateEd25519SingleKeyAccountFromPrivateKeyArgs): SingleKeyAccount;\n static fromPrivateKey(args: CreateSingleKeyAccountFromPrivateKeyArgs): SingleKeyAccount;\n static fromPrivateKey(args: CreateAccountFromPrivateKeyArgs): Account;\n static fromPrivateKey(args: CreateAccountFromPrivateKeyArgs) {\n const { privateKey, address, legacy = true } = args;\n if (privateKey instanceof Ed25519PrivateKey && legacy) {\n return new Ed25519Account({\n privateKey,\n address,\n });\n }\n return new SingleKeyAccount({ privateKey, address });\n }\n\n /**\n * @deprecated use `fromPrivateKey` instead.\n * Instantiates an account given a private key and a specified account address.\n * This is primarily used to instantiate an `Account` that has had its authentication key rotated.\n *\n * @param args.privateKey PrivateKey - the underlying private key for the account\n * @param args.address AccountAddress - The account address the `Account` will sign for\n * @param args.legacy optional. If set to false, the keypair generated is a Unified keypair. Defaults\n * to generating a Legacy Ed25519 keypair\n *\n * @returns Account\n */\n static fromPrivateKeyAndAddress(args: CreateAccountFromPrivateKeyArgs) {\n return this.fromPrivateKey(args);\n }\n\n /**\n * Derives an account with bip44 path and mnemonics\n *\n * @param args.scheme The signature scheme to derive the private key with\n * @param args.path the BIP44 derive hardened path (e.g. m/44'/637'/0'/0'/0') for Ed25519,\n * or non-hardened path (e.g. m/44'/637'/0'/0/0) for secp256k1\n * Detailed description: {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}\n * @param args.mnemonic the mnemonic seed phrase of the account\n */\n static fromDerivationPath(args: GenerateEd25519AccountArgs & PrivateKeyFromDerivationPathArgs): Ed25519Account;\n static fromDerivationPath(\n args: GenerateEd25519SingleKeyAccountArgs & PrivateKeyFromDerivationPathArgs,\n ): SingleKeyAccount;\n static fromDerivationPath(args: GenerateSingleKeyAccountArgs & PrivateKeyFromDerivationPathArgs): SingleKeyAccount;\n static fromDerivationPath(args: GenerateAccountArgs & PrivateKeyFromDerivationPathArgs): Account;\n static fromDerivationPath(args: GenerateAccountArgs & PrivateKeyFromDerivationPathArgs) {\n const { scheme = SigningSchemeInput.Ed25519, mnemonic, path, legacy = true } = args;\n if (scheme === SigningSchemeInput.Ed25519 && legacy) {\n return Ed25519Account.fromDerivationPath({ mnemonic, path });\n }\n return SingleKeyAccount.fromDerivationPath({ scheme, mnemonic, path });\n }\n\n /**\n * @deprecated use `publicKey.authKey()` instead.\n * This key enables account owners to rotate their private key(s)\n * associated with the account without changing the address that hosts their account.\n * See here for more info: {@link https://aptos.dev/concepts/accounts#single-signer-authentication}\n *\n * @param args.publicKey PublicKey - public key of the account\n * @returns The authentication key for the associated account\n */\n static authKey(args: { publicKey: AccountPublicKey }): AuthenticationKey {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Sign a message using the available signing capabilities.\n * @param message the signing message, as binary input\n * @return the AccountAuthenticator containing the signature, together with the account's public key\n */\n abstract signWithAuthenticator(message: HexInput): AccountAuthenticator;\n\n /**\n * Sign the given message with the private key.\n * @param message in HexInput format\n * @returns AccountSignature\n */\n abstract sign(message: HexInput): Signature;\n\n /**\n * @param args.message raw message data in HexInput format\n * @param args.signature signed message signature\n */\n verifySignature(args: VerifySignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/account}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * account namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { AptosApiError, getAptosFullNode, paginateWithCursor } from \"../client\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { Account } from \"../core/account\";\nimport { AnyPublicKey, Ed25519PublicKey, PrivateKey } from \"../core/crypto\";\nimport { getTableItem, queryIndexer } from \"./general\";\nimport {\n AccountData,\n GetAccountCoinsDataResponse,\n GetAccountCollectionsWithOwnedTokenResponse,\n GetAccountOwnedObjectsResponse,\n GetAccountOwnedTokensFromCollectionResponse,\n GetAccountOwnedTokensQueryResponse,\n LedgerVersionArg,\n MoveModuleBytecode,\n MoveResource,\n MoveStructId,\n OrderByArg,\n PaginationArgs,\n TokenStandardArg,\n TransactionResponse,\n WhereArg,\n} from \"../types\";\nimport {\n GetAccountCoinsCountQuery,\n GetAccountCoinsDataQuery,\n GetAccountCollectionsWithOwnedTokensQuery,\n GetAccountOwnedObjectsQuery,\n GetAccountOwnedTokensFromCollectionQuery,\n GetAccountOwnedTokensQuery,\n GetAccountTokensCountQuery,\n GetAccountTransactionsCountQuery,\n} from \"../types/generated/operations\";\nimport {\n GetAccountCoinsCount,\n GetAccountCoinsData,\n GetAccountCollectionsWithOwnedTokens,\n GetAccountOwnedObjects,\n GetAccountOwnedTokens,\n GetAccountOwnedTokensFromCollection,\n GetAccountTokensCount,\n GetAccountTransactionsCount,\n} from \"../types/generated/queries\";\nimport { memoizeAsync } from \"../utils/memoize\";\nimport { Secp256k1PrivateKey, AuthenticationKey, Ed25519PrivateKey } from \"../core\";\nimport { CurrentFungibleAssetBalancesBoolExp } from \"../types/generated/types\";\n\nexport async function getInfo(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n}): Promise<AccountData> {\n const { aptosConfig, accountAddress } = args;\n const { data } = await getAptosFullNode<{}, AccountData>({\n aptosConfig,\n originMethod: \"getInfo\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}`,\n });\n return data;\n}\n\nexport async function getModules(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & LedgerVersionArg;\n}): Promise<MoveModuleBytecode[]> {\n const { aptosConfig, accountAddress, options } = args;\n return paginateWithCursor<{}, MoveModuleBytecode[]>({\n aptosConfig,\n originMethod: \"getModules\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/modules`,\n params: {\n ledger_version: options?.ledgerVersion,\n start: options?.offset,\n limit: options?.limit ?? 1000,\n },\n });\n}\n\n/**\n * Queries for a move module given account address and module name\n *\n * @param args.accountAddress Hex-encoded 32 byte Aptos account address\n * @param args.moduleName The name of the module\n * @param args.query.ledgerVersion Specifies ledger version of transactions. By default, latest version will be used\n * @returns The move module.\n */\nexport async function getModule(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n moduleName: string;\n options?: LedgerVersionArg;\n}): Promise<MoveModuleBytecode> {\n // We don't memoize the account module by ledger version, as it's not a common use case, this would be handled\n // by the developer directly\n if (args.options?.ledgerVersion !== undefined) {\n return getModuleInner(args);\n }\n\n return memoizeAsync(\n async () => getModuleInner(args),\n `module-${args.accountAddress}-${args.moduleName}`,\n 1000 * 60 * 5, // 5 minutes\n )();\n}\n\nasync function getModuleInner(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n moduleName: string;\n options?: LedgerVersionArg;\n}): Promise<MoveModuleBytecode> {\n const { aptosConfig, accountAddress, moduleName, options } = args;\n\n const { data } = await getAptosFullNode<{}, MoveModuleBytecode>({\n aptosConfig,\n originMethod: \"getModule\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/module/${moduleName}`,\n params: { ledger_version: options?.ledgerVersion },\n });\n return data;\n}\n\nexport async function getTransactions(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs;\n}): Promise<TransactionResponse[]> {\n const { aptosConfig, accountAddress, options } = args;\n return paginateWithCursor<{}, TransactionResponse[]>({\n aptosConfig,\n originMethod: \"getTransactions\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/transactions`,\n params: { start: options?.offset, limit: options?.limit },\n });\n}\n\nexport async function getResources(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & LedgerVersionArg;\n}): Promise<MoveResource[]> {\n const { aptosConfig, accountAddress, options } = args;\n return paginateWithCursor<{}, MoveResource[]>({\n aptosConfig,\n originMethod: \"getResources\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/resources`,\n params: {\n ledger_version: options?.ledgerVersion,\n start: options?.offset,\n limit: options?.limit ?? 999,\n },\n });\n}\n\nexport async function getResource<T extends {}>(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n resourceType: MoveStructId;\n options?: LedgerVersionArg;\n}): Promise<T> {\n const { aptosConfig, accountAddress, resourceType, options } = args;\n const { data } = await getAptosFullNode<{}, MoveResource>({\n aptosConfig,\n originMethod: \"getResource\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/resource/${resourceType}`,\n params: { ledger_version: options?.ledgerVersion },\n });\n return data.data as T;\n}\n\nexport async function lookupOriginalAccountAddress(args: {\n aptosConfig: AptosConfig;\n authenticationKey: AccountAddressInput;\n options?: LedgerVersionArg;\n}): Promise<AccountAddress> {\n const { aptosConfig, authenticationKey, options } = args;\n type OriginatingAddress = {\n address_map: { handle: string };\n };\n const resource = await getResource<OriginatingAddress>({\n aptosConfig,\n accountAddress: \"0x1\",\n resourceType: \"0x1::account::OriginatingAddress\",\n options,\n });\n\n const {\n address_map: { handle },\n } = resource;\n\n const authKeyAddress = AccountAddress.from(authenticationKey);\n\n // If the address is not found in the address map, which means its not rotated\n // then return the address as is\n try {\n const originalAddress = await getTableItem<string>({\n aptosConfig,\n handle,\n data: {\n key: authKeyAddress.toString(),\n key_type: \"address\",\n value_type: \"address\",\n },\n options,\n });\n\n return AccountAddress.from(originalAddress);\n } catch (err) {\n if (err instanceof AptosApiError && err.data.error_code === \"table_item_not_found\") {\n return authKeyAddress;\n }\n\n throw err;\n }\n}\n\nexport async function getAccountTokensCount(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, accountAddress } = args;\n\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const whereCondition: { owner_address: { _eq: string }; amount: { _gt: number } } = {\n owner_address: { _eq: address },\n amount: { _gt: 0 },\n };\n\n const graphqlQuery = {\n query: GetAccountTokensCount,\n variables: { where_condition: whereCondition },\n };\n\n const data = await queryIndexer<GetAccountTokensCountQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountTokensCount\",\n });\n\n // commonjs (aka cjs) doesnt handle Nullish Coalescing for some reason\n // might be because of how ts infer the graphql generated scheme type\n return data.current_token_ownerships_v2_aggregate.aggregate\n ? data.current_token_ownerships_v2_aggregate.aggregate.count\n : 0;\n}\n\nexport async function getAccountOwnedTokens(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountOwnedTokensQueryResponse[0]>;\n}): Promise<GetAccountOwnedTokensQueryResponse> {\n const { aptosConfig, accountAddress, options } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const whereCondition: { owner_address: { _eq: string }; amount: { _gt: number }; token_standard?: { _eq: string } } =\n {\n owner_address: { _eq: address },\n amount: { _gt: 0 },\n };\n\n if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard };\n }\n\n const graphqlQuery = {\n query: GetAccountOwnedTokens,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetAccountOwnedTokensQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountOwnedTokens\",\n });\n\n return data.current_token_ownerships_v2;\n}\n\nexport async function getAccountOwnedTokensFromCollectionAddress(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n collectionAddress: AccountAddressInput;\n options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountOwnedTokensFromCollectionResponse[0]>;\n}): Promise<GetAccountOwnedTokensFromCollectionResponse> {\n const { aptosConfig, accountAddress, collectionAddress, options } = args;\n const ownerAddress = AccountAddress.from(accountAddress).toStringLong();\n const collAddress = AccountAddress.from(collectionAddress).toStringLong();\n\n const whereCondition: {\n owner_address: { _eq: string };\n current_token_data: { collection_id: { _eq: string } };\n amount: { _gt: number };\n token_standard?: { _eq: string };\n } = {\n owner_address: { _eq: ownerAddress },\n current_token_data: { collection_id: { _eq: collAddress } },\n amount: { _gt: 0 },\n };\n\n if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard };\n }\n\n const graphqlQuery = {\n query: GetAccountOwnedTokensFromCollection,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetAccountOwnedTokensFromCollectionQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountOwnedTokensFromCollectionAddress\",\n });\n\n return data.current_token_ownerships_v2;\n}\n\nexport async function getAccountCollectionsWithOwnedTokens(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountCollectionsWithOwnedTokenResponse[0]>;\n}): Promise<GetAccountCollectionsWithOwnedTokenResponse> {\n const { aptosConfig, accountAddress, options } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const whereCondition: {\n owner_address: { _eq: string };\n amount: { _gt: number };\n current_collection?: { token_standard: { _eq: string } };\n } = {\n owner_address: { _eq: address },\n amount: { _gt: 0 },\n };\n\n if (options?.tokenStandard) {\n whereCondition.current_collection = {\n token_standard: { _eq: options?.tokenStandard },\n };\n }\n\n const graphqlQuery = {\n query: GetAccountCollectionsWithOwnedTokens,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetAccountCollectionsWithOwnedTokensQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountCollectionsWithOwnedTokens\",\n });\n\n return data.current_collection_ownership_v2_view;\n}\n\nexport async function getAccountTransactionsCount(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, accountAddress } = args;\n\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const graphqlQuery = {\n query: GetAccountTransactionsCount,\n variables: { address },\n };\n\n const data = await queryIndexer<GetAccountTransactionsCountQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountTransactionsCount\",\n });\n\n // commonjs (aka cjs) doesnt handle Nullish Coalescing for some reason\n // might be because of how ts infer the graphql generated scheme type\n return data.account_transactions_aggregate.aggregate ? data.account_transactions_aggregate.aggregate.count : 0;\n}\n\nexport async function getAccountCoinAmount(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n coinType: MoveStructId;\n}): Promise<number> {\n const { aptosConfig, accountAddress, coinType } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const data = await getAccountCoinsData({\n aptosConfig,\n accountAddress: address,\n options: {\n where: { asset_type: { _eq: coinType } },\n },\n });\n\n // commonjs (aka cjs) doesnt handle Nullish Coalescing for some reason\n // might be because of how ts infer the graphql generated scheme type\n return data[0] ? data[0].amount : 0;\n}\n\nexport async function getAccountCoinsData(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & OrderByArg<GetAccountCoinsDataResponse[0]> & WhereArg<CurrentFungibleAssetBalancesBoolExp>;\n}): Promise<GetAccountCoinsDataResponse> {\n const { aptosConfig, accountAddress, options } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const whereCondition: { owner_address: { _eq: string } } = {\n ...options?.where,\n owner_address: { _eq: address },\n };\n\n const graphqlQuery = {\n query: GetAccountCoinsData,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetAccountCoinsDataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountCoinsData\",\n });\n\n return data.current_fungible_asset_balances;\n}\n\nexport async function getAccountCoinsCount(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, accountAddress } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const graphqlQuery = {\n query: GetAccountCoinsCount,\n variables: { address },\n };\n\n const data = await queryIndexer<GetAccountCoinsCountQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountCoinsCount\",\n });\n\n if (!data.current_fungible_asset_balances_aggregate.aggregate) {\n throw Error(\"Failed to get the count of account coins\");\n }\n\n return data.current_fungible_asset_balances_aggregate.aggregate.count;\n}\n\nexport async function getAccountOwnedObjects(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & OrderByArg<GetAccountOwnedObjectsResponse[0]>;\n}): Promise<GetAccountOwnedObjectsResponse> {\n const { aptosConfig, accountAddress, options } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const whereCondition: { owner_address: { _eq: string } } = {\n owner_address: { _eq: address },\n };\n const graphqlQuery = {\n query: GetAccountOwnedObjects,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n const data = await queryIndexer<GetAccountOwnedObjectsQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountOwnedObjects\",\n });\n\n return data.current_objects;\n}\n\n/**\n * NOTE: There is a potential issue once unified single signer scheme will be adopted\n * by the community.\n *\n * Becuase on could create 2 accounts with the same private key with this new authenticator type,\n * we’ll need to determine the order in which we lookup the accounts. First unified\n * scheme and then legacy scheme vs first legacy scheme and then unified scheme.\n *\n */\nexport async function deriveAccountFromPrivateKey(args: {\n aptosConfig: AptosConfig;\n privateKey: PrivateKey;\n}): Promise<Account> {\n const { aptosConfig, privateKey } = args;\n const publicKey = new AnyPublicKey(privateKey.publicKey());\n\n if (privateKey instanceof Secp256k1PrivateKey) {\n // private key is secp256k1, therefore we know it for sure uses a single signer key\n const authKey = AuthenticationKey.fromPublicKey({ publicKey });\n const address = authKey.derivedAddress();\n return Account.fromPrivateKey({ privateKey, address });\n }\n\n if (privateKey instanceof Ed25519PrivateKey) {\n // lookup single sender ed25519\n const singleSenderTransactionAuthenticatorAuthKey = AuthenticationKey.fromPublicKey({\n publicKey,\n });\n const isSingleSenderTransactionAuthenticator = await isAccountExist({\n authKey: singleSenderTransactionAuthenticatorAuthKey,\n aptosConfig,\n });\n if (isSingleSenderTransactionAuthenticator) {\n const address = singleSenderTransactionAuthenticatorAuthKey.derivedAddress();\n return Account.fromPrivateKey({ privateKey, address, legacy: false });\n }\n // lookup legacy ed25519\n const legacyAuthKey = AuthenticationKey.fromPublicKey({\n publicKey: publicKey.publicKey as Ed25519PublicKey,\n });\n const isLegacyEd25519 = await isAccountExist({ authKey: legacyAuthKey, aptosConfig });\n if (isLegacyEd25519) {\n const address = legacyAuthKey.derivedAddress();\n return Account.fromPrivateKey({ privateKey, address, legacy: true });\n }\n }\n // if we are here, it means we couldn't find an address with an\n // auth key that matches the provided private key\n throw new Error(`Can't derive account from private key ${privateKey}`);\n}\n\nexport async function isAccountExist(args: { aptosConfig: AptosConfig; authKey: AuthenticationKey }): Promise<boolean> {\n const { aptosConfig, authKey } = args;\n const accountAddress = await lookupOriginalAccountAddress({\n aptosConfig,\n authenticationKey: authKey.derivedAddress(),\n });\n\n try {\n await getInfo({\n aptosConfig,\n accountAddress,\n });\n return true;\n } catch (error: any) {\n // account not found\n if (error.status === 404) {\n return false;\n }\n throw new Error(`Error while looking for an account info ${accountAddress.toString()}`);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { parseTypeTag } from \"../typeTag/parser\";\nimport { TypeTag, TypeTagStruct } from \"../typeTag\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport {\n EntryFunctionArgumentTypes,\n SimpleEntryFunctionArgumentTypes,\n EntryFunctionABI,\n ViewFunctionABI,\n FunctionABI,\n} from \"../types\";\nimport { Bool, MoveOption, MoveString, MoveVector, U128, U16, U256, U32, U64, U8 } from \"../../bcs\";\nimport { AccountAddress } from \"../../core\";\nimport { getModule } from \"../../internal/account\";\nimport {\n findFirstNonSignerArg,\n isBcsAddress,\n isBcsBool,\n isBcsString,\n isBcsU128,\n isBcsU16,\n isBcsU256,\n isBcsU32,\n isBcsU64,\n isBcsU8,\n isBool,\n isEncodedEntryFunctionArgument,\n isLargeNumber,\n isNull,\n isNumber,\n isString,\n throwTypeMismatch,\n} from \"./helpers\";\nimport { MoveFunction } from \"../../types\";\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * Convert type arguments to only type tags, allowing for string representations of type tags\n */\nexport function standardizeTypeTags(typeArguments?: Array<TypeTag | string>): Array<TypeTag> {\n return (\n typeArguments?.map((typeArg: string | TypeTag): TypeTag => {\n // Convert to TypeTag if it's a string representation\n if (isString(typeArg)) {\n return parseTypeTag(typeArg);\n }\n return typeArg;\n }) ?? []\n );\n}\n\n/**\n * Fetches a function ABI from the on-chain module ABI. It doesn't validate whether it's a view or entry function.\n * @param moduleAddress\n * @param moduleName\n * @param functionName\n * @param aptosConfig\n */\nexport async function fetchFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<MoveFunction | undefined> {\n // This fetch from the API is currently cached\n const module = await getModule({ aptosConfig, accountAddress: moduleAddress, moduleName });\n\n if (module.abi) {\n return module.abi.exposed_functions.find((func) => func.name === functionName);\n }\n\n return undefined;\n}\n\n/**\n * Fetches the ABI for an entry function from the module\n *\n * @param moduleAddress\n * @param moduleName\n * @param functionName\n * @param aptosConfig\n */\nexport async function fetchEntryFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<EntryFunctionABI> {\n const functionAbi = await fetchFunctionAbi(moduleAddress, moduleName, functionName, aptosConfig);\n\n // If there's no ABI, then the function is invalid\n if (!functionAbi) {\n throw new Error(`Could not find entry function ABI for '${moduleAddress}::${moduleName}::${functionName}'`);\n }\n\n // Non-entry functions also can't be used\n if (!functionAbi.is_entry) {\n throw new Error(`'${moduleAddress}::${moduleName}::${functionName}' is not an entry function`);\n }\n\n // Remove the signer arguments\n const numSigners = findFirstNonSignerArg(functionAbi);\n const params: TypeTag[] = [];\n for (let i = numSigners; i < functionAbi.params.length; i += 1) {\n params.push(parseTypeTag(functionAbi.params[i], { allowGenerics: true }));\n }\n\n return {\n signers: numSigners,\n typeParameters: functionAbi.generic_type_params,\n parameters: params,\n };\n}\n\n/**\n * Fetches the ABI for a view function from the module\n *\n * @param moduleAddress\n * @param moduleName\n * @param functionName\n * @param aptosConfig\n */\nexport async function fetchViewFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<ViewFunctionABI> {\n const functionAbi = await fetchFunctionAbi(moduleAddress, moduleName, functionName, aptosConfig);\n\n // If there's no ABI, then the function is invalid\n if (!functionAbi) {\n throw new Error(`Could not find view function ABI for '${moduleAddress}::${moduleName}::${functionName}'`);\n }\n\n // Non-view functions can't be used\n if (!functionAbi.is_view) {\n throw new Error(`'${moduleAddress}::${moduleName}::${functionName}' is not an view function`);\n }\n\n // Type tag parameters for the function\n const params: TypeTag[] = [];\n for (let i = 0; i < functionAbi.params.length; i += 1) {\n params.push(parseTypeTag(functionAbi.params[i], { allowGenerics: true }));\n }\n\n // The return types of the view function\n const returnTypes: TypeTag[] = [];\n for (let i = 0; i < functionAbi.return.length; i += 1) {\n returnTypes.push(parseTypeTag(functionAbi.return[i], { allowGenerics: true }));\n }\n\n return {\n typeParameters: functionAbi.generic_type_params,\n parameters: params,\n returnTypes,\n };\n}\n\n/**\n * Converts a non-BCS encoded argument into BCS encoded, if necessary\n * @param functionName\n * @param functionAbi\n * @param arg\n * @param position\n */\nexport function convertArgument(\n functionName: string,\n functionAbi: FunctionABI,\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n position: number,\n genericTypeParams: Array<TypeTag>,\n) {\n // Ensure not too many arguments\n if (position >= functionAbi.parameters.length) {\n throw new Error(`Too many arguments for '${functionName}', expected ${functionAbi.parameters.length}`);\n }\n\n const param = functionAbi.parameters[position];\n return checkOrConvertArgument(arg, param, position, genericTypeParams);\n}\n\nexport function checkOrConvertArgument(\n arg: SimpleEntryFunctionArgumentTypes | EntryFunctionArgumentTypes,\n param: TypeTag,\n position: number,\n genericTypeParams: Array<TypeTag>,\n) {\n // If the argument is bcs encoded, we can just use it directly\n if (isEncodedEntryFunctionArgument(arg)) {\n // Ensure the type matches the ABI\n checkType(param, arg, position);\n return arg;\n }\n\n // If it is not BCS encoded, we will need to convert it with the ABI\n return parseArg(arg, param, position, genericTypeParams);\n}\n\n/**\n * Parses a non-BCS encoded argument into a BCS encoded argument recursively\n * @param arg\n * @param param\n * @param position\n * @param genericTypeParams\n */\nfunction parseArg(\n arg: SimpleEntryFunctionArgumentTypes,\n param: TypeTag,\n position: number,\n genericTypeParams: Array<TypeTag>,\n): EntryFunctionArgumentTypes {\n if (param.isBool()) {\n if (isBool(arg)) {\n return new Bool(arg);\n }\n throwTypeMismatch(\"boolean\", position);\n }\n // TODO: support uint8array?\n if (param.isAddress()) {\n if (isString(arg)) {\n return AccountAddress.fromString(arg);\n }\n throwTypeMismatch(\"string | AccountAddress\", position);\n }\n if (param.isU8()) {\n if (isNumber(arg)) {\n return new U8(arg);\n }\n throwTypeMismatch(\"number\", position);\n }\n if (param.isU16()) {\n if (isNumber(arg)) {\n return new U16(arg);\n }\n throwTypeMismatch(\"number\", position);\n }\n if (param.isU32()) {\n if (isNumber(arg)) {\n return new U32(arg);\n }\n throwTypeMismatch(\"number\", position);\n }\n if (param.isU64()) {\n if (isLargeNumber(arg)) {\n return new U64(BigInt(arg));\n }\n throwTypeMismatch(\"bigint | number | string\", position);\n }\n if (param.isU128()) {\n if (isLargeNumber(arg)) {\n return new U128(BigInt(arg));\n }\n throwTypeMismatch(\"bigint | number | string\", position);\n }\n if (param.isU256()) {\n if (isLargeNumber(arg)) {\n return new U256(BigInt(arg));\n }\n throwTypeMismatch(\"bigint | number | string\", position);\n }\n\n // Generic needs to use the sub-type\n if (param.isGeneric()) {\n const genericIndex = param.value;\n if (genericIndex < 0 || genericIndex >= genericTypeParams.length) {\n throw new Error(`Generic argument ${param.toString()} is invalid for argument ${position}`);\n }\n\n return checkOrConvertArgument(arg, genericTypeParams[genericIndex], position, genericTypeParams);\n }\n\n // We have to special case some vectors for Vector<u8>\n if (param.isVector()) {\n // Check special case for Vector<u8>\n if (param.value.isU8()) {\n // We don't allow vector<u8>, but we convert strings to UTF8 uint8array\n // This is legacy behavior from the original SDK\n if (isString(arg)) {\n return MoveVector.U8(TEXT_ENCODER.encode(arg));\n }\n if (arg instanceof Uint8Array) {\n return MoveVector.U8(arg);\n }\n if (arg instanceof ArrayBuffer) {\n return MoveVector.U8(new Uint8Array(arg));\n }\n }\n\n // TODO: Support Uint16Array, Uint32Array, BigUint64Array?\n\n if (Array.isArray(arg)) {\n return new MoveVector(arg.map((item) => checkOrConvertArgument(item, param.value, position, genericTypeParams)));\n }\n\n throw new Error(`Type mismatch for argument ${position}, type '${param.toString()}'`);\n }\n\n // Handle structs as they're more complex\n if (param.isStruct()) {\n if (param.isString()) {\n if (isString(arg)) {\n return new MoveString(arg);\n }\n throwTypeMismatch(\"string\", position);\n }\n if (param.isObject()) {\n // The inner type of Object doesn't matter, since it's just syntactic sugar\n if (isString(arg)) {\n return AccountAddress.fromString(arg);\n }\n throwTypeMismatch(\"string | AccountAddress\", position);\n }\n\n if (param.isOption()) {\n // Empty option must be handled specially\n if (isNull(arg)) {\n // Note: This is a placeholder U8 type, and does not match the actual type, as that can't be dynamically grabbed\n return new MoveOption<U8>(null);\n }\n\n return new MoveOption(checkOrConvertArgument(arg, param.value.typeArgs[0], position, genericTypeParams));\n }\n\n throw new Error(`Unsupported struct input type for argument ${position}, type '${param.toString()}'`);\n }\n\n throw new Error(`Type mismatch for argument ${position}, type '${param.toString()}'`);\n}\n\n/**\n * Checks that the type of an already BCS encoded argument matches the ABI\n * @param param\n * @param arg\n * @param position\n */\nfunction checkType(param: TypeTag, arg: EntryFunctionArgumentTypes, position: number) {\n if (param.isBool()) {\n if (isBcsBool(arg)) {\n return;\n }\n throwTypeMismatch(\"Bool\", position);\n }\n if (param.isAddress()) {\n if (isBcsAddress(arg)) {\n return;\n }\n throwTypeMismatch(\"AccountAddress\", position);\n }\n if (param.isU8()) {\n if (isBcsU8(arg)) {\n return;\n }\n throwTypeMismatch(\"U8\", position);\n }\n if (param.isU16()) {\n if (isBcsU16(arg)) {\n return;\n }\n throwTypeMismatch(\"U16\", position);\n }\n if (param.isU32()) {\n if (isBcsU32(arg)) {\n return;\n }\n throwTypeMismatch(\"U32\", position);\n }\n if (param.isU64()) {\n if (isBcsU64(arg)) {\n return;\n }\n throwTypeMismatch(\"U64\", position);\n }\n if (param.isU128()) {\n if (isBcsU128(arg)) {\n return;\n }\n throwTypeMismatch(\"U128\", position);\n }\n if (param.isU256()) {\n if (isBcsU256(arg)) {\n return;\n }\n throwTypeMismatch(\"U256\", position);\n }\n if (param.isVector()) {\n if (arg instanceof MoveVector) {\n // If there's anything in it, check that the inner types match\n // Note that since it's typed, the first item should be the same as the rest\n if (arg.values.length > 0) {\n checkType(param.value, arg.values[0], position);\n }\n\n return;\n }\n throwTypeMismatch(\"MoveVector\", position);\n }\n\n // Handle structs as they're more complex\n if (param instanceof TypeTagStruct) {\n if (param.isString()) {\n if (isBcsString(arg)) {\n return;\n }\n throwTypeMismatch(\"MoveString\", position);\n }\n if (param.isObject()) {\n if (isBcsAddress(arg)) {\n return;\n }\n throwTypeMismatch(\"AccountAddress\", position);\n }\n if (param.isOption()) {\n if (arg instanceof MoveOption) {\n // If there's a value, we can check the inner type (otherwise it doesn't really matter)\n if (arg.value !== undefined) {\n checkType(param.value.typeArgs[0], arg.value, position);\n }\n return;\n }\n throwTypeMismatch(\"MoveOption\", position);\n }\n }\n\n throw new Error(`Type mismatch for argument ${position}, expected '${param.toString()}'`);\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { AccountAddress } from \"../../core\";\nimport { Identifier } from \"./identifier\";\nimport { MoveModuleId } from \"../../types\";\n\n/**\n * Representation of a ModuleId that can serialized and deserialized\n * ModuleId means the module address (e.g \"0x1\") and the module name (e.g \"coin\")\n */\nexport class ModuleId extends Serializable {\n public readonly address: AccountAddress;\n\n public readonly name: Identifier;\n\n /**\n * Full name of a module.\n * @param address The account address. e.g \"0x1\"\n * @param name The module name under the \"address\". e.g \"coin\"\n */\n constructor(address: AccountAddress, name: Identifier) {\n super();\n this.address = address;\n this.name = name;\n }\n\n /**\n * Converts a string literal to a ModuleId\n * @param moduleId String literal in format \"account_address::module_name\", e.g. \"0x1::coin\"\n * @returns ModuleId\n */\n static fromStr(moduleId: MoveModuleId): ModuleId {\n const parts = moduleId.split(\"::\");\n if (parts.length !== 2) {\n throw new Error(\"Invalid module id.\");\n }\n return new ModuleId(AccountAddress.fromString(parts[0]), new Identifier(parts[1]));\n }\n\n serialize(serializer: Serializer): void {\n this.address.serialize(serializer);\n this.name.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): ModuleId {\n const address = AccountAddress.deserialize(deserializer);\n const name = Identifier.deserialize(deserializer);\n return new ModuleId(address, name);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../serializer\";\nimport { Deserializer } from \"../deserializer\";\nimport { FixedBytes } from \"./fixedBytes\";\nimport { EntryFunctionArgument } from \"../../transactions/instances/transactionArgument\";\nimport { HexInput } from \"../../types\";\n\n/**\n * This class exists solely to represent a sequence of fixed bytes as a serialized entry function, because\n * serializing an entry function appends a prefix that's *only* used for entry function arguments.\n *\n * NOTE: Attempting to use this class for a serialized script function will result in erroneous\n * and unexpected behavior.\n *\n * If you wish to convert this class back to a TransactionArgument, you must know the type\n * of the argument beforehand, and use the appropriate class to deserialize the bytes within\n * an instance of this class.\n */\nexport class EntryFunctionBytes extends Serializable implements EntryFunctionArgument {\n public readonly value: FixedBytes;\n\n private constructor(value: HexInput) {\n super();\n this.value = new FixedBytes(value);\n }\n\n // Note that to see the Move, BCS-serialized representation of the underlying fixed byte vector,\n // we must not serialize the length prefix.\n //\n // In other words, this class is only used to represent a sequence of bytes that are already\n // BCS-serialized as a type. To represent those bytes accurately, the BCS-serialized form is the same exact\n // representation.\n serialize(serializer: Serializer): void {\n serializer.serialize(this.value);\n }\n\n // When we serialize these bytes as an entry function argument, we need to\n // serialize the length prefix. This essentially converts the underlying fixed byte vector to a type-agnostic\n // byte vector to an `any` type.\n // NOTE: This, and the lack of a `serializeForScriptFunction`, is the only meaningful difference between this\n // class and FixedBytes.\n serializeForEntryFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.value.value.length);\n serializer.serialize(this);\n }\n\n /**\n * The only way to create an instance of this class is to use this static method.\n *\n * This function should only be used when deserializing a sequence of EntryFunctionPayload arguments.\n * @param deserializer the deserializer instance with the buffered bytes\n * @param length the length of the bytes to deserialize\n * @returns an instance of this class, which will now only be usable as an EntryFunctionArgument\n */\n static deserialize(deserializer: Deserializer, length: number): EntryFunctionBytes {\n const fixedBytes = FixedBytes.deserialize(deserializer, length);\n return new EntryFunctionBytes(fixedBytes.value);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { EntryFunctionBytes } from \"../../bcs/serializable/entryFunctionBytes\";\nimport { Bool, U128, U16, U256, U32, U64, U8 } from \"../../bcs/serializable/movePrimitives\";\nimport { MoveVector } from \"../../bcs/serializable/moveStructs\";\nimport { AccountAddress } from \"../../core\";\nimport { Identifier } from \"./identifier\";\nimport { ModuleId } from \"./moduleId\";\nimport type { EntryFunctionArgument, ScriptFunctionArgument, TransactionArgument } from \"./transactionArgument\";\nimport { MoveModuleId, ScriptTransactionArgumentVariants, TransactionPayloadVariants } from \"../../types\";\nimport { TypeTag } from \"../typeTag\";\n\n/**\n * Deserialize a Script Transaction Argument\n */\nexport function deserializeFromScriptArgument(deserializer: Deserializer): TransactionArgument {\n // index enum variant\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case ScriptTransactionArgumentVariants.U8:\n return U8.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.U64:\n return U64.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.U128:\n return U128.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.Address:\n return AccountAddress.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.U8Vector:\n return MoveVector.deserialize(deserializer, U8);\n case ScriptTransactionArgumentVariants.Bool:\n return Bool.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.U16:\n return U16.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.U32:\n return U32.deserialize(deserializer);\n case ScriptTransactionArgumentVariants.U256:\n return U256.deserialize(deserializer);\n default:\n throw new Error(`Unknown variant index for ScriptTransactionArgument: ${index}`);\n }\n}\n\n/**\n * Representation of the supported Transaction Payload\n * that can serialized and deserialized\n */\nexport abstract class TransactionPayload extends Serializable {\n /**\n * Serialize a Transaction Payload\n */\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserialize a Transaction Payload\n */\n static deserialize(deserializer: Deserializer): TransactionPayload {\n // index enum variant\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TransactionPayloadVariants.Script:\n return TransactionPayloadScript.load(deserializer);\n case TransactionPayloadVariants.EntryFunction:\n return TransactionPayloadEntryFunction.load(deserializer);\n case TransactionPayloadVariants.Multisig:\n return TransactionPayloadMultiSig.load(deserializer);\n default:\n throw new Error(`Unknown variant index for TransactionPayload: ${index}`);\n }\n }\n}\n\n/**\n * Representation of a Transaction Payload Script that can serialized and deserialized\n */\nexport class TransactionPayloadScript extends TransactionPayload {\n public readonly script: Script;\n\n constructor(script: Script) {\n super();\n this.script = script;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionPayloadVariants.Script);\n this.script.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionPayloadScript {\n const script = Script.deserialize(deserializer);\n return new TransactionPayloadScript(script);\n }\n}\n\n/**\n * Representation of a Transaction Payload Entry Function that can serialized and deserialized\n */\nexport class TransactionPayloadEntryFunction extends TransactionPayload {\n public readonly entryFunction: EntryFunction;\n\n constructor(entryFunction: EntryFunction) {\n super();\n this.entryFunction = entryFunction;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionPayloadVariants.EntryFunction);\n this.entryFunction.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionPayloadEntryFunction {\n const entryFunction = EntryFunction.deserialize(deserializer);\n return new TransactionPayloadEntryFunction(entryFunction);\n }\n}\n\n/**\n * Representation of a Transaction Payload Multi-sig that can serialized and deserialized\n */\nexport class TransactionPayloadMultiSig extends TransactionPayload {\n public readonly multiSig: MultiSig;\n\n constructor(multiSig: MultiSig) {\n super();\n this.multiSig = multiSig;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionPayloadVariants.Multisig);\n this.multiSig.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionPayloadMultiSig {\n const value = MultiSig.deserialize(deserializer);\n return new TransactionPayloadMultiSig(value);\n }\n}\n\n/**\n * Representation of a EntryFunction that can serialized and deserialized\n */\nexport class EntryFunction {\n public readonly module_name: ModuleId;\n\n public readonly function_name: Identifier;\n\n public readonly type_args: Array<TypeTag>;\n\n public readonly args: Array<EntryFunctionArgument>;\n\n /**\n * Contains the payload to run a function within a module.\n * @param module_name Fully qualified module name in format \"account_address::module_name\" e.g. \"0x1::coin\"\n * @param function_name The function name. e.g \"transfer\"\n * @param type_args Type arguments that move function requires.\n *\n * @example\n * A coin transfer function has one type argument \"CoinType\".\n * ```\n * public entry fun transfer<CoinType>(from: &signer, to: address, amount: u64)\n * ```\n * @param args arguments to the move function.\n *\n * @example\n * A coin transfer function has three arguments \"from\", \"to\" and \"amount\".\n * ```\n * public entry fun transfer<CoinType>(from: &signer, to: address, amount: u64)\n * ```\n */\n constructor(\n module_name: ModuleId,\n function_name: Identifier,\n type_args: Array<TypeTag>,\n args: Array<EntryFunctionArgument>,\n ) {\n this.module_name = module_name;\n this.function_name = function_name;\n this.type_args = type_args;\n this.args = args;\n }\n\n /**\n * A helper function to build a EntryFunction payload from raw primitive values\n *\n * @param module_id Fully qualified module name in format \"AccountAddress::module_id\" e.g. \"0x1::coin\"\n * @param function_name Function name\n * @param type_args Type arguments that move function requires.\n *\n * @example\n * A coin transfer function has one type argument \"CoinType\".\n * ```\n * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,)\n * ```\n * @param args Arguments to the move function.\n *\n * @example\n * A coin transfer function has three arguments \"from\", \"to\" and \"amount\".\n * ```\n * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,)\n * ```\n * @returns EntryFunction\n */\n static build(\n module_id: MoveModuleId,\n function_name: string,\n type_args: Array<TypeTag>,\n args: Array<EntryFunctionArgument>,\n ): EntryFunction {\n return new EntryFunction(ModuleId.fromStr(module_id), new Identifier(function_name), type_args, args);\n }\n\n serialize(serializer: Serializer): void {\n this.module_name.serialize(serializer);\n this.function_name.serialize(serializer);\n serializer.serializeVector<TypeTag>(this.type_args);\n serializer.serializeU32AsUleb128(this.args.length);\n this.args.forEach((item: EntryFunctionArgument) => {\n item.serializeForEntryFunction(serializer);\n });\n }\n\n /**\n * Deserializes an entry function payload with the arguments represented as EntryFunctionBytes instances.\n * @see EntryFunctionBytes\n *\n * NOTE: When you deserialize an EntryFunction payload with this method, the entry function\n * arguments are populated into the deserialized instance as type-agnostic, raw fixed bytes\n * in the form of the EntryFunctionBytes class.\n *\n * In order to correctly deserialize these arguments as their actual type representations, you\n * must know the types of the arguments beforehand and deserialize them yourself individually.\n *\n * One way you could achieve this is by using the ABIs for an entry function and deserializing each\n * argument as its given, corresponding type.\n *\n * @param deserializer\n * @returns A deserialized EntryFunction payload for a transaction.\n *\n */\n static deserialize(deserializer: Deserializer): EntryFunction {\n const module_name = ModuleId.deserialize(deserializer);\n const function_name = Identifier.deserialize(deserializer);\n const type_args = deserializer.deserializeVector(TypeTag);\n\n const length = deserializer.deserializeUleb128AsU32();\n const args: Array<EntryFunctionArgument> = new Array<EntryFunctionBytes>();\n\n for (let i = 0; i < length; i += 1) {\n const fixedBytesLength = deserializer.deserializeUleb128AsU32();\n const fixedBytes = EntryFunctionBytes.deserialize(deserializer, fixedBytesLength);\n args.push(fixedBytes);\n }\n\n return new EntryFunction(module_name, function_name, type_args, args);\n }\n}\n\n/**\n * Representation of a Script that can serialized and deserialized\n */\nexport class Script {\n /**\n * The move module bytecode\n */\n public readonly bytecode: Uint8Array;\n\n /**\n * The type arguments that the bytecode function requires.\n */\n public readonly type_args: Array<TypeTag>;\n\n /**\n * The arguments that the bytecode function requires.\n */\n public readonly args: Array<ScriptFunctionArgument>;\n\n /**\n * Scripts contain the Move bytecodes payload that can be submitted to Aptos chain for execution.\n *\n * @param bytecode The move module bytecode\n * @param type_args The type arguments that the bytecode function requires.\n *\n * @example\n * A coin transfer function has one type argument \"CoinType\".\n * ```\n * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,)\n * ```\n * @param args The arguments that the bytecode function requires.\n *\n * @example\n * A coin transfer function has three arguments \"from\", \"to\" and \"amount\".\n * ```\n * public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64,)\n * ```\n */\n constructor(bytecode: Uint8Array, type_args: Array<TypeTag>, args: Array<ScriptFunctionArgument>) {\n this.bytecode = bytecode;\n this.type_args = type_args;\n this.args = args;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.bytecode);\n serializer.serializeVector<TypeTag>(this.type_args);\n serializer.serializeU32AsUleb128(this.args.length);\n this.args.forEach((item: ScriptFunctionArgument) => {\n item.serializeForScriptFunction(serializer);\n });\n }\n\n static deserialize(deserializer: Deserializer): Script {\n const bytecode = deserializer.deserializeBytes();\n const type_args = deserializer.deserializeVector(TypeTag);\n const length = deserializer.deserializeUleb128AsU32();\n const args = new Array<ScriptFunctionArgument>();\n for (let i = 0; i < length; i += 1) {\n // Note that we deserialize directly to the Move value, not its Script argument representation.\n // We are abstracting away the Script argument representation because knowing about it is\n // functionally useless.\n const scriptArgument = deserializeFromScriptArgument(deserializer);\n args.push(scriptArgument);\n }\n return new Script(bytecode, type_args, args);\n }\n}\n\n/**\n * Representation of a MultiSig that can serialized and deserialized\n */\nexport class MultiSig {\n public readonly multisig_address: AccountAddress;\n\n public readonly transaction_payload?: MultiSigTransactionPayload;\n\n /**\n * Contains the payload to run a multi-sig account transaction.\n *\n * @param multisig_address The multi-sig account address the transaction will be executed as.\n *\n * @param transaction_payload The payload of the multi-sig transaction. This is optional when executing a multi-sig\n * transaction whose payload is already stored on chain.\n */\n constructor(multisig_address: AccountAddress, transaction_payload?: MultiSigTransactionPayload) {\n this.multisig_address = multisig_address;\n this.transaction_payload = transaction_payload;\n }\n\n serialize(serializer: Serializer): void {\n this.multisig_address.serialize(serializer);\n // Options are encoded with an extra u8 field before the value - 0x0 is none and 0x1 is present.\n // We use serializeBool below to create this prefix value.\n if (this.transaction_payload === undefined) {\n serializer.serializeBool(false);\n } else {\n serializer.serializeBool(true);\n this.transaction_payload.serialize(serializer);\n }\n }\n\n static deserialize(deserializer: Deserializer): MultiSig {\n const multisig_address = AccountAddress.deserialize(deserializer);\n const payloadPresent = deserializer.deserializeBool();\n let transaction_payload;\n if (payloadPresent) {\n transaction_payload = MultiSigTransactionPayload.deserialize(deserializer);\n }\n return new MultiSig(multisig_address, transaction_payload);\n }\n}\n\n/**\n * Representation of a MultiSig Transaction Payload from `multisig_account.move`\n * that can be serialized and deserialized\n\n * This class exists right now to represent an extensible transaction payload class for\n * transactions used in `multisig_account.move`. Eventually, this class will be able to\n * support script payloads when the `multisig_account.move` module supports them.\n */\nexport class MultiSigTransactionPayload extends Serializable {\n public readonly transaction_payload: EntryFunction;\n\n /**\n * Contains the payload to run a multi-sig account transaction.\n *\n * @param transaction_payload The payload of the multi-sig transaction.\n * This can only be EntryFunction for now but,\n * Script might be supported in the future.\n */\n constructor(transaction_payload: EntryFunction) {\n super();\n this.transaction_payload = transaction_payload;\n }\n\n serialize(serializer: Serializer): void {\n /**\n * We can support multiple types of inner transaction payload in the future.\n * For now, it's only EntryFunction but if we support more types,\n * we need to serialize with the right enum values here\n */\n serializer.serializeU32AsUleb128(0);\n this.transaction_payload.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): MultiSigTransactionPayload {\n // TODO: Support other types of payload beside EntryFunction.\n // This is the enum value indicating which type of payload the multisig tx contains.\n deserializer.deserializeUleb128AsU32();\n return new MultiSigTransactionPayload(EntryFunction.deserialize(deserializer));\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../../bcs/serializer\";\nimport { Deserializer } from \"../../bcs/deserializer\";\n\n/**\n * Representation of a ChainId that can serialized and deserialized\n */\nexport class ChainId extends Serializable {\n public readonly chainId: number;\n\n constructor(chainId: number) {\n super();\n this.chainId = chainId;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU8(this.chainId);\n }\n\n static deserialize(deserializer: Deserializer): ChainId {\n const chainId = deserializer.deserializeU8();\n return new ChainId(chainId);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { ChainId } from \"./chainId\";\nimport { AccountAddress } from \"../../core\";\nimport { TransactionPayload } from \"./transactionPayload\";\nimport { TransactionVariants } from \"../../types\";\n\n/**\n * Representation of a Raw Transaction that can serialized and deserialized\n */\nexport class RawTransaction extends Serializable {\n public readonly sender: AccountAddress;\n\n public readonly sequence_number: bigint;\n\n public readonly payload: TransactionPayload;\n\n public readonly max_gas_amount: bigint;\n\n public readonly gas_unit_price: bigint;\n\n public readonly expiration_timestamp_secs: bigint;\n\n public readonly chain_id: ChainId;\n\n /**\n * RawTransactions contain the metadata and payloads that can be submitted to Aptos chain for execution.\n * RawTransactions must be signed before Aptos chain can execute them.\n *\n * @param sender The sender Account Address\n * @param sequence_number Sequence number of this transaction. This must match the sequence number stored in\n * the sender's account at the time the transaction executes.\n * @param payload Instructions for the Aptos Blockchain, including publishing a module,\n * execute an entry function or execute a script payload.\n * @param max_gas_amount Maximum total gas to spend for this transaction. The account must have more\n * than this gas or the transaction will be discarded during validation.\n * @param gas_unit_price Price to be paid per gas unit.\n * @param expiration_timestamp_secs The blockchain timestamp at which the blockchain would discard this transaction.\n * @param chain_id The chain ID of the blockchain that this transaction is intended to be run on.\n */\n constructor(\n sender: AccountAddress,\n sequence_number: bigint,\n payload: TransactionPayload,\n max_gas_amount: bigint,\n gas_unit_price: bigint,\n expiration_timestamp_secs: bigint,\n chain_id: ChainId,\n ) {\n super();\n this.sender = sender;\n this.sequence_number = sequence_number;\n this.payload = payload;\n this.max_gas_amount = max_gas_amount;\n this.gas_unit_price = gas_unit_price;\n this.expiration_timestamp_secs = expiration_timestamp_secs;\n this.chain_id = chain_id;\n }\n\n serialize(serializer: Serializer): void {\n this.sender.serialize(serializer);\n serializer.serializeU64(this.sequence_number);\n this.payload.serialize(serializer);\n serializer.serializeU64(this.max_gas_amount);\n serializer.serializeU64(this.gas_unit_price);\n serializer.serializeU64(this.expiration_timestamp_secs);\n this.chain_id.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): RawTransaction {\n const sender = AccountAddress.deserialize(deserializer);\n const sequence_number = deserializer.deserializeU64();\n const payload = TransactionPayload.deserialize(deserializer);\n const max_gas_amount = deserializer.deserializeU64();\n const gas_unit_price = deserializer.deserializeU64();\n const expiration_timestamp_secs = deserializer.deserializeU64();\n const chain_id = ChainId.deserialize(deserializer);\n return new RawTransaction(\n sender,\n sequence_number,\n payload,\n max_gas_amount,\n gas_unit_price,\n expiration_timestamp_secs,\n chain_id,\n );\n }\n}\n\n/**\n * Representation of a Raw Transaction With Data that can serialized and deserialized\n */\nexport abstract class RawTransactionWithData extends Serializable {\n /**\n * Serialize a Raw Transaction With Data\n */\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserialize a Raw Transaction With Data\n */\n static deserialize(deserializer: Deserializer): RawTransactionWithData {\n // index enum variant\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TransactionVariants.MultiAgentTransaction:\n return MultiAgentRawTransaction.load(deserializer);\n case TransactionVariants.FeePayerTransaction:\n return FeePayerRawTransaction.load(deserializer);\n default:\n throw new Error(`Unknown variant index for RawTransactionWithData: ${index}`);\n }\n }\n}\n\n/**\n * Representation of a Multi Agent Transaction that can serialized and deserialized\n */\nexport class MultiAgentRawTransaction extends RawTransactionWithData {\n /**\n * The raw transaction\n */\n public readonly raw_txn: RawTransaction;\n\n /**\n * The secondary signers on this transaction\n */\n public readonly secondary_signer_addresses: Array<AccountAddress>;\n\n constructor(raw_txn: RawTransaction, secondary_signer_addresses: Array<AccountAddress>) {\n super();\n this.raw_txn = raw_txn;\n this.secondary_signer_addresses = secondary_signer_addresses;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionVariants.MultiAgentTransaction);\n this.raw_txn.serialize(serializer);\n serializer.serializeVector(this.secondary_signer_addresses);\n }\n\n static load(deserializer: Deserializer): MultiAgentRawTransaction {\n const rawTxn = RawTransaction.deserialize(deserializer);\n const secondarySignerAddresses = deserializer.deserializeVector(AccountAddress);\n\n return new MultiAgentRawTransaction(rawTxn, secondarySignerAddresses);\n }\n}\n\n/**\n * Representation of a Fee Payer Transaction that can serialized and deserialized\n */\nexport class FeePayerRawTransaction extends RawTransactionWithData {\n /**\n * The raw transaction\n */\n public readonly raw_txn: RawTransaction;\n\n /**\n * The secondary signers on this transaction - optional and can be empty\n */\n public readonly secondary_signer_addresses: Array<AccountAddress>;\n\n /**\n * The fee payer account address\n */\n public readonly fee_payer_address: AccountAddress;\n\n constructor(\n raw_txn: RawTransaction,\n secondary_signer_addresses: Array<AccountAddress>,\n fee_payer_address: AccountAddress,\n ) {\n super();\n this.raw_txn = raw_txn;\n this.secondary_signer_addresses = secondary_signer_addresses;\n this.fee_payer_address = fee_payer_address;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionVariants.FeePayerTransaction);\n this.raw_txn.serialize(serializer);\n serializer.serializeVector(this.secondary_signer_addresses);\n this.fee_payer_address.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): FeePayerRawTransaction {\n const rawTxn = RawTransaction.deserialize(deserializer);\n const secondarySignerAddresses = deserializer.deserializeVector(AccountAddress);\n const feePayerAddress = AccountAddress.deserialize(deserializer);\n\n return new FeePayerRawTransaction(rawTxn, secondarySignerAddresses, feePayerAddress);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { AccountAddress } from \"../../core\";\nimport { RawTransaction } from \"./rawTransaction\";\n\n/**\n * Representation of a Raw Transaction that can serialized and deserialized\n */\nexport class MultiAgentTransaction extends Serializable {\n public rawTransaction: RawTransaction;\n\n public feePayerAddress?: AccountAddress | undefined;\n\n public secondarySignerAddresses: AccountAddress[];\n\n /**\n * SimpleTransaction represents a simple transaction type of a single signer that\n * can be submitted to Aptos chain for execution.\n *\n * SimpleTransaction metadata contains the Raw Transaction and an optional\n * sponsor Account Address to pay the gas fees.\n *\n * @param rawTransaction The Raw Tranasaction\n * @param feePayerAddress The sponsor Account Address\n */\n constructor(\n rawTransaction: RawTransaction,\n secondarySignerAddresses: AccountAddress[],\n feePayerAddress?: AccountAddress,\n ) {\n super();\n this.rawTransaction = rawTransaction;\n this.feePayerAddress = feePayerAddress;\n this.secondarySignerAddresses = secondarySignerAddresses;\n }\n\n serialize(serializer: Serializer): void {\n this.rawTransaction.serialize(serializer);\n\n serializer.serializeVector<AccountAddress>(this.secondarySignerAddresses);\n\n if (this.feePayerAddress === undefined) {\n serializer.serializeBool(false);\n } else {\n serializer.serializeBool(true);\n this.feePayerAddress.serialize(serializer);\n }\n }\n\n static deserialize(deserializer: Deserializer): MultiAgentTransaction {\n const rawTransaction = RawTransaction.deserialize(deserializer);\n\n const secondarySignerAddresses = deserializer.deserializeVector(AccountAddress);\n\n const feepayerPresent = deserializer.deserializeBool();\n let feePayerAddress;\n if (feepayerPresent) {\n feePayerAddress = AccountAddress.deserialize(deserializer);\n }\n\n return new MultiAgentTransaction(rawTransaction, secondarySignerAddresses, feePayerAddress);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { AccountAuthenticator } from \"./account\";\nimport { Deserializer, Serializable, Serializer } from \"../../bcs\";\nimport { AccountAddress } from \"../../core\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"../../core/crypto/ed25519\";\nimport { MultiEd25519PublicKey, MultiEd25519Signature } from \"../../core/crypto/multiEd25519\";\nimport { TransactionAuthenticatorVariant } from \"../../types\";\n\nexport abstract class TransactionAuthenticator extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n static deserialize(deserializer: Deserializer): TransactionAuthenticator {\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TransactionAuthenticatorVariant.Ed25519:\n return TransactionAuthenticatorEd25519.load(deserializer);\n case TransactionAuthenticatorVariant.MultiEd25519:\n return TransactionAuthenticatorMultiEd25519.load(deserializer);\n case TransactionAuthenticatorVariant.MultiAgent:\n return TransactionAuthenticatorMultiAgent.load(deserializer);\n case TransactionAuthenticatorVariant.FeePayer:\n return TransactionAuthenticatorFeePayer.load(deserializer);\n case TransactionAuthenticatorVariant.SingleSender:\n return TransactionAuthenticatorSingleSender.load(deserializer);\n default:\n throw new Error(`Unknown variant index for TransactionAuthenticator: ${index}`);\n }\n }\n}\n\n/**\n * Transaction authenticator Ed25519 for a single signer transaction\n *\n * @param public_key Client's public key.\n * @param signature Ed25519 signature of a raw transaction.\n * @see {@link https://aptos.dev/integration/creating-a-signed-transaction | Creating a Signed Transaction}\n * for details about generating a signature.\n */\nexport class TransactionAuthenticatorEd25519 extends TransactionAuthenticator {\n public readonly public_key: Ed25519PublicKey;\n\n public readonly signature: Ed25519Signature;\n\n constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionAuthenticatorVariant.Ed25519);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionAuthenticatorEd25519 {\n const public_key = Ed25519PublicKey.deserialize(deserializer);\n const signature = Ed25519Signature.deserialize(deserializer);\n return new TransactionAuthenticatorEd25519(public_key, signature);\n }\n}\n\n/**\n * Transaction authenticator Ed25519 for a multi signers transaction\n *\n * @param public_key Client's public key.\n * @param signature Multi Ed25519 signature of a raw transaction.\n *\n */\nexport class TransactionAuthenticatorMultiEd25519 extends TransactionAuthenticator {\n public readonly public_key: MultiEd25519PublicKey;\n\n public readonly signature: MultiEd25519Signature;\n\n constructor(public_key: MultiEd25519PublicKey, signature: MultiEd25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionAuthenticatorVariant.MultiEd25519);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionAuthenticatorMultiEd25519 {\n const public_key = MultiEd25519PublicKey.deserialize(deserializer);\n const signature = MultiEd25519Signature.deserialize(deserializer);\n return new TransactionAuthenticatorMultiEd25519(public_key, signature);\n }\n}\n\n/**\n * Transaction authenticator for a multi-agent transaction\n *\n * @param sender Sender account authenticator\n * @param secondary_signer_addresses Secondary signers address\n * @param secondary_signers Secondary signers account authenticators\n *\n */\nexport class TransactionAuthenticatorMultiAgent extends TransactionAuthenticator {\n public readonly sender: AccountAuthenticator;\n\n public readonly secondary_signer_addresses: Array<AccountAddress>;\n\n public readonly secondary_signers: Array<AccountAuthenticator>;\n\n constructor(\n sender: AccountAuthenticator,\n secondary_signer_addresses: Array<AccountAddress>,\n secondary_signers: Array<AccountAuthenticator>,\n ) {\n super();\n this.sender = sender;\n this.secondary_signer_addresses = secondary_signer_addresses;\n this.secondary_signers = secondary_signers;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionAuthenticatorVariant.MultiAgent);\n this.sender.serialize(serializer);\n serializer.serializeVector<AccountAddress>(this.secondary_signer_addresses);\n serializer.serializeVector<AccountAuthenticator>(this.secondary_signers);\n }\n\n static load(deserializer: Deserializer): TransactionAuthenticatorMultiAgent {\n const sender = AccountAuthenticator.deserialize(deserializer);\n const secondary_signer_addresses = deserializer.deserializeVector(AccountAddress);\n const secondary_signers = deserializer.deserializeVector(AccountAuthenticator);\n return new TransactionAuthenticatorMultiAgent(sender, secondary_signer_addresses, secondary_signers);\n }\n}\n\n/**\n * Transaction authenticator for a fee payer transaction\n *\n * @param sender Sender account authenticator\n * @param secondary_signer_addresses Secondary signers address\n * @param secondary_signers Secondary signers account authenticators\n * @param fee_payer Object of the fee payer account address and the fee payer authentication\n *\n */\nexport class TransactionAuthenticatorFeePayer extends TransactionAuthenticator {\n public readonly sender: AccountAuthenticator;\n\n public readonly secondary_signer_addresses: Array<AccountAddress>;\n\n public readonly secondary_signers: Array<AccountAuthenticator>;\n\n public readonly fee_payer: {\n address: AccountAddress;\n authenticator: AccountAuthenticator;\n };\n\n constructor(\n sender: AccountAuthenticator,\n secondary_signer_addresses: Array<AccountAddress>,\n secondary_signers: Array<AccountAuthenticator>,\n fee_payer: { address: AccountAddress; authenticator: AccountAuthenticator },\n ) {\n super();\n this.sender = sender;\n this.secondary_signer_addresses = secondary_signer_addresses;\n this.secondary_signers = secondary_signers;\n this.fee_payer = fee_payer;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionAuthenticatorVariant.FeePayer);\n this.sender.serialize(serializer);\n serializer.serializeVector<AccountAddress>(this.secondary_signer_addresses);\n serializer.serializeVector<AccountAuthenticator>(this.secondary_signers);\n this.fee_payer.address.serialize(serializer);\n this.fee_payer.authenticator.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionAuthenticatorMultiAgent {\n const sender = AccountAuthenticator.deserialize(deserializer);\n const secondary_signer_addresses = deserializer.deserializeVector(AccountAddress);\n const secondary_signers = deserializer.deserializeVector(AccountAuthenticator);\n const address = AccountAddress.deserialize(deserializer);\n const authenticator = AccountAuthenticator.deserialize(deserializer);\n const fee_payer = { address, authenticator };\n return new TransactionAuthenticatorFeePayer(sender, secondary_signer_addresses, secondary_signers, fee_payer);\n }\n}\n\n/**\n * Single Sender authenticator for a single signer transaction\n *\n * @param sender AccountAuthenticator\n */\nexport class TransactionAuthenticatorSingleSender extends TransactionAuthenticator {\n public readonly sender: AccountAuthenticator;\n\n constructor(sender: AccountAuthenticator) {\n super();\n this.sender = sender;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionAuthenticatorVariant.SingleSender);\n this.sender.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionAuthenticatorSingleSender {\n const sender = AccountAuthenticator.deserialize(deserializer);\n return new TransactionAuthenticatorSingleSender(sender);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { TransactionAuthenticator } from \"../authenticator/transaction\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { RawTransaction } from \"./rawTransaction\";\n\nexport class SignedTransaction extends Serializable {\n public readonly raw_txn: RawTransaction;\n\n public readonly authenticator: TransactionAuthenticator;\n\n /**\n * A SignedTransaction consists of a raw transaction and an authenticator. The authenticator\n * contains a client's public key and the signature of the raw transaction.\n *\n * @see {@link https://aptos.dev/integration/creating-a-signed-transaction | Creating a Signed Transaction}\n *\n * @param raw_txn\n * @param authenticator Contains a client's public key and the signature of the raw transaction.\n * Authenticator has 3 flavors: single signature, multi-signature and multi-agent.\n * @see {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/authenticator.rs} for details.\n */\n constructor(raw_txn: RawTransaction, authenticator: TransactionAuthenticator) {\n super();\n this.raw_txn = raw_txn;\n this.authenticator = authenticator;\n }\n\n serialize(serializer: Serializer): void {\n this.raw_txn.serialize(serializer);\n this.authenticator.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): SignedTransaction {\n const raw_txn = RawTransaction.deserialize(deserializer);\n const authenticator = TransactionAuthenticator.deserialize(deserializer);\n return new SignedTransaction(raw_txn, authenticator);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { AccountAddress } from \"../../core\";\nimport { RawTransaction } from \"./rawTransaction\";\n\n/**\n * Representation of a SimpleTransaction that can serialized and deserialized\n */\nexport class SimpleTransaction extends Serializable {\n public rawTransaction: RawTransaction;\n\n public feePayerAddress?: AccountAddress | undefined;\n\n // We dont really need it, we add it for type checkings we do\n // throughout the SDK\n public readonly secondarySignerAddresses: undefined;\n\n /**\n * SimpleTransaction represents a simple transaction type of a single signer that\n * can be submitted to Aptos chain for execution.\n *\n * SimpleTransaction metadata contains the Raw Transaction and an optional\n * sponsor Account Address to pay the gas fees.\n *\n * @param rawTransaction The Raw Tranasaction\n * @param feePayerAddress The sponsor Account Address\n */\n constructor(rawTransaction: RawTransaction, feePayerAddress?: AccountAddress) {\n super();\n this.rawTransaction = rawTransaction;\n this.feePayerAddress = feePayerAddress;\n }\n\n serialize(serializer: Serializer): void {\n this.rawTransaction.serialize(serializer);\n\n if (this.feePayerAddress === undefined) {\n serializer.serializeBool(false);\n } else {\n serializer.serializeBool(true);\n this.feePayerAddress.serialize(serializer);\n }\n }\n\n static deserialize(deserializer: Deserializer): SimpleTransaction {\n const rawTransaction = RawTransaction.deserialize(deserializer);\n const feepayerPresent = deserializer.deserializeBool();\n let feePayerAddress;\n if (feepayerPresent) {\n feePayerAddress = AccountAddress.deserialize(deserializer);\n }\n\n return new SimpleTransaction(rawTransaction, feePayerAddress);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable no-bitwise */\nimport { MAX_U32_NUMBER } from \"./consts\";\nimport { Uint8, Uint16, Uint32, Uint64, Uint128, Uint256 } from \"../types\";\n\n/**\n * This interface exists to define Deserializable<T> inputs for functions that\n * deserialize a byte buffer into a type T.\n * It is not intended to be implemented or extended, because Typescript has no support\n * for static methods in interfaces.\n */\nexport interface Deserializable<T> {\n deserialize(deserializer: Deserializer): T;\n}\n\nexport class Deserializer {\n private buffer: ArrayBuffer;\n\n private offset: number;\n\n constructor(data: Uint8Array) {\n // copies data to prevent outside mutation of buffer.\n this.buffer = new ArrayBuffer(data.length);\n new Uint8Array(this.buffer).set(data, 0);\n this.offset = 0;\n }\n\n private read(length: number): ArrayBuffer {\n if (this.offset + length > this.buffer.byteLength) {\n throw new Error(\"Reached to the end of buffer\");\n }\n\n const bytes = this.buffer.slice(this.offset, this.offset + length);\n this.offset += length;\n return bytes;\n }\n\n /**\n * Deserializes a string. UTF8 string is supported. Reads the string's bytes length \"l\" first,\n * and then reads \"l\" bytes of content. Decodes the byte array into a string.\n *\n * BCS layout for \"string\": string_length | string_content\n * where string_length is a u32 integer encoded as a uleb128 integer, equal to the number of bytes in string_content.\n *\n * @example\n * ```ts\n * const deserializer = new Deserializer(new Uint8Array([8, 49, 50, 51, 52, 97, 98, 99, 100]));\n * assert(deserializer.deserializeStr() === \"1234abcd\");\n * ```\n */\n deserializeStr(): string {\n const value = this.deserializeBytes();\n const textDecoder = new TextDecoder();\n return textDecoder.decode(value);\n }\n\n /**\n * Deserializes an array of bytes.\n *\n * BCS layout for \"bytes\": bytes_length | bytes\n * where bytes_length is a u32 integer encoded as a uleb128 integer, equal to the length of the bytes array.\n */\n deserializeBytes(): Uint8Array {\n const len = this.deserializeUleb128AsU32();\n return new Uint8Array(this.read(len));\n }\n\n /**\n * Deserializes an array of bytes. The number of bytes to read is already known.\n *\n */\n deserializeFixedBytes(len: number): Uint8Array {\n return new Uint8Array(this.read(len));\n }\n\n /**\n * Deserializes a boolean value.\n *\n * BCS layout for \"boolean\": One byte. \"0x01\" for true and \"0x00\" for false.\n */\n deserializeBool(): boolean {\n const bool = new Uint8Array(this.read(1))[0];\n if (bool !== 1 && bool !== 0) {\n throw new Error(\"Invalid boolean value\");\n }\n return bool === 1;\n }\n\n /**\n * Deserializes a uint8 number.\n *\n * BCS layout for \"uint8\": One byte. Binary format in little-endian representation.\n */\n deserializeU8(): Uint8 {\n return new DataView(this.read(1)).getUint8(0);\n }\n\n /**\n * Deserializes a uint16 number.\n *\n * BCS layout for \"uint16\": Two bytes. Binary format in little-endian representation.\n * @example\n * ```ts\n * const deserializer = new Deserializer(new Uint8Array([0x34, 0x12]));\n * assert(deserializer.deserializeU16() === 4660);\n * ```\n */\n deserializeU16(): Uint16 {\n return new DataView(this.read(2)).getUint16(0, true);\n }\n\n /**\n * Deserializes a uint32 number.\n *\n * BCS layout for \"uint32\": Four bytes. Binary format in little-endian representation.\n * @example\n * ```ts\n * const deserializer = new Deserializer(new Uint8Array([0x78, 0x56, 0x34, 0x12]));\n * assert(deserializer.deserializeU32() === 305419896);\n * ```\n */\n deserializeU32(): Uint32 {\n return new DataView(this.read(4)).getUint32(0, true);\n }\n\n /**\n * Deserializes a uint64 number.\n *\n * BCS layout for \"uint64\": Eight bytes. Binary format in little-endian representation.\n * @example\n * ```ts\n * const deserializer = new Deserializer(new Uint8Array([0x00, 0xEF, 0xCD, 0xAB, 0x78, 0x56, 0x34, 0x12]));\n * assert(deserializer.deserializeU64() === 1311768467750121216);\n * ```\n */\n deserializeU64(): Uint64 {\n const low = this.deserializeU32();\n const high = this.deserializeU32();\n\n // combine the two 32-bit values and return (little endian)\n return BigInt((BigInt(high) << BigInt(32)) | BigInt(low));\n }\n\n /**\n * Deserializes a uint128 number.\n *\n * BCS layout for \"uint128\": Sixteen bytes. Binary format in little-endian representation.\n */\n deserializeU128(): Uint128 {\n const low = this.deserializeU64();\n const high = this.deserializeU64();\n\n // combine the two 64-bit values and return (little endian)\n return BigInt((high << BigInt(64)) | low);\n }\n\n /**\n * Deserializes a uint256 number.\n *\n * BCS layout for \"uint256\": Thirty-two bytes. Binary format in little-endian representation.\n */\n deserializeU256(): Uint256 {\n const low = this.deserializeU128();\n const high = this.deserializeU128();\n\n // combine the two 128-bit values and return (little endian)\n return BigInt((high << BigInt(128)) | low);\n }\n\n /**\n * Deserializes a uleb128 encoded uint32 number.\n *\n * BCS use uleb128 encoding in two cases: (1) lengths of variable-length sequences and (2) tags of enum values\n */\n deserializeUleb128AsU32(): Uint32 {\n let value: bigint = BigInt(0);\n let shift = 0;\n\n while (value < MAX_U32_NUMBER) {\n const byte = this.deserializeU8();\n value |= BigInt(byte & 0x7f) << BigInt(shift);\n\n if ((byte & 0x80) === 0) {\n break;\n }\n shift += 7;\n }\n\n if (value > MAX_U32_NUMBER) {\n throw new Error(\"Overflow while parsing uleb128-encoded uint32 value\");\n }\n\n return Number(value);\n }\n\n /**\n * Helper function that primarily exists to support alternative syntax for deserialization.\n * That is, if we have a `const deserializer: new Deserializer(...)`, instead of having to use\n * `MyClass.deserialize(deserializer)`, we can call `deserializer.deserialize(MyClass)`.\n *\n * @example const deserializer = new Deserializer(new Uint8Array([1, 2, 3]));\n * const value = deserializer.deserialize(MyClass); // where MyClass has a `deserialize` function\n * // value is now an instance of MyClass\n * // equivalent to `const value = MyClass.deserialize(deserializer)`\n * @param cls The BCS-deserializable class to deserialize the buffered bytes into.\n *\n * @returns the deserialized value of class type T\n */\n deserialize<T>(cls: Deserializable<T>): T {\n // NOTE: `deserialize` in `cls.deserialize(this)` here is a static method defined in `cls`,\n // It is separate from the `deserialize` instance method defined here in Deserializer.\n return cls.deserialize(this);\n }\n\n /**\n * Deserializes an array of BCS Deserializable values given an existing Deserializer\n * instance with a loaded byte buffer.\n *\n * @param cls The BCS-deserializable class to deserialize the buffered bytes into.\n * @example\n * // serialize a vector of addresses\n * const addresses = new Array<AccountAddress>(\n * AccountAddress.from(\"0x1\"),\n * AccountAddress.from(\"0x2\"),\n * AccountAddress.from(\"0xa\"),\n * AccountAddress.from(\"0xb\"),\n * );\n * const serializer = new Serializer();\n * serializer.serializeVector(addresses);\n * const serializedBytes = serializer.toUint8Array();\n *\n * // deserialize the bytes into an array of addresses\n * const deserializer = new Deserializer(serializedBytes);\n * const deserializedAddresses = deserializer.deserializeVector(AccountAddress);\n * // deserializedAddresses is now an array of AccountAddress instances\n * @returns an array of deserialized values of type T\n */\n deserializeVector<T>(cls: Deserializable<T>): Array<T> {\n const length = this.deserializeUleb128AsU32();\n const vector = new Array<T>();\n for (let i = 0; i < length; i += 1) {\n vector.push(this.deserialize(cls));\n }\n return vector;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Deserializer, Serializable } from \"../bcs\";\n\nexport type DeserializableClass<T extends Serializable> = {\n deserialize(deserializer: Deserializer): T;\n};\n\n/**\n * Utility function that serializes and deserialize an object back into the same bundle as the sdk.\n * This is a workaround to have the `instanceof` operator work when input objects come from a different\n * bundle.\n * @param cls The class of the object to normalize\n * @param value the instance to normalize\n */\nexport function normalizeBundle<T extends Serializable>(cls: DeserializableClass<T>, value: T) {\n const serializedBytes = value.bcsToBytes();\n const deserializer = new Deserializer(serializedBytes);\n return cls.deserialize(deserializer);\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nexport const NetworkToIndexerAPI: Record<string, string> = {\n mainnet: \"https://api.mainnet.aptoslabs.com/v1/graphql\",\n testnet: \"https://api.testnet.aptoslabs.com/v1/graphql\",\n devnet: \"https://api.devnet.aptoslabs.com/v1/graphql\",\n local: \"http://127.0.0.1:8090/v1/graphql\",\n};\n\nexport const NetworkToNodeAPI: Record<string, string> = {\n mainnet: \"https://api.mainnet.aptoslabs.com/v1\",\n testnet: \"https://api.testnet.aptoslabs.com/v1\",\n devnet: \"https://api.devnet.aptoslabs.com/v1\",\n local: \"http://127.0.0.1:8080/v1\",\n};\n\nexport const NetworkToFaucetAPI: Record<string, string> = {\n mainnet: \"https://faucet.mainnet.aptoslabs.com\",\n testnet: \"https://faucet.testnet.aptoslabs.com\",\n devnet: \"https://faucet.devnet.aptoslabs.com\",\n local: \"http://127.0.0.1:8081\",\n};\n\nexport enum Network {\n MAINNET = \"mainnet\",\n TESTNET = \"testnet\",\n DEVNET = \"devnet\",\n LOCAL = \"local\",\n CUSTOM = \"custom\",\n}\n\nexport const NetworkToChainId: Record<string, number> = {\n mainnet: 1,\n testnet: 2,\n local: 4,\n};\n\nexport const NetworkToNetworkName: Record<string, Network> = {\n mainnet: Network.MAINNET,\n testnet: Network.TESTNET,\n devnet: Network.DEVNET,\n local: Network.LOCAL,\n custom: Network.CUSTOM,\n};\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file handles the transaction creation lifecycle.\n * It holds different operations to generate a transaction payload, a raw transaction,\n * and a signed transaction that can be simulated, signed and submitted to chain.\n */\nimport { sha3_256 as sha3Hash } from \"@noble/hashes/sha3\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport { AccountAddress, AccountAddressInput, Hex, PublicKey } from \"../../core\";\nimport { Account } from \"../../core/account\";\nimport { AnyPublicKey, AnySignature } from \"../../core/crypto\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"../../core/crypto/ed25519\";\nimport { Secp256k1PublicKey, Secp256k1Signature } from \"../../core/crypto/secp256k1\";\nimport { getInfo } from \"../../internal/account\";\nimport { getLedgerInfo } from \"../../internal/general\";\nimport { getGasPriceEstimation } from \"../../internal/transaction\";\nimport { NetworkToChainId } from \"../../utils/apiEndpoints\";\nimport {\n DEFAULT_MAX_GAS_AMOUNT,\n DEFAULT_TXN_EXP_SEC_FROM_NOW,\n RAW_TRANSACTION_SALT,\n RAW_TRANSACTION_WITH_DATA_SALT,\n} from \"../../utils/const\";\nimport { normalizeBundle } from \"../../utils/normalizeBundle\";\nimport {\n AccountAuthenticator,\n AccountAuthenticatorEd25519,\n AccountAuthenticatorSingleKey,\n} from \"../authenticator/account\";\nimport {\n TransactionAuthenticator,\n TransactionAuthenticatorEd25519,\n TransactionAuthenticatorFeePayer,\n TransactionAuthenticatorMultiAgent,\n TransactionAuthenticatorSingleSender,\n} from \"../authenticator/transaction\";\nimport {\n ChainId,\n EntryFunction,\n FeePayerRawTransaction,\n MultiAgentRawTransaction,\n MultiSig,\n MultiSigTransactionPayload,\n RawTransaction,\n Script,\n TransactionPayloadEntryFunction,\n TransactionPayloadMultiSig,\n TransactionPayloadScript,\n} from \"../instances\";\nimport { SignedTransaction } from \"../instances/signedTransaction\";\nimport {\n AnyRawTransaction,\n AnyTransactionPayloadInstance,\n AnyRawTransactionInstance,\n EntryFunctionArgumentTypes,\n InputGenerateMultiAgentRawTransactionArgs,\n InputGenerateRawTransactionArgs,\n InputGenerateSingleSignerRawTransactionArgs,\n InputGenerateTransactionOptions,\n InputScriptData,\n InputSimulateTransactionData,\n InputMultiSigDataWithRemoteABI,\n InputEntryFunctionDataWithRemoteABI,\n InputGenerateTransactionPayloadDataWithRemoteABI,\n InputSubmitTransactionData,\n InputGenerateTransactionPayloadDataWithABI,\n InputEntryFunctionDataWithABI,\n InputMultiSigDataWithABI,\n InputViewFunctionDataWithRemoteABI,\n InputViewFunctionDataWithABI,\n FunctionABI,\n} from \"../types\";\nimport { convertArgument, fetchEntryFunctionAbi, fetchViewFunctionAbi, standardizeTypeTags } from \"./remoteAbi\";\nimport { memoizeAsync } from \"../../utils/memoize\";\nimport { getFunctionParts, isScriptDataInput } from \"./helpers\";\nimport { SimpleTransaction } from \"../instances/simpleTransaction\";\nimport { MultiAgentTransaction } from \"../instances/multiAgentTransaction\";\n\n/**\n * We are defining function signatures, each with its specific input and output.\n * These are the possible function signature for our `generateTransactionPayload` function.\n * When we call our `generateTransactionPayload` function with the relevant type properties,\n * Typescript can infer the return type based on the appropriate function overload.\n */\nexport async function generateTransactionPayload(args: InputScriptData): Promise<TransactionPayloadScript>;\nexport async function generateTransactionPayload(\n args: InputEntryFunctionDataWithRemoteABI,\n): Promise<TransactionPayloadEntryFunction>;\nexport async function generateTransactionPayload(\n args: InputMultiSigDataWithRemoteABI,\n): Promise<TransactionPayloadMultiSig>;\n\n/**\n * Builds a transaction payload based on the data argument and returns\n * a transaction payload - TransactionPayloadScript | TransactionPayloadMultiSig | TransactionPayloadEntryFunction\n *\n * This uses the RemoteABI by default, and the remote ABI can be skipped by using generateTransactionPayloadWithABI\n *\n * @param args.data GenerateTransactionPayloadData\n *\n * @return TransactionPayload\n */\nexport async function generateTransactionPayload(\n args: InputGenerateTransactionPayloadDataWithRemoteABI,\n): Promise<AnyTransactionPayloadInstance> {\n if (isScriptDataInput(args)) {\n return generateTransactionPayloadScript(args);\n }\n const { moduleAddress, moduleName, functionName } = getFunctionParts(args.function);\n\n const functionAbi = await fetchAbi({\n key: \"entry-function\",\n moduleAddress,\n moduleName,\n functionName,\n aptosConfig: args.aptosConfig,\n abi: args.abi,\n fetch: fetchEntryFunctionAbi,\n });\n\n // Fill in the ABI\n return generateTransactionPayloadWithABI({ ...args, abi: functionAbi });\n}\n\nexport function generateTransactionPayloadWithABI(args: InputEntryFunctionDataWithABI): TransactionPayloadEntryFunction;\nexport function generateTransactionPayloadWithABI(args: InputMultiSigDataWithABI): TransactionPayloadMultiSig;\nexport function generateTransactionPayloadWithABI(\n args: InputGenerateTransactionPayloadDataWithABI,\n): AnyTransactionPayloadInstance {\n const functionAbi = args.abi;\n const { moduleAddress, moduleName, functionName } = getFunctionParts(args.function);\n\n // Ensure that all type arguments are typed properly\n const typeArguments = standardizeTypeTags(args.typeArguments);\n\n // Check the type argument count against the ABI\n if (typeArguments.length !== functionAbi.typeParameters.length) {\n throw new Error(\n `Type argument count mismatch, expected ${functionAbi.typeParameters.length}, received ${typeArguments.length}`,\n );\n }\n\n // Check all BCS types, and convert any non-BCS types\n const functionArguments: Array<EntryFunctionArgumentTypes> = args.functionArguments.map((arg, i) =>\n convertArgument(args.function, functionAbi, arg, i, typeArguments),\n );\n\n // Check that all arguments are accounted for\n if (functionArguments.length !== functionAbi.parameters.length) {\n throw new Error(\n // eslint-disable-next-line max-len\n `Too few arguments for '${moduleAddress}::${moduleName}::${functionName}', expected ${functionAbi.parameters.length} but got ${functionArguments.length}`,\n );\n }\n\n // Generate entry function payload\n const entryFunctionPayload = EntryFunction.build(\n `${moduleAddress}::${moduleName}`,\n functionName,\n typeArguments,\n functionArguments,\n );\n\n // Send it as multi sig if it's a multisig payload\n if (\"multisigAddress\" in args) {\n const multisigAddress = AccountAddress.from(args.multisigAddress);\n return new TransactionPayloadMultiSig(\n new MultiSig(multisigAddress, new MultiSigTransactionPayload(entryFunctionPayload)),\n );\n }\n\n // Otherwise send as an entry function\n return new TransactionPayloadEntryFunction(entryFunctionPayload);\n}\n\nexport async function generateViewFunctionPayload(args: InputViewFunctionDataWithRemoteABI): Promise<EntryFunction> {\n const { moduleAddress, moduleName, functionName } = getFunctionParts(args.function);\n\n const functionAbi = await fetchAbi({\n key: \"view-function\",\n moduleAddress,\n moduleName,\n functionName,\n aptosConfig: args.aptosConfig,\n abi: args.abi,\n fetch: fetchViewFunctionAbi,\n });\n\n // Fill in the ABI\n return generateViewFunctionPayloadWithABI({ abi: functionAbi, ...args });\n}\n\nexport function generateViewFunctionPayloadWithABI(args: InputViewFunctionDataWithABI): EntryFunction {\n const functionAbi = args.abi;\n const { moduleAddress, moduleName, functionName } = getFunctionParts(args.function);\n\n // Ensure that all type arguments are typed properly\n const typeArguments = standardizeTypeTags(args.typeArguments);\n\n // Check the type argument count against the ABI\n if (typeArguments.length !== functionAbi.typeParameters.length) {\n throw new Error(\n `Type argument count mismatch, expected ${functionAbi.typeParameters.length}, received ${typeArguments.length}`,\n );\n }\n\n // Check all BCS types, and convert any non-BCS types\n const functionArguments: Array<EntryFunctionArgumentTypes> =\n args?.functionArguments?.map((arg, i) => convertArgument(args.function, functionAbi, arg, i, typeArguments)) ?? [];\n\n // Check that all arguments are accounted for\n if (functionArguments.length !== functionAbi.parameters.length) {\n throw new Error(\n // eslint-disable-next-line max-len\n `Too few arguments for '${moduleAddress}::${moduleName}::${functionName}', expected ${functionAbi.parameters.length} but got ${functionArguments.length}`,\n );\n }\n\n // Generate entry function payload\n return EntryFunction.build(`${moduleAddress}::${moduleName}`, functionName, typeArguments, functionArguments);\n}\n\nfunction generateTransactionPayloadScript(args: InputScriptData) {\n return new TransactionPayloadScript(\n new Script(Hex.fromHexInput(args.bytecode).toUint8Array(), args.typeArguments ?? [], args.functionArguments),\n );\n}\n\n/**\n * Generates a raw transaction\n *\n * @param args.aptosConfig AptosConfig\n * @param args.sender The transaction's sender account address as a hex input\n * @param args.payload The transaction payload - can create by using generateTransactionPayload()\n *\n * @returns RawTransaction\n */\nexport async function generateRawTransaction(args: {\n aptosConfig: AptosConfig;\n sender: AccountAddressInput;\n payload: AnyTransactionPayloadInstance;\n options?: InputGenerateTransactionOptions;\n feePayerAddress?: AccountAddressInput;\n}): Promise<RawTransaction> {\n const { aptosConfig, sender, payload, options, feePayerAddress } = args;\n\n const getChainId = async () => {\n if (NetworkToChainId[aptosConfig.network]) {\n return { chainId: NetworkToChainId[aptosConfig.network] };\n }\n const info = await getLedgerInfo({ aptosConfig });\n return { chainId: info.chain_id };\n };\n\n const getGasUnitPrice = async () => {\n if (options?.gasUnitPrice) {\n return { gasEstimate: options.gasUnitPrice };\n }\n const estimation = await getGasPriceEstimation({ aptosConfig });\n return { gasEstimate: estimation.gas_estimate };\n };\n\n const getSequenceNumberForAny = async () => {\n const getSequenceNumber = async () => {\n if (options?.accountSequenceNumber !== undefined) {\n return options.accountSequenceNumber;\n }\n\n return (await getInfo({ aptosConfig, accountAddress: sender })).sequence_number;\n };\n\n /**\n * Check if is sponsored transaction to honor AIP-52\n * {@link https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-52.md}\n */\n if (feePayerAddress && AccountAddress.from(feePayerAddress).equals(AccountAddress.ZERO)) {\n // Handle sponsored transaction generation with the option that\n // the main signer has not been created on chain\n try {\n // Check if main signer has been created on chain, if not assign sequence number 0\n return await getSequenceNumber();\n } catch (e: any) {\n return 0;\n }\n } else {\n return getSequenceNumber();\n }\n };\n const [{ chainId }, { gasEstimate }, sequenceNumber] = await Promise.all([\n getChainId(),\n getGasUnitPrice(),\n getSequenceNumberForAny(),\n ]);\n\n const { maxGasAmount, gasUnitPrice, expireTimestamp } = {\n maxGasAmount: options?.maxGasAmount ? BigInt(options.maxGasAmount) : BigInt(DEFAULT_MAX_GAS_AMOUNT),\n gasUnitPrice: options?.gasUnitPrice ?? BigInt(gasEstimate),\n expireTimestamp: options?.expireTimestamp ?? BigInt(Math.floor(Date.now() / 1000) + DEFAULT_TXN_EXP_SEC_FROM_NOW),\n };\n\n return new RawTransaction(\n AccountAddress.from(sender),\n BigInt(sequenceNumber),\n payload,\n BigInt(maxGasAmount),\n BigInt(gasUnitPrice),\n BigInt(expireTimestamp),\n new ChainId(chainId),\n );\n}\n\n/**\n * We are defining function signatures, each with its specific input and output.\n * These are the possible function signature for our `generateTransaction` function.\n * When we call our `generateTransaction` function with the relevant type properties,\n * Typescript can infer the return type based on the appropriate function overload.\n */\nexport async function buildTransaction(args: InputGenerateSingleSignerRawTransactionArgs): Promise<SimpleTransaction>;\nexport async function buildTransaction(args: InputGenerateMultiAgentRawTransactionArgs): Promise<MultiAgentTransaction>;\n\n/**\n * Generates a transaction based on the provided arguments\n *\n * Note: we can start with one function to support all different payload/transaction types,\n * and if to complex to use, we could have function for each type\n *\n * @param args.aptosConfig AptosConfig\n * @param args.sender The transaction's sender account address as a hex input\n * @param args.payload The transaction payload - can create by using generateTransactionPayload()\n * @param args.options optional. Transaction options object\n * @param args.secondarySignerAddresses optional. For when want to create a multi signers transaction\n * @param args.feePayerAddress optional. For when want to create a fee payer (aka sponsored) transaction\n *\n * @return An instance of a RawTransaction, plus optional secondary/fee payer addresses\n * ```\n * {\n * rawTransaction: RawTransaction,\n * secondarySignerAddresses? : Array<AccountAddress>,\n * feePayerAddress?: AccountAddress\n * }\n * ```\n */\nexport async function buildTransaction(args: InputGenerateRawTransactionArgs): Promise<AnyRawTransaction> {\n const { aptosConfig, sender, payload, options, feePayerAddress } = args;\n // generate raw transaction\n const rawTxn = await generateRawTransaction({\n aptosConfig,\n sender,\n payload,\n options,\n feePayerAddress,\n });\n\n // if multi agent transaction\n if (\"secondarySignerAddresses\" in args) {\n const signers: Array<AccountAddress> =\n args.secondarySignerAddresses?.map((signer) => AccountAddress.from(signer)) ?? [];\n\n return new MultiAgentTransaction(\n rawTxn,\n signers,\n args.feePayerAddress ? AccountAddress.from(args.feePayerAddress) : undefined,\n );\n }\n // return the raw transaction\n return new SimpleTransaction(rawTxn, args.feePayerAddress ? AccountAddress.from(args.feePayerAddress) : undefined);\n}\n\n/**\n * Simulate a transaction before signing and submit to chain\n *\n * @param args.transaction A aptos transaction type to sign\n * @param args.signerPublicKey The signer public key\n * @param args.secondarySignersPublicKeys optional. The secondary signers public keys if multi signers transaction\n * @param args.feePayerPublicKey optional. The fee payer public key is a fee payer (aka sponsored) transaction\n * @param args.options optional. SimulateTransactionOptions\n *\n * @returns A signed serialized transaction that can be simulated\n */\nexport function generateSignedTransactionForSimulation(args: InputSimulateTransactionData): Uint8Array {\n const { signerPublicKey, transaction, secondarySignersPublicKeys, feePayerPublicKey } = args;\n\n const accountAuthenticator = getAuthenticatorForSimulation(signerPublicKey);\n\n // fee payer transaction\n if (transaction.feePayerAddress) {\n const transactionToSign = new FeePayerRawTransaction(\n transaction.rawTransaction,\n transaction.secondarySignerAddresses ?? [],\n transaction.feePayerAddress,\n );\n let secondaryAccountAuthenticators: Array<AccountAuthenticator> = [];\n if (secondarySignersPublicKeys) {\n secondaryAccountAuthenticators = secondarySignersPublicKeys.map((publicKey) =>\n getAuthenticatorForSimulation(publicKey),\n );\n }\n const feePayerAuthenticator = getAuthenticatorForSimulation(feePayerPublicKey!);\n\n const transactionAuthenticator = new TransactionAuthenticatorFeePayer(\n accountAuthenticator,\n transaction.secondarySignerAddresses ?? [],\n secondaryAccountAuthenticators,\n {\n address: transaction.feePayerAddress,\n authenticator: feePayerAuthenticator,\n },\n );\n return new SignedTransaction(transactionToSign.raw_txn, transactionAuthenticator).bcsToBytes();\n }\n\n // multi agent transaction\n if (transaction.secondarySignerAddresses) {\n const transactionToSign = new MultiAgentRawTransaction(\n transaction.rawTransaction,\n transaction.secondarySignerAddresses,\n );\n\n let secondaryAccountAuthenticators: Array<AccountAuthenticator> = [];\n\n secondaryAccountAuthenticators = secondarySignersPublicKeys!.map((publicKey) =>\n getAuthenticatorForSimulation(publicKey),\n );\n\n const transactionAuthenticator = new TransactionAuthenticatorMultiAgent(\n accountAuthenticator,\n transaction.secondarySignerAddresses,\n secondaryAccountAuthenticators,\n );\n\n return new SignedTransaction(transactionToSign.raw_txn, transactionAuthenticator).bcsToBytes();\n }\n\n // single signer raw transaction\n let transactionAuthenticator;\n if (accountAuthenticator instanceof AccountAuthenticatorEd25519) {\n transactionAuthenticator = new TransactionAuthenticatorEd25519(\n accountAuthenticator.public_key,\n accountAuthenticator.signature,\n );\n } else if (accountAuthenticator instanceof AccountAuthenticatorSingleKey) {\n transactionAuthenticator = new TransactionAuthenticatorSingleSender(accountAuthenticator);\n } else {\n throw new Error(\"Invalid public key\");\n }\n return new SignedTransaction(transaction.rawTransaction, transactionAuthenticator).bcsToBytes();\n}\n\nexport function getAuthenticatorForSimulation(publicKey: PublicKey) {\n // TODO add support for AnyMultiKey\n if (publicKey instanceof AnyPublicKey) {\n if (publicKey.publicKey instanceof Ed25519PublicKey) {\n return new AccountAuthenticatorSingleKey(publicKey, new AnySignature(new Ed25519Signature(new Uint8Array(64))));\n }\n if (publicKey.publicKey instanceof Secp256k1PublicKey) {\n return new AccountAuthenticatorSingleKey(publicKey, new AnySignature(new Secp256k1Signature(new Uint8Array(64))));\n }\n }\n\n // legacy code\n return new AccountAuthenticatorEd25519(\n new Ed25519PublicKey(publicKey.toUint8Array()),\n new Ed25519Signature(new Uint8Array(64)),\n );\n}\n\n/**\n * Sign a transaction that can later be submitted to chain\n *\n * @param args.signer The signer account to sign the transaction\n * @param args.transaction A aptos transaction type to sign\n *\n * @return The signer AccountAuthenticator\n */\nexport function sign(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n const { signer, transaction } = args;\n\n // get the signing message\n const message = generateSigningMessage(transaction);\n\n // account.signMessage\n return signer.signWithAuthenticator(message);\n}\n\n/**\n * Prepare a transaction to be submitted to chain\n *\n * @param args.transaction A aptos transaction type\n * @param args.senderAuthenticator The account authenticator of the transaction sender\n * @param args.secondarySignerAuthenticators optional. For when the transaction is a multi signers transaction\n *\n * @returns A SignedTransaction\n */\nexport function generateSignedTransaction(args: InputSubmitTransactionData): Uint8Array {\n const { transaction, feePayerAuthenticator, additionalSignersAuthenticators } = args;\n const senderAuthenticator = normalizeBundle(AccountAuthenticator, args.senderAuthenticator);\n\n let txnAuthenticator: TransactionAuthenticator;\n if (transaction.feePayerAddress) {\n if (!feePayerAuthenticator) {\n throw new Error(\"Must provide a feePayerAuthenticator argument to generate a signed fee payer transaction\");\n }\n txnAuthenticator = new TransactionAuthenticatorFeePayer(\n senderAuthenticator,\n transaction.secondarySignerAddresses ?? [],\n additionalSignersAuthenticators ?? [],\n {\n address: transaction.feePayerAddress,\n authenticator: feePayerAuthenticator,\n },\n );\n } else if (transaction.secondarySignerAddresses) {\n if (!additionalSignersAuthenticators) {\n throw new Error(\n \"Must provide a additionalSignersAuthenticators argument to generate a signed multi agent transaction\",\n );\n }\n txnAuthenticator = new TransactionAuthenticatorMultiAgent(\n senderAuthenticator,\n transaction.secondarySignerAddresses,\n additionalSignersAuthenticators,\n );\n } else if (senderAuthenticator instanceof AccountAuthenticatorEd25519) {\n txnAuthenticator = new TransactionAuthenticatorEd25519(\n senderAuthenticator.public_key,\n senderAuthenticator.signature,\n );\n } else {\n txnAuthenticator = new TransactionAuthenticatorSingleSender(senderAuthenticator);\n }\n\n return new SignedTransaction(transaction.rawTransaction, txnAuthenticator).bcsToBytes();\n}\n\n/**\n * Hashes the set of values with a SHA-3 256 hash\n * @param input array of UTF-8 strings or Uint8array byte arrays\n */\nexport function hashValues(input: (Uint8Array | string)[]): Uint8Array {\n const hash = sha3Hash.create();\n for (const item of input) {\n hash.update(item);\n }\n return hash.digest();\n}\n\n/**\n * The domain separated prefix for hashing transacitons\n */\nconst TRANSACTION_PREFIX = hashValues([\"APTOS::Transaction\"]);\n\n/**\n * Generates a user transaction hash for the given transaction payload. It must already have an authenticator\n * @param args InputSubmitTransactionData\n */\nexport function generateUserTransactionHash(args: InputSubmitTransactionData): string {\n const signedTransaction = generateSignedTransaction(args);\n\n // Transaction signature is defined as, the domain separated prefix based on struct (Transaction)\n // Then followed by the type of the transaction for the enum, UserTransaction is 0\n // Then followed by BCS encoded bytes of the signed transaction\n return new Hex(hashValues([TRANSACTION_PREFIX, new Uint8Array([0]), signedTransaction])).toString();\n}\n\n/**\n * Derive the raw transaction type - FeePayerRawTransaction or MultiAgentRawTransaction or RawTransaction\n *\n * @param transaction A aptos transaction type\n *\n * @returns FeePayerRawTransaction | MultiAgentRawTransaction | RawTransaction\n */\nexport function deriveTransactionType(transaction: AnyRawTransaction): AnyRawTransactionInstance {\n if (transaction.feePayerAddress) {\n return new FeePayerRawTransaction(\n transaction.rawTransaction,\n transaction.secondarySignerAddresses ?? [],\n transaction.feePayerAddress,\n );\n }\n if (transaction.secondarySignerAddresses) {\n return new MultiAgentRawTransaction(transaction.rawTransaction, transaction.secondarySignerAddresses);\n }\n\n return transaction.rawTransaction;\n}\n\nexport function generateSigningMessage(transaction: AnyRawTransaction): Uint8Array {\n const hash = sha3Hash.create();\n\n if (transaction.feePayerAddress) {\n hash.update(RAW_TRANSACTION_WITH_DATA_SALT);\n } else if (transaction.secondarySignerAddresses) {\n hash.update(RAW_TRANSACTION_WITH_DATA_SALT);\n } else {\n hash.update(RAW_TRANSACTION_SALT);\n }\n\n const prefix = hash.digest();\n\n const rawTxn = deriveTransactionType(transaction);\n const body = rawTxn.bcsToBytes();\n\n const mergedArray = new Uint8Array(prefix.length + body.length);\n mergedArray.set(prefix);\n mergedArray.set(body, prefix.length);\n\n return mergedArray;\n}\n\n/**\n * Fetches and caches ABIs with allowing for pass-through on provided ABIs\n * @param key\n * @param moduleAddress\n * @param moduleName\n * @param functionName\n * @param aptosConfig\n * @param abi\n * @param fetch\n */\nasync function fetchAbi<T extends FunctionABI>({\n key,\n moduleAddress,\n moduleName,\n functionName,\n aptosConfig,\n abi,\n fetch,\n}: {\n key: string;\n moduleAddress: string;\n moduleName: string;\n functionName: string;\n aptosConfig: AptosConfig;\n abi?: T;\n fetch: (moduleAddress: string, moduleName: string, functionName: string, aptosConfig: AptosConfig) => Promise<T>;\n}): Promise<T> {\n if (abi !== undefined) {\n return abi;\n }\n\n // We fetch the entry function ABI, and then pretend that we already had the ABI\n return memoizeAsync(\n async () => fetch(moduleAddress, moduleName, functionName, aptosConfig),\n `${key}-${aptosConfig.network}-${moduleAddress}-${moduleName}-${functionName}`,\n 1000 * 60 * 5, // 5 minutes\n )();\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../../bcs/serializer\";\nimport { AccountAddress } from \"../../core/accountAddress\";\nimport { AnyNumber } from \"../../types\";\nimport { PublicKey } from \"../../core/crypto\";\nimport { MoveString, MoveVector, U64, U8 } from \"../../bcs\";\n\n/**\n * Representation of the challenge which is needed to sign by owner of the account\n * to rotate the authentication key.\n */\nexport class RotationProofChallenge extends Serializable {\n // Resource account address\n public readonly accountAddress: AccountAddress = AccountAddress.ONE;\n\n // Module name, i.e: 0x1::account\n public readonly moduleName: MoveString = new MoveString(\"account\");\n\n // The rotation proof challenge struct name that live under the module\n public readonly structName: MoveString = new MoveString(\"RotationProofChallenge\");\n\n // Signer's address\n public readonly originator: AccountAddress;\n\n // Signer's current authentication key\n public readonly currentAuthKey: AccountAddress;\n\n // New public key to rotate to\n public readonly newPublicKey: MoveVector<U8>;\n\n // Sequence number of the account\n public readonly sequenceNumber: U64;\n\n constructor(args: {\n sequenceNumber: AnyNumber;\n originator: AccountAddress;\n currentAuthKey: AccountAddress;\n newPublicKey: PublicKey;\n }) {\n super();\n this.sequenceNumber = new U64(args.sequenceNumber);\n this.originator = args.originator;\n this.currentAuthKey = args.currentAuthKey;\n this.newPublicKey = MoveVector.U8(args.newPublicKey.toUint8Array());\n }\n\n serialize(serializer: Serializer): void {\n serializer.serialize(this.accountAddress);\n serializer.serialize(this.moduleName);\n serializer.serialize(this.structName);\n serializer.serialize(this.sequenceNumber);\n serializer.serialize(this.originator);\n serializer.serialize(this.currentAuthKey);\n serializer.serialize(this.newPublicKey);\n }\n}\n","/**\n * This file contains the underlying implementations for exposed submission API surface in\n * the {@link api/transaction}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * transaction namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { MoveVector, U8 } from \"../bcs\";\nimport { postAptosFullNode } from \"../client\";\nimport { Account } from \"../core/account\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { PrivateKey } from \"../core/crypto\";\nimport { AccountAuthenticator } from \"../transactions/authenticator/account\";\nimport { RotationProofChallenge } from \"../transactions/instances/rotationProofChallenge\";\nimport {\n buildTransaction,\n generateTransactionPayload,\n generateSignedTransactionForSimulation,\n generateSignedTransaction,\n sign,\n generateSigningMessage,\n} from \"../transactions/transactionBuilder/transactionBuilder\";\nimport {\n InputGenerateTransactionData,\n AnyRawTransaction,\n InputSimulateTransactionData,\n InputGenerateTransactionOptions,\n InputGenerateTransactionPayloadDataWithRemoteABI,\n InputSubmitTransactionData,\n InputGenerateMultiAgentRawTransactionData,\n InputGenerateSingleSignerRawTransactionData,\n AnyTransactionPayloadInstance,\n EntryFunctionABI,\n} from \"../transactions/types\";\nimport { getInfo } from \"./account\";\nimport { UserTransactionResponse, PendingTransactionResponse, MimeType, HexInput, TransactionResponse } from \"../types\";\nimport { TypeTagU8, TypeTagVector } from \"../transactions\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\nimport { MultiAgentTransaction } from \"../transactions/instances/multiAgentTransaction\";\n\n/**\n * We are defining function signatures, each with its specific input and output.\n * These are the possible function signature for `generateTransaction` function.\n * When we call `generateTransaction` function with the relevant type properties,\n * Typescript can infer the return type based on the appropriate function overload.\n */\nexport async function generateTransaction(\n args: { aptosConfig: AptosConfig } & InputGenerateSingleSignerRawTransactionData,\n): Promise<SimpleTransaction>;\nexport async function generateTransaction(\n args: { aptosConfig: AptosConfig } & InputGenerateMultiAgentRawTransactionData,\n): Promise<MultiAgentTransaction>;\n/**\n * Generates any transaction by passing in the required arguments\n *\n * @param args.sender The transaction sender's account address as a AccountAddressInput\n * @param args.data EntryFunctionData | ScriptData | MultiSigData\n * @param args.feePayerAddress optional. For a fee payer (aka sponsored) transaction\n * @param args.secondarySignerAddresses optional. For a multi-agent or fee payer (aka sponsored) transactions\n * @param args.options optional. GenerateTransactionOptions type\n *\n * @example\n * For a single signer entry function\n * move function name, move function type arguments, move function arguments\n * `\n * data: {\n * function:\"0x1::aptos_account::transfer\",\n * typeArguments:[]\n * functionArguments :[receiverAddress,10]\n * }\n * `\n *\n * @example\n * For a single signer script function\n * module bytecode, move function type arguments, move function arguments\n * ```\n * data: {\n * bytecode:\"0x001234567\",\n * typeArguments:[],\n * functionArguments :[receiverAddress,10]\n * }\n * ```\n *\n * @return An instance of a RawTransaction, plus optional secondary/fee payer addresses\n * ```\n * {\n * rawTransaction: RawTransaction,\n * secondarySignerAddresses? : Array<AccountAddress>,\n * feePayerAddress?: AccountAddress\n * }\n * ```\n */\nexport async function generateTransaction(\n args: { aptosConfig: AptosConfig } & InputGenerateTransactionData,\n): Promise<AnyRawTransaction> {\n const payload = await buildTransactionPayload(args);\n return buildRawTransaction(args, payload);\n}\n\nexport async function buildTransactionPayload(\n args: { aptosConfig: AptosConfig } & InputGenerateTransactionData,\n): Promise<AnyTransactionPayloadInstance> {\n const { aptosConfig, data } = args;\n // Merge in aptosConfig for remote ABI on non-script payloads\n let generateTransactionPayloadData: InputGenerateTransactionPayloadDataWithRemoteABI;\n let payload: AnyTransactionPayloadInstance;\n\n if (\"bytecode\" in data) {\n // TODO: Add ABI checking later\n payload = await generateTransactionPayload(data);\n } else if (\"multisigAddress\" in data) {\n generateTransactionPayloadData = {\n aptosConfig,\n multisigAddress: data.multisigAddress,\n function: data.function,\n functionArguments: data.functionArguments,\n typeArguments: data.typeArguments,\n abi: data.abi,\n };\n payload = await generateTransactionPayload(generateTransactionPayloadData);\n } else {\n generateTransactionPayloadData = {\n aptosConfig,\n function: data.function,\n functionArguments: data.functionArguments,\n typeArguments: data.typeArguments,\n abi: data.abi,\n };\n payload = await generateTransactionPayload(generateTransactionPayloadData);\n }\n return payload;\n}\n\nexport async function buildRawTransaction(\n args: { aptosConfig: AptosConfig } & InputGenerateTransactionData,\n payload: AnyTransactionPayloadInstance,\n): Promise<AnyRawTransaction> {\n const { aptosConfig, sender, options } = args;\n\n let feePayerAddress;\n if (isFeePayerTransactionInput(args)) {\n feePayerAddress = AccountAddress.ZERO.toString();\n }\n\n if (isMultiAgentTransactionInput(args)) {\n const { secondarySignerAddresses } = args;\n return buildTransaction({\n aptosConfig,\n sender,\n payload,\n options,\n secondarySignerAddresses,\n feePayerAddress,\n });\n }\n\n return buildTransaction({\n aptosConfig,\n sender,\n payload,\n options,\n feePayerAddress,\n });\n}\n\nfunction isFeePayerTransactionInput(data: InputGenerateTransactionData): boolean {\n return data.withFeePayer === true;\n}\n\nfunction isMultiAgentTransactionInput(\n data: InputGenerateTransactionData,\n): data is InputGenerateMultiAgentRawTransactionData {\n return \"secondarySignerAddresses\" in data;\n}\n\n/**\n * Builds a signing message that can be signed by external signers\n *\n * Note: Please prefer using `signTransaction` unless signing outside the SDK\n *\n * @param args.transaction AnyRawTransaction, as generated by `generateTransaction()`\n *\n * @return The message to be signed\n */\nexport function getSigningMessage(args: { transaction: AnyRawTransaction }): Uint8Array {\n const { transaction } = args;\n return generateSigningMessage(transaction);\n}\n\n/**\n * Sign a transaction that can later be submitted to chain\n *\n * @param args.signer The signer account to sign the transaction\n * @param args.transaction An instance of a RawTransaction, plus optional secondary/fee payer addresses\n * ```\n * {\n * rawTransaction: RawTransaction,\n * secondarySignerAddresses? : Array<AccountAddress>,\n * feePayerAddress?: AccountAddress\n * }\n * ```\n *\n * @return The signer AccountAuthenticator\n */\nexport function signTransaction(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n const accountAuthenticator = sign({ ...args });\n return accountAuthenticator;\n}\n\n/**\n * Simulates a transaction before singing it.\n *\n * @param args.signerPublicKey The signer public key\n * @param args.transaction The raw transaction to simulate\n * @param args.secondarySignersPublicKeys optional. For when the transaction is a multi signers transaction\n * @param args.feePayerPublicKey optional. For when the transaction is a fee payer (aka sponsored) transaction\n * @param args.options optional. A config to simulate the transaction with\n */\nexport async function simulateTransaction(\n args: { aptosConfig: AptosConfig } & InputSimulateTransactionData,\n): Promise<Array<UserTransactionResponse>> {\n const { aptosConfig, transaction, signerPublicKey, secondarySignersPublicKeys, feePayerPublicKey, options } = args;\n\n const signedTransaction = generateSignedTransactionForSimulation({\n transaction,\n signerPublicKey,\n secondarySignersPublicKeys,\n feePayerPublicKey,\n options,\n });\n\n const { data } = await postAptosFullNode<Uint8Array, Array<UserTransactionResponse>>({\n aptosConfig,\n body: signedTransaction,\n path: \"transactions/simulate\",\n params: {\n estimate_gas_unit_price: args.options?.estimateGasUnitPrice ?? false,\n estimate_max_gas_amount: args.options?.estimateMaxGasAmount ?? false,\n estimate_prioritized_gas_unit_price: args.options?.estimatePrioritizedGasUnitPrice ?? false,\n },\n originMethod: \"simulateTransaction\",\n contentType: MimeType.BCS_SIGNED_TRANSACTION,\n });\n return data;\n}\n\n/**\n * Submit transaction to chain\n *\n * @param args.transaction A aptos transaction type\n * @param args.senderAuthenticator The account authenticator of the transaction sender\n * @param args.secondarySignerAuthenticators optional. For when the transaction is a multi signers transaction\n *\n * @return PendingTransactionResponse\n */\nexport async function submitTransaction(\n args: {\n aptosConfig: AptosConfig;\n } & InputSubmitTransactionData,\n): Promise<PendingTransactionResponse> {\n const { aptosConfig } = args;\n const signedTransaction = generateSignedTransaction({ ...args });\n const { data } = await postAptosFullNode<Uint8Array, PendingTransactionResponse>({\n aptosConfig,\n body: signedTransaction,\n path: \"transactions\",\n originMethod: \"submitTransaction\",\n contentType: MimeType.BCS_SIGNED_TRANSACTION,\n });\n return data;\n}\n\nexport async function signAndSubmitTransaction(args: {\n aptosConfig: AptosConfig;\n signer: Account;\n transaction: AnyRawTransaction;\n}): Promise<PendingTransactionResponse> {\n const { aptosConfig, signer, transaction } = args;\n const authenticator = signTransaction({ signer, transaction });\n return submitTransaction({\n aptosConfig,\n transaction,\n senderAuthenticator: authenticator,\n });\n}\n\nconst packagePublishAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [TypeTagVector.u8(), new TypeTagVector(TypeTagVector.u8())],\n};\n\nexport async function publicPackageTransaction(args: {\n aptosConfig: AptosConfig;\n account: AccountAddressInput;\n metadataBytes: HexInput;\n moduleBytecode: Array<HexInput>;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, account, metadataBytes, moduleBytecode, options } = args;\n\n const totalByteCode = moduleBytecode.map((bytecode) => MoveVector.U8(bytecode));\n\n return generateTransaction({\n aptosConfig,\n sender: AccountAddress.from(account),\n data: {\n function: \"0x1::code::publish_package_txn\",\n functionArguments: [MoveVector.U8(metadataBytes), new MoveVector(totalByteCode)],\n abi: packagePublishAbi,\n },\n options,\n });\n}\n\nconst rotateAuthKeyAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [\n new TypeTagU8(),\n TypeTagVector.u8(),\n new TypeTagU8(),\n TypeTagVector.u8(),\n TypeTagVector.u8(),\n TypeTagVector.u8(),\n ],\n};\n\n/**\n * TODO: Need to refactor and move this function out of transactionSubmission\n */\nexport async function rotateAuthKey(args: {\n aptosConfig: AptosConfig;\n fromAccount: Account;\n toNewPrivateKey: PrivateKey;\n}): Promise<TransactionResponse> {\n const { aptosConfig, fromAccount, toNewPrivateKey } = args;\n const accountInfo = await getInfo({\n aptosConfig,\n accountAddress: fromAccount.accountAddress,\n });\n\n const newAccount = Account.fromPrivateKey({ privateKey: toNewPrivateKey, legacy: true });\n\n const challenge = new RotationProofChallenge({\n sequenceNumber: BigInt(accountInfo.sequence_number),\n originator: fromAccount.accountAddress,\n currentAuthKey: AccountAddress.from(accountInfo.authentication_key),\n newPublicKey: newAccount.publicKey,\n });\n\n // Sign the challenge\n const challengeHex = challenge.bcsToBytes();\n const proofSignedByCurrentPrivateKey = fromAccount.sign(challengeHex);\n const proofSignedByNewPrivateKey = newAccount.sign(challengeHex);\n\n // Generate transaction\n const rawTxn = await generateTransaction({\n aptosConfig,\n sender: fromAccount.accountAddress,\n data: {\n function: \"0x1::account::rotate_authentication_key\",\n functionArguments: [\n new U8(fromAccount.signingScheme), // from scheme\n MoveVector.U8(fromAccount.publicKey.toUint8Array()),\n new U8(newAccount.signingScheme), // to scheme\n MoveVector.U8(newAccount.publicKey.toUint8Array()),\n MoveVector.U8(proofSignedByCurrentPrivateKey.toUint8Array()),\n MoveVector.U8(proofSignedByNewPrivateKey.toUint8Array()),\n ],\n abi: rotateAuthKeyAbi,\n },\n });\n return signAndSubmitTransaction({\n aptosConfig,\n signer: fromAccount,\n transaction: rawTxn,\n });\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AccountAddressInput } from \"../../core\";\nimport { generateTransaction } from \"../../internal/transactionSubmission\";\nimport { InputGenerateTransactionPayloadData, InputGenerateTransactionOptions } from \"../../transactions\";\nimport { MultiAgentTransaction } from \"../../transactions/instances/multiAgentTransaction\";\nimport { SimpleTransaction } from \"../../transactions/instances/simpleTransaction\";\nimport { AptosConfig } from \"../aptosConfig\";\n\n/**\n * A class to handle all `Build` transaction operations\n */\nexport class Build {\n readonly config: AptosConfig;\n\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Build a simple transaction\n *\n * @param args.sender The sender account address\n * @param args.data The transaction data\n * @param args.options optional. Optional transaction configurations\n * @param args.withFeePayer optional. Whether there is a fee payer for the transaction\n *\n * @returns SimpleTransaction\n */\n async simple(args: {\n sender: AccountAddressInput;\n data: InputGenerateTransactionPayloadData;\n options?: InputGenerateTransactionOptions;\n withFeePayer?: boolean;\n }): Promise<SimpleTransaction> {\n return generateTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Build a multi agent transaction\n *\n * @param args.sender The sender account address\n * @param args.data The transaction data\n * @param args.secondarySignerAddresses An array of the secondary signers account addresses\n * @param args.options optional. Optional transaction configurations\n * @param args.withFeePayer optional. Whether there is a fee payer for the transaction\n *\n * @returns MultiAgentTransaction\n */\n async multiAgent(args: {\n sender: AccountAddressInput;\n data: InputGenerateTransactionPayloadData;\n secondarySignerAddresses: AccountAddressInput[];\n options?: InputGenerateTransactionOptions;\n withFeePayer?: boolean;\n }): Promise<MultiAgentTransaction> {\n return generateTransaction({ aptosConfig: this.config, ...args });\n }\n}\n","/**\n * A wrapper that handles and manages an account sequence number.\n *\n * Submit up to `maximumInFlight` transactions per account in parallel with a timeout of `sleepTime`\n * If local assumes `maximumInFlight` are in flight, determine the actual committed state from the network\n * If there are less than `maximumInFlight` due to some being committed, adjust the window\n * If `maximumInFlight` are in flight, wait `sleepTime` seconds before re-evaluating\n * If ever waiting more than `maxWaitTime` restart the sequence number to the current on-chain state\n *\n * Assumptions:\n * Accounts are expected to be managed by a single AccountSequenceNumber and not used otherwise.\n * They are initialized to the current on-chain state, so if there are already transactions in\n * flight, they may take some time to reset.\n * Accounts are automatically initialized if not explicitly\n *\n * Notes:\n * This is co-routine safe, that is many async tasks can be reading from this concurrently.\n * The state of an account cannot be used across multiple AccountSequenceNumber services.\n * The synchronize method will create a barrier that prevents additional nextSequenceNumber\n * calls until it is complete.\n * This only manages the distribution of sequence numbers it does not help handle transaction\n * failures.\n * If a transaction fails, you should call synchronize and wait for timeouts.\n */\n\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport { Account } from \"../../core\";\nimport { getInfo } from \"../../internal/account\";\nimport { sleep } from \"../../utils/helpers\";\n\n// returns `now` time in seconds\nconst now = () => Math.floor(Date.now() / 1000);\n\nexport class AccountSequenceNumber {\n readonly aptosConfig: AptosConfig;\n\n readonly account: Account;\n\n // sequence number on chain\n lastUncommintedNumber: bigint | null = null;\n\n // local sequence number\n currentNumber: bigint | null = null;\n\n /**\n * We want to guarantee that we preserve ordering of workers to requests.\n *\n * `lock` is used to try to prevent multiple coroutines from accessing a shared resource at the same time,\n * which can result in race conditions and data inconsistency.\n * This code actually doesn't do it though, since we aren't giving out a slot, it is still somewhat a race condition.\n *\n * The ideal solution is likely that each thread grabs the next number from a incremental integer.\n * When they complete, they increment that number and that entity is able to enter the `lock`.\n * That would guarantee ordering.\n */\n lock = false;\n\n maxWaitTime: number;\n\n maximumInFlight: number;\n\n sleepTime: number;\n\n constructor(\n aptosConfig: AptosConfig,\n account: Account,\n maxWaitTime: number,\n maximumInFlight: number,\n sleepTime: number,\n ) {\n this.aptosConfig = aptosConfig;\n this.account = account;\n this.maxWaitTime = maxWaitTime;\n this.maximumInFlight = maximumInFlight;\n this.sleepTime = sleepTime;\n }\n\n /**\n * Returns the next available sequence number for this account\n *\n * @returns next available sequence number\n */\n async nextSequenceNumber(): Promise<bigint | null> {\n /* eslint-disable no-await-in-loop */\n while (this.lock) {\n await sleep(this.sleepTime);\n }\n\n this.lock = true;\n let nextNumber = BigInt(0);\n try {\n if (this.lastUncommintedNumber === null || this.currentNumber === null) {\n await this.initialize();\n }\n\n if (this.currentNumber! - this.lastUncommintedNumber! >= this.maximumInFlight) {\n await this.update();\n\n const startTime = now();\n while (this.currentNumber! - this.lastUncommintedNumber! >= this.maximumInFlight) {\n await sleep(this.sleepTime);\n if (now() - startTime > this.maxWaitTime) {\n /* eslint-disable no-console */\n console.warn(\n `Waited over 30 seconds for a transaction to commit, resyncing ${this.account.accountAddress.toString()}`,\n );\n await this.initialize();\n } else {\n await this.update();\n }\n }\n }\n nextNumber = this.currentNumber!;\n this.currentNumber! += BigInt(1);\n } catch (e) {\n console.error(\"error in getting next sequence number for this account\", e);\n } finally {\n this.lock = false;\n }\n return nextNumber;\n }\n\n /**\n * Initializes this account with the sequence number on chain\n */\n async initialize(): Promise<void> {\n const { sequence_number: sequenceNumber } = await getInfo({\n aptosConfig: this.aptosConfig,\n accountAddress: this.account.accountAddress,\n });\n this.currentNumber = BigInt(sequenceNumber);\n this.lastUncommintedNumber = BigInt(sequenceNumber);\n }\n\n /**\n * Updates this account sequence number with the one on-chain\n *\n * @returns on-chain sequence number for this account\n */\n async update(): Promise<bigint> {\n const { sequence_number: sequenceNumber } = await getInfo({\n aptosConfig: this.aptosConfig,\n accountAddress: this.account.accountAddress,\n });\n this.lastUncommintedNumber = BigInt(sequenceNumber);\n return this.lastUncommintedNumber;\n }\n\n /**\n * Synchronizes local sequence number with the seqeunce number on chain for this account.\n *\n * Poll the network until all submitted transactions have either been committed or until\n * the maximum wait time has elapsed\n */\n async synchronize(): Promise<void> {\n if (this.lastUncommintedNumber === this.currentNumber) return;\n\n /* eslint-disable no-await-in-loop */\n while (this.lock) {\n await sleep(this.sleepTime);\n }\n\n this.lock = true;\n\n try {\n await this.update();\n const startTime = now();\n while (this.lastUncommintedNumber !== this.currentNumber) {\n if (now() - startTime > this.maxWaitTime) {\n /* eslint-disable no-console */\n console.warn(\n `Waited over 30 seconds for a transaction to commit, resyncing ${this.account.accountAddress.toString()}`,\n );\n await this.initialize();\n } else {\n await sleep(this.sleepTime);\n await this.update();\n }\n }\n } catch (e) {\n console.error(\"error in synchronizing this account sequence number with the one on chain\", e);\n } finally {\n this.lock = false;\n }\n }\n}\n","/**\n * The AsyncQueue class is an async-aware data structure that provides a queue-like\n * behavior for managing asynchronous tasks or operations.\n * It allows to enqueue items and dequeue them asynchronously.\n * This is not thread-safe but it is async concurrency safe and\n * it does not guarantee ordering for those that call into and await on enqueue.\n */\n\ninterface PendingDequeue<T> {\n resolve: (value: T) => void;\n reject: (reason?: AsyncQueueCancelledError) => void;\n}\n\nexport class AsyncQueue<T> {\n readonly queue: T[] = [];\n\n // The pendingDequeue is used to handle the resolution of promises when items are enqueued and dequeued.\n private pendingDequeue: PendingDequeue<T>[] = [];\n\n private cancelled: boolean = false;\n\n /**\n * The enqueue method adds an item to the queue. If there are pending dequeued promises,\n * in the pendingDequeue, it resolves the oldest promise with the enqueued item immediately.\n * Otherwise, it adds the item to the queue.\n *\n * @param item T\n */\n enqueue(item: T): void {\n this.cancelled = false;\n\n if (this.pendingDequeue.length > 0) {\n const promise = this.pendingDequeue.shift();\n\n promise?.resolve(item);\n\n return;\n }\n\n this.queue.push(item);\n }\n\n /**\n * The dequeue method returns a promise that resolves to the next item in the queue.\n * If the queue is not empty, it resolves the promise immediately with the next item.\n * Otherwise, it creates a new promise. The promise's resolve function is stored\n * in the pendingDequeue with a unique counter value as the key.\n * The newly created promise is then returned, and it will be resolved later when an item is enqueued.\n *\n * @returns Promise<T>\n */\n async dequeue(): Promise<T> {\n if (this.queue.length > 0) {\n return Promise.resolve(this.queue.shift()!);\n }\n\n return new Promise<T>((resolve, reject) => {\n this.pendingDequeue.push({ resolve, reject });\n });\n }\n\n /**\n * The isEmpty method returns whether the queue is empty or not.\n *\n * @returns boolean\n */\n isEmpty(): boolean {\n return this.queue.length === 0;\n }\n\n /**\n * The cancel method cancels all pending promises in the queue.\n * It rejects the promises with a AsyncQueueCancelledError error,\n * ensuring that any awaiting code can handle the cancellation appropriately.\n */\n cancel(): void {\n this.cancelled = true;\n\n this.pendingDequeue.forEach(async ({ reject }) => {\n reject(new AsyncQueueCancelledError(\"Task cancelled\"));\n });\n\n this.pendingDequeue = [];\n\n this.queue.length = 0;\n }\n\n /**\n * The isCancelled method returns whether the queue is cancelled or not.\n *\n * @returns boolean\n */\n isCancelled(): boolean {\n return this.cancelled;\n }\n\n /**\n * The pendingDequeueLength method returns the length of the pendingDequeue.\n *\n * @returns number\n */\n pendingDequeueLength(): number {\n return this.pendingDequeue.length;\n }\n}\n\nexport class AsyncQueueCancelledError extends Error {}\n","import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n","/* eslint-disable no-await-in-loop */\n\nimport EventEmitter from \"eventemitter3\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport { Account } from \"../../core\";\nimport { waitForTransaction } from \"../../internal/transaction\";\nimport { generateTransaction, signAndSubmitTransaction } from \"../../internal/transactionSubmission\";\nimport { PendingTransactionResponse, TransactionResponse } from \"../../types\";\nimport { InputGenerateTransactionOptions, InputGenerateTransactionPayloadData } from \"../types\";\nimport { AccountSequenceNumber } from \"./accountSequenceNumber\";\nimport { AsyncQueue, AsyncQueueCancelledError } from \"./asyncQueue\";\nimport { SimpleTransaction } from \"../instances/simpleTransaction\";\n\nexport const promiseFulfilledStatus = \"fulfilled\";\n\n// Event types the worker fires during execution and\n// the dapp can listen to\nexport enum TransactionWorkerEventsEnum {\n // fired after a transaction gets sent to the chain\n TransactionSent = \"transactionSent\",\n // fired if there is an error sending the transaction to the chain\n TransactionSendFailed = \"transactionSendFailed\",\n // fired when a single transaction has executed successfully\n TransactionExecuted = \"transactionExecuted\",\n // fired if a single transaction fails in execution\n TransactionExecutionFailed = \"transactionExecutionFailed\",\n // fired when the worker has finished its job / when the queue has been emptied\n ExecutionFinish = \"executionFinish\",\n}\n\n// Typed interface of the worker events\nexport interface TransactionWorkerEvents {\n transactionSent: (data: SuccessEventData) => void;\n transactionSendFailed: (data: FailureEventData) => void;\n transactionExecuted: (data: SuccessEventData) => void;\n transactionExecutionFailed: (data: FailureEventData) => void;\n executionFinish: (data: ExecutionFinishEventData) => void;\n}\n\n// Type for when the worker has finished its job\nexport type ExecutionFinishEventData = {\n message: string;\n};\n\n// Type for a success event\nexport type SuccessEventData = {\n message: string;\n transactionHash: string;\n};\n\n// Type for a failure event\nexport type FailureEventData = {\n message: string;\n error: string;\n};\n\n/**\n * TransactionWorker provides a simple framework for receiving payloads to be processed.\n *\n * Once one `start()` the process and pushes a new transaction, the worker acquires\n * the current account's next sequence number (by using the AccountSequenceNumber class),\n * generates a signed transaction and pushes an async submission process into the `outstandingTransactions` queue.\n * At the same time, the worker processes transactions by reading the `outstandingTransactions` queue\n * and submits the next transaction to chain, it\n * 1) waits for resolution of the submission process or get pre-execution validation error\n * and 2) waits for the resolution of the execution process or get an execution error.\n * The worker fires events for any submission and/or execution success and/or failure.\n */\nexport class TransactionWorker extends EventEmitter<TransactionWorkerEvents> {\n readonly aptosConfig: AptosConfig;\n\n readonly account: Account;\n\n // current account sequence number\n readonly accountSequnceNumber: AccountSequenceNumber;\n\n readonly taskQueue: AsyncQueue<() => Promise<void>> = new AsyncQueue<() => Promise<void>>();\n\n // process has started\n started: boolean;\n\n /**\n * transactions payloads waiting to be generated and signed\n *\n * TODO support entry function payload from ABI builder\n */\n transactionsQueue = new AsyncQueue<\n [InputGenerateTransactionPayloadData, InputGenerateTransactionOptions | undefined]\n >();\n\n /**\n * signed transactions waiting to be submitted\n */\n outstandingTransactions = new AsyncQueue<[Promise<PendingTransactionResponse>, bigint]>();\n\n /**\n * transactions that have been submitted to chain\n */\n sentTransactions: Array<[string, bigint, any]> = [];\n\n /**\n * transactions that have been committed to chain\n */\n executedTransactions: Array<[string, bigint, any]> = [];\n\n /**\n * Provides a simple framework for receiving payloads to be processed.\n *\n * @param aptosConfig - a config object\n * @param sender - a sender as Account\n * @param maxWaitTime - the max wait time to wait before resyncing the sequence number\n * to the current on-chain state, default to 30\n * @param maximumInFlight - submit up to `maximumInFlight` transactions per account.\n * Mempool limits the number of transactions per account to 100, hence why we default to 100.\n * @param sleepTime - If `maximumInFlight` are in flight, wait `sleepTime` seconds before re-evaluating, default to 10\n */\n constructor(\n aptosConfig: AptosConfig,\n account: Account,\n maxWaitTime: number = 30,\n maximumInFlight: number = 100,\n sleepTime: number = 10,\n ) {\n super();\n this.aptosConfig = aptosConfig;\n this.account = account;\n this.started = false;\n this.accountSequnceNumber = new AccountSequenceNumber(\n aptosConfig,\n account,\n maxWaitTime,\n maximumInFlight,\n sleepTime,\n );\n }\n\n /**\n * Gets the current account sequence number,\n * generates the transaction with the account sequence number,\n * adds the transaction to the outstanding transaction queue\n * to be processed later.\n */\n async submitNextTransaction() {\n try {\n /* eslint-disable no-constant-condition */\n while (true) {\n const sequenceNumber = await this.accountSequnceNumber.nextSequenceNumber();\n if (sequenceNumber === null) return;\n const transaction = await this.generateNextTransaction(this.account, sequenceNumber);\n if (!transaction) return;\n const pendingTransaction = signAndSubmitTransaction({\n aptosConfig: this.aptosConfig,\n transaction,\n signer: this.account,\n });\n await this.outstandingTransactions.enqueue([pendingTransaction, sequenceNumber]);\n }\n } catch (error: any) {\n if (error instanceof AsyncQueueCancelledError) {\n return;\n }\n throw new Error(`Submit transaction failed for ${this.account.accountAddress.toString()} with error ${error}`);\n }\n }\n\n /**\n * Reads the outstanding transaction queue and submits the transaction to chain.\n *\n * If the transaction has fulfilled, it pushes the transaction to the processed\n * transactions queue and fires a transactionsFulfilled event.\n *\n * If the transaction has failed, it pushes the transaction to the processed\n * transactions queue with the failure reason and fires a transactionsFailed event.\n */\n async processTransactions() {\n try {\n /* eslint-disable no-constant-condition */\n while (true) {\n const awaitingTransactions = [];\n const sequenceNumbers = [];\n let [pendingTransaction, sequenceNumber] = await this.outstandingTransactions.dequeue();\n\n awaitingTransactions.push(pendingTransaction);\n sequenceNumbers.push(sequenceNumber);\n\n while (!this.outstandingTransactions.isEmpty()) {\n [pendingTransaction, sequenceNumber] = await this.outstandingTransactions.dequeue();\n\n awaitingTransactions.push(pendingTransaction);\n sequenceNumbers.push(sequenceNumber);\n }\n // send awaiting transactions to chain\n const sentTransactions = await Promise.allSettled(awaitingTransactions);\n for (let i = 0; i < sentTransactions.length && i < sequenceNumbers.length; i += 1) {\n // check sent transaction status\n const sentTransaction = sentTransactions[i];\n sequenceNumber = sequenceNumbers[i];\n if (sentTransaction.status === promiseFulfilledStatus) {\n // transaction sent to chain\n this.sentTransactions.push([sentTransaction.value.hash, sequenceNumber, null]);\n // check sent transaction execution\n this.emit(TransactionWorkerEventsEnum.TransactionSent, {\n message: `transaction hash ${sentTransaction.value.hash} has been committed to chain`,\n transactionHash: sentTransaction.value.hash,\n });\n await this.checkTransaction(sentTransaction, sequenceNumber);\n } else {\n // send transaction failed\n this.sentTransactions.push([sentTransaction.status, sequenceNumber, sentTransaction.reason]);\n this.emit(TransactionWorkerEventsEnum.TransactionSendFailed, {\n message: `failed to commit transaction ${this.sentTransactions.length} with error ${sentTransaction.reason}`,\n error: sentTransaction.reason,\n });\n }\n }\n this.emit(TransactionWorkerEventsEnum.ExecutionFinish, {\n message: `execute ${sentTransactions.length} transactions finished`,\n });\n }\n } catch (error: any) {\n if (error instanceof AsyncQueueCancelledError) {\n return;\n }\n throw new Error(`Process execution failed for ${this.account.accountAddress.toString()} with error ${error}`);\n }\n }\n\n /**\n * Once transaction has been sent to chain, we check for its execution status.\n * @param sentTransaction transactions that were sent to chain and are now waiting to be executed\n * @param sequenceNumber the account's sequence number that was sent with the transaction\n */\n async checkTransaction(sentTransaction: PromiseFulfilledResult<PendingTransactionResponse>, sequenceNumber: bigint) {\n try {\n const waitFor: Array<Promise<TransactionResponse>> = [];\n waitFor.push(waitForTransaction({ aptosConfig: this.aptosConfig, transactionHash: sentTransaction.value.hash }));\n const sentTransactions = await Promise.allSettled(waitFor);\n\n for (let i = 0; i < sentTransactions.length; i += 1) {\n const executedTransaction = sentTransactions[i];\n if (executedTransaction.status === promiseFulfilledStatus) {\n // transaction executed to chain\n this.executedTransactions.push([executedTransaction.value.hash, sequenceNumber, null]);\n this.emit(TransactionWorkerEventsEnum.TransactionExecuted, {\n message: `transaction hash ${executedTransaction.value.hash} has been executed on chain`,\n transactionHash: sentTransaction.value.hash,\n });\n } else {\n // transaction execution failed\n this.executedTransactions.push([executedTransaction.status, sequenceNumber, executedTransaction.reason]);\n this.emit(TransactionWorkerEventsEnum.TransactionExecutionFailed, {\n message: `failed to execute transaction ${this.executedTransactions.length} with error ${executedTransaction.reason}`,\n error: executedTransaction.reason,\n });\n }\n }\n } catch (error: any) {\n throw new Error(`Check transaction failed for ${this.account.accountAddress.toString()} with error ${error}`);\n }\n }\n\n /**\n * Push transaction to the transactions queue\n *\n * @param transactionData Transaction payload\n * @param transactionData.abi For all entry function payloads, the ABI to skip remote ABI lookups\n * @param options.maxGasAmount Maximum gas amount for the transaction\n * @param options.gasUnitPrice Gas unit price for the transaction\n * @param options.expireTimestamp expiration timestamp on the transaction\n * @param options.accountSequenceNumber the sequence number for the transaction\n */\n async push(\n transactionData: InputGenerateTransactionPayloadData,\n options?: InputGenerateTransactionOptions,\n ): Promise<void> {\n this.transactionsQueue.enqueue([transactionData, options]);\n }\n\n /**\n * Generates a signed transaction that can be submitted to chain\n * @param account an Aptos account\n * @param sequenceNumber a sequence number the transaction will be generated with\n * @returns\n */\n async generateNextTransaction(account: Account, sequenceNumber: bigint): Promise<SimpleTransaction | undefined> {\n if (this.transactionsQueue.isEmpty()) return undefined;\n const [transactionData, options] = await this.transactionsQueue.dequeue();\n return generateTransaction({\n aptosConfig: this.aptosConfig,\n sender: account.accountAddress,\n data: transactionData,\n options: { ...options, accountSequenceNumber: sequenceNumber },\n });\n }\n\n /**\n * Starts transaction submission and transaction processing.\n */\n async run() {\n try {\n while (!this.taskQueue.isCancelled()) {\n const task = await this.taskQueue.dequeue();\n await task();\n }\n } catch (error: any) {\n throw new Error(`Unable to start transaction batching: ${error}`);\n }\n }\n\n /**\n * Starts the transaction management process.\n */\n start() {\n if (this.started) {\n throw new Error(\"worker has already started\");\n }\n this.started = true;\n this.taskQueue.enqueue(() => this.submitNextTransaction());\n this.taskQueue.enqueue(() => this.processTransactions());\n this.run();\n }\n\n /**\n * Stops the the transaction management process.\n */\n stop() {\n if (this.taskQueue.isCancelled()) {\n throw new Error(\"worker has already stopped\");\n }\n this.started = false;\n this.taskQueue.cancel();\n }\n}\n","import EventEmitter from \"eventemitter3\";\nimport { TransactionWorkerEvents, TransactionWorker, TransactionWorkerEventsEnum } from \"../../transactions/management\";\nimport { InputGenerateTransactionPayloadData, InputGenerateTransactionOptions } from \"../../transactions\";\nimport { AptosConfig } from \"../aptosConfig\";\nimport { Account } from \"../../core\";\n\nexport class TransactionManagement extends EventEmitter<TransactionWorkerEvents> {\n account!: Account;\n\n transactionWorker!: TransactionWorker;\n\n readonly config: AptosConfig;\n\n constructor(config: AptosConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Internal function to start the transaction worker and\n * listen to worker events\n *\n * @param args.sender The sender account to sign and submit the transaction\n */\n private start(args: { sender: Account }): void {\n const { sender } = args;\n this.account = sender;\n this.transactionWorker = new TransactionWorker(this.config, sender);\n\n this.transactionWorker.start();\n this.registerToEvents();\n }\n\n /**\n * Internal function to push transaction data to the transaction worker.\n *\n * @param args.data An array of transaction payloads\n * @param args.options optional. Transaction generation configurations (excluding accountSequenceNumber)\n *\n * TODO - make this public once worker supports adding transactions to existing queue\n */\n private push(args: {\n data: InputGenerateTransactionPayloadData[];\n options?: Omit<InputGenerateTransactionOptions, \"accountSequenceNumber\">;\n }): void {\n const { data, options } = args;\n\n for (const d of data) {\n this.transactionWorker.push(d, options);\n }\n }\n\n /**\n * Internal function to start listening to transaction worker events\n *\n * TODO - should we ask events to listen to as an input?\n */\n private registerToEvents() {\n this.transactionWorker.on(TransactionWorkerEventsEnum.TransactionSent, async (data) => {\n this.emit(TransactionWorkerEventsEnum.TransactionSent, data);\n });\n this.transactionWorker.on(TransactionWorkerEventsEnum.TransactionSendFailed, async (data) => {\n this.emit(TransactionWorkerEventsEnum.TransactionSendFailed, data);\n });\n this.transactionWorker.on(TransactionWorkerEventsEnum.TransactionExecuted, async (data) => {\n this.emit(TransactionWorkerEventsEnum.TransactionExecuted, data);\n });\n this.transactionWorker.on(TransactionWorkerEventsEnum.TransactionExecutionFailed, async (data) => {\n this.emit(TransactionWorkerEventsEnum.TransactionExecutionFailed, data);\n });\n this.transactionWorker.on(TransactionWorkerEventsEnum.ExecutionFinish, async (data) => {\n this.emit(TransactionWorkerEventsEnum.ExecutionFinish, data);\n });\n }\n\n /**\n * Send batch transactions for a single account.\n *\n * This function uses a transaction worker that receives payloads to be processed\n * and submitted to chain.\n * Note that this process is best for submitting multiple transactions that\n * dont rely on each other, i.e batch funds, batch token mints, etc.\n *\n * If any worker failure, the functions throws an error.\n *\n * @param args.sender The sender account to sign and submit the transaction\n * @param args.data An array of transaction payloads\n * @param args.options optional. Transaction generation configurations (excluding accountSequenceNumber)\n *\n * @return void. Throws if any error\n */\n forSingleAccount(args: {\n sender: Account;\n data: InputGenerateTransactionPayloadData[];\n options?: Omit<InputGenerateTransactionOptions, \"accountSequenceNumber\">;\n }): void {\n try {\n const { sender, data, options } = args;\n this.start({ sender });\n\n this.push({ data, options });\n } catch (error: any) {\n throw new Error(`failed to submit transactions with error: ${error}`);\n }\n }\n}\n","export function ValidateFeePayerDataOnSubmission(target: unknown, propertyKey: string, descriptor: PropertyDescriptor) {\n const originalMethod = descriptor.value;\n /* eslint-disable-next-line func-names, no-param-reassign */\n descriptor.value = async function (...args: any[]) {\n const [methodArgs] = args;\n\n if (methodArgs.transaction.feePayerAddress && !methodArgs.feePayerAuthenticator) {\n throw new Error(\"You are submitting a Fee Payer transaction but missing the feePayerAuthenticator\");\n }\n\n return originalMethod.apply(this, args);\n };\n\n return descriptor;\n}\n\nexport function ValidateFeePayerDataOnSimulation(target: unknown, propertyKey: string, descriptor: PropertyDescriptor) {\n const originalMethod = descriptor.value;\n /* eslint-disable-next-line func-names, no-param-reassign */\n descriptor.value = async function (...args: any[]) {\n const [methodArgs] = args;\n\n if (methodArgs.transaction.feePayerAddress && !methodArgs.feePayerPublicKey) {\n throw new Error(\"You are simulating a Fee Payer transaction but missing the feePayerPublicKey\");\n }\n\n return originalMethod.apply(this, args);\n };\n\n return descriptor;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { PublicKey } from \"../../core\";\nimport { simulateTransaction } from \"../../internal/transactionSubmission\";\nimport { AnyRawTransaction, InputSimulateTransactionOptions } from \"../../transactions\";\nimport { UserTransactionResponse } from \"../../types\";\nimport { AptosConfig } from \"../aptosConfig\";\nimport { ValidateFeePayerDataOnSimulation } from \"./helpers\";\n\n/**\n * A class to handle all `Simulate` transaction operations\n */\nexport class Simulate {\n readonly config: AptosConfig;\n\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Simulate a simple transaction\n *\n * @param args.signerPublicKey The signer public key\n * @param args.transaction An instance of a raw transaction\n * @param args.options optional. Optional transaction configurations\n * @param args.feePayerPublicKey optional. The fee payer public key if it is a fee payer transaction\n *\n * @returns Array<UserTransactionResponse>\n */\n @ValidateFeePayerDataOnSimulation\n async simple(args: {\n signerPublicKey: PublicKey;\n transaction: AnyRawTransaction;\n feePayerPublicKey?: PublicKey;\n options?: InputSimulateTransactionOptions;\n }): Promise<Array<UserTransactionResponse>> {\n return simulateTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Simulate a multi agent transaction\n *\n * @param args.signerPublicKey The signer public key\n * @param args.transaction An instance of a raw transaction\n * @param args.secondarySignersPublicKeys An array of the secondary signers public keys\n * @param args.options optional. Optional transaction configurations\n * @param args.feePayerPublicKey optional. The fee payer public key if it is a fee payer transaction\n *\n * @returns Array<UserTransactionResponse>\n */\n @ValidateFeePayerDataOnSimulation\n async multiAgent(args: {\n signerPublicKey: PublicKey;\n transaction: AnyRawTransaction;\n secondarySignersPublicKeys: Array<PublicKey>;\n feePayerPublicKey?: PublicKey;\n options?: InputSimulateTransactionOptions;\n }): Promise<Array<UserTransactionResponse>> {\n return simulateTransaction({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { submitTransaction } from \"../../internal/transactionSubmission\";\nimport { AccountAuthenticator, AnyRawTransaction } from \"../../transactions\";\nimport { PendingTransactionResponse } from \"../../types\";\nimport { AptosConfig } from \"../aptosConfig\";\nimport { ValidateFeePayerDataOnSubmission } from \"./helpers\";\n\n/**\n * A class to handle all `Submit` transaction operations\n */\nexport class Submit {\n readonly config: AptosConfig;\n\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Submit a simple transaction\n *\n * @param args.transaction An instance of a raw transaction\n * @param args.senderAuthenticator optional. The sender account authenticator\n * @param args.feePayerAuthenticator optional. The fee payer account authenticator if it is a fee payer transaction\n *\n * @returns PendingTransactionResponse\n */\n @ValidateFeePayerDataOnSubmission\n async simple(args: {\n transaction: AnyRawTransaction;\n senderAuthenticator: AccountAuthenticator;\n feePayerAuthenticator?: AccountAuthenticator;\n }): Promise<PendingTransactionResponse> {\n return submitTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Submit a multi agent transaction\n *\n * @param args.transaction An instance of a raw transaction\n * @param args.senderAuthenticator optional. The sender account authenticator\n * @param args.additionalSignersAuthenticators An array of the secondary signers account authenticators\n * @param args.feePayerAuthenticator optional. The fee payer account authenticator if it is a fee payer transaction\n *\n * @returns PendingTransactionResponse\n */\n @ValidateFeePayerDataOnSubmission\n async multiAgent(args: {\n transaction: AnyRawTransaction;\n senderAuthenticator: AccountAuthenticator;\n additionalSignersAuthenticators: Array<AccountAuthenticator>;\n feePayerAuthenticator?: AccountAuthenticator;\n }): Promise<PendingTransactionResponse> {\n return submitTransaction({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosConfig } from \"./aptosConfig\";\nimport {\n getGasPriceEstimation,\n getTransactionByHash,\n getTransactionByVersion,\n getTransactions,\n isTransactionPending,\n waitForTransaction,\n} from \"../internal/transaction\";\nimport {\n AnyNumber,\n CommittedTransactionResponse,\n GasEstimation,\n HexInput,\n PaginationArgs,\n PendingTransactionResponse,\n TransactionResponse,\n WaitForTransactionOptions,\n} from \"../types\";\nimport {\n getSigningMessage,\n publicPackageTransaction,\n rotateAuthKey,\n signAndSubmitTransaction,\n signTransaction,\n} from \"../internal/transactionSubmission\";\nimport {\n AccountAuthenticator,\n AnyRawTransaction,\n InputGenerateTransactionOptions,\n InputGenerateTransactionPayloadData,\n} from \"../transactions\";\nimport { AccountAddressInput, Account, PrivateKey } from \"../core\";\nimport { Build } from \"./transactionSubmission/build\";\nimport { Simulate } from \"./transactionSubmission/simulate\";\nimport { Submit } from \"./transactionSubmission/submit\";\nimport { TransactionManagement } from \"./transactionSubmission/management\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\nexport class Transaction {\n readonly config: AptosConfig;\n\n readonly build: Build;\n\n readonly simulate: Simulate;\n\n readonly submit: Submit;\n\n readonly batch: TransactionManagement;\n\n constructor(config: AptosConfig) {\n this.config = config;\n this.build = new Build(this.config);\n this.simulate = new Simulate(this.config);\n this.submit = new Submit(this.config);\n this.batch = new TransactionManagement(this.config);\n }\n\n /**\n * Queries on-chain transactions. This function will not return pending\n * transactions. For that, use `getTransactionsByHash`.\n *\n * @example\n * const transactions = await aptos.getTransactions()\n *\n * @param args.options.offset The number transaction to start with\n * @param args.options.limit Number of results to return\n *\n * @returns Array of on-chain transactions\n */\n async getTransactions(args?: { options?: PaginationArgs }): Promise<TransactionResponse[]> {\n return getTransactions({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries on-chain transaction by version. This function will not return pending transactions.\n *\n * @example\n * const transaction = await aptos.getTransactions({ledgerVersion:1})\n *\n * @param args.ledgerVersion - Transaction version is an unsigned 64-bit number.\n * @returns On-chain transaction. Only on-chain transactions have versions, so this\n * function cannot be used to query pending transactions.\n */\n async getTransactionByVersion(args: { ledgerVersion: AnyNumber }): Promise<TransactionResponse> {\n return getTransactionByVersion({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries on-chain transaction by transaction hash. This function will return pending transactions.\n *\n * @example\n * const transaction = await aptos.getTransactionByHash({transactionHash:\"0x123\"})\n *\n * @param args.transactionHash - Transaction hash should be hex-encoded bytes string with 0x prefix.\n * @returns Transaction from mempool (pending) or on-chain (committed) transaction\n */\n async getTransactionByHash(args: { transactionHash: HexInput }): Promise<TransactionResponse> {\n return getTransactionByHash({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Defines if specified transaction is currently in pending state\n *\n * To create a transaction hash:\n *\n * 1. Create a hash message from the bytes: \"Aptos::Transaction\" bytes + the BCS-serialized Transaction bytes.\n * 2. Apply hash algorithm SHA3-256 to the hash message bytes.\n * 3. Hex-encode the hash bytes with 0x prefix.\n *\n * @example\n * const isPendingTransaction = await aptos.isPendingTransaction({transactionHash:\"0x123\"})\n *\n * @param args.transactionHash A hash of transaction\n * @returns `true` if transaction is in pending state and `false` otherwise\n */\n async isPendingTransaction(args: { transactionHash: HexInput }): Promise<boolean> {\n return isTransactionPending({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Waits for a transaction to move past the pending state.\n *\n * There are 4 cases.\n * 1. Transaction is successfully processed and committed to the chain.\n * - The function will resolve with the transaction response from the API.\n * 2. Transaction is rejected for some reason, and is therefore not committed to the blockchain.\n * - The function will throw an AptosApiError with an HTTP status code indicating some problem with the request.\n * 3. Transaction is committed but execution failed, meaning no changes were\n * written to the blockchain state.\n * - If `checkSuccess` is true, the function will throw a FailedTransactionError\n * If `checkSuccess` is false, the function will resolve with the transaction response where the `success` field is false.\n * 4. Transaction does not move past the pending state within `args.options.timeoutSecs` seconds.\n * - The function will throw a WaitForTransactionError\n *\n * @example\n * const transaction = await aptos.waitForTransaction({transactionHash:\"0x123\"})\n *\n * @param args.transactionHash The hash of a transaction previously submitted to the blockchain.\n * @param args.options.timeoutSecs Timeout in seconds. Defaults to 20 seconds.\n * @param args.options.checkSuccess A boolean which controls whether the function will error if the transaction failed.\n * Defaults to true. See case 3 above.\n * @returns The transaction on-chain. See above for more details.\n */\n async waitForTransaction(args: {\n transactionHash: HexInput;\n options?: WaitForTransactionOptions;\n }): Promise<CommittedTransactionResponse> {\n return waitForTransaction({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Gives an estimate of the gas unit price required to get a\n * transaction on chain in a reasonable amount of time.\n * For more information {@link https://api.mainnet.aptoslabs.com/v1/spec#/operations/estimate_gas_price}\n *\n * @returns Object holding the outputs of the estimate gas API\n *\n * @example\n * const gasPrice = await aptos.waitForTransaction()\n */\n async getGasPriceEstimation(): Promise<GasEstimation> {\n return getGasPriceEstimation({\n aptosConfig: this.config,\n });\n }\n\n /**\n * Returns a signing message for a transaction.\n *\n * This allows a user to sign a transaction using their own preferred signing method, and\n * then submit it to the network.\n *\n * @example\n * const transaction = await aptos.transaction.build.simple({...})\n * const message = await aptos.getSigningMessage({transaction})\n *\n * @param args.transaction A raw transaction for signing elsewhere\n */\n // eslint-disable-next-line class-methods-use-this\n getSigningMessage(args: { transaction: AnyRawTransaction }): Uint8Array {\n return getSigningMessage(args);\n }\n\n /**\n * Generates a transaction to publish a move package to chain.\n *\n * To get the `metadataBytes` and `byteCode`, can compile using Aptos CLI with command\n * `aptos move compile --save-metadata ...`,\n * For more info {@link https://aptos.dev/tutorials/your-first-dapp/#step-4-publish-a-move-module}\n *\n * @example\n * const transaction = await aptos.publishPackageTransaction({\n * account: alice,\n * metadataBytes,\n * moduleBytecode: [byteCode],\n * })\n *\n * @param args.account The publisher account\n * @param args.metadataBytes The package metadata bytes\n * @param args.moduleBytecode An array of the bytecode of each module in the package in compiler output order\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async publishPackageTransaction(args: {\n account: AccountAddressInput;\n metadataBytes: HexInput;\n moduleBytecode: Array<HexInput>;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return publicPackageTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Rotate an account's auth key. After rotation, only the new private key can be used to sign txns for\n * the account.\n * Note: Only legacy Ed25519 scheme is supported for now.\n * More info: {@link https://aptos.dev/guides/account-management/key-rotation/}\n *\n * @example\n * const response = await aptos.rotateAuthKey({\n * fromAccount: alice,\n * toNewPrivateKey: new ED25519PublicKey(\"0x123\"),\n * })\n *\n * @param args.fromAccount The account to rotate the auth key for\n * @param args.toNewPrivateKey The new private key to rotate to\n *\n * @returns PendingTransactionResponse\n */\n async rotateAuthKey(args: { fromAccount: Account; toNewPrivateKey: PrivateKey }): Promise<TransactionResponse> {\n return rotateAuthKey({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Sign a transaction that can later be submitted to chain\n *\n * @example\n * const transaction = await aptos.transaction.build.simple({...})\n * const transaction = await aptos.transaction.sign({\n * signer: alice,\n * transaction\n * })\n *\n * @param args.signer The signer account\n * @param args.transaction A raw transaction to sign on\n *\n * @returns AccountAuthenticator\n */\n // eslint-disable-next-line class-methods-use-this\n sign(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n return signTransaction({\n ...args,\n });\n }\n\n /**\n * Sign a transaction as a fee payer that can later be submitted to chain\n *\n * @example\n * const transaction = await aptos.transaction.build.simple({...})\n * const transaction = await aptos.transaction.signAsFeePayer({\n * signer: alice,\n * transaction\n * })\n *\n * @param args.signer The fee payer signer account\n * @param args.transaction A raw transaction to sign on\n *\n * @returns AccountAuthenticator\n */\n // eslint-disable-next-line class-methods-use-this\n signAsFeePayer(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n const { signer, transaction } = args;\n\n // if transaction doesnt hold a \"feePayerAddress\" prop it means\n // this is not a fee payer transaction\n if (!transaction.feePayerAddress) {\n throw new Error(`Transaction ${transaction} is not a Fee Payer transaction`);\n }\n\n // Set the feePayerAddress to the signer account address\n transaction.feePayerAddress = signer.accountAddress;\n\n return signTransaction({\n signer,\n transaction,\n });\n }\n\n // TRANSACTION SUBMISSION //\n\n /**\n * @deprecated Prefer to use `aptos.transaction.batch.forSingleAccount()`\n *\n * Batch transactions for a single account.\n *\n * This function uses a transaction worker that receives payloads to be processed\n * and submitted to chain.\n * Note that this process is best for submitting multiple transactions that\n * dont rely on each other, i.e batch funds, batch token mints, etc.\n *\n * If any worker failure, the functions throws an error.\n *\n * @param args.sender The sender account to sign and submit the transaction\n * @param args.data An array of transaction payloads\n * @param args.options optional. Transaction generation configurations (excluding accountSequenceNumber)\n *\n * @return void. Throws if any error\n */\n async batchTransactionsForSingleAccount(args: {\n sender: Account;\n data: InputGenerateTransactionPayloadData[];\n options?: Omit<InputGenerateTransactionOptions, \"accountSequenceNumber\">;\n }): Promise<void> {\n try {\n const { sender, data, options } = args;\n this.batch.forSingleAccount({ sender, data, options });\n } catch (error: any) {\n throw new Error(`failed to submit transactions with error: ${error}`);\n }\n }\n\n /**\n * Sign and submit a single signer transaction to chain\n *\n * @param args.signer The signer account to sign the transaction\n * @param args.transaction An instance of a RawTransaction, plus optional secondary/fee payer addresses\n *\n * @example\n * const transaction = await aptos.transaction.build.simple({...})\n * const transaction = await aptos.signAndSubmitTransaction({\n * signer: alice,\n * transaction\n * })\n *\n * @return PendingTransactionResponse\n */\n async signAndSubmitTransaction(args: {\n signer: Account;\n transaction: AnyRawTransaction;\n }): Promise<PendingTransactionResponse> {\n const { signer, transaction } = args;\n return signAndSubmitTransaction({\n aptosConfig: this.config,\n signer,\n transaction,\n });\n }\n}\n","import got, { OptionsOfJSONResponseBody, RequestError, Response } from \"got\";\nimport { CookieJar } from \"./cookieJar\";\nimport { AptosClientRequest, AptosClientResponse } from \"./types\";\n\nconst cookieJar = new CookieJar();\n\nexport default async function aptosClient<Res>(requestOptions: AptosClientRequest): Promise<AptosClientResponse<Res>> {\n const { params, method, url, headers, body } = requestOptions;\n\n const request: OptionsOfJSONResponseBody = {\n http2: true,\n searchParams: convertBigIntToString(params),\n method,\n url,\n responseType: \"json\",\n headers,\n hooks: {\n beforeRequest: [\n (options) => {\n const cookies = cookieJar.getCookies(new URL(options.url!));\n\n if (cookies?.length > 0 && options.headers) {\n /* eslint-disable no-param-reassign */\n options.headers.cookie = cookies.map((cookie: any) => `${cookie.name}=${cookie.value}`).join(\"; \");\n }\n },\n ],\n afterResponse: [\n (response) => {\n if (Array.isArray(response.headers[\"set-cookie\"])) {\n response.headers[\"set-cookie\"].forEach((c) => {\n cookieJar.setCookie(new URL(response.url!), c);\n });\n }\n return response;\n },\n ],\n },\n };\n\n if (body) {\n if (body instanceof Uint8Array) {\n request.body = Buffer.from(body);\n } else {\n request.body = Buffer.from(JSON.stringify(body));\n }\n }\n\n try {\n const response = await got<Res>(request);\n return parseResponse<Res>(response);\n } catch (error) {\n const gotError = error as RequestError;\n if (gotError.response) {\n return parseResponse<Res>(gotError.response as Response<Res>);\n }\n throw error;\n }\n}\n\nfunction parseResponse<Res>(response: Response<Res>): AptosClientResponse<Res> {\n return {\n status: response.statusCode,\n statusText: response.statusMessage || \"\",\n data: response.body,\n config: response.request.options,\n request: response.request,\n response,\n headers: response.headers,\n };\n}\n\n/**\n * got supports only - string | number | boolean | null | undefined as searchParam value,\n * so if we have bigint type, convert it to string\n */\nfunction convertBigIntToString(obj: any): any {\n const result: any = {};\n if (!obj) return result;\n\n Object.entries(obj).forEach(([key, value]) => {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n if (typeof value === \"bigint\") {\n result[key] = String(value);\n } else {\n result[key] = value;\n }\n }\n });\n\n return result;\n}\n","interface Cookie {\n name: string;\n value: string;\n expires?: Date;\n path?: string;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n secure?: boolean;\n}\n\nexport class CookieJar {\n constructor(private jar = new Map<string, Cookie[]>()) {}\n\n setCookie(url: URL, cookieStr: string) {\n const key = url.origin.toLowerCase();\n if (!this.jar.has(key)) {\n this.jar.set(key, []);\n }\n\n const cookie = CookieJar.parse(cookieStr);\n this.jar.set(key, [...(this.jar.get(key)?.filter((c) => c.name !== cookie.name) || []), cookie]);\n }\n\n getCookies(url: URL): Cookie[] {\n const key = url.origin.toLowerCase();\n if (!this.jar.get(key)) {\n return [];\n }\n\n // Filter out expired cookies\n return this.jar.get(key)?.filter((cookie) => !cookie.expires || cookie.expires > new Date()) || [];\n }\n\n static parse(str: string): Cookie {\n if (typeof str !== \"string\") {\n throw new Error(\"argument str must be a string\");\n }\n\n const parts = str.split(\";\").map((part) => part.trim());\n\n let cookie: Cookie;\n\n if (parts.length > 0) {\n const [name, value] = parts[0].split(\"=\");\n if (!name || !value) {\n throw new Error(\"Invalid cookie\");\n }\n\n cookie = {\n name,\n value,\n };\n } else {\n throw new Error(\"Invalid cookie\");\n }\n\n parts.slice(1).forEach((part) => {\n const [name, value] = part.split(\"=\");\n if (!name.trim()) {\n throw new Error(\"Invalid cookie\");\n }\n\n const nameLow = name.toLowerCase();\n // eslint-disable-next-line quotes\n const val = value?.charAt(0) === \"'\" || value?.charAt(0) === '\"' ? value?.slice(1, -1) : value;\n if (nameLow === \"expires\") {\n cookie.expires = new Date(val);\n }\n if (nameLow === \"path\") {\n cookie.path = val;\n }\n if (nameLow === \"samesite\") {\n if (val !== \"Lax\" && val !== \"None\" && val !== \"Strict\") {\n throw new Error(\"Invalid cookie SameSite value\");\n }\n cookie.sameSite = val;\n }\n if (nameLow === \"secure\") {\n cookie.secure = true;\n }\n });\n\n return cookie;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport aptosClient from \"@aptos-labs/aptos-client\";\nimport { AptosSettings, ClientConfig, Client, FullNodeConfig, IndexerConfig, FaucetConfig } from \"../types\";\nimport { NetworkToNodeAPI, NetworkToFaucetAPI, NetworkToIndexerAPI, Network } from \"../utils/apiEndpoints\";\nimport { AptosApiType } from \"../utils/const\";\n\n/**\n * This class holds the config information for the SDK client instance.\n *\n * @example\n *\n * const aptosConfig = new AptosConfig({network:Network.TESTNET})\n */\nexport class AptosConfig {\n /**\n * The Network that this SDK is associated with. Defaults to DEVNET\n */\n readonly network: Network;\n\n /**\n * The client instance the SDK uses. Defaults to `@aptos-labs/aptos-client\n */\n readonly client: Client;\n\n /**\n * The optional hardcoded fullnode URL to send requests to instead of using the network\n */\n readonly fullnode?: string;\n\n /**\n * The optional hardcoded faucet URL to send requests to instead of using the network\n */\n readonly faucet?: string;\n\n /**\n * The optional hardcoded indexer URL to send requests to instead of using the network\n */\n readonly indexer?: string;\n\n /**\n * Optional client configurations\n */\n readonly clientConfig?: ClientConfig;\n\n /**\n * Optional specific Fullnode configurations\n */\n readonly fullnodeConfig?: FullNodeConfig;\n\n /**\n * Optional specific Indexer configurations\n */\n readonly indexerConfig?: IndexerConfig;\n\n /**\n * Optional specific Faucet configurations\n */\n readonly faucetConfig?: FaucetConfig;\n\n constructor(settings?: AptosSettings) {\n this.network = settings?.network ?? Network.DEVNET;\n this.fullnode = settings?.fullnode;\n this.faucet = settings?.faucet;\n this.indexer = settings?.indexer;\n this.client = settings?.client ?? { provider: aptosClient };\n this.clientConfig = settings?.clientConfig ?? {};\n this.fullnodeConfig = settings?.fullnodeConfig ?? {};\n this.indexerConfig = settings?.indexerConfig ?? {};\n this.faucetConfig = settings?.faucetConfig ?? {};\n }\n\n /**\n * Returns the URL endpoint to send the request to.\n * If a custom URL was provided in the config, that URL is returned.\n * If a custom URL was provided but not URL endpoints, an error is thrown.\n * Otherwise, the URL endpoint is derived from the network.\n *\n * @param apiType - The type of Aptos API to get the URL for.\n *\n * @internal\n */\n getRequestUrl(apiType: AptosApiType): string {\n switch (apiType) {\n case AptosApiType.FULLNODE:\n if (this.fullnode !== undefined) return this.fullnode;\n if (this.network === Network.CUSTOM) throw new Error(\"Please provide a custom full node url\");\n return NetworkToNodeAPI[this.network];\n case AptosApiType.FAUCET:\n if (this.faucet !== undefined) return this.faucet;\n if (this.network === Network.CUSTOM) throw new Error(\"Please provide a custom faucet url\");\n return NetworkToFaucetAPI[this.network];\n case AptosApiType.INDEXER:\n if (this.indexer !== undefined) return this.indexer;\n if (this.network === Network.CUSTOM) throw new Error(\"Please provide a custom indexer url\");\n return NetworkToIndexerAPI[this.network];\n default:\n throw Error(`apiType ${apiType} is not supported`);\n }\n }\n}\n","import { AptosConfig } from \"../api/aptosConfig\";\nimport { AccountAddressInput } from \"../core\";\nimport { EntryFunctionABI, InputGenerateTransactionOptions } from \"../transactions/types\";\nimport { AnyNumber, MoveStructId } from \"../types\";\nimport { APTOS_COIN } from \"../utils/const\";\nimport { generateTransaction } from \"./transactionSubmission\";\nimport { TypeTagAddress, TypeTagU64 } from \"../transactions\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\nconst coinTransferAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [] }],\n parameters: [new TypeTagAddress(), new TypeTagU64()],\n};\n\nexport async function transferCoinTransaction(args: {\n aptosConfig: AptosConfig;\n sender: AccountAddressInput;\n recipient: AccountAddressInput;\n amount: AnyNumber;\n coinType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, recipient, amount, coinType, options } = args;\n const coinStructType = coinType ?? APTOS_COIN;\n return generateTransaction({\n aptosConfig,\n sender,\n data: {\n function: \"0x1::aptos_account::transfer_coins\",\n typeArguments: [coinStructType],\n functionArguments: [recipient, amount],\n abi: coinTransferAbi,\n },\n options,\n });\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AccountAddressInput } from \"../core\";\nimport { transferCoinTransaction } from \"../internal/coin\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\nimport { InputGenerateTransactionOptions } from \"../transactions/types\";\nimport { AnyNumber, MoveStructId } from \"../types\";\nimport { AptosConfig } from \"./aptosConfig\";\n\n/**\n * A class to handle all `Coin` operations\n */\nexport class Coin {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Generate a transfer coin transaction that can be simulated and/or signed and submitted\n *\n * @example\n * const transferCoinTransaction = await aptos.transferCoinTransaction({\n * sender: \"0x123\",\n * recipient:\"0x456\",\n * amount: 10,\n * })\n *\n * @param args.sender The sender account\n * @param args.recipient The recipient address\n * @param args.amount The amount to transfer\n * @param args.coinType optional. The coin struct type to transfer. Defaults to 0x1::aptos_coin::AptosCoin\n *\n * @returns SimpleTransaction\n */\n async transferCoinTransaction(args: {\n sender: AccountAddressInput;\n recipient: AccountAddressInput;\n amount: AnyNumber;\n coinType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return transferCoinTransaction({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/digitalAsset}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * digitalAsset namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { Bool, MoveString, MoveVector, U64 } from \"../bcs\";\nimport { Account, AccountAddress, AccountAddressInput } from \"../core\";\nimport { EntryFunctionABI, InputGenerateTransactionOptions } from \"../transactions/types\";\nimport {\n AnyNumber,\n GetCollectionDataResponse,\n GetCurrentTokenOwnershipResponse,\n GetOwnedTokensResponse,\n GetTokenActivityResponse,\n GetTokenDataResponse,\n MoveAbility,\n MoveStructId,\n OrderByArg,\n PaginationArgs,\n TokenStandardArg,\n} from \"../types\";\nimport {\n GetCollectionDataQuery,\n GetCurrentTokenOwnershipQuery,\n GetTokenActivityQuery,\n GetTokenDataQuery,\n} from \"../types/generated/operations\";\nimport {\n GetCollectionData,\n GetCurrentTokenOwnership,\n GetTokenActivity,\n GetTokenData,\n} from \"../types/generated/queries\";\nimport { queryIndexer } from \"./general\";\nimport { generateTransaction } from \"./transactionSubmission\";\nimport { MAX_U64_BIG_INT } from \"../bcs/consts\";\nimport { CurrentTokenOwnershipsV2BoolExp, TokenActivitiesV2BoolExp } from \"../types/generated/types\";\nimport {\n checkOrConvertArgument,\n objectStructTag,\n parseTypeTag,\n stringStructTag,\n TypeTagAddress,\n TypeTagBool,\n TypeTagGeneric,\n TypeTagStruct,\n TypeTagU64,\n TypeTagVector,\n} from \"../transactions\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\n// A property type map for the user input and what Move expects\nconst PropertyTypeMap = {\n BOOLEAN: \"bool\",\n U8: \"u8\",\n U16: \"u16\",\n U32: \"u32\",\n U64: \"u64\",\n U128: \"u128\",\n U256: \"u256\",\n ADDRESS: \"address\",\n STRING: \"0x1::string::String\",\n ARRAY: \"vector<u8>\",\n};\n\nexport type PropertyType = keyof typeof PropertyTypeMap;\n\n// Accepted property value types for user input\n// To pass in an Array, use Uint8Array type\n// for example `new MoveVector([new MoveString(\"hello\"), new MoveString(\"world\")]).bcsToBytes()`\nexport type PropertyValue = boolean | number | bigint | string | AccountAddress | Uint8Array;\n\n// The default digital asset type to use if non provided\nconst defaultDigitalAssetType = \"0x4::token::Token\";\n\n// FETCH QUERIES\n\nexport async function getDigitalAssetData(args: {\n aptosConfig: AptosConfig;\n digitalAssetAddress: AccountAddressInput;\n}): Promise<GetTokenDataResponse> {\n const { aptosConfig, digitalAssetAddress } = args;\n\n const whereCondition: { token_data_id: { _eq: string } } = {\n token_data_id: { _eq: AccountAddress.from(digitalAssetAddress).toStringLong() },\n };\n\n const graphqlQuery = {\n query: GetTokenData,\n variables: {\n where_condition: whereCondition,\n },\n };\n\n const data = await queryIndexer<GetTokenDataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getDigitalAssetData\",\n });\n\n return data.current_token_datas_v2[0];\n}\n\nexport async function getCurrentDigitalAssetOwnership(args: {\n aptosConfig: AptosConfig;\n digitalAssetAddress: AccountAddressInput;\n}): Promise<GetCurrentTokenOwnershipResponse> {\n const { aptosConfig, digitalAssetAddress } = args;\n\n const whereCondition: CurrentTokenOwnershipsV2BoolExp = {\n token_data_id: { _eq: AccountAddress.from(digitalAssetAddress).toStringLong() },\n amount: { _gt: 0 },\n };\n\n const graphqlQuery = {\n query: GetCurrentTokenOwnership,\n variables: {\n where_condition: whereCondition,\n },\n };\n\n const data = await queryIndexer<GetCurrentTokenOwnershipQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getCurrentDigitalAssetOwnership\",\n });\n\n return data.current_token_ownerships_v2[0];\n}\n\nexport async function getOwnedDigitalAssets(args: {\n aptosConfig: AptosConfig;\n ownerAddress: AccountAddressInput;\n options?: PaginationArgs & OrderByArg<GetTokenActivityResponse[0]>;\n}): Promise<GetOwnedTokensResponse> {\n const { aptosConfig, ownerAddress, options } = args;\n\n const whereCondition: CurrentTokenOwnershipsV2BoolExp = {\n owner_address: { _eq: AccountAddress.from(ownerAddress).toStringLong() },\n amount: { _gt: 0 },\n };\n\n const graphqlQuery = {\n query: GetCurrentTokenOwnership,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetCurrentTokenOwnershipQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getOwnedDigitalAssets\",\n });\n\n return data.current_token_ownerships_v2;\n}\n\nexport async function getDigitalAssetActivity(args: {\n aptosConfig: AptosConfig;\n digitalAssetAddress: AccountAddressInput;\n options?: PaginationArgs & OrderByArg<GetTokenActivityResponse[0]>;\n}): Promise<GetTokenActivityResponse> {\n const { aptosConfig, digitalAssetAddress, options } = args;\n\n const whereCondition: TokenActivitiesV2BoolExp = {\n token_data_id: { _eq: AccountAddress.from(digitalAssetAddress).toStringLong() },\n };\n\n const graphqlQuery = {\n query: GetTokenActivity,\n variables: {\n where_condition: whereCondition,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetTokenActivityQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getDigitalAssetActivity\",\n });\n\n return data.token_activities_v2;\n}\n\nexport interface CreateCollectionOptions {\n maxSupply?: AnyNumber;\n mutableDescription?: boolean;\n mutableRoyalty?: boolean;\n mutableURI?: boolean;\n mutableTokenDescription?: boolean;\n mutableTokenName?: boolean;\n mutableTokenProperties?: boolean;\n mutableTokenURI?: boolean;\n tokensBurnableByCreator?: boolean;\n tokensFreezableByCreator?: boolean;\n royaltyNumerator?: number;\n royaltyDenominator?: number;\n}\n\nconst createCollectionAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [\n new TypeTagStruct(stringStructTag()),\n new TypeTagU64(),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagBool(),\n new TypeTagU64(),\n new TypeTagU64(),\n ],\n};\n\nexport async function createCollectionTransaction(\n args: {\n aptosConfig: AptosConfig;\n creator: Account;\n description: string;\n name: string;\n uri: string;\n options?: InputGenerateTransactionOptions;\n } & CreateCollectionOptions,\n): Promise<SimpleTransaction> {\n const { aptosConfig, options, creator } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::create_collection\",\n functionArguments: [\n // Do not change the order\n new MoveString(args.description),\n new U64(args.maxSupply ?? MAX_U64_BIG_INT),\n new MoveString(args.name),\n new MoveString(args.uri),\n new Bool(args.mutableDescription ?? true),\n new Bool(args.mutableRoyalty ?? true),\n new Bool(args.mutableURI ?? true),\n new Bool(args.mutableTokenDescription ?? true),\n new Bool(args.mutableTokenName ?? true),\n new Bool(args.mutableTokenProperties ?? true),\n new Bool(args.mutableTokenURI ?? true),\n new Bool(args.tokensBurnableByCreator ?? true),\n new Bool(args.tokensFreezableByCreator ?? true),\n new U64(args.royaltyNumerator ?? 0),\n new U64(args.royaltyDenominator ?? 1),\n ],\n abi: createCollectionAbi,\n },\n options,\n });\n}\n\nexport async function getCollectionData(args: {\n aptosConfig: AptosConfig;\n creatorAddress: AccountAddressInput;\n collectionName: string;\n options?: TokenStandardArg;\n}): Promise<GetCollectionDataResponse> {\n const { aptosConfig, creatorAddress, collectionName, options } = args;\n const address = AccountAddress.from(creatorAddress);\n\n const whereCondition: any = {\n collection_name: { _eq: collectionName },\n creator_address: { _eq: address.toStringLong() },\n };\n\n if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard ?? \"v2\" };\n }\n\n const graphqlQuery = {\n query: GetCollectionData,\n variables: {\n where_condition: whereCondition,\n },\n };\n const data = await queryIndexer<GetCollectionDataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getCollectionData\",\n });\n\n return data.current_collections_v2[0];\n}\n\nexport async function getCollectionDataByCollectionId(args: {\n aptosConfig: AptosConfig;\n collectionId: AccountAddressInput;\n}): Promise<GetCollectionDataResponse> {\n const { aptosConfig, collectionId } = args;\n const address = AccountAddress.from(collectionId);\n\n const whereCondition: any = {\n collection_id: { _eq: address.toStringLong() },\n };\n\n const graphqlQuery = {\n query: GetCollectionData,\n variables: {\n where_condition: whereCondition,\n },\n };\n const data = await queryIndexer<GetCollectionDataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getCollectionData\",\n });\n\n return data.current_collections_v2[0];\n}\n\nexport async function getCollectionId(args: {\n aptosConfig: AptosConfig;\n creatorAddress: AccountAddressInput;\n collectionName: string;\n options?: TokenStandardArg;\n}): Promise<string> {\n return (await getCollectionData(args)).collection_id;\n}\n\n// TRANSACTIONS\n\nconst mintDigitalAssetAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagVector(new TypeTagStruct(stringStructTag())),\n new TypeTagVector(new TypeTagStruct(stringStructTag())),\n new TypeTagVector(TypeTagVector.u8()),\n ],\n};\n\nexport async function mintDigitalAssetTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n collection: string;\n description: string;\n name: string;\n uri: string;\n propertyKeys?: Array<string>;\n propertyTypes?: Array<PropertyType>;\n propertyValues?: Array<PropertyValue>;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const {\n aptosConfig,\n options,\n creator,\n collection,\n description,\n name,\n uri,\n propertyKeys,\n propertyTypes,\n propertyValues,\n } = args;\n const convertedPropertyType = propertyTypes?.map((type) => PropertyTypeMap[type]);\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::mint\",\n functionArguments: [\n new MoveString(collection),\n new MoveString(description),\n new MoveString(name),\n new MoveString(uri),\n MoveVector.MoveString(propertyKeys ?? []),\n MoveVector.MoveString(convertedPropertyType ?? []),\n getPropertyValueRaw(propertyValues ?? [], convertedPropertyType ?? []),\n ],\n abi: mintDigitalAssetAbi,\n },\n options,\n });\n}\n\nconst transferDigitalAssetAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))), new TypeTagAddress()],\n};\n\nexport async function transferDigitalAssetTransaction(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n digitalAssetAddress: AccountAddressInput;\n recipient: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, digitalAssetAddress, recipient, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: sender.accountAddress,\n data: {\n function: \"0x1::object::transfer\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [AccountAddress.from(digitalAssetAddress), AccountAddress.from(recipient)],\n abi: transferDigitalAssetAbi,\n },\n options,\n });\n}\n\nconst mintSoulBoundAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n new TypeTagVector(new TypeTagStruct(stringStructTag())),\n new TypeTagVector(new TypeTagStruct(stringStructTag())),\n new TypeTagVector(TypeTagVector.u8()),\n new TypeTagAddress(),\n ],\n};\n\nexport async function mintSoulBoundTransaction(args: {\n aptosConfig: AptosConfig;\n account: Account;\n collection: string;\n description: string;\n name: string;\n uri: string;\n recipient: AccountAddressInput;\n propertyKeys?: Array<string>;\n propertyTypes?: Array<PropertyType>;\n propertyValues?: Array<PropertyValue>;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const {\n aptosConfig,\n account,\n collection,\n description,\n name,\n uri,\n recipient,\n propertyKeys,\n propertyTypes,\n propertyValues,\n options,\n } = args;\n if (propertyKeys?.length !== propertyValues?.length) {\n throw new Error(\"Property keys and property values counts do not match\");\n }\n if (propertyTypes?.length !== propertyValues?.length) {\n throw new Error(\"Property types and property values counts do not match\");\n }\n const convertedPropertyType = propertyTypes?.map((type) => PropertyTypeMap[type]);\n return generateTransaction({\n aptosConfig,\n sender: account.accountAddress,\n data: {\n function: \"0x4::aptos_token::mint_soul_bound\",\n functionArguments: [\n collection,\n description,\n name,\n uri,\n MoveVector.MoveString(propertyKeys ?? []),\n MoveVector.MoveString(convertedPropertyType ?? []),\n getPropertyValueRaw(propertyValues ?? [], convertedPropertyType ?? []),\n recipient,\n ],\n abi: mintSoulBoundAbi,\n },\n options,\n });\n}\n\nconst burnDigitalAssetAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0)))],\n};\n\nexport async function burnDigitalAssetTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::burn\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [AccountAddress.from(digitalAssetAddress)],\n abi: burnDigitalAssetAbi,\n },\n options,\n });\n}\n\nconst freezeDigitalAssetAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0)))],\n};\n\nexport async function freezeDigitalAssetTransferTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::freeze_transfer\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [digitalAssetAddress],\n abi: freezeDigitalAssetAbi,\n },\n options,\n });\n}\n\nconst unfreezeDigitalAssetAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0)))],\n};\n\nexport async function unfreezeDigitalAssetTransferTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::unfreeze_transfer\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [digitalAssetAddress],\n abi: unfreezeDigitalAssetAbi,\n },\n options,\n });\n}\n\nconst setDigitalAssetDescriptionAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))), new TypeTagStruct(stringStructTag())],\n};\n\nexport async function setDigitalAssetDescriptionTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n description: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, description, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::set_description\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [AccountAddress.from(digitalAssetAddress), new MoveString(description)],\n abi: setDigitalAssetDescriptionAbi,\n },\n options,\n });\n}\n\nconst setDigitalAssetNameAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))), new TypeTagStruct(stringStructTag())],\n};\n\nexport async function setDigitalAssetNameTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n name: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, name, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::set_name\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [AccountAddress.from(digitalAssetAddress), new MoveString(name)],\n abi: setDigitalAssetNameAbi,\n },\n options,\n });\n}\n\nconst setDigitalAssetURIAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))), new TypeTagStruct(stringStructTag())],\n};\n\nexport async function setDigitalAssetURITransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n uri: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, uri, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::set_uri\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [AccountAddress.from(digitalAssetAddress), new MoveString(uri)],\n abi: setDigitalAssetURIAbi,\n },\n options,\n });\n}\n\nconst addDigitalAssetPropertyAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [\n new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n TypeTagVector.u8(),\n ],\n};\n\nexport async function addDigitalAssetPropertyTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const {\n aptosConfig,\n creator,\n propertyKey,\n propertyType,\n propertyValue,\n digitalAssetAddress,\n digitalAssetType,\n options,\n } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::add_property\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [\n AccountAddress.from(digitalAssetAddress),\n new MoveString(propertyKey),\n new MoveString(PropertyTypeMap[propertyType]),\n MoveVector.U8(getSinglePropertyValueRaw(propertyValue, PropertyTypeMap[propertyType])),\n ],\n abi: addDigitalAssetPropertyAbi,\n },\n options,\n });\n}\n\nconst removeDigitalAssetPropertyAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))), new TypeTagStruct(stringStructTag())],\n};\n\nexport async function removeDigitalAssetPropertyTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n propertyKey: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, creator, propertyKey, digitalAssetAddress, digitalAssetType, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::remove_property\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [AccountAddress.from(digitalAssetAddress), new MoveString(propertyKey)],\n abi: removeDigitalAssetPropertyAbi,\n },\n options,\n });\n}\n\nconst updateDigitalAssetPropertyAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }],\n parameters: [\n new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))),\n new TypeTagStruct(stringStructTag()),\n new TypeTagStruct(stringStructTag()),\n TypeTagVector.u8(),\n ],\n};\n\nexport async function updateDigitalAssetPropertyTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const {\n aptosConfig,\n creator,\n propertyKey,\n propertyType,\n propertyValue,\n digitalAssetAddress,\n digitalAssetType,\n options,\n } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::update_property\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType],\n functionArguments: [\n AccountAddress.from(digitalAssetAddress),\n new MoveString(propertyKey),\n new MoveString(PropertyTypeMap[propertyType]),\n getSinglePropertyValueRaw(propertyValue, PropertyTypeMap[propertyType]),\n ],\n abi: updateDigitalAssetPropertyAbi,\n },\n options,\n });\n}\n\nconst addDigitalAssetTypedPropertyAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }, { constraints: [] }],\n parameters: [\n new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))),\n new TypeTagStruct(stringStructTag()),\n new TypeTagGeneric(1),\n ],\n};\n\nexport async function addDigitalAssetTypedPropertyTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const {\n aptosConfig,\n creator,\n propertyKey,\n propertyType,\n propertyValue,\n digitalAssetAddress,\n digitalAssetType,\n options,\n } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::add_typed_property\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType, PropertyTypeMap[propertyType]],\n functionArguments: [AccountAddress.from(digitalAssetAddress), new MoveString(propertyKey), propertyValue],\n abi: addDigitalAssetTypedPropertyAbi,\n },\n options,\n });\n}\n\nconst updateDigitalAssetTypedPropertyAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [MoveAbility.KEY] }, { constraints: [] }],\n parameters: [\n new TypeTagStruct(objectStructTag(new TypeTagGeneric(0))),\n new TypeTagStruct(stringStructTag()),\n new TypeTagGeneric(1),\n ],\n};\n\nexport async function updateDigitalAssetTypedPropertyTransaction(args: {\n aptosConfig: AptosConfig;\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const {\n aptosConfig,\n creator,\n propertyKey,\n propertyType,\n propertyValue,\n digitalAssetAddress,\n digitalAssetType,\n options,\n } = args;\n return generateTransaction({\n aptosConfig,\n sender: creator.accountAddress,\n data: {\n function: \"0x4::aptos_token::update_typed_property\",\n typeArguments: [digitalAssetType ?? defaultDigitalAssetType, PropertyTypeMap[propertyType]],\n functionArguments: [AccountAddress.from(digitalAssetAddress), new MoveString(propertyKey), propertyValue],\n abi: updateDigitalAssetTypedPropertyAbi,\n },\n options,\n });\n}\n\nfunction getPropertyValueRaw(propertyValues: Array<PropertyValue>, propertyTypes: Array<string>): Array<Uint8Array> {\n const results = new Array<Uint8Array>();\n propertyTypes.forEach((typ, index) => {\n results.push(getSinglePropertyValueRaw(propertyValues[index], typ));\n });\n\n return results;\n}\n\nfunction getSinglePropertyValueRaw(propertyValue: PropertyValue, propertyType: string): Uint8Array {\n const typeTag = parseTypeTag(propertyType);\n const res = checkOrConvertArgument(propertyValue, typeTag, 0, []);\n return res.bcsToBytes();\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n AnyNumber,\n GetCollectionDataResponse,\n GetCurrentTokenOwnershipResponse,\n GetOwnedTokensResponse,\n GetTokenActivityResponse,\n GetTokenDataResponse,\n MoveStructId,\n OrderByArg,\n PaginationArgs,\n TokenStandardArg,\n} from \"../types\";\nimport { Account, AccountAddress, AccountAddressInput } from \"../core\";\nimport { InputGenerateTransactionOptions } from \"../transactions/types\";\nimport {\n addDigitalAssetPropertyTransaction,\n addDigitalAssetTypedPropertyTransaction,\n burnDigitalAssetTransaction,\n CreateCollectionOptions,\n createCollectionTransaction,\n freezeDigitalAssetTransferTransaction,\n getCollectionData,\n getCollectionDataByCollectionId,\n getCollectionId,\n getCurrentDigitalAssetOwnership,\n getDigitalAssetActivity,\n getDigitalAssetData,\n getOwnedDigitalAssets,\n mintDigitalAssetTransaction,\n mintSoulBoundTransaction,\n PropertyType,\n PropertyValue,\n removeDigitalAssetPropertyTransaction,\n setDigitalAssetDescriptionTransaction,\n setDigitalAssetNameTransaction,\n setDigitalAssetURITransaction,\n transferDigitalAssetTransaction,\n unfreezeDigitalAssetTransferTransaction,\n updateDigitalAssetPropertyTransaction,\n updateDigitalAssetTypedPropertyTransaction,\n} from \"../internal/digitalAsset\";\nimport { ProcessorType } from \"../utils/const\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexerOnVersion } from \"./utils\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\n/**\n * A class to query all `DigitalAsset` related queries on Aptos.\n */\nexport class DigitalAsset {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries data of a specific collection by the collection creator address and the collection name.\n *\n * If, for some reason, a creator account has 2 collections with the same name in v1 and v2,\n * can pass an optional `tokenStandard` parameter to query a specific standard\n *\n * @example\n * const collection = await aptos.getCollectionData({creatorAddress:\"0x123\",collectionName:\"myCollection\"})\n *\n * @param args.creatorAddress the address of the collection's creator\n * @param args.collectionName the name of the collection\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.tokenStandard the token standard to query\n * @returns GetCollectionDataResponse response type\n */\n async getCollectionData(args: {\n creatorAddress: AccountAddressInput;\n collectionName: string;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg;\n }): Promise<GetCollectionDataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getCollectionData({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries data of a specific collection by the collection ID.\n *\n * @example\n * const collection = await aptos.getCollectionDataByCollectionId({collectionId:\"0x123\"})\n *\n * @param args.collectionId the ID of the collection, it's the same thing as the address of the collection object\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns GetCollectionDataResponse response type\n */\n async getCollectionDataByCollectionId(args: {\n collectionId: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetCollectionDataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getCollectionDataByCollectionId({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries a collection's ID.\n *\n * This is the same as the collection's object address in V2, but V1 does\n * not use objects, and does not have an address\n *\n * @example\n * const collection = await aptos.getCollectionId({creatorAddress:\"0x123\",collectionName:\"myCollection\"})\n *\n * @param args.creatorAddress the address of the collection's creator\n * @param args.collectionName the name of the collection\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.tokenStandard the token standard to query\n * @returns the collection id\n */\n async getCollectionId(args: {\n creatorAddress: AccountAddressInput;\n collectionName: string;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg;\n }): Promise<string> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getCollectionId({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Gets digital asset data given the address of a digital asset.\n *\n * @example\n * const digitalAsset = await aptos.getDigitalAssetData({digitalAssetAddress:\"0x123\"})\n *\n * @param args.tokenAddress The address of the digital asset\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns GetTokenDataResponse containing relevant data to the digital asset.\n */\n async getDigitalAssetData(args: {\n digitalAssetAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetTokenDataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getDigitalAssetData({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Gets digital asset ownership data given the address of a digital asset.\n *\n * @example\n * const digitalAssetOwner = await aptos.getCurrentDigitalAssetOwnership({digitalAssetAddress:\"0x123\"})\n *\n * @param args.tokenAddress The address of the digital asset\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n *\n * @returns GetCurrentTokenOwnershipResponse containing relevant ownership data of the digital asset.\n */\n async getCurrentDigitalAssetOwnership(args: {\n digitalAssetAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetCurrentTokenOwnershipResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getCurrentDigitalAssetOwnership({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Gets the digital assets that the given address owns.\n *\n * @example\n * const digitalAssets = await aptos.getOwnedDigitalAssets({ownerAddress:\"0x123\"})\n *\n * @param args.ownerAddress The address of the owner\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n *\n * @returns GetOwnedTokensResponse containing ownership data of the digital assets belonging to the ownerAddresss.\n */\n async getOwnedDigitalAssets(args: {\n ownerAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetOwnedTokensResponse[0]>;\n }): Promise<GetOwnedTokensResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getOwnedDigitalAssets({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Gets the activity data given the address of a digital asset.\n *\n * @example\n * const digitalAssetActivity = await aptos.getDigitalAssetActivity({digitalAssetAddress:\"0x123\"})\n *\n * @param args.tokenAddress The address of the digital asset\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n *\n * @returns GetTokenActivityResponse containing relevant activity data to the digital asset.\n */\n async getDigitalAssetActivity(args: {\n digitalAssetAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetTokenActivityResponse[0]>;\n }): Promise<GetTokenActivityResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getDigitalAssetActivity({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Creates a new collection within the specified account\n *\n * @example\n * const transaction = await aptos.createCollectionTransaction({\n * creator: alice,\n * description: \"collectionDescription\",\n * name: \"collectionName\",\n * uri: \"collection-uri.com\",\n * });\n *\n * @param args.creator the account of the collection's creator\n * @param args.description the description of the collection\n * @param args.name the name of the collection\n * @param args.uri the URI to additional info about the collection\n *\n * The parameters below are optional.\n * @param args.maxSupply controls the max supply of the digital assets - defaults MAX_U64_BIG_INT\n * @param args.mutableDescription controls mutability of the collection's description - defaults true\n * @param args.mutableRoyalty controls mutability of the collection's description - defaults true\n * @param args.mutableUri controls mutability of the collection's URI - defaults true\n * @param args.mutableTokenDescription controls mutability of the digital asset's description - defaults true\n * @param args.mutableTokenName controls mutability of the digital asset's name - defaults true\n * @param args.mutableTokenProperties controls mutability of digital asset's properties - defaults true\n * @param args.mutableTokenUri controls mutability of the digital asset's URI - defaults true\n * @param args.tokensBurnableByCreator controls whether digital assets can be burnable by the creator - defaults true\n * @param args.tokensFreezableByCreator controls whether digital assets can be frozen by the creator - defaults true\n * @param args.royaltyNumerator the numerator of the royalty to be paid to the creator when\n * a digital asset is transferred - defaults 0\n * @param args.royaltyDenominator the denominator of the royalty to be paid to the creator\n * when a digital asset is transferred - defaults 1\n *\n * @returns A SimpleTransaction that when submitted will create the collection.\n */\n async createCollectionTransaction(\n args: {\n creator: Account;\n description: string;\n name: string;\n uri: string;\n options?: InputGenerateTransactionOptions;\n } & CreateCollectionOptions,\n ): Promise<SimpleTransaction> {\n return createCollectionTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Create a transaction to mint a digital asset into the creators account within an existing collection.\n *\n * @example\n * const transaction = await aptos.mintDigitalAssetTransaction({\n * creator: alice,\n * description: \"collectionDescription\",\n * collection: \"collectionName\",\n * name: \"digitalAssetName\",\n * uri: \"digital-asset-uri.com\",\n * });\n *\n * @param args.creator the creator of the collection\n * @param args.collection the name of the collection the digital asset belongs to\n * @param args.description the description of the digital asset\n * @param args.name the name of the digital asset\n * @param args.uri the URI to additional info about the digital asset\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async mintDigitalAssetTransaction(args: {\n creator: Account;\n collection: string;\n description: string;\n name: string;\n uri: string;\n propertyKeys?: Array<string>;\n propertyTypes?: Array<PropertyType>;\n propertyValues?: Array<PropertyValue>;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return mintDigitalAssetTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Transfer a digital asset (non fungible digital asset) ownership.\n *\n * We can transfer a digital asset only when the digital asset is not frozen\n * (i.e. owner transfer is not disabled such as for soul bound digital assets)\n *\n * @example\n * const transaction = await aptos.transferDigitalAssetTransaction({\n * sender: alice,\n * digitalAssetAddress: \"0x123\",\n * recipient: \"0x456\",\n * });\n *\n * @param args.sender The sender account of the current digital asset owner\n * @param args.digitalAssetAddress The digital asset address\n * @param args.recipient The recipient account address\n * @param args.digitalAssetType optional. The digital asset type, default to \"0x4::token::Token\"\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async transferDigitalAssetTransaction(args: {\n sender: Account;\n digitalAssetAddress: AccountAddressInput;\n recipient: AccountAddress;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return transferDigitalAssetTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Mint a soul bound digital asset into a recipient's account\n *\n * @example\n * const transaction = await aptos.mintSoulBoundTransaction({\n * account: alice,\n * collection: \"collectionName\",\n * description: \"collectionDescription\",\n * name: \"digitalAssetName\",\n * uri: \"digital-asset-uri.com\",\n * recipient: \"0x123\"\n * });\n *\n * @param args.account The account that mints the digital asset\n * @param args.collection The collection name that the digital asset belongs to\n * @param args.description The digital asset description\n * @param args.name The digital asset name\n * @param args.uri The digital asset URL\n * @param args.recipient The account address where the digital asset will be created\n * @param args.propertyKeys The property keys for storing on-chain properties\n * @param args.propertyTypes The type of property values\n * @param args.propertyValues The property values to be stored on-chain\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async mintSoulBoundTransaction(args: {\n account: Account;\n collection: string;\n description: string;\n name: string;\n uri: string;\n recipient: AccountAddressInput;\n propertyKeys?: Array<string>;\n propertyTypes?: Array<PropertyType>;\n propertyValues?: Array<PropertyValue>;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return mintSoulBoundTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Burn a digital asset by its creator\n *\n * @example\n * const transaction = await aptos.burnDigitalAssetTransaction({\n * creator: alice,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.creator The creator account\n * @param args.digitalAssetAddress The digital asset address\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async burnDigitalAssetTransaction(args: {\n creator: Account;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return burnDigitalAssetTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Freeze digital asset transfer ability\n *\n * @example\n * const transaction = await aptos.freezeDigitalAssetTransaferTransaction({\n * creator: alice,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.creator The creator account\n * @param args.digitalAssetAddress The digital asset address\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async freezeDigitalAssetTransaferTransaction(args: {\n creator: Account;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return freezeDigitalAssetTransferTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Unfreeze digital asset transfer ability\n *\n * @example\n * const transaction = await aptos.unfreezeDigitalAssetTransaferTransaction({\n * creator: alice,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.creator The creator account\n * @param args.digitalAssetAddress The digital asset address\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async unfreezeDigitalAssetTransaferTransaction(args: {\n creator: Account;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return unfreezeDigitalAssetTransferTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Set the digital asset description\n *\n * @example\n * const transaction = await aptos.setDigitalAssetDescriptionTransaction({\n * creator: alice,\n * description: \"digitalAssetDescription\",\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.creator The creator account\n * @param args.description The digital asset description\n * @param args.digitalAssetAddress The digital asset address\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async setDigitalAssetDescriptionTransaction(args: {\n creator: Account;\n description: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return setDigitalAssetDescriptionTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Set the digital asset name\n *\n * @example\n * const transaction = await aptos.setDigitalAssetNameTransaction({\n * creator: alice,\n * name: \"digitalAssetName\",\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.creator The creator account\n * @param args.name The digital asset name\n * @param args.digitalAssetAddress The digital asset address\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async setDigitalAssetNameTransaction(args: {\n creator: Account;\n name: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return setDigitalAssetNameTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Set the digital asset name\n *\n * @example\n * const transaction = await aptos.setDigitalAssetURITransaction({\n * creator: alice,\n * uri: \"digital-asset-uri.com\",\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.creator The creator account\n * @param args.uri The digital asset uri\n * @param args.digitalAssetAddress The digital asset address\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async setDigitalAssetURITransaction(args: {\n creator: Account;\n uri: string;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return setDigitalAssetURITransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Add a digital asset property\n *\n * @example\n * const transaction = await aptos.addDigitalAssetPropertyTransaction({\n * creator: alice,\n * propertyKey: \"newKey\",\n * propertyType: \"BOOLEAN\",\n * propertyValue: true,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.account The account that mints the digital asset\n * @param args.digitalAssetAddress The digital asset address\n * @param args.propertyKey The property key for storing on-chain properties\n * @param args.propertyType The type of property value\n * @param args.propertyValue The property value to be stored on-chain\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async addDigitalAssetPropertyTransaction(args: {\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return addDigitalAssetPropertyTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Remove a digital asset property\n *\n * @example\n * const transaction = await aptos.removeDigitalAssetPropertyTransaction({\n * creator: alice,\n * propertyKey: \"newKey\",\n * propertyType: \"BOOLEAN\",\n * propertyValue: true,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.account The account that mints the digital asset\n * @param args.digitalAssetAddress The digital asset address\n * @param args.propertyKey The property key for storing on-chain properties\n * @param args.propertyType The type of property value\n * @param args.propertyValue The property value to be stored on-chain\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async removeDigitalAssetPropertyTransaction(args: {\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return removeDigitalAssetPropertyTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Update a digital asset property\n *\n * @example\n * const transaction = await aptos.updateDigitalAssetPropertyTransaction({\n * creator: alice,\n * propertyKey: \"newKey\",\n * propertyType: \"BOOLEAN\",\n * propertyValue: false,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.account The account that mints the digital asset\n * @param args.digitalAssetAddress The digital asset address\n * @param args.propertyKey The property key for storing on-chain properties\n * @param args.propertyType The type of property value\n * @param args.propertyValue The property value to be stored on-chain\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async updateDigitalAssetPropertyTransaction(args: {\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return updateDigitalAssetPropertyTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Add a typed digital asset property\n *\n * @example\n * const transaction = await aptos.addDigitalAssetTypedPropertyTransaction({\n * creator: alice,\n * propertyKey: \"typedKey\",\n * propertyType: \"STRING\",\n * propertyValue: \"hello\",\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.account The account that mints the digital asset\n * @param args.digitalAssetAddress The digital asset address\n * @param args.propertyKey The property key for storing on-chain properties\n * @param args.propertyType The type of property value\n * @param args.propertyValue The property value to be stored on-chain\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async addDigitalAssetTypedPropertyTransaction(args: {\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return addDigitalAssetTypedPropertyTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Update a typed digital asset property\n *\n * @example\n * const transaction = await aptos.updateDigitalAssetTypedPropertyTransaction({\n * creator: alice,\n * propertyKey: \"typedKey\",\n * propertyType: \"U8\",\n * propertyValue: 2,\n * digitalAssetAddress: \"0x123\",\n * });\n *\n * @param args.account The account that mints the digital asset\n * @param args.digitalAssetAddress The digital asset address\n * @param args.propertyKey The property key for storing on-chain properties\n * @param args.propertyType The type of property value\n * @param args.propertyValue The property value to be stored on-chain\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain\n */\n async updateDigitalAssetTypedPropertyTransaction(args: {\n creator: Account;\n propertyKey: string;\n propertyType: PropertyType;\n propertyValue: PropertyValue;\n digitalAssetAddress: AccountAddressInput;\n digitalAssetType?: MoveStructId;\n options?: InputGenerateTransactionOptions;\n }) {\n return updateDigitalAssetTypedPropertyTransaction({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/event}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * event namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { AccountAddress, AccountAddressInput } from \"../core\";\nimport { AnyNumber, GetEventsResponse, PaginationArgs, MoveStructId, OrderByArg, WhereArg } from \"../types\";\nimport { GetEventsQuery } from \"../types/generated/operations\";\nimport { GetEvents } from \"../types/generated/queries\";\nimport { EventsBoolExp, InputMaybe } from \"../types/generated/types\";\nimport { queryIndexer } from \"./general\";\n\nconst MAX_EVENT_TYPE_LENGTH = 300;\nconst checkEventTypeLength = (eventType?: InputMaybe<string>) => {\n if (eventType && eventType.length > MAX_EVENT_TYPE_LENGTH) {\n throw new Error(`Event type length exceeds the maximum length of ${MAX_EVENT_TYPE_LENGTH}`);\n }\n};\n\nexport async function getModuleEventsByEventType(args: {\n aptosConfig: AptosConfig;\n eventType: MoveStructId;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;\n}): Promise<GetEventsResponse> {\n const { aptosConfig, eventType, options } = args;\n\n const whereCondition: EventsBoolExp = {\n account_address: { _eq: \"0x0000000000000000000000000000000000000000000000000000000000000000\" },\n creation_number: { _eq: \"0\" },\n sequence_number: { _eq: \"0\" },\n indexed_type: { _eq: eventType },\n };\n\n const customOptions = {\n where: whereCondition,\n pagination: options,\n orderBy: options?.orderBy,\n };\n\n return getEvents({ aptosConfig, options: customOptions });\n}\n\nexport async function getAccountEventsByCreationNumber(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n creationNumber: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;\n}): Promise<GetEventsResponse> {\n const { accountAddress, aptosConfig, creationNumber, options } = args;\n const address = AccountAddress.from(accountAddress);\n\n const whereCondition: EventsBoolExp = {\n account_address: { _eq: address.toStringLong() },\n creation_number: { _eq: creationNumber },\n };\n\n const customOptions = {\n where: whereCondition,\n pagination: options,\n orderBy: options?.orderBy,\n };\n\n return getEvents({ aptosConfig, options: customOptions });\n}\n\nexport async function getAccountEventsByEventType(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n eventType: MoveStructId;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;\n}): Promise<GetEventsResponse> {\n const { accountAddress, aptosConfig, eventType, options } = args;\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n const whereCondition: EventsBoolExp = {\n account_address: { _eq: address },\n indexed_type: { _eq: eventType },\n };\n\n const customOptions = {\n where: whereCondition,\n pagination: options,\n orderBy: options?.orderBy,\n };\n\n return getEvents({ aptosConfig, options: customOptions });\n}\n\nexport async function getEvents(args: {\n aptosConfig: AptosConfig;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]> & WhereArg<EventsBoolExp>;\n}): Promise<GetEventsResponse> {\n const { aptosConfig, options } = args;\n // eslint-disable-next-line no-underscore-dangle\n checkEventTypeLength(options?.where?.indexed_type?._eq);\n\n const graphqlQuery = {\n query: GetEvents,\n variables: {\n where_condition: options?.where,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n\n const data = await queryIndexer<GetEventsQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getEvents\",\n });\n\n return data.events;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n getAccountEventsByCreationNumber,\n getAccountEventsByEventType,\n getModuleEventsByEventType,\n getEvents,\n} from \"../internal/event\";\nimport { AnyNumber, GetEventsResponse, MoveStructId, OrderByArg, PaginationArgs, WhereArg } from \"../types\";\nimport { EventsBoolExp } from \"../types/generated/types\";\nimport { AccountAddressInput } from \"../core\";\nimport { ProcessorType } from \"../utils/const\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexerOnVersion } from \"./utils\";\n\n/**\n * A class to query all `Event` Aptos related queries\n */\nexport class Event {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Get module events by event type\n *\n * @example\n * const events = await aptos.getModuleEventsByEventType({eventType:\"0x1::transaction_fee::FeeStatement\"})\n *\n * @param args.eventType - The event type\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n *\n * @returns Promise<GetEventsResponse>\n */\n async getModuleEventsByEventType(args: {\n eventType: MoveStructId;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;\n }): Promise<GetEventsResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.EVENTS_PROCESSOR,\n });\n return getModuleEventsByEventType({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Get events by creation number and an account address\n *\n * @example\n * const events = await aptos.getAccountEventsByCreationNumber({accountAddress:\"0x123\",creationNumber: 0})\n *\n * @param args.accountAddress - The account address\n * @param args.creationNumber - The event creation number\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n *\n * @returns Promise<GetEventsResponse>\n */\n async getAccountEventsByCreationNumber(args: {\n accountAddress: AccountAddressInput;\n creationNumber: AnyNumber;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetEventsResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.EVENTS_PROCESSOR,\n });\n return getAccountEventsByCreationNumber({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Get events by event type and an account address\n *\n * @example\n * const events = await aptos.getAccountEventsByEventType({accountAddress:\"0x123\",eventType: \"0x1::transaction_fee::FeeStatement\"})\n *\n * @param args.accountAddress - The account address\n * @param args.eventType - The event type\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n *\n * @returns Promise<GetEventsResponse>\n */\n async getAccountEventsByEventType(args: {\n accountAddress: AccountAddressInput;\n eventType: MoveStructId;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;\n }): Promise<GetEventsResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.EVENTS_PROCESSOR,\n });\n return getAccountEventsByEventType({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Get all events\n *\n * An optional `where` can be passed in to filter out the response.\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @example\n * const events = await aptos.getEvents()\n * // with filtering\n * const events = await aptos.getEvents({options: { where: { account_address: { _eq: \"0x123\" } } }});\n *\n * @returns GetEventsQuery response type\n */\n async getEvents(args?: {\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetEventsResponse[0]> & WhereArg<EventsBoolExp>;\n }): Promise<GetEventsResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.EVENTS_PROCESSOR,\n });\n return getEvents({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/faucet}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * faucet namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { postAptosFaucet } from \"../client\";\nimport { AccountAddress, AccountAddressInput } from \"../core\";\nimport { TransactionResponseType, UserTransactionResponse, WaitForTransactionOptions } from \"../types\";\nimport { DEFAULT_TXN_TIMEOUT_SEC } from \"../utils/const\";\nimport { waitForTransaction } from \"./transaction\";\n\nexport async function fundAccount(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n amount: number;\n options?: WaitForTransactionOptions;\n}): Promise<UserTransactionResponse> {\n const { aptosConfig, accountAddress, amount, options } = args;\n const timeout = options?.timeoutSecs || DEFAULT_TXN_TIMEOUT_SEC;\n const { data } = await postAptosFaucet<any, { txn_hashes: Array<string> }>({\n aptosConfig,\n path: \"fund\",\n body: {\n address: AccountAddress.from(accountAddress).toString(),\n amount,\n },\n originMethod: \"fundAccount\",\n });\n\n const txnHash = data.txn_hashes[0];\n\n const res = await waitForTransaction({\n aptosConfig,\n transactionHash: txnHash,\n options: {\n timeoutSecs: timeout,\n checkSuccess: options?.checkSuccess,\n },\n });\n\n // Response is always User transaction for a user submitted transaction\n if (res.type === TransactionResponseType.User) {\n return res;\n }\n\n throw new Error(`Unexpected transaction received for fund account: ${res.type}`);\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fundAccount } from \"../internal/faucet\";\nimport { UserTransactionResponse, WaitForTransactionOptions } from \"../types\";\nimport { AccountAddressInput } from \"../core\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexer } from \"../internal/transaction\";\n\n/**\n * A class to query all `Faucet` related queries on Aptos.\n */\nexport class Faucet {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * This creates an account if it does not exist and mints the specified amount of\n * coins into that account\n *\n * @example\n * const transaction = await aptos.fundAccount({accountAddress:\"0x123\", amount: 100})\n *\n * @param args.accountAddress Address of the account to fund\n * @param args.amount Amount of tokens to fund the account with\n * @param args.options Configuration options for waitForTransaction\n * @returns Transaction hash of the transaction that funded the account\n */\n async fundAccount(args: {\n accountAddress: AccountAddressInput;\n amount: number;\n options?: WaitForTransactionOptions;\n }): Promise<UserTransactionResponse> {\n const fundTxn = await fundAccount({ aptosConfig: this.config, ...args });\n\n if (args.options?.waitForIndexer !== false) {\n await waitForIndexer({ aptosConfig: this.config, minimumLedgerVersion: BigInt(fundTxn.version) });\n }\n\n return fundTxn;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/fungible_asset}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * fungible_asset namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport {\n AnyNumber,\n GetCurrentFungibleAssetBalancesResponse,\n GetFungibleAssetActivitiesResponse,\n GetFungibleAssetMetadataResponse,\n PaginationArgs,\n WhereArg,\n} from \"../types\";\nimport { queryIndexer } from \"./general\";\nimport {\n GetCurrentFungibleAssetBalances,\n GetFungibleAssetActivities,\n GetFungibleAssetMetadata,\n} from \"../types/generated/queries\";\nimport {\n GetCurrentFungibleAssetBalancesQuery,\n GetFungibleAssetActivitiesQuery,\n GetFungibleAssetMetadataQuery,\n} from \"../types/generated/operations\";\nimport {\n CurrentFungibleAssetBalancesBoolExp,\n FungibleAssetActivitiesBoolExp,\n FungibleAssetMetadataBoolExp,\n} from \"../types/generated/types\";\nimport { Account, AccountAddressInput } from \"../core\";\nimport {\n EntryFunctionABI,\n InputGenerateTransactionOptions,\n parseTypeTag,\n TypeTagAddress,\n TypeTagU64,\n} from \"../transactions\";\nimport { generateTransaction } from \"./transactionSubmission\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\nexport async function getFungibleAssetMetadata(args: {\n aptosConfig: AptosConfig;\n options?: PaginationArgs & WhereArg<FungibleAssetMetadataBoolExp>;\n}): Promise<GetFungibleAssetMetadataResponse> {\n const { aptosConfig, options } = args;\n\n const graphqlQuery = {\n query: GetFungibleAssetMetadata,\n variables: {\n where_condition: options?.where,\n limit: options?.limit,\n offset: options?.offset,\n },\n };\n\n const data = await queryIndexer<GetFungibleAssetMetadataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getFungibleAssetMetadata\",\n });\n\n return data.fungible_asset_metadata;\n}\n\nexport async function getFungibleAssetActivities(args: {\n aptosConfig: AptosConfig;\n options?: PaginationArgs & WhereArg<FungibleAssetActivitiesBoolExp>;\n}): Promise<GetFungibleAssetActivitiesResponse> {\n const { aptosConfig, options } = args;\n\n const graphqlQuery = {\n query: GetFungibleAssetActivities,\n variables: {\n where_condition: options?.where,\n limit: options?.limit,\n offset: options?.offset,\n },\n };\n\n const data = await queryIndexer<GetFungibleAssetActivitiesQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getFungibleAssetActivities\",\n });\n\n return data.fungible_asset_activities;\n}\n\nexport async function getCurrentFungibleAssetBalances(args: {\n aptosConfig: AptosConfig;\n options?: PaginationArgs & WhereArg<CurrentFungibleAssetBalancesBoolExp>;\n}): Promise<GetCurrentFungibleAssetBalancesResponse> {\n const { aptosConfig, options } = args;\n\n const graphqlQuery = {\n query: GetCurrentFungibleAssetBalances,\n variables: {\n where_condition: options?.where,\n limit: options?.limit,\n offset: options?.offset,\n },\n };\n\n const data = await queryIndexer<GetCurrentFungibleAssetBalancesQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getCurrentFungibleAssetBalances\",\n });\n\n return data.current_fungible_asset_balances;\n}\n\nconst faTransferAbi: EntryFunctionABI = {\n typeParameters: [{ constraints: [] }],\n parameters: [parseTypeTag(\"0x1::object::Object\"), new TypeTagAddress(), new TypeTagU64()],\n};\n\nexport async function transferFungibleAsset(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n fungibleAssetMetadataAddress: AccountAddressInput;\n recipient: AccountAddressInput;\n amount: AnyNumber;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, fungibleAssetMetadataAddress, recipient, amount, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: sender.accountAddress,\n data: {\n function: \"0x1::primary_fungible_store::transfer\",\n typeArguments: [\"0x1::fungible_asset::Metadata\"],\n functionArguments: [fungibleAssetMetadataAddress, recipient, amount],\n abi: faTransferAbi,\n },\n options,\n });\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n AnyNumber,\n GetCurrentFungibleAssetBalancesResponse,\n GetFungibleAssetActivitiesResponse,\n GetFungibleAssetMetadataResponse,\n PaginationArgs,\n WhereArg,\n} from \"../types\";\nimport {\n getCurrentFungibleAssetBalances,\n getFungibleAssetActivities,\n getFungibleAssetMetadata,\n transferFungibleAsset,\n} from \"../internal/fungibleAsset\";\nimport {\n CurrentFungibleAssetBalancesBoolExp,\n FungibleAssetActivitiesBoolExp,\n FungibleAssetMetadataBoolExp,\n} from \"../types/generated/types\";\nimport { ProcessorType } from \"../utils/const\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexerOnVersion } from \"./utils\";\nimport { Account, AccountAddressInput } from \"../core\";\nimport { InputGenerateTransactionOptions } from \"../transactions\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\n/**\n * A class to query all `FungibleAsset` related queries on Aptos.\n */\nexport class FungibleAsset {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries all fungible asset metadata.\n *\n * @example\n * const fungibleAsset = await aptos.getFungibleAssetMetadata()\n *\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options Optional configuration for pagination and filtering\n *\n * @returns A list of fungible asset metadata\n */\n async getFungibleAssetMetadata(args?: {\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & WhereArg<FungibleAssetMetadataBoolExp>;\n }): Promise<GetFungibleAssetMetadataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n return getFungibleAssetMetadata({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries a fungible asset metadata\n *\n * This query returns the fungible asset metadata for a specific fungible asset.\n *\n * @example\n * const fungibleAsset = await aptos.getFungibleAssetMetadataByAssetType({assetType:\"0x123::test_coin::TestCoin\"})\n *\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.assetType The asset type of the fungible asset.\n * e.g\n * \"0x1::aptos_coin::AptosCoin\" for Aptos Coin\n * \"0xc2948283c2ce03aafbb294821de7ee684b06116bb378ab614fa2de07a99355a8\" - address format if this is fungible asset\n *\n * @returns A fungible asset metadata item\n */\n async getFungibleAssetMetadataByAssetType(args: {\n assetType: string;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetFungibleAssetMetadataResponse[0]> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n const data = await getFungibleAssetMetadata({\n aptosConfig: this.config,\n options: {\n where: {\n asset_type: { _eq: args.assetType },\n },\n },\n });\n\n return data[0];\n }\n\n /**\n * Queries all fungible asset activities\n *\n * @example\n * const fungibleAssetActivities = await aptos.getFungibleAssetActivities()\n *\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options Optional configuration for pagination and filtering\n *\n * @returns A list of fungible asset metadata\n */\n async getFungibleAssetActivities(args?: {\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & WhereArg<FungibleAssetActivitiesBoolExp>;\n }): Promise<GetFungibleAssetActivitiesResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n return getFungibleAssetActivities({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries all fungible asset balances\n *\n * @example\n * const fungibleAssetBalances = await aptos.getCurrentFungibleAssetBalances()\n *\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options Optional configuration for pagination and filtering\n *\n * @returns A list of fungible asset metadata\n */\n async getCurrentFungibleAssetBalances(args?: {\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & WhereArg<CurrentFungibleAssetBalancesBoolExp>;\n }): Promise<GetCurrentFungibleAssetBalancesResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args?.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n return getCurrentFungibleAssetBalances({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Transfer `amount` of fungible asset from sender's primary store to recipient's primary store.\n *\n * Use this method to transfer any fungible asset including fungible token.\n *\n * @example\n * const transaction = await aptos.transferFungibleAsset({\n * sender: alice,\n * fungibleAssetMetadataAddress: \"0x123\",\n * recipient: \"0x456\",\n * amount: 5\n * })\n *\n * @param sender The sender account\n * @param fungibleAssetMetadataAddress The fungible asset account address.\n * For example if you’re transferring USDT this would be the USDT address\n * @param recipient The recipient account address\n * @param amount Number of assets to transfer\n *\n * @returns A SimpleTransaction that can be simulated or submitted to chain.\n */\n async transferFungibleAsset(args: {\n sender: Account;\n fungibleAssetMetadataAddress: AccountAddressInput;\n recipient: AccountAddressInput;\n amount: AnyNumber;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return transferFungibleAsset({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { LedgerVersionArg, MimeType, MoveValue } from \"../types\";\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { generateViewFunctionPayload, InputViewFunctionData } from \"../transactions\";\nimport { Serializer } from \"../bcs\";\nimport { postAptosFullNode } from \"../client\";\n\nexport async function view<T extends Array<MoveValue> = Array<MoveValue>>(args: {\n aptosConfig: AptosConfig;\n payload: InputViewFunctionData;\n options?: LedgerVersionArg;\n}): Promise<T> {\n const { aptosConfig, payload, options } = args;\n const viewFunctionPayload = await generateViewFunctionPayload({\n ...payload,\n aptosConfig,\n });\n\n const serializer = new Serializer();\n viewFunctionPayload.serialize(serializer);\n const bytes = serializer.toUint8Array();\n\n const { data } = await postAptosFullNode<Uint8Array, MoveValue[]>({\n aptosConfig,\n path: \"view\",\n originMethod: \"view\",\n contentType: MimeType.BCS_VIEW_FUNCTION,\n params: { ledger_version: options?.ledgerVersion },\n body: bytes,\n });\n\n return data as T;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosConfig } from \"./aptosConfig\";\nimport {\n getBlockByHeight,\n getBlockByVersion,\n getChainTopUserTransactions,\n getIndexerLastSuccessVersion,\n getLedgerInfo,\n getProcessorStatus,\n getTableItem,\n queryIndexer,\n} from \"../internal/general\";\nimport { view } from \"../internal/view\";\nimport {\n AnyNumber,\n Block,\n GetChainTopUserTransactionsResponse,\n GetProcessorStatusResponse,\n GraphqlQuery,\n LedgerInfo,\n LedgerVersionArg,\n MoveValue,\n TableItemRequest,\n} from \"../types\";\nimport { ProcessorType } from \"../utils/const\";\nimport { InputViewFunctionData } from \"../transactions\";\n\n/**\n * A class to query all `General` Aptos related queries\n */\nexport class General {\n readonly config: AptosConfig;\n\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Queries for the Aptos ledger info\n *\n * @returns Aptos Ledger Info\n *\n * @example\n * const ledgerInfo = await aptos.getLedgerInfo()\n * // an example of the returned data\n * ```\n * {\n * \"chain_id\": 4,\n * \"epoch\": \"8\",\n * \"ledger_version\": \"714\",\n * \"oldest_ledger_version\": \"0\",\n * \"ledger_timestamp\": \"1694695496521775\",\n * \"node_role\": \"validator\",\n * \"oldest_block_height\": \"0\",\n * \"block_height\": \"359\",\n * \"git_hash\": \"c82193f36f4e185fed9f68c4ad21f6c6dd390c6e\"\n * }\n * ```\n */\n async getLedgerInfo(): Promise<LedgerInfo> {\n return getLedgerInfo({ aptosConfig: this.config });\n }\n\n /**\n * Queries for the chain id\n *\n * @example\n * const chainId = await aptos.getChainId()\n *\n * @returns The chain id\n */\n async getChainId(): Promise<number> {\n const result = await this.getLedgerInfo();\n return result.chain_id;\n }\n\n /**\n * Queries for block by transaction version\n *\n * @example\n * const block = await aptos.getBlockByVersion({ledgerVersion:5})\n *\n * @param args.ledgerVersion Ledger version to lookup block information for\n * @param args.options.withTransactions If set to true, include all transactions in the block\n *\n * @returns Block information with optional transactions\n */\n async getBlockByVersion(args: {\n ledgerVersion: AnyNumber;\n options?: { withTransactions?: boolean };\n }): Promise<Block> {\n return getBlockByVersion({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Get block by block height\n *\n * @example\n * const block = await aptos.getBlockByVersion({blockHeight:5})\n *\n * @param args.blockHeight Block height to lookup. Starts at 0\n * @param args.options.withTransactions If set to true, include all transactions in the block\n *\n * @returns Block with optional transactions\n */\n async getBlockByHeight(args: { blockHeight: AnyNumber; options?: { withTransactions?: boolean } }): Promise<Block> {\n return getBlockByHeight({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries for a table item for a table identified by the handle and the key for the item.\n * Key and value types need to be passed in to help with key serialization and value deserialization.\n *\n * @example https://api.devnet.aptoslabs.com/v1/accounts/0x1/resource/0x1::coin::CoinInfo%3C0x1::aptos_coin::AptosCoin%3E\n * const tableItem = await aptos.getTableItem({\n * handle: \"0x123\",\n * data: {\n * key_type: \"address\", // Move type of table key\n * value_type: \"u128\", // Move type of table value\n * key: \"0x619dc29a0aac8fa146714058e8dd6d2d0f3bdf5f6331907bf91f3acd81e6935\" // Value of table key\n * },\n * })\n *\n * @param args.handle A pointer to where that table is stored\n * @param args.data Object that describes table item\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n *\n * @returns Table item value rendered in JSON\n */\n async getTableItem<T>(args: { handle: string; data: TableItemRequest; options?: LedgerVersionArg }): Promise<T> {\n return getTableItem<T>({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries for a Move view function\n * @param args.payload Payload for the view function\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n *\n * @example\n * const data = await aptos.view({\n * payload: {\n * function: \"0x1::coin::balance\",\n * typeArguments: [\"0x1::aptos_coin::AptosCoin\"],\n * functionArguments: [accountAddress],\n * }\n * })\n *\n * @returns an array of Move values\n */\n async view<T extends Array<MoveValue>>(args: {\n payload: InputViewFunctionData;\n options?: LedgerVersionArg;\n }): Promise<T> {\n return view<T>({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries top user transactions\n *\n * @example\n * const topUserTransactions = await aptos.getChainTopUserTransactions({limit:5})\n *\n * @param args.limit The number of transactions to return\n * @returns GetChainTopUserTransactionsResponse\n */\n async getChainTopUserTransactions(args: { limit: number }): Promise<GetChainTopUserTransactionsResponse> {\n return getChainTopUserTransactions({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * A generic function for retrieving data from Aptos Indexer.\n * For more detailed queries specification see\n * {@link https://cloud.hasura.io/public/graphiql?endpoint=https://api.mainnet.aptoslabs.com/v1/graphql}\n *\n * @example\n * const topUserTransactions = await aptos.queryIndexer({\n * query: `query MyQuery {\n * ledger_infos {\n * chain_id\n * }}`;\n * })\n *\n * @param args.query.query A GraphQL query\n * @param args.query.variables The variables for the query\n *\n * @return The provided T type\n */\n async queryIndexer<T extends {}>(args: { query: GraphqlQuery }): Promise<T> {\n return queryIndexer<T>({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries for the last successful indexer version\n *\n * This is useful to tell what ledger version the indexer is updated to, as it can be behind the full nodes.\n *\n * @example\n * const version = await aptos.getIndexerLastSuccessVersion()\n */\n async getIndexerLastSuccessVersion(): Promise<bigint> {\n return getIndexerLastSuccessVersion({ aptosConfig: this.config });\n }\n\n /**\n * Query the processor status for a specific processor type.\n *\n * @example\n * const status = await aptos.getProcessorStatus({processorType:\"account_transactions_processor\"})\n *\n * @param processorType The processor type to query\n * @returns\n */\n async getProcessorStatus(processorType: ProcessorType): Promise<GetProcessorStatusResponse[0]> {\n return getProcessorStatus({ aptosConfig: this.config, processorType });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AccountAddress, PrivateKey, Account as AccountModule, AccountAddressInput } from \"../core\";\nimport {\n AccountData,\n AnyNumber,\n GetAccountCoinsDataResponse,\n GetAccountCollectionsWithOwnedTokenResponse,\n GetAccountOwnedObjectsResponse,\n GetAccountOwnedTokensFromCollectionResponse,\n GetAccountOwnedTokensQueryResponse,\n LedgerVersionArg,\n MoveModuleBytecode,\n MoveResource,\n MoveStructId,\n OrderByArg,\n PaginationArgs,\n TokenStandardArg,\n TransactionResponse,\n WhereArg,\n} from \"../types\";\nimport {\n deriveAccountFromPrivateKey,\n getAccountCoinAmount,\n getAccountCoinsCount,\n getAccountCoinsData,\n getAccountCollectionsWithOwnedTokens,\n getAccountOwnedObjects,\n getAccountOwnedTokens,\n getAccountOwnedTokensFromCollectionAddress,\n getAccountTokensCount,\n getAccountTransactionsCount,\n getInfo,\n getModule,\n getModules,\n getResource,\n getResources,\n getTransactions,\n lookupOriginalAccountAddress,\n} from \"../internal/account\";\nimport { APTOS_COIN, ProcessorType } from \"../utils/const\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexerOnVersion } from \"./utils\";\nimport { CurrentFungibleAssetBalancesBoolExp } from \"../types/generated/types\";\n\n/**\n * A class to query all `Account` related queries on Aptos.\n */\nexport class Account {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries the current state for an Aptos account given its account address\n *\n * @param args.accountAddress Aptos account address\n *\n * @returns The account data\n *\n * @example An example of the returned account\n * ```\n * {\n * sequence_number: \"1\",\n * authentication_key: \"0x5307b5f4bc67829097a8ba9b43dba3b88261eeccd1f709d9bde240fc100fbb69\"\n * }\n * ```\n */\n async getAccountInfo(args: { accountAddress: AccountAddressInput }): Promise<AccountData> {\n return getInfo({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries for all modules in an account given an account address\n *\n * Note: In order to get all account modules, this function may call the API\n * multiple times as it auto paginates.\n *\n * @param args.accountAddress Aptos account address\n * @param args.options.offset The number module to start returning results from\n * @param args.options.limit The number of results to return\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n *\n * @returns Account modules\n */\n\n async getAccountModules(args: {\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & LedgerVersionArg;\n }): Promise<MoveModuleBytecode[]> {\n return getModules({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries for a specific account module given account address and module name\n *\n * @param args.accountAddress Aptos account address\n * @param args.moduleName The name of the module\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n *\n * @returns Account module\n *\n * @example\n * const module = await aptos.getAccountModule({accountAddress:\"0x456\"})\n * // An example of an account module response\n * ```\n * {\n * bytecode: \"0xa11ceb0b0600000006010002030206050807070f0d081c200\",\n * abi: { address: \"0x1\" }\n * }\n * ```\n */\n async getAccountModule(args: {\n accountAddress: AccountAddressInput;\n moduleName: string;\n options?: LedgerVersionArg;\n }): Promise<MoveModuleBytecode> {\n return getModule({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries account transactions given an account address\n *\n * Note: In order to get all account transactions, this function may call the API\n * multiple times as it auto paginates.\n *\n * @example\n * const transactions = await aptos.getAccountTransactions({accountAddress:\"0x456\"})\n *\n * @param args.accountAddress Aptos account address\n * @param args.options.offset The number transaction to start returning results from\n * @param args.options.limit The number of results to return\n *\n * @returns The account transactions\n */\n async getAccountTransactions(args: {\n accountAddress: AccountAddressInput;\n options?: PaginationArgs;\n }): Promise<TransactionResponse[]> {\n return getTransactions({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries all account resources given an account address\n *\n * Note: In order to get all account resources, this function may call the API\n * multiple times as it auto paginates.\n *\n * @example\n * const resources = await aptos.getAccountResources({accountAddress:\"0x456\"})\n *\n * @param args.accountAddress Aptos account address\n * @param args.options.offset The number resource to start returning results from\n * @param args.options.limit The number of results to return\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n * @returns Account resources\n */\n async getAccountResources(args: {\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & LedgerVersionArg;\n }): Promise<MoveResource[]> {\n return getResources({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries a specific account resource given account address and resource type. Note that the default is `any` in order\n * to allow for ease of accessing properties of the object.\n *\n * @type The typed output of the resource\n * @param args.accountAddress Aptos account address\n * @param args.resourceType String representation of an on-chain Move struct type, i.e \"0x1::aptos_coin::AptosCoin\"\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n *\n * @returns Account resource\n *\n * @example\n * const resource = await aptos.getAccountResource({accountAddress:\"0x456\"})\n *\n */\n async getAccountResource<T extends {} = any>(args: {\n accountAddress: AccountAddressInput;\n resourceType: MoveStructId;\n options?: LedgerVersionArg;\n }): Promise<T> {\n return getResource<T>({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Looks up the account address for a given authentication key\n *\n * This handles both if the account's authentication key has been rotated or not.\n *\n * @example\n * const accountAddress = await aptos.lookupOriginalAccountAddress({authenticationKey:account.accountAddress})\n *\n * @param args.authenticationKey The authentication key\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version\n * @returns Promise<AccountAddress> The accountAddress associated with the authentication key\n */\n async lookupOriginalAccountAddress(args: {\n authenticationKey: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: LedgerVersionArg;\n }): Promise<AccountAddress> {\n return lookupOriginalAccountAddress({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries the current count of tokens owned by an account\n *\n * @example\n * const tokensCount = await aptos.getAccountTokensCount({accountAddress:\"0x456\"})\n *\n * @param args.accountAddress The account address\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns Current count of tokens owned by the account\n */\n async getAccountTokensCount(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.ACCOUNT_TRANSACTION_PROCESSOR,\n });\n return getAccountTokensCount({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries the account's current owned tokens.\n *\n * This query returns all tokens (v1 and v2 standards) an account owns, including NFTs, fungible, soulbound, etc.\n * If you want to get only the token from a specific standard, you can pass an optional tokenStandard param\n *\n * @example\n * const accountOwnedTokens = await aptos.getAccountOwnedTokens({accountAddress:\"0x456\"})\n *\n * @param args.accountAddress The account address we want to get the tokens for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.tokenStandard The NFT standard to query for\n * @param args.options.offset The number token to start returning results from\n * @param args.options.limit The number of results to return\n * @param args.options.orderBy The order to sort the tokens by\n * @returns Tokens array with the token data\n */\n async getAccountOwnedTokens(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountOwnedTokensQueryResponse[0]>;\n }): Promise<GetAccountOwnedTokensQueryResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getAccountOwnedTokens({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries all current tokens of a specific collection that an account owns by the collection address\n *\n * This query returns all tokens (v1 and v2 standards) an account owns, including NFTs, fungible, soulbound, etc.\n * If you want to get only the token from a specific standard, you can pass an optional tokenStandard param\n *\n * @example\n * const accountOwnedTokens = await aptos.getAccountOwnedTokensFromCollectionAddress({accountAddress:\"0x123\", collectionAddress:\"0x456\"})\n *\n * @param args.accountAddress The account address we want to get the tokens for\n * @param args.collectionAddress The address of the collection being queried\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.tokenStandard The NFT standard to query for\n * @param args.options.offset The number token to start returning results from\n * @param args.options.limit The number of results to return\n * @param args.options.orderBy The order to sort the tokens by\n * @returns Tokens array with the token data\n */\n async getAccountOwnedTokensFromCollectionAddress(args: {\n accountAddress: AccountAddressInput;\n collectionAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountOwnedTokensFromCollectionResponse[0]>;\n }): Promise<GetAccountOwnedTokensFromCollectionResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getAccountOwnedTokensFromCollectionAddress({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries for all collections that an account currently has tokens for.\n *\n * This query returns all tokens (v1 and v2 standards) an account owns, including NFTs, fungible, soulbound, etc.\n * If you want to get only the token from a specific standard, you can pass an optional tokenStandard param\n *\n * @example\n * const accountCollectionsWithOwnedTokens = await aptos.getAccountCollectionsWithOwnedTokens({accountAddress:\"0x123\"})\n *\n * @param args.accountAddress The account address we want to get the collections for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.tokenStandard The NFT standard to query for\n * @param args.options.offset The number collection to start returning results from\n * @param args.options.limit The number of results to return\n * @param args.options.orderBy The order to sort the tokens by\n * @returns Collections array with the collections data\n */\n async getAccountCollectionsWithOwnedTokens(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountCollectionsWithOwnedTokenResponse[0]>;\n }): Promise<GetAccountCollectionsWithOwnedTokenResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n return getAccountCollectionsWithOwnedTokens({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries the current count of transactions submitted by an account\n *\n * @example\n * const accountTransactionsCount = await aptos.getAccountTransactionsCount({accountAddress:\"0x123\"})\n *\n * @param args.accountAddress The account address we want to get the total count for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns Current count of transactions made by an account\n */\n async getAccountTransactionsCount(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.ACCOUNT_TRANSACTION_PROCESSOR,\n });\n return getAccountTransactionsCount({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries an account's coins data\n *\n * @example\n * const accountCoinsData = await aptos.getAccountCoinsData({accountAddress:\"0x123\"})\n *\n * @param args.accountAddress The account address we want to get the coins data for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.offset optional. The number coin to start returning results from\n * @param args.options.limit optional. The number of results to return\n * @param args.options.orderBy optional. The order to sort the coins by\n * @param args.options.where optional. Filter the results by\n * @returns Array with the coins data\n */\n async getAccountCoinsData(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs &\n OrderByArg<GetAccountCoinsDataResponse[0]> &\n WhereArg<CurrentFungibleAssetBalancesBoolExp>;\n }): Promise<GetAccountCoinsDataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n return getAccountCoinsData({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Queries the current count of an account's coins aggregated\n *\n * @example\n * const accountCoinsCount = await aptos.getAccountCoinsCount({accountAddress:\"0x123\"})\n *\n * @param args.accountAddress The account address we want to get the total count for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns Current count of the aggregated count of all account's coins\n */\n async getAccountCoinsCount(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n return getAccountCoinsCount({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries the account's APT amount\n *\n * @example\n * const accountAPTAmount = await aptos.getAccountAPTAmount({accountAddress:\"0x123\"})\n *\n * @param args.accountAddress The account address we want to get the total count for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns Current amount of account's APT\n */\n async getAccountAPTAmount(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n return this.getAccountCoinAmount({ coinType: APTOS_COIN, ...args });\n }\n\n /**\n * Queries the account's coin amount by the coin type\n *\n * @example\n * const accountCoinAmount = await aptos.getAccountCoinAmount({accountAddress:\"0x123\", coinType:\"0x1::aptos_coin::AptosCoin\"})\n *\n * @param args.accountAddress The account address we want to get the total count for\n * @param args.coinType The coin type to query\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @returns Current amount of account's coin\n */\n async getAccountCoinAmount(args: {\n accountAddress: AccountAddressInput;\n coinType: MoveStructId;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\n return getAccountCoinAmount({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries an account's owned objects\n *\n * @example\n * const accountOwnedObjects = await aptos.getAccountOwnedObjects({accountAddress:\"0x123\"})\n *\n * @param args.accountAddress The account address we want to get the objects for\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying\n * @param args.options.offset The starting position to start returning results from\n * @param args.options.limit The number of results to return\n * @param args.options.orderBy The order to sort the objects by\n * @returns Objects array with the object data\n */\n async getAccountOwnedObjects(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetAccountOwnedObjectsResponse[0]>;\n }): Promise<GetAccountOwnedObjectsResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.DEFAULT,\n });\n return getAccountOwnedObjects({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Derives an account by providing a private key.\n * This functions resolves the provided private key type and derives the public key from it.\n *\n * If the privateKey is a Secp256k1 type, it derives the account using the derived public key and\n * auth key using the SingleKey scheme locally.\n *\n * If the privateKey is a ED25519 type, it looks up the authentication key on chain, and uses it to resolve\n * whether it is a Legacy ED25519 key or a Unified ED25519 key. It then derives the account based\n * on that.\n *\n * @example\n * const account = await aptos.deriveAccountFromPrivateKey({privateKey:new Ed25519PrivateKey(\"0x123\")})\n *\n * @param args.privateKey An account private key\n * @returns Account type\n */\n async deriveAccountFromPrivateKey(args: { privateKey: PrivateKey }): Promise<AccountModule> {\n return deriveAccountFromPrivateKey({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/name}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * name namespace and without having a dependency cycle error.\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { Account, AccountAddress, AccountAddressInput } from \"../core\";\nimport { InputGenerateTransactionOptions } from \"../transactions/types\";\nimport { GetANSNameResponse, MoveAddressType, OrderByArg, PaginationArgs, WhereArg } from \"../types\";\nimport { GetNamesQuery } from \"../types/generated/operations\";\nimport { GetNames } from \"../types/generated/queries\";\nimport { CurrentAptosNamesBoolExp } from \"../types/generated/types\";\nimport { Network } from \"../utils/apiEndpoints\";\nimport { queryIndexer } from \"./general\";\nimport { view } from \"./view\";\nimport { generateTransaction } from \"./transactionSubmission\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\nexport const VALIDATION_RULES_DESCRIPTION = [\n \"A name must be between 3 and 63 characters long,\",\n \"and can only contain lowercase a-z, 0-9, and hyphens.\",\n \"A name may not start or end with a hyphen.\",\n].join(\" \");\n\n/**\n *\n * @param fragment A fragment of a name, either the domain or subdomain\n * @returns boolean indicating if the fragment is a valid fragment\n */\nexport function isValidANSSegment(fragment: string): boolean {\n if (!fragment) return false;\n if (fragment.length < 3) return false;\n if (fragment.length > 63) return false;\n // only lowercase a-z and 0-9 are allowed, along with -. a domain may not start or end with a hyphen\n if (!/^[a-z\\d][a-z\\d-]{1,61}[a-z\\d]$/.test(fragment)) return false;\n return true;\n}\n\n/**\n * Checks if an ANS name is valid or not\n *\n * @param name A string of the domain name, can include or exclude the .apt suffix\n */\nexport function isValidANSName(name: string): { domainName: string; subdomainName?: string } {\n const [first, second, ...rest] = name.replace(/\\.apt$/, \"\").split(\".\");\n\n if (rest.length > 0) {\n throw new Error(`${name} is invalid. A name can only have two parts, a domain and a subdomain separated by a \".\"`);\n }\n\n if (!isValidANSSegment(first)) {\n throw new Error(`${first} is not valid. ${VALIDATION_RULES_DESCRIPTION}`);\n }\n\n if (second && !isValidANSSegment(second)) {\n throw new Error(`${second} is not valid. ${VALIDATION_RULES_DESCRIPTION}`);\n }\n\n return {\n domainName: second || first,\n subdomainName: second ? first : undefined,\n };\n}\n\nexport const LOCAL_ANS_ACCOUNT_PK =\n process.env.ANS_TEST_ACCOUNT_PRIVATE_KEY ?? \"0x37368b46ce665362562c6d1d4ec01a08c8644c488690df5a17e13ba163e20221\";\nexport const LOCAL_ANS_ACCOUNT_ADDRESS =\n process.env.ANS_TEST_ACCOUNT_ADDRESS ?? \"0x585fc9f0f0c54183b039ffc770ca282ebd87307916c215a3e692f2f8e4305e82\";\n\nconst NetworkToAnsContract: Record<Network, string | null> = {\n [Network.TESTNET]: \"0x5f8fd2347449685cf41d4db97926ec3a096eaf381332be4f1318ad4d16a8497c\",\n [Network.MAINNET]: \"0x867ed1f6bf916171b1de3ee92849b8978b7d1b9e0a8cc982a3d19d535dfd9c0c\",\n [Network.LOCAL]: LOCAL_ANS_ACCOUNT_ADDRESS,\n [Network.CUSTOM]: null,\n [Network.DEVNET]: null,\n};\n\nfunction getRouterAddress(aptosConfig: AptosConfig): string {\n const address = NetworkToAnsContract[aptosConfig.network];\n if (!address) throw new Error(`The ANS contract is not deployed to ${aptosConfig.network}`);\n return address;\n}\n\nconst unwrapOption = <T>(option: any): T | undefined => {\n if (!!option && typeof option === \"object\" && \"vec\" in option && Array.isArray(option.vec)) {\n return option.vec[0];\n }\n\n return undefined;\n};\n\nexport async function getOwnerAddress(args: {\n aptosConfig: AptosConfig;\n name: string;\n}): Promise<AccountAddress | undefined> {\n const { aptosConfig, name } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n const { domainName, subdomainName } = isValidANSName(name);\n\n const res = await view({\n aptosConfig,\n payload: {\n function: `${routerAddress}::router::get_owner_addr`,\n functionArguments: [domainName, subdomainName],\n },\n });\n\n const owner = unwrapOption<MoveAddressType>(res[0]);\n\n return owner ? AccountAddress.from(owner) : undefined;\n}\n\nexport interface RegisterNameParameters {\n aptosConfig: AptosConfig;\n sender: Account;\n name: string;\n expiration:\n | { policy: \"domain\"; years?: 1 }\n | { policy: \"subdomain:follow-domain\" }\n | { policy: \"subdomain:independent\"; expirationDate: number };\n transferable?: boolean;\n toAddress?: AccountAddressInput;\n targetAddress?: AccountAddressInput;\n options?: InputGenerateTransactionOptions;\n}\n\nexport async function registerName(args: RegisterNameParameters): Promise<SimpleTransaction> {\n const { aptosConfig, expiration, name, sender, targetAddress, toAddress, options, transferable } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n const { domainName, subdomainName } = isValidANSName(name);\n\n const hasSubdomainPolicy =\n expiration.policy === \"subdomain:independent\" || expiration.policy === \"subdomain:follow-domain\";\n\n if (subdomainName && !hasSubdomainPolicy) {\n throw new Error(\n \"Subdomains must have an expiration policy of either 'subdomain:independent' or 'subdomain:follow-domain'\",\n );\n }\n\n if (hasSubdomainPolicy && !subdomainName) {\n throw new Error(`Policy is set to ${expiration.policy} but no subdomain was provided`);\n }\n\n if (expiration.policy === \"domain\") {\n const years = expiration.years ?? 1;\n if (years !== 1) {\n throw new Error(\"For now, names can only be registered for 1 year at a time\");\n }\n\n const secondsInYear = 31536000;\n const registrationDuration = years * secondsInYear;\n\n const transaction = await generateTransaction({\n aptosConfig,\n sender: sender.accountAddress.toString(),\n data: {\n function: `${routerAddress}::router::register_domain`,\n functionArguments: [domainName, registrationDuration, targetAddress, toAddress],\n },\n options,\n });\n\n return transaction;\n }\n\n // We are a subdomain\n if (!subdomainName) {\n throw new Error(`${expiration.policy} requires a subdomain to be provided.`);\n }\n\n const tldExpiration = await getExpiration({ aptosConfig, name: domainName });\n if (!tldExpiration) {\n throw new Error(\"The domain does not exist\");\n }\n\n const expirationDateInMillisecondsSinceEpoch =\n expiration.policy === \"subdomain:independent\" ? expiration.expirationDate : tldExpiration;\n\n if (expirationDateInMillisecondsSinceEpoch > tldExpiration) {\n throw new Error(\"The subdomain expiration time cannot be greater than the domain expiration time\");\n }\n\n const transaction = await generateTransaction({\n aptosConfig,\n sender: sender.accountAddress.toString(),\n data: {\n function: `${routerAddress}::router::register_subdomain`,\n functionArguments: [\n domainName,\n subdomainName,\n Math.round(expirationDateInMillisecondsSinceEpoch / 1000),\n expiration.policy === \"subdomain:follow-domain\" ? 1 : 0,\n !!transferable,\n targetAddress,\n toAddress,\n ],\n },\n options,\n });\n\n return transaction;\n}\n\nexport async function getExpiration(args: { aptosConfig: AptosConfig; name: string }): Promise<number | undefined> {\n const { aptosConfig, name } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n const { domainName, subdomainName } = isValidANSName(name);\n\n try {\n const res = await view({\n aptosConfig,\n payload: {\n function: `${routerAddress}::router::get_expiration`,\n functionArguments: [domainName, subdomainName],\n },\n });\n\n // Normalize expiration time from epoch seconds to epoch milliseconds\n return Number(res[0]) * 1000;\n } catch (e) {\n return undefined;\n }\n}\n\nexport async function getPrimaryName(args: {\n aptosConfig: AptosConfig;\n address: AccountAddressInput;\n}): Promise<string | undefined> {\n const { aptosConfig, address } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n\n const res = await view({\n aptosConfig,\n payload: {\n function: `${routerAddress}::router::get_primary_name`,\n functionArguments: [AccountAddress.from(address).toString()],\n },\n });\n\n const domainName = unwrapOption<MoveAddressType>(res[1]);\n const subdomainName = unwrapOption<MoveAddressType>(res[0]);\n\n if (!domainName) return undefined;\n\n return [subdomainName, domainName].filter(Boolean).join(\".\");\n}\n\nexport async function setPrimaryName(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n name?: string;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, name, options } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n\n if (!name) {\n const transaction = await generateTransaction({\n aptosConfig,\n sender: sender.accountAddress.toString(),\n data: {\n function: `${routerAddress}::router::clear_primary_name`,\n functionArguments: [],\n },\n options,\n });\n\n return transaction;\n }\n\n const { domainName, subdomainName } = isValidANSName(name);\n\n const transaction = await generateTransaction({\n aptosConfig,\n sender: sender.accountAddress.toString(),\n data: {\n function: `${routerAddress}::router::set_primary_name`,\n functionArguments: [domainName, subdomainName],\n },\n options,\n });\n\n return transaction;\n}\n\nexport async function getTargetAddress(args: {\n aptosConfig: AptosConfig;\n name: string;\n}): Promise<AccountAddress | undefined> {\n const { aptosConfig, name } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n const { domainName, subdomainName } = isValidANSName(name);\n\n const res = await view({\n aptosConfig,\n payload: {\n function: `${routerAddress}::router::get_target_addr`,\n functionArguments: [domainName, subdomainName],\n },\n });\n\n const target = unwrapOption<MoveAddressType>(res[0]);\n return target ? AccountAddress.from(target) : undefined;\n}\n\nexport async function setTargetAddress(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n name: string;\n address: AccountAddressInput;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, name, address, options } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n const { domainName, subdomainName } = isValidANSName(name);\n\n const transaction = await generateTransaction({\n aptosConfig,\n sender: sender.accountAddress.toString(),\n data: {\n function: `${routerAddress}::router::set_target_addr`,\n functionArguments: [domainName, subdomainName, address],\n },\n options,\n });\n\n return transaction;\n}\n\nexport async function getName(args: {\n aptosConfig: AptosConfig;\n name: string;\n}): Promise<GetANSNameResponse[0] | undefined> {\n const { aptosConfig, name } = args;\n const { domainName, subdomainName = \"\" } = isValidANSName(name);\n\n const where: CurrentAptosNamesBoolExp = {\n domain: { _eq: domainName },\n subdomain: { _eq: subdomainName },\n is_active: { _eq: true },\n };\n\n const data = await queryIndexer<GetNamesQuery>({\n aptosConfig,\n query: {\n query: GetNames,\n variables: {\n where_condition: where,\n limit: 1,\n },\n },\n originMethod: \"getName\",\n });\n\n // Convert the expiration_timestamp from an ISO string to milliseconds since epoch\n let res = data.current_aptos_names[0];\n if (res) {\n res = sanitizeANSName(res);\n }\n\n return res;\n}\n\ninterface QueryNamesOptions {\n options?: PaginationArgs & OrderByArg<GetANSNameResponse[0]> & WhereArg<CurrentAptosNamesBoolExp>;\n}\n\nexport interface GetAccountNamesArgs extends QueryNamesOptions {\n accountAddress: AccountAddressInput;\n}\n\nexport async function getAccountNames(\n args: { aptosConfig: AptosConfig } & GetAccountNamesArgs,\n): Promise<GetANSNameResponse> {\n const { aptosConfig, options, accountAddress } = args;\n\n const expirationDate = await getANSExpirationDate({ aptosConfig });\n\n const data = await queryIndexer<GetNamesQuery>({\n aptosConfig,\n originMethod: \"getAccountNames\",\n query: {\n query: GetNames,\n variables: {\n limit: options?.limit,\n offset: options?.offset,\n order_by: options?.orderBy,\n where_condition: {\n ...(args.options?.where ?? {}),\n owner_address: { _eq: accountAddress.toString() },\n expiration_timestamp: { _gte: expirationDate },\n },\n },\n },\n });\n\n return data.current_aptos_names.map(sanitizeANSName);\n}\n\nexport interface GetAccountDomainsArgs extends QueryNamesOptions {\n accountAddress: AccountAddressInput;\n}\n\nexport async function getAccountDomains(\n args: { aptosConfig: AptosConfig } & GetAccountDomainsArgs,\n): Promise<GetANSNameResponse> {\n const { aptosConfig, options, accountAddress } = args;\n\n const expirationDate = await getANSExpirationDate({ aptosConfig });\n\n const data = await queryIndexer<GetNamesQuery>({\n aptosConfig,\n originMethod: \"getAccountDomains\",\n query: {\n query: GetNames,\n variables: {\n limit: options?.limit,\n offset: options?.offset,\n order_by: options?.orderBy,\n where_condition: {\n ...(args.options?.where ?? {}),\n owner_address: { _eq: accountAddress.toString() },\n expiration_timestamp: { _gte: expirationDate },\n subdomain: { _eq: \"\" },\n },\n },\n },\n });\n\n return data.current_aptos_names.map(sanitizeANSName);\n}\n\nexport interface GetAccountSubdomainsArgs extends QueryNamesOptions {\n accountAddress: AccountAddressInput;\n}\n\nexport async function getAccountSubdomains(\n args: { aptosConfig: AptosConfig } & GetAccountSubdomainsArgs,\n): Promise<GetANSNameResponse> {\n const { aptosConfig, options, accountAddress } = args;\n\n const expirationDate = await getANSExpirationDate({ aptosConfig });\n\n const data = await queryIndexer<GetNamesQuery>({\n aptosConfig,\n originMethod: \"getAccountSubdomains\",\n query: {\n query: GetNames,\n variables: {\n limit: options?.limit,\n offset: options?.offset,\n order_by: options?.orderBy,\n where_condition: {\n ...(args.options?.where ?? {}),\n owner_address: { _eq: accountAddress.toString() },\n expiration_timestamp: { _gte: expirationDate },\n subdomain: { _neq: \"\" },\n },\n },\n },\n });\n\n return data.current_aptos_names.map(sanitizeANSName);\n}\n\nexport interface GetDomainSubdomainsArgs extends QueryNamesOptions {\n domain: string;\n}\n\nexport async function getDomainSubdomains(\n args: { aptosConfig: AptosConfig } & GetDomainSubdomainsArgs,\n): Promise<GetANSNameResponse> {\n const { aptosConfig, options, domain } = args;\n\n const data = await queryIndexer<GetNamesQuery>({\n aptosConfig,\n originMethod: \"getDomainSubdomains\",\n query: {\n query: GetNames,\n variables: {\n limit: options?.limit,\n offset: options?.offset,\n order_by: options?.orderBy,\n where_condition: {\n ...(args.options?.where ?? {}),\n domain: { _eq: domain },\n subdomain: { _neq: \"\" },\n is_active: { _eq: true },\n },\n },\n },\n });\n\n return data.current_aptos_names.map(sanitizeANSName);\n}\n\n/**\n * This function returns the expiration date in which a name is fully expired as\n * defined by the contract. The grace period allows for names to be past\n * expiration for a certain amount of time before they are released to the\n * public. The names will not function as normal, but the owner can renew\n * without others taking ownership of the name. At the time of writing, the\n * contract specified 30 days.\n *\n * @param args.aptosConfig an AptosConfig object\n * @returns\n */\nasync function getANSExpirationDate(args: { aptosConfig: AptosConfig }): Promise<string> {\n const { aptosConfig } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n\n const [gracePeriodInSeconds] = await view<[number]>({\n aptosConfig,\n payload: {\n function: `${routerAddress}::config::reregistration_grace_sec`,\n functionArguments: [],\n },\n });\n\n const gracePeriodInDays = gracePeriodInSeconds / 60 / 60 / 24;\n const now = () => new Date();\n return new Date(now().setDate(now().getDate() - gracePeriodInDays)).toISOString();\n}\n\nexport async function renewDomain(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n name: string;\n years?: 1;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, name, years = 1, options } = args;\n const routerAddress = getRouterAddress(aptosConfig);\n const renewalDuration = years * 31536000;\n const { domainName, subdomainName } = isValidANSName(name);\n\n if (subdomainName) {\n throw new Error(\"Subdomains cannot be renewed\");\n }\n\n if (years !== 1) {\n throw new Error(\"Currently, only 1 year renewals are supported\");\n }\n\n const transaction = await generateTransaction({\n aptosConfig,\n sender: sender.accountAddress.toString(),\n data: {\n function: `${routerAddress}::router::renew_domain`,\n functionArguments: [domainName, renewalDuration],\n },\n options,\n });\n\n return transaction;\n}\n\n/**\n * The indexer returns ISO strings for expiration, however the contract works in\n * epoch milliseconds. This function converts the ISO string to epoch\n * milliseconds. In the future, if other properties need sanitization, this can\n * be extended.\n */\nfunction sanitizeANSName(name: GetANSNameResponse[0]): GetANSNameResponse[0] {\n return {\n ...name,\n expiration_timestamp: new Date(name.expiration_timestamp).getTime(),\n };\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Account, AccountAddress, AccountAddressInput } from \"../core\";\nimport {\n RegisterNameParameters,\n getExpiration,\n getOwnerAddress,\n registerName,\n getPrimaryName,\n setPrimaryName,\n getTargetAddress,\n setTargetAddress,\n renewDomain,\n getName,\n getAccountDomains,\n GetAccountDomainsArgs,\n GetAccountSubdomainsArgs,\n getAccountSubdomains,\n getAccountNames,\n GetAccountNamesArgs,\n getDomainSubdomains,\n GetDomainSubdomainsArgs,\n} from \"../internal/ans\";\nimport { GetANSNameResponse } from \"../types\";\nimport { InputGenerateTransactionOptions } from \"../transactions/types\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\n/**\n * A class to handle all `ANS` operations\n */\nexport class ANS {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Retrieve the owner address of a domain name or subdomain name from the contract.\n *\n * @example\n * // Will return the owner address of \"test.aptos.apt\" or undefined\n * const owner = await aptos.getOwnerAddress({name: \"test.aptos\"})\n * // owner = 0x123...\n *\n * @param args.name - A string of the name to retrieve\n *\n * @returns AccountAddress if the name is owned, undefined otherwise\n */\n async getOwnerAddress(args: { name: string }): Promise<AccountAddress | undefined> {\n return getOwnerAddress({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Retrieve the expiration time of a domain name or subdomain name from the contract.\n *\n * @example\n * // Will return the expiration of \"test.aptos.apt\" or undefined\n * const exp = await aptos.getExpiration({name: \"test.aptos\"})\n * // new Date(exp) would give you the date in question: 2021-01-01T00:00:00.000Z\n *\n * @param args.name - A string of the name to retrieve\n *\n * @returns number as a unix timestamp in milliseconds.\n */\n async getExpiration(args: { name: string }): Promise<number | undefined> {\n return getExpiration({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Retrieve the target address of a domain or subdomain name. This is the\n * address the name points to for use on chain. Note, the target address can\n * point to addresses that are not the owner of the name\n *\n * @example\n * const targetAddr = await aptos.getTargetAddress({name: \"test.aptos\"})\n * // targetAddr = 0x123...\n *\n * @param args.name - A string of the name: primary, primary.apt, secondary.primary, secondary.primary.apt, etc.\n *\n * @returns AccountAddress if the name has a target, undefined otherwise\n */\n async getTargetAddress(args: { name: string }): Promise<AccountAddress | undefined> {\n return getTargetAddress({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Sets the target address of a domain or subdomain name. This is the\n * address the name points to for use on chain. Note, the target address can\n * point to addresses that are not the owner of the name\n *\n * @example\n * await aptos.setTargetAddress({sender: alice, name: \"test.aptos\", address: bob.accountAddress})\n * const address = await aptos.getTargetAddress({name: \"test.aptos\"})\n * // address = bob.accountAddress\n *\n * @param args.name - A string of the name: test.aptos.apt, test.apt, test, test.aptos, etc.\n * @param args.address - A AccountAddressInput of the address to set the domain or subdomain to\n *\n * @returns SimpleTransaction\n */\n async setTargetAddress(args: {\n sender: Account;\n name: string;\n address: AccountAddressInput;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return setTargetAddress({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Retrieve the primary name for an account. An account can have\n * multiple names that target it, but only a single name that is primary. An\n * account also may not have a primary name.\n *\n * @example\n * const name = await aptos.getPrimaryName({address: alice.accountAddress})\n * // name = test.aptos\n *\n * @param args.address - A AccountAddressInput (address) of the account\n *\n * @returns a string if the account has a primary name, undefined otherwise\n */\n async getPrimaryName(args: { address: AccountAddressInput }): Promise<string | undefined> {\n return getPrimaryName({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Sets the primary name for the sender. An account can have\n * multiple names that target it, but only a single name that is primary. An\n * account also may not have a primary name.\n *\n * @example\n * await aptos.setPrimaryName({sender: alice, name: \"test.aptos\"})\n * const primaryName = await aptos.getPrimaryName({address: alice.accountAddress})\n * // primaryName = test.aptos\n *\n * @param args.sender - The sender account\n * @param args.name - A string of the name: test, test.apt, test.aptos, test.aptos.apt, etc.\n *\n * @returns SimpleTransaction\n */\n async setPrimaryName(args: {\n sender: Account;\n name?: string;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return setPrimaryName({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Registers a new name\n *\n * @example\n * // An example of registering a subdomain name assuming def.apt is already registered\n * // and belongs to the sender alice.\n * const txn = aptos.registerName({\n * sender: alice,\n * name: \"test.aptos.apt\",\n * expiration: {\n * policy: \"subdomain:independent\",\n * expirationDate: Date.now() + 30 * 24 * 60 * 60 * 1000,\n * },\n * });\n *\n * @param args.sender - The sender account\n * @param args.name - A string of the name to register. This can be inclusive or exclusive of the .apt suffix.\n * Examples include: \"test\", \"test.apt\", \"test.aptos.apt\", etc.\n * @param args.expiration - An object with the expiration policy of the name.\n * @param args.expiration.policy - 'domain' | 'subdomain:follow-domain' | 'subdomain:independent'\n * - domain: Years is required and the name will expire after the given number of years.\n * - subdomain:follow-domain: The name will expire at the same time as the domain name.\n * - subdomain:independent: The name will expire at the given date.\n * @param args.expiration.expirationDate - An epoch number in milliseconds of\n * the date when the subdomain will expire. Only applicable when the policy is\n * set to 'subdomain:independent'.\n * @param args.transferable - Determines if the subdomain being minted is soul-bound. Applicable only to subdomains.\n * @param args.targetAddress optional - The address the domain name will resolve to. If not provided,\n * the sender's address will be used.\n * @param args.toAddress optional - The address to send the domain name to. If not provided,\n * the transaction will be sent to the router.\n *\n * @returns SimpleTransaction\n */\n async registerName(args: Omit<RegisterNameParameters, \"aptosConfig\">): Promise<SimpleTransaction> {\n return registerName({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Renews a domain name\n *\n * Note: If a domain name was minted with V1 of the contract, it will automatically be upgraded to V2 via this transaction.\n *\n * @example\n * await aptos.renewDomain({sender: alice, name: \"test\"})\n * // test.apt will be renewed for one year\n *\n * @param args.sender - The sender account\n * @param args.name - A string of the domain the subdomain will be under. The signer must be the domain owner.\n * Subdomains cannot be renewed.\n * @param args.years - The number of years to renew the name. Currently only one year is permitted.\n *\n * @returns SimpleTransaction\n */\n async renewDomain(args: {\n sender: Account;\n name: string;\n years?: 1;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return renewDomain({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches a single name from the indexer\n * @param args.name - A string of the name to retrieve, e.g. \"test.aptos.apt\"\n * or \"test.apt\" or \"test\". Can be inclusive or exclusive of the .apt suffix.\n * Can be a subdomain.\n *\n * @returns A promise of an ANSName or undefined\n */\n async getName(args: { name: string }): Promise<GetANSNameResponse[0] | undefined> {\n return getName({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches all names for an account (both top level domains and subdomains)\n *\n * @param args\n * @param args.accountAddress - A AccountAddressInput of the address to retrieve names for.\n * @param args.options.offset - Optional, the offset to start from when fetching names\n * @param args.options.limit - Optional, A number of the names to fetch per request\n * @param args.options.orderBy - The order to sort the names by\n * @param args.options.where - Additional filters to apply to the query\n *\n * @returns a promise of an array of ANSName\n */\n async getAccountNames(args: GetAccountNamesArgs): Promise<GetANSNameResponse> {\n return getAccountNames({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches all top level domain names for an account\n *\n * @param args\n * @param args.accountAddress - A AccountAddressInput of the address to retrieve domain names for.\n * @param args.options.offset - Optional, the offset to start from when fetching names\n * @param args.options.limit - Optional, A number of the names to fetch per request\n * @param args.options.orderBy - The order to sort the names by\n * @param args.options.where - Additional filters to apply to the query\n *\n * @returns a promise of an array of ANSName\n */\n async getAccountDomains(args: GetAccountDomainsArgs): Promise<GetANSNameResponse> {\n return getAccountDomains({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches all subdomains names for an account\n *\n * @param args\n * @param args.accountAddress - A AccountAddressInput of the address to retrieve subdomains names for.\n * @param args.options.offset - Optional, the offset to start from when fetching names\n * @param args.options.limit - Optional, A number of the names to fetch per request\n * @param args.options.orderBy - The order to sort the names by\n * @param args.options.where - Additional filters to apply to the query\n *\n * @returns a promise of an array of ANSName\n */\n async getAccountSubdomains(args: GetAccountSubdomainsArgs): Promise<GetANSNameResponse> {\n return getAccountSubdomains({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches all subdomains names for a given domain. Note, this will not return the domain itself.\n *\n * @param args\n * @param args.domain - A string of the domain name: eg. \"test.apt\" or \"test\" (without the suffix of .apt)\n * @param args.options.offset - Optional, the offset to start from when fetching names\n * @param args.options.limit - Optional, A number of the names to fetch per request\n * @param args.options.orderBy - The order to sort the names by\n * @param args.options.where - Additional filters to apply to the query\n *\n * @returns a promise of an array of ANSName\n */\n async getDomainSubdomains(args: GetDomainSubdomainsArgs): Promise<GetANSNameResponse> {\n return getDomainSubdomains({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Account } from \"./account\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { Coin } from \"./coin\";\nimport { DigitalAsset } from \"./digitalAsset\";\nimport { Event } from \"./event\";\nimport { Faucet } from \"./faucet\";\nimport { FungibleAsset } from \"./fungibleAsset\";\nimport { General } from \"./general\";\nimport { ANS } from \"./ans\";\nimport { Staking } from \"./staking\";\nimport { Transaction } from \"./transaction\";\n\n/**\n * This class is the main entry point into Aptos's\n * APIs and separates functionality into different namespaces.\n *\n * To use the SDK, create a new Aptos instance to get access\n * to all the sdk functionality.\n *\n * @example\n *\n * const aptos = new Aptos();\n */\nexport class Aptos {\n readonly config: AptosConfig;\n\n readonly account: Account;\n\n readonly ans: ANS;\n\n readonly coin: Coin;\n\n readonly digitalAsset: DigitalAsset;\n\n readonly event: Event;\n\n readonly faucet: Faucet;\n\n readonly fungibleAsset: FungibleAsset;\n\n readonly general: General;\n\n readonly staking: Staking;\n\n readonly transaction: Transaction;\n\n constructor(settings?: AptosConfig) {\n this.config = new AptosConfig(settings);\n this.account = new Account(this.config);\n this.ans = new ANS(this.config);\n this.coin = new Coin(this.config);\n this.digitalAsset = new DigitalAsset(this.config);\n this.event = new Event(this.config);\n this.faucet = new Faucet(this.config);\n this.fungibleAsset = new FungibleAsset(this.config);\n this.general = new General(this.config);\n this.staking = new Staking(this.config);\n this.transaction = new Transaction(this.config);\n }\n}\n\n// extends Aptos interface so all the methods and properties\n// from the other classes will be recognized by typescript.\nexport interface Aptos\n extends Account,\n ANS,\n Coin,\n DigitalAsset,\n Event,\n Faucet,\n FungibleAsset,\n General,\n Staking,\n Omit<Transaction, \"build\" | \"simulate\" | \"submit\" | \"batch\"> {}\n\n/**\nIn TypeScript, we can’t inherit or extend from more than one class,\nMixins helps us to get around that by creating a partial classes\nthat we can combine to form a single class that contains all the methods and properties from the partial classes.\n{@link https://www.typescriptlang.org/docs/handbook/mixins.html#alternative-pattern}\n\nHere, we combine any subclass and the Aptos class.\n*/\nfunction applyMixin(targetClass: any, baseClass: any, baseClassProp: string) {\n // Mixin instance methods\n Object.getOwnPropertyNames(baseClass.prototype).forEach((propertyName) => {\n const propertyDescriptor = Object.getOwnPropertyDescriptor(baseClass.prototype, propertyName);\n if (!propertyDescriptor) return;\n // eslint-disable-next-line func-names\n propertyDescriptor.value = function (...args: any) {\n return (this as any)[baseClassProp][propertyName](...args);\n };\n Object.defineProperty(targetClass.prototype, propertyName, propertyDescriptor);\n });\n}\n\napplyMixin(Aptos, Account, \"account\");\napplyMixin(Aptos, ANS, \"ans\");\napplyMixin(Aptos, Coin, \"coin\");\napplyMixin(Aptos, DigitalAsset, \"digitalAsset\");\napplyMixin(Aptos, Event, \"event\");\napplyMixin(Aptos, Faucet, \"faucet\");\napplyMixin(Aptos, FungibleAsset, \"fungibleAsset\");\napplyMixin(Aptos, General, \"general\");\napplyMixin(Aptos, Staking, \"staking\");\napplyMixin(Aptos, Transaction, \"transaction\");\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Network } from \"../utils/apiEndpoints\";\nimport { OrderBy, TokenStandard } from \"./indexer\";\n\nexport * from \"./indexer\";\n\nexport enum MimeType {\n /**\n * JSON representation, used for transaction submission and accept type JSON output\n */\n JSON = \"application/json\",\n /**\n * BCS representation, used for accept type BCS output\n */\n BCS = \"application/x-bcs\",\n /**\n * BCS representation, used for transaction submission in BCS input\n */\n BCS_SIGNED_TRANSACTION = \"application/x.aptos.signed_transaction+bcs\",\n BCS_VIEW_FUNCTION = \"application/x.aptos.view_function+bcs\",\n}\n\n/**\n * Hex data as input to a function\n */\nexport type HexInput = string | Uint8Array;\n\n/**\n * TypeTag enum as they are represented in Rust\n * {@link https://github.com/aptos-labs/aptos-core/blob/main/third_party/move/move-core/types/src/language_storage.rs#L27}\n */\nexport enum TypeTagVariants {\n Bool = 0,\n U8 = 1,\n U64 = 2,\n U128 = 3,\n Address = 4,\n Signer = 5,\n Vector = 6,\n Struct = 7,\n U16 = 8,\n U32 = 9,\n U256 = 10,\n Reference = 254, // This is specifically a placeholder and does not represent a real type\n Generic = 255, // This is specifically a placeholder and does not represent a real type\n}\n\n/**\n * Script transaction arguments enum as they are represented in Rust\n * {@link https://github.com/aptos-labs/aptos-core/blob/main/third_party/move/move-core/types/src/transaction_argument.rs#L11}\n */\nexport enum ScriptTransactionArgumentVariants {\n U8 = 0,\n U64 = 1,\n U128 = 2,\n Address = 3,\n U8Vector = 4,\n Bool = 5,\n U16 = 6,\n U32 = 7,\n U256 = 8,\n}\n\n/**\n * Transaction payload enum as they are represented in Rust\n * {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/mod.rs#L478}\n */\nexport enum TransactionPayloadVariants {\n Script = 0,\n EntryFunction = 2,\n Multisig = 3,\n}\n\n/**\n * Transaction variants enum as they are represented in Rust\n * {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/mod.rs#L440}\n */\nexport enum TransactionVariants {\n MultiAgentTransaction = 0,\n FeePayerTransaction = 1,\n}\n\n/**\n * Transaction Authenticator enum as they are represented in Rust\n * {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/authenticator.rs#L44}\n */\nexport enum TransactionAuthenticatorVariant {\n Ed25519 = 0,\n MultiEd25519 = 1,\n MultiAgent = 2,\n FeePayer = 3,\n SingleSender = 4,\n}\n\n/**\n * Transaction Authenticator enum as they are represented in Rust\n * {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/authenticator.rs#L414}\n */\nexport enum AccountAuthenticatorVariant {\n Ed25519 = 0,\n MultiEd25519 = 1,\n SingleKey = 2,\n MultiKey = 3,\n}\n\nexport enum AnyPublicKeyVariant {\n Ed25519 = 0,\n Secp256k1 = 1,\n}\n\nexport enum AnySignatureVariant {\n Ed25519 = 0,\n Secp256k1 = 1,\n}\n\n/**\n * BCS types\n */\nexport type Uint8 = number;\nexport type Uint16 = number;\nexport type Uint32 = number;\nexport type Uint64 = bigint;\nexport type Uint128 = bigint;\nexport type Uint256 = bigint;\nexport type AnyNumber = number | bigint;\n\n/**\n * Set of configuration options that can be provided when initializing the SDK.\n * The purpose of these options is to configure various aspects of the SDK's\n * behavior and interaction with the Aptos network\n */\nexport type AptosSettings = {\n readonly network?: Network;\n\n readonly fullnode?: string;\n\n readonly faucet?: string;\n\n readonly indexer?: string;\n\n readonly clientConfig?: ClientConfig;\n\n readonly client?: Client;\n\n readonly fullnodeConfig?: FullNodeConfig;\n\n readonly indexerConfig?: IndexerConfig;\n\n readonly faucetConfig?: FaucetConfig;\n};\n\n/**\n *\n * Controls the number of results that are returned and the starting position of those results.\n * @param offset parameter specifies the starting position of the query result within the set of data. Default is 0.\n * @param limit specifies the maximum number of items or records to return in a query result. Default is 25.\n */\nexport interface PaginationArgs {\n offset?: AnyNumber;\n limit?: number;\n}\n\nexport interface TokenStandardArg {\n tokenStandard?: TokenStandard;\n}\n\nexport interface OrderByArg<T extends {}> {\n orderBy?: OrderBy<T>;\n}\n\nexport interface WhereArg<T extends {}> {\n where?: T;\n}\n\n/**\n * QUERY TYPES\n */\n\n/**\n * A configuration object we can pass with the request to the server.\n *\n * @param API_KEY - api key generated from developer portal {@link https://developers.aptoslabs.com/manage/api-keys}}\n * @param HEADERS - extra headers we want to send with the request\n * @param WITH_CREDENTIALS - whether to carry cookies. By default, it is set to true and cookies will be sent\n */\nexport type ClientConfig = ClientHeadersType & {\n WITH_CREDENTIALS?: boolean;\n API_KEY?: string;\n};\n\n/**\n * A Fullnode only configuration object\n *\n * @param HEADERS - extra headers we want to send with the request\n */\nexport type FullNodeConfig = ClientHeadersType;\n\n/**\n * An Indexer only configuration object\n *\n * @param HEADERS - extra headers we want to send with the request\n */\nexport type IndexerConfig = ClientHeadersType;\n\n/**\n * A Faucet only configuration object\n *\n * @param HEADERS - extra headers we want to send with the request\n * @param AUTH_TOKEN - an auth token to send with a faucet request\n */\nexport type FaucetConfig = ClientHeadersType & {\n AUTH_TOKEN?: string;\n};\n\n/**\n * General type definition for client HEADERS\n */\nexport type ClientHeadersType = {\n HEADERS?: Record<string, string | number | boolean>;\n};\n\nexport interface ClientRequest<Req> {\n url: string;\n method: \"GET\" | \"POST\";\n originMethod?: string;\n body?: Req;\n contentType?: string;\n params?: any;\n overrides?: ClientConfig & FullNodeConfig & IndexerConfig & FaucetConfig;\n headers?: Record<string, any>;\n}\n\nexport interface ClientResponse<Res> {\n status: number;\n statusText: string;\n data: Res;\n config?: any;\n request?: any;\n response?: any;\n headers?: any;\n}\n\nexport interface Client {\n provider<Req, Res>(requestOptions: ClientRequest<Req>): Promise<ClientResponse<Res>>;\n}\n\n/**\n * The API request type\n *\n * @param url - the url to make the request to, i.e https://fullnode.devnet.aptoslabs.com/v1\n * @param method - the request method \"GET\" | \"POST\"\n * @param endpoint (optional) - the endpoint to make the request to, i.e transactions\n * @param body (optional) - the body of the request\n * @param contentType (optional) - the content type to set the `content-type` header to,\n * by default is set to `application/json`\n * @param params (optional) - query params to add to the request\n * @param originMethod (optional) - the local method the request came from\n * @param overrides (optional) - a `ClientConfig` object type to override request data\n */\nexport type AptosRequest = {\n url: string;\n method: \"GET\" | \"POST\";\n path?: string;\n body?: any;\n contentType?: string;\n acceptType?: string;\n params?: Record<string, string | AnyNumber | boolean | undefined>;\n originMethod?: string;\n overrides?: ClientConfig & FullNodeConfig & IndexerConfig & FaucetConfig;\n};\n\n/**\n * Specifies ledger version of transactions. By default latest version will be used\n */\nexport type LedgerVersionArg = {\n ledgerVersion?: AnyNumber;\n};\n\n/**\n * RESPONSE TYPES\n */\n\n/**\n * Type holding the outputs of the estimate gas API\n */\nexport type GasEstimation = {\n /**\n * The deprioritized estimate for the gas unit price\n */\n deprioritized_gas_estimate?: number;\n /**\n * The current estimate for the gas unit price\n */\n gas_estimate: number;\n /**\n * The prioritized estimate for the gas unit price\n */\n prioritized_gas_estimate?: number;\n};\n\nexport type MoveResource = {\n type: MoveStructId;\n data: {};\n};\n\nexport type AccountData = {\n sequence_number: string;\n authentication_key: string;\n};\n\nexport type MoveModuleBytecode = {\n bytecode: string;\n abi?: MoveModule;\n};\n\n/**\n * TRANSACTION TYPES\n */\n\nexport enum TransactionResponseType {\n Pending = \"pending_transaction\",\n User = \"user_transaction\",\n Genesis = \"genesis_transaction\",\n BlockMetadata = \"block_metadata_transaction\",\n StateCheckpoint = \"state_checkpoint_transaction\",\n Validator = \"validator_transaction\",\n}\n\nexport type TransactionResponse = PendingTransactionResponse | CommittedTransactionResponse;\nexport type CommittedTransactionResponse =\n | UserTransactionResponse\n | GenesisTransactionResponse\n | BlockMetadataTransactionResponse\n | StateCheckpointTransactionResponse\n | ValidatorTransactionResponse;\n\nexport function isPendingTransactionResponse(response: TransactionResponse): response is PendingTransactionResponse {\n return response.type === TransactionResponseType.Pending;\n}\n\nexport function isUserTransactionResponse(response: TransactionResponse): response is UserTransactionResponse {\n return response.type === TransactionResponseType.User;\n}\n\nexport function isGenesisTransactionResponse(response: TransactionResponse): response is GenesisTransactionResponse {\n return response.type === TransactionResponseType.Genesis;\n}\n\nexport function isBlockMetadataTransactionResponse(\n response: TransactionResponse,\n): response is BlockMetadataTransactionResponse {\n return response.type === TransactionResponseType.BlockMetadata;\n}\n\nexport function isStateCheckpointTransactionResponse(\n response: TransactionResponse,\n): response is StateCheckpointTransactionResponse {\n return response.type === TransactionResponseType.StateCheckpoint;\n}\n\nexport function isValidatorTransactionResponse(\n response: TransactionResponse,\n): response is ValidatorTransactionResponse {\n return response.type === TransactionResponseType.Validator;\n}\n\nexport type PendingTransactionResponse = {\n type: TransactionResponseType.Pending;\n hash: string;\n sender: string;\n sequence_number: string;\n max_gas_amount: string;\n gas_unit_price: string;\n expiration_timestamp_secs: string;\n payload: TransactionPayloadResponse;\n signature?: TransactionSignature;\n};\n\nexport type UserTransactionResponse = {\n type: TransactionResponseType.User;\n version: string;\n hash: string;\n state_change_hash: string;\n event_root_hash: string;\n state_checkpoint_hash: string | null;\n gas_used: string;\n /**\n * Whether the transaction was successful\n */\n success: boolean;\n /**\n * The VM status of the transaction, can tell useful information in a failure\n */\n vm_status: string;\n accumulator_root_hash: string;\n /**\n * Final state of resources changed by the transaction\n */\n changes: Array<WriteSetChange>;\n sender: string;\n sequence_number: string;\n max_gas_amount: string;\n gas_unit_price: string;\n expiration_timestamp_secs: string;\n payload: TransactionPayloadResponse;\n signature?: TransactionSignature;\n /**\n * Events generated by the transaction\n */\n events: Array<Event>;\n timestamp: string;\n};\n\nexport type GenesisTransactionResponse = {\n type: TransactionResponseType.Genesis;\n version: string;\n hash: string;\n state_change_hash: string;\n event_root_hash: string;\n state_checkpoint_hash?: string;\n gas_used: string;\n /**\n * Whether the transaction was successful\n */\n success: boolean;\n /**\n * The VM status of the transaction, can tell useful information in a failure\n */\n vm_status: string;\n accumulator_root_hash: string;\n /**\n * Final state of resources changed by the transaction\n */\n changes: Array<WriteSetChange>;\n payload: GenesisPayload;\n /**\n * Events emitted during genesis\n */\n events: Array<Event>;\n};\n\nexport type BlockMetadataTransactionResponse = {\n type: TransactionResponseType.BlockMetadata;\n version: string;\n hash: string;\n state_change_hash: string;\n event_root_hash: string;\n state_checkpoint_hash: string | null;\n gas_used: string;\n /**\n * Whether the transaction was successful\n */\n success: boolean;\n /**\n * The VM status of the transaction, can tell useful information in a failure\n */\n vm_status: string;\n accumulator_root_hash: string;\n /**\n * Final state of resources changed by the transaction\n */\n changes: Array<WriteSetChange>;\n id: string;\n epoch: string;\n round: string;\n /**\n * The events emitted at the block creation\n */\n events: Array<Event>;\n /**\n * Previous block votes\n */\n previous_block_votes_bitvec: Array<number>;\n proposer: string;\n /**\n * The indices of the proposers who failed to propose\n */\n failed_proposer_indices: Array<number>;\n timestamp: string;\n};\n\nexport type StateCheckpointTransactionResponse = {\n type: TransactionResponseType.StateCheckpoint;\n version: string;\n hash: string;\n state_change_hash: string;\n event_root_hash: string;\n state_checkpoint_hash: string | null;\n gas_used: string;\n /**\n * Whether the transaction was successful\n */\n success: boolean;\n /**\n * The VM status of the transaction, can tell useful information in a failure\n */\n vm_status: string;\n accumulator_root_hash: string;\n /**\n * Final state of resources changed by the transaction\n */\n changes: Array<WriteSetChange>;\n timestamp: string;\n};\n\nexport type ValidatorTransactionResponse = {\n type: TransactionResponseType.Validator;\n version: string;\n hash: string;\n state_change_hash: string;\n event_root_hash: string;\n state_checkpoint_hash: string | null;\n gas_used: string;\n /**\n * Whether the transaction was successful\n */\n success: boolean;\n /**\n * The VM status of the transaction, can tell useful information in a failure\n */\n vm_status: string;\n accumulator_root_hash: string;\n /**\n * Final state of resources changed by the transaction\n */\n changes: Array<WriteSetChange>;\n /**\n * The events emitted by the validator transaction\n */\n events: Array<Event>;\n timestamp: string;\n};\n\n/**\n * WRITESET CHANGE TYPES\n */\n\nexport type WriteSetChange =\n | WriteSetChangeDeleteModule\n | WriteSetChangeDeleteResource\n | WriteSetChangeDeleteTableItem\n | WriteSetChangeWriteModule\n | WriteSetChangeWriteResource\n | WriteSetChangeWriteTableItem;\n\nexport type WriteSetChangeDeleteModule = {\n type: string;\n address: string;\n /**\n * State key hash\n */\n state_key_hash: string;\n module: MoveModuleId;\n};\n\nexport type WriteSetChangeDeleteResource = {\n type: string;\n address: string;\n state_key_hash: string;\n resource: string;\n};\n\nexport type WriteSetChangeDeleteTableItem = {\n type: string;\n state_key_hash: string;\n handle: string;\n key: string;\n data?: DeletedTableData;\n};\n\nexport type WriteSetChangeWriteModule = {\n type: string;\n address: string;\n state_key_hash: string;\n data: MoveModuleBytecode;\n};\n\nexport type WriteSetChangeWriteResource = {\n type: string;\n address: string;\n state_key_hash: string;\n data: MoveResource;\n};\n\nexport type WriteSetChangeWriteTableItem = {\n type: string;\n state_key_hash: string;\n handle: string;\n key: string;\n value: string;\n data?: DecodedTableData;\n};\n\nexport type DecodedTableData = {\n /**\n * Key of table in JSON\n */\n key: any;\n /**\n * Type of key\n */\n key_type: string;\n /**\n * Value of table in JSON\n */\n value: any;\n /**\n * Type of value\n */\n value_type: string;\n};\n\n/**\n * Deleted table data\n */\nexport type DeletedTableData = {\n /**\n * Deleted key\n */\n key: any;\n /**\n * Deleted key type\n */\n key_type: string;\n};\n\nexport type TransactionPayloadResponse = EntryFunctionPayloadResponse | ScriptPayloadResponse | MultisigPayloadResponse;\n\nexport type EntryFunctionPayloadResponse = {\n type: string;\n function: MoveFunctionId;\n /**\n * Type arguments of the function\n */\n type_arguments: Array<string>;\n /**\n * Arguments of the function\n */\n arguments: Array<any>;\n};\n\nexport type ScriptPayloadResponse = {\n type: string;\n code: MoveScriptBytecode;\n /**\n * Type arguments of the function\n */\n type_arguments: Array<string>;\n /**\n * Arguments of the function\n */\n arguments: Array<any>;\n};\n\nexport type MultisigPayloadResponse = {\n type: string;\n multisig_address: string;\n transaction_payload?: EntryFunctionPayloadResponse;\n};\n\nexport type GenesisPayload = {\n type: string;\n write_set: WriteSet;\n};\n\n/**\n * Move script bytecode\n */\nexport type MoveScriptBytecode = {\n bytecode: string;\n abi?: MoveFunction;\n};\n\n/**\n * These are the JSON representations of transaction signatures returned from the node API.\n */\nexport type TransactionSignature =\n | TransactionEd25519Signature\n | TransactionSecp256k1Signature\n | TransactionMultiEd25519Signature\n | TransactionMultiAgentSignature\n | TransactionFeePayerSignature;\n\nexport function isEd25519Signature(signature: TransactionSignature): signature is TransactionFeePayerSignature {\n return \"signature\" in signature && signature.signature === \"ed25519_signature\";\n}\n\nexport function isSecp256k1Signature(signature: TransactionSignature): signature is TransactionFeePayerSignature {\n return \"signature\" in signature && signature.signature === \"secp256k1_ecdsa_signature\";\n}\n\nexport function isMultiAgentSignature(signature: TransactionSignature): signature is TransactionMultiAgentSignature {\n return signature.type === \"multi_agent_signature\";\n}\n\nexport function isFeePayerSignature(signature: TransactionSignature): signature is TransactionFeePayerSignature {\n return signature.type === \"fee_payer_signature\";\n}\n\nexport function isMultiEd25519Signature(\n signature: TransactionSignature,\n): signature is TransactionMultiEd25519Signature {\n return signature.type === \"multi_ed25519_signature\";\n}\n\nexport type TransactionEd25519Signature = {\n type: string;\n public_key: string;\n signature: \"ed25519_signature\";\n};\n\nexport type TransactionSecp256k1Signature = {\n type: string;\n public_key: string;\n signature: \"secp256k1_ecdsa_signature\";\n};\n\nexport type TransactionMultiEd25519Signature = {\n type: \"multi_ed25519_signature\";\n /**\n * The public keys for the Ed25519 signature\n */\n public_keys: Array<string>;\n /**\n * Signature associated with the public keys in the same order\n */\n signatures: Array<string>;\n /**\n * The number of signatures required for a successful transaction\n */\n threshold: number;\n bitmap: string;\n};\n\nexport type TransactionMultiAgentSignature = {\n type: \"multi_agent_signature\";\n sender: AccountSignature;\n /**\n * The other involved parties' addresses\n */\n secondary_signer_addresses: Array<string>;\n /**\n * The associated signatures, in the same order as the secondary addresses\n */\n secondary_signers: Array<AccountSignature>;\n};\n\nexport type TransactionFeePayerSignature = {\n type: \"fee_payer_signature\";\n sender: AccountSignature;\n /**\n * The other involved parties' addresses\n */\n secondary_signer_addresses: Array<string>;\n /**\n * The associated signatures, in the same order as the secondary addresses\n */\n secondary_signers: Array<AccountSignature>;\n fee_payer_address: string;\n fee_payer_signer: AccountSignature;\n};\n\n/**\n * The union of all single account signatures.\n */\nexport type AccountSignature =\n | TransactionEd25519Signature\n | TransactionSecp256k1Signature\n | TransactionMultiEd25519Signature;\n\nexport type WriteSet = ScriptWriteSet | DirectWriteSet;\n\nexport type ScriptWriteSet = {\n type: string;\n execute_as: string;\n script: ScriptPayloadResponse;\n};\n\nexport type DirectWriteSet = {\n type: string;\n changes: Array<WriteSetChange>;\n events: Array<Event>;\n};\n\nexport type EventGuid = {\n creation_number: string;\n account_address: string;\n};\n\nexport type Event = {\n guid: EventGuid;\n sequence_number: string;\n type: string;\n /**\n * The JSON representation of the event\n */\n data: any;\n};\n\n/**\n * Map of Move types to local TypeScript types\n */\nexport type MoveUint8Type = number;\nexport type MoveUint16Type = number;\nexport type MoveUint32Type = number;\nexport type MoveUint64Type = string;\nexport type MoveUint128Type = string;\nexport type MoveUint256Type = string;\nexport type MoveAddressType = string;\nexport type MoveObjectType = string;\nexport type MoveOptionType = MoveType | null | undefined;\n/**\n * This is the format for a fully qualified struct, resource, or entry function in Move.\n */\nexport type MoveStructId = `${string}::${string}::${string}`;\n// These are the same, unfortunately, it reads really strangely to take a StructId for a Function and there wasn't a\n// good middle ground name.\nexport type MoveFunctionId = MoveStructId;\n\n// TODO: Add support for looking up ABI to add proper typing\nexport type MoveStructType = {};\n\nexport type MoveType =\n | boolean\n | string\n | MoveUint8Type\n | MoveUint16Type\n | MoveUint32Type\n | MoveUint64Type\n | MoveUint128Type\n | MoveUint256Type\n | MoveAddressType\n | MoveObjectType\n | MoveStructType\n | Array<MoveType>;\n\n/**\n * Possible Move values acceptable by move functions (entry, view)\n *\n * Map of a Move value to the corresponding TypeScript value\n *\n * `Bool -> boolean`\n *\n * `u8, u16, u32 -> number`\n *\n * `u64, u128, u256 -> string`\n *\n * `String -> string`\n *\n * `Address -> 0x${string}`\n *\n * `Struct - 0x${string}::${string}::${string}`\n *\n * `Object -> 0x${string}`\n *\n * `Vector -> Array<MoveValue>`\n *\n * `Option -> MoveValue | null | undefined`\n */\nexport type MoveValue =\n | boolean\n | string\n | MoveUint8Type\n | MoveUint16Type\n | MoveUint32Type\n | MoveUint64Type\n | MoveUint128Type\n | MoveUint256Type\n | MoveAddressType\n | MoveObjectType\n | MoveStructId\n | MoveOptionType\n | Array<MoveValue>;\n\n/**\n * Move module id is a string representation of Move module.\n * Module name is case-sensitive.\n */\nexport type MoveModuleId = `${string}::${string}`;\n\n/**\n * Move function visibility\n */\nexport enum MoveFunctionVisibility {\n PRIVATE = \"private\",\n PUBLIC = \"public\",\n FRIEND = \"friend\",\n}\n\n/**\n * Move function ability\n */\nexport enum MoveAbility {\n STORE = \"store\",\n DROP = \"drop\",\n KEY = \"key\",\n COPY = \"copy\",\n}\n\n/**\n * Move abilities tied to the generic type param and associated with the function that uses it\n */\nexport type MoveFunctionGenericTypeParam = {\n constraints: Array<MoveAbility>;\n};\n\n/**\n * Move struct field\n */\nexport type MoveStructField = {\n name: string;\n type: string;\n};\n\n/**\n * A Move module\n */\nexport type MoveModule = {\n address: string;\n name: string;\n /**\n * Friends of the module\n */\n friends: Array<MoveModuleId>;\n /**\n * Public functions of the module\n */\n exposed_functions: Array<MoveFunction>;\n /**\n * Structs of the module\n */\n structs: Array<MoveStruct>;\n};\n\n/**\n * A move struct\n */\nexport type MoveStruct = {\n name: string;\n /**\n * Whether the struct is a native struct of Move\n */\n is_native: boolean;\n /**\n * Abilities associated with the struct\n */\n abilities: Array<MoveAbility>;\n /**\n * Generic types associated with the struct\n */\n generic_type_params: Array<MoveFunctionGenericTypeParam>;\n /**\n * Fields associated with the struct\n */\n fields: Array<MoveStructField>;\n};\n\n/**\n * Move function\n */\nexport type MoveFunction = {\n name: string;\n visibility: MoveFunctionVisibility;\n /**\n * Whether the function can be called as an entry function directly in a transaction\n */\n is_entry: boolean;\n /**\n * Whether the function is a view function or not\n */\n is_view: boolean;\n /**\n * Generic type params associated with the Move function\n */\n generic_type_params: Array<MoveFunctionGenericTypeParam>;\n /**\n * Parameters associated with the move function\n */\n params: Array<string>;\n /**\n * Return type of the function\n */\n return: Array<string>;\n};\n\nexport enum RoleType {\n VALIDATOR = \"validator\",\n FULL_NODE = \"full_node\",\n}\n\nexport type LedgerInfo = {\n /**\n * Chain ID of the current chain\n */\n chain_id: number;\n epoch: string;\n ledger_version: string;\n oldest_ledger_version: string;\n ledger_timestamp: string;\n node_role: RoleType;\n oldest_block_height: string;\n block_height: string;\n /**\n * Git hash of the build of the API endpoint. Can be used to determine the exact\n * software version used by the API endpoint.\n */\n git_hash?: string;\n};\n\n/**\n * A Block type\n */\nexport type Block = {\n block_height: string;\n block_hash: string;\n block_timestamp: string;\n first_version: string;\n last_version: string;\n /**\n * The transactions in the block in sequential order\n */\n transactions?: Array<TransactionResponse>;\n};\n\n// REQUEST TYPES\n\n/**\n * Table Item request for the GetTableItem API\n */\nexport type TableItemRequest = {\n key_type: MoveValue;\n value_type: MoveValue;\n /**\n * The value of the table item's key\n */\n key: any;\n};\n\n/**\n * A list of Authentication Key schemes that are supported by Aptos.\n *\n * They are combinations of signing schemes and derive schemes.\n */\nexport type AuthenticationKeyScheme = SigningScheme | DeriveScheme;\n\nexport enum SigningScheme {\n /**\n * For Ed25519PublicKey\n */\n Ed25519 = 0,\n /**\n * For MultiEd25519PublicKey\n */\n MultiEd25519 = 1,\n /**\n * For SingleKey ecdsa\n */\n SingleKey = 2,\n\n MultiKey = 3,\n}\n\nexport enum SigningSchemeInput {\n /**\n * For Ed25519PublicKey\n */\n Ed25519 = 0,\n /**\n * For Secp256k1Ecdsa\n */\n Secp256k1Ecdsa = 2,\n}\n\n/**\n * Scheme used for deriving account addresses from other data\n */\nexport enum DeriveScheme {\n /**\n * Derives an address using an AUID, used for objects\n */\n DeriveAuid = 251,\n /**\n * Derives an address from another object address\n */\n DeriveObjectAddressFromObject = 252,\n /**\n * Derives an address from a GUID, used for objects\n */\n DeriveObjectAddressFromGuid = 253,\n /**\n * Derives an address from seed bytes, used for named objects\n */\n DeriveObjectAddressFromSeed = 254,\n /**\n * Derives an address from seed bytes, used for resource accounts\n */\n DeriveResourceAccountAddress = 255,\n}\n\n/**\n * Option properties to pass for waitForTransaction() function\n */\nexport type WaitForTransactionOptions = {\n timeoutSecs?: number;\n checkSuccess?: boolean;\n waitForIndexer?: boolean;\n};\n\n/**\n * Input type to generate an account using Single Signer\n * Ed25519 or Legacy Ed25519\n */\nexport type GenerateAccountWithEd25519 = {\n scheme: SigningSchemeInput.Ed25519;\n legacy: boolean;\n};\n\n/**\n * Input type to generate an account using Single Signer\n * Secp256k1\n */\nexport type GenerateAccountWithSingleSignerSecp256k1Key = {\n scheme: SigningSchemeInput.Secp256k1Ecdsa;\n legacy?: false;\n};\n\nexport type GenerateAccount = GenerateAccountWithEd25519 | GenerateAccountWithSingleSignerSecp256k1Key;\n","import {\n InternalMoveFunction,\n InternalMoveFunctionVisibility,\n InternalMoveModule,\n InternalMoveStruct,\n InternalMoveStructField,\n parseMoveType\n} from '@typemove/move'\nimport {\n MoveFunctionVisibility,\n MoveFunction,\n MoveModuleBytecode,\n MoveStruct,\n MoveStructField\n} from '@aptos-labs/ts-sdk'\n\nexport function toInternalModule(module: MoveModuleBytecode): InternalMoveModule {\n if (!module.abi) {\n throw Error('module with no ABI found')\n }\n const abi = module.abi\n return {\n address: abi.address,\n exposedFunctions: abi.exposed_functions.map(toInternalFunction),\n name: abi.name,\n structs: abi.structs.map(toInternalStruct)\n }\n}\n\nexport function toInternalFunction(func: MoveFunction): InternalMoveFunction {\n let visibility\n switch (func.visibility) {\n case MoveFunctionVisibility.PRIVATE:\n visibility = InternalMoveFunctionVisibility.PRIVATE\n break\n case MoveFunctionVisibility.PUBLIC:\n visibility = InternalMoveFunctionVisibility.PUBLIC\n break\n case MoveFunctionVisibility.FRIEND:\n visibility = InternalMoveFunctionVisibility.FRIEND\n break\n }\n return {\n typeParams: func.generic_type_params,\n isEntry: func.is_entry,\n isView: func.is_view,\n name: func.name,\n params: func.params.map(parseMoveType),\n return: func.return.map(parseMoveType),\n visibility: visibility\n }\n}\n\nexport function toInternalStruct(struct: MoveStruct): InternalMoveStruct {\n return {\n abilities: struct.abilities,\n fields: struct.fields.map(toInternalField),\n typeParams: struct.generic_type_params,\n isNative: struct.is_native,\n name: struct.name\n }\n}\n\nexport function toInternalField(module: MoveStructField): InternalMoveStructField {\n return {\n name: module.name,\n type: parseMoveType(module.type)\n }\n}\n","import {\n ChainAdapter,\n moduleQname,\n SPLITTER,\n TypeDescriptor,\n InternalMoveModule,\n InternalMoveStruct\n} from '@typemove/move'\n\nimport { Aptos, Event, MoveModuleBytecode, MoveResource } from '@aptos-labs/ts-sdk'\nimport { toInternalModule } from './to-internal.js'\n\nexport class AptosChainAdapter extends ChainAdapter<MoveModuleBytecode, Event | MoveResource> {\n // static INSTANCE = new AptosChainAdapter()\n client: Aptos\n constructor(client: Aptos) {\n super()\n this.client = client\n }\n\n async fetchModules(account: string): Promise<MoveModuleBytecode[]> {\n return await this.client.getAccountModules({\n accountAddress: account\n })\n }\n\n async fetchModule(account: string, module: string): Promise<MoveModuleBytecode> {\n return await this.client.getAccountModule({\n accountAddress: account,\n moduleName: module\n })\n }\n\n toInternalModules(modules: MoveModuleBytecode[]): InternalMoveModule[] {\n return modules.flatMap((m) => (m.abi ? [toInternalModule(m)] : []))\n }\n\n getMeaningfulFunctionParams(params: TypeDescriptor[]): TypeDescriptor[] {\n if (params.length === 0) {\n return params\n }\n if (params[0].qname === 'signer' && params[0].reference) {\n params = params.slice(1)\n }\n return params\n }\n\n getAllEventStructs(modules: InternalMoveModule[]) {\n const eventMap = new Map<string, InternalMoveStruct>()\n\n for (const module of modules) {\n const qname = moduleQname(module)\n\n for (const struct of module.structs) {\n const abilities = new Set(struct.abilities)\n if (abilities.has('drop') && abilities.has('store')) {\n eventMap.set(qname + SPLITTER + struct.name, struct)\n }\n }\n }\n return eventMap\n\n // const eventMap = new Map<string, InternalMoveStruct>()\n // const structMap = new Map<string, InternalMoveStruct>()\n // for (const module of modules) {\n // const qname = moduleQname(module)\n // for (const struct of module.structs) {\n // structMap.set(qname + SPLITTER + struct.name, struct)\n // }\n // }\n //\n // for (const module of modules) {\n // for (const struct of module.structs) {\n // for (const field of struct.fields) {\n // const t = field.type\n // if (t.qname === '0x1::event::EventHandle') {\n // const event = t.typeArgs[0].qname\n // const eventStruct = structMap.get(event)\n // if (eventStruct) {\n // eventMap.set(event, eventStruct)\n // }\n // }\n // }\n // }\n // }\n // return eventMap\n }\n\n getType(data: Event | MoveResource): string {\n return data.type\n }\n\n getData(data: Event | MoveResource) {\n if ('data' in data && 'type' in data) {\n return data.data\n }\n return data\n }\n\n async getChainId(): Promise<string> {\n return (await this.client.getChainId()).toString()\n }\n // validateAndNormalizeAddress(address: string): string {\n // return validateAndNormalizeAddress(address)\n // }\n}\n"],"mappings":";8jBAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAEA,IAAIC,GAAM,OAAO,UAAU,eACvBC,GAAS,IASb,SAASC,IAAS,CAAC,CASf,OAAO,SACTA,GAAO,UAAY,OAAO,OAAO,IAAI,EAMhC,IAAIA,GAAO,EAAE,YAAWD,GAAS,KAYxC,SAASE,GAAGC,EAAIC,EAASC,EAAM,CAC7B,KAAK,GAAKF,EACV,KAAK,QAAUC,EACf,KAAK,KAAOC,GAAQ,EACtB,CAaA,SAASC,GAAYC,EAASC,EAAOL,EAAIC,EAASC,EAAM,CACtD,GAAI,OAAOF,GAAO,WAChB,MAAM,IAAI,UAAU,iCAAiC,EAGvD,IAAIM,EAAW,IAAIP,GAAGC,EAAIC,GAAWG,EAASF,CAAI,EAC9CK,EAAMV,GAASA,GAASQ,EAAQA,EAEpC,OAAKD,EAAQ,QAAQG,CAAG,EAC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H,CAEA,kBAAkBC,EAA6B,CAC7C,OAAOA,EAAQ,QAASC,GAAOA,EAAE,IAAM,CAACC,GAAiBD,CAAC,CAAC,EAAI,CAAA,CAAG,CACpE,CAEA,4BAA4BE,EAAwB,CAClD,OAAIA,EAAO,SAAW,GAGlBA,EAAO,CAAC,EAAE,QAAU,UAAYA,EAAO,CAAC,EAAE,YAC5CA,EAASA,EAAO,MAAM,CAAC,GAElBA,CACT,CAEA,mBAAmBH,EAA6B,CAC9C,IAAMI,EAAW,IAAI,IAErB,QAAWL,KAAUC,EAAS,CAC5B,IAAMK,EAAQC,GAAYP,CAAM,EAEhC,QAAWQ,KAAUR,EAAO,QAAS,CACnC,IAAMS,EAAY,IAAI,IAAID,EAAO,SAAS,EACtCC,EAAU,IAAI,MAAM,GAAKA,EAAU,IAAI,OAAO,GAChDJ,EAAS,IAAIC,EAAQI,GAAWF,EAAO,KAAMA,CAAM,GAIzD,OAAOH,CA0BT,CAEA,QAAQM,EAA0B,CAChC,OAAOA,EAAK,IACd,CAEA,QAAQA,EAA0B,CAChC,MAAI,SAAUA,GAAQ,SAAUA,EACvBA,EAAK,KAEPA,CACT,CAEA,MAAM,YAAU,CACd,OAAQ,MAAM,KAAK,OAAO,WAAU,GAAI,SAAQ,CAClD","names":["require_eventemitter3","__commonJSMin","exports","module","has","prefix","Events","EE","fn","context","once","addListener","emitter","event","listener","evt","clearEvent","EventEmitter","names","events","name","handlers","l","ee","listeners","a1","a2","a3","a4","a5","len","args","i","length","j","require_dist","__commonJSMin","exports","module","typedArrayTypeNames","isTypedArrayName","name","objectTypeNames","isObjectTypeName","primitiveTypeNames","isPrimitiveTypeName","isOfType","type","value","toString","getObjectType","objectTypeName","is","isObjectOfType","tagType","isNumberType","assertion","_a","_b","_c","_d","hasPromiseAPI","targetEnum","instance","class_","prototype","isValidLength","range","NODE_TYPE_ELEMENT","DOM_PROPERTIES_TO_CHECK","property","isAbsoluteMod2","remainder","isWhiteSpaceString","predicateOnArray","method","predicate","values","singlePredicate","assertType","condition","description","options","multipleValues","valuesMessage","singleValue","require_p_cancelable","__commonJSMin","exports","module","CancelError","reason","PCancelable","userFn","arguments_","resolve","reject","onCancel","executor","onResolve","value","onReject","error","handler","boolean","onFulfilled","onRejected","onFinally","require_source","__commonJSMin","exports","module","isTLSSocket","socket","deferToConnect","fn","listeners","hasConnectListener","hasSecureConnectListener","hasCloseListener","onConnect","require_source","__commonJSMin","exports","module","defer_to_connect_1","util_1","nodejsMajorVersion","timer","request","timings","handleError","origin","emit","event","args","onAbort","onSocket","socket","lookupListener","onUpload","_a","response","require_source","__commonJSMin","exports","module","V4MAPPED","ADDRCONFIG","ALL","AsyncResolver","dnsLookup","promisify","os","kCacheableLookupCreateConnection","kCacheableLookupInstance","kExpires","supportsALL","verifyAgent","agent","map4to6","entries","entry","getIfaceInfo","has4","has6","device","iface","isIterable","map","ttl","all","CacheableLookup","cache","maxTtl","fallbackDuration","errorTtl","resolver","lookup","interval","servers","hostname","options","callback","result","cached","filtered","_iface","error","pending","newPromise","wrap","promise","A","AAAA","aTtl","aaaaTtl","cacheTtl","now","data","cacheError","query","ms","nextRemovalTime","nextExpiry","expires","require_normalize_url","__commonJSMin","exports","module","DATA_URL_DEFAULT_MIME_TYPE","DATA_URL_DEFAULT_CHARSET","testParameter","name","filters","filter","normalizeDataURL","urlString","stripHash","match","type","data","hash","mediaType","isBase64","mimeType","normalizedMediaType","attribute","key","value","string","normalizeUrl","options","hasRelativeProtocol","urlObj","pathComponents","lastComponent","oldUrlString","require_end_of_stream","__commonJSMin","exports","module","once","noop","isRequest","stream","isChildProcess","eos","opts","callback","ws","rs","readable","writable","cancelled","onlegacyfinish","onfinish","onend","onexit","exitCode","onerror","err","onclose","onclosenexttick","onrequest","require_pump","__commonJSMin","exports","module","once","eos","fs","noop","ancient","isFn","fn","isFS","stream","isRequest","destroyer","reading","writing","callback","closed","err","destroyed","call","pipe","from","to","pump","streams","error","destroys","i","require_buffer_stream","__commonJSMin","exports","module","PassThroughStream","options","array","encoding","isBuffer","objectMode","stream","length","chunks","chunk","require_get_stream","__commonJSMin","exports","module","BufferConstants","pump","bufferStream","MaxBufferError","getStream","inputStream","options","maxBuffer","stream","resolve","reject","rejectPromise","error","require_http_cache_semantics","__commonJSMin","exports","module","statusCodeCacheableByDefault","understoodStatuses","errorStatusCodes","hopByHopHeaders","excludedFromRevalidationUpdate","toNumberOrZero","s","n","isErrorResponse","response","parseCacheControl","header","cc","parts","part","k","v","formatCacheControl","req","res","shared","cacheHeuristic","immutableMinTimeToLive","ignoreCargoCult","_fromObject","requestCC","allowHeadMethod","fields","name","inHeaders","headers","tokens","warnings","warning","age","serverDate","residentTime","defaultMinTtl","expires","lastModified","staleIfErrorAge","staleWhileRevalidateAge","obj","incomingReq","etags","etag","request","matches","newResponse","require_lowercase_keys","__commonJSMin","exports","module","object","result","key","value","require_src","__commonJSMin","exports","module","Readable","lowercaseKeys","Response","statusCode","headers","body","url","require_mimic_response","__commonJSMin","exports","module","knownProps","fromStream","toStream","fromProps","prop","require_src","__commonJSMin","exports","module","PassThrough","mimicResponse","cloneResponse","response","clone","require_json_buffer","__commonJSMin","exports","stringify","o","s","array","first","k","ignore","key","value","require_src","__commonJSMin","exports","module","EventEmitter","JSONB","loadStore","options","adapters","adapter","__require","iterableAdapters","Keyv","uri","emitErrors","adapterOptions","compression","error","generateIterator","iterator","key","raw","data","element","keys","store","isArray","keyPrefixed","promises","values","value","row","index","ttl","expires","x","require_src","__commonJSMin","exports","module","EventEmitter","urlLib","normalizeUrl","getStream","CachePolicy","Response","lowercaseKeys","cloneResponse","Keyv","CacheableRequest","request","cacheAdapter","opts","cb","url","normalizeUrlObject","pathname","searchParts","search","urlObjectToRequestOptions","ee","normalizedUrlString","key","revalidate","madeRequest","makeRequest","requestErrored","requestErrorCallback","requestErrorPromise","resolve","handler","response","revalidatedPolicy","headers","clonedResponse","bodyPromise","body","value","ttl","error","req","get","cacheEntry","policy","errorHandler","options","require_mimic_response","__commonJSMin","exports","module","knownProperties","fromStream","toStream","fromProperties","properties","property","value","require_decompress_response","__commonJSMin","exports","module","Transform","PassThrough","zlib","mimicResponse","response","contentEncoding","isBrotli","isEmpty","checker","data","_encoding","callback","finalStream","error","decompressStream","require_quick_lru","__commonJSMin","exports","module","QuickLRU","options","key","value","deleted","item","oldCacheSize","require_agent","__commonJSMin","exports","module","EventEmitter","tls","http2","QuickLRU","kCurrentStreamsCount","kRequest","kOriginSet","kGracefullyClosing","nameKeys","getSortedIndex","array","value","compare","low","high","mid","compareSessions","a","b","closeCoveredSessions","where","session","coveredSession","origin","gracefullyClose","closeSessionIfCovered","getSessions","agent","isFree","result","normalizedOptions","filtered","Agent","timeout","maxSessions","maxFreeSessions","maxCachedTlsSessions","url","servername","options","normalized","key","normalizedOrigin","item","listeners","resolve","reject","sessions","maxConcurrentStreams","currentStreamsCount","optimalSession","sessionMaxConcurrentStreams","sessionCurrentStreamsCount","error","removeFromQueue","entry","name","receivedSettings","wasFree","tlsSession","processListeners","listener","headers","streamOptions","stream","isEmpty","port","host","reason","entriesOfAuthority","require_incoming_message","__commonJSMin","exports","module","Readable","IncomingMessage","socket","highWaterMark","error","ms","callback","require_url_to_options","__commonJSMin","exports","module","url","options","require_proxy_events","__commonJSMin","exports","module","from","to","events","event","args","require_is_request_pseudo_header","__commonJSMin","exports","module","header","require_errors","__commonJSMin","exports","module","makeError","Base","key","getMessage","args","type","valid","isManyTypes","require_client_request","__commonJSMin","exports","module","http2","Writable","Agent","globalAgent","IncomingMessage","urlToOptions","proxyEvents","isRequestPseudoHeader","ERR_INVALID_ARG_TYPE","ERR_INVALID_PROTOCOL","ERR_HTTP_HEADERS_SENT","ERR_INVALID_HTTP_TOKEN","ERR_HTTP_INVALID_HEADER_VALUE","ERR_INVALID_CHAR","HTTP2_HEADER_STATUS","HTTP2_HEADER_METHOD","HTTP2_HEADER_PATH","HTTP2_METHOD_CONNECT","kHeaders","kOrigin","kSession","kOptions","kFlushedHeaders","kJobs","isValidHttpToken","isInvalidHeaderValue","ClientRequest","input","options","callback","hasInput","port","host","timeout","header","value","chunk","encoding","callWrite","callEnd","error","isConnectMethod","onStream","stream","waitForEnd","fn","args","headers","flags","rawHeaders","response","trailers","rawTrailers","res","socket","job","name","ms","applyTimeout","_value","require_resolve_alpn","__commonJSMin","exports","module","tls","options","connect","resolve","reject","timeout","socket","callback","socketPromise","onTimeout","error","require_calculate_server_name","__commonJSMin","exports","module","net","options","servername","hostHeader","require_auto","__commonJSMin","exports","module","http","https","resolveALPN","QuickLRU","Http2ClientRequest","calculateServerName","urlToOptions","cache","queue","installSocket","agent","socket","options","onFree","onClose","onRemove","resolveProtocol","name","path","resultPromise","alpnProtocol","globalAgent","defaultCreateConnection","error","input","callback","isHttps","agents","require_source","__commonJSMin","exports","module","http2","agent","ClientRequest","IncomingMessage","auto","request","url","options","callback","get","req","require_is_form_data","__commonJSMin","exports","is_1","body","require_get_body_size","__commonJSMin","exports","fs_1","util_1","is_1","is_form_data_1","statAsync","body","headers","size","require_proxy_events","__commonJSMin","exports","default_1","from","to","events","fns","event","args","require_unhandle","__commonJSMin","exports","handlers","origin","event","fn","handler","require_timed_out","__commonJSMin","exports","net","unhandle_1","reentry","noop","TimeoutError","threshold","event","request","delays","options","cancelers","once","unhandleAll","addTimeout","delay","callback","_a","timeout","cancel","host","hostname","timeoutHandler","cancelTimeouts","error","response","socketTimeoutHandler","socket","socketPath","hasPath","cancelTimeout","timeConnect","timeRequest","require_url_to_options","__commonJSMin","exports","is_1","url","options","require_options_to_url","__commonJSMin","exports","url_1","keys","origin","options","_a","_b","url","searchIndex","key","require_weakable_map","__commonJSMin","exports","WeakableMap","key","value","require_get_buffer","__commonJSMin","exports","getBuffer","stream","chunks","length","chunk","require_dns_ip_version","__commonJSMin","exports","conversionTable","value","dnsLookupIpVersion","require_is_response_ok","__commonJSMin","exports","response","statusCode","limitStatusCode","require_deprecation_warning","__commonJSMin","exports","alreadyWarned","message","require_normalize_arguments","__commonJSMin","exports","is_1","normalizeArguments","options","defaults","retry","retryObject","method","pagination","require_calculate_retry_delay","__commonJSMin","exports","calculateRetryDelay","attemptCount","retryOptions","error","retryAfter","hasMethod","hasErrorCode","hasStatusCode","noise","require_core","__commonJSMin","exports","util_1","stream_1","fs_1","url_1","http","http_1","https","http_timer_1","cacheable_lookup_1","CacheableRequest","decompressResponse","http2wrapper","lowercaseKeys","is_1","get_body_size_1","is_form_data_1","proxy_events_1","timed_out_1","url_to_options_1","options_to_url_1","weakable_map_1","get_buffer_1","dns_ip_version_1","is_response_ok_1","deprecation_warning_1","normalize_arguments_1","calculate_retry_delay_1","globalDnsCache","kRequest","kResponse","kResponseSize","kDownloadedSize","kBodySize","kUploadedSize","kServerResponsesPiped","kUnproxyEvents","kIsFromCache","kCancelTimeouts","kStartedReading","kStopReading","kTriggerRead","kBody","kJobs","kOriginalResponse","kRetryTimeout","supportsBrotli","validateSearchParameters","searchParameters","key","value","isClientRequest","clientRequest","cacheableStore","waitForOpenFile","file","resolve","reject","onError","error","redirectCodes","nonEnumerableProperties","sources","to","properties","source","name","RequestError","message","self","_a","_b","Request","indexOfMessage","thisStackTrace","errorStackTrace","MaxRedirectsError","request","HTTPError","response","CacheError","UploadError","TimeoutError","timings","ReadError","UnsupportedProtocolError","options","proxiedRequestEvents","url","defaults","unlockWrite","lockWrite","json","body","form","normalizedURL","job","_c","_d","_e","rawOptions","prefixUrl","protocol","cookieJar","setCookie","getCookieString","cache","requestOptions","handler","result","event","areHooksDefault","onLockedWrite","headers","isForm","isJSON","isBody","hasPayload","cannotHaveBody","isTrue","noContentType","uploadBodySize","statusCode","typedResponse","rawCookies","promises","rawCookie","p","isUnixSocketURL","redirectBuffer","redirectUrl","redirectString","hook","destination","isAllowed","timeout","responseEventName","currentRequest","cacheRequest","requestOrPromise","cookieString","agent","matches","socketPath","path","isHttps","fallbackFn","realFn","fn","requestOrResponse","error_","retryCount","typedError","backoff","retryAfter","retry","data","progress","chunk","encoding","callback","write","endRequest","percent","require_types","__commonJSMin","exports","__createBinding","o","m","k","k2","__exportStar","p","core_1","ParseError","error","response","options","CancelError","request","require_parse_body","__commonJSMin","exports","types_1","parseBody","response","responseType","parseJson","encoding","rawBody","error","require_as_promise","__commonJSMin","exports","__createBinding","o","m","k","k2","__exportStar","p","events_1","is_1","PCancelable","types_1","parse_body_1","core_1","proxy_events_1","get_buffer_1","is_response_ok_1","proxiedRequestEvents","asPromise","normalizedOptions","globalRequest","globalResponse","emitter","promise","resolve","reject","onCancel","makeRequest","retryCount","request","response","_a","rawBody","contentEncoding","isCompressed","options","error","index","hook","updatedOptions","typedOptions","onError","previousBody","newRetryCount","_b","event","fn","shortcut","responseType","newPromise","headers","require_create_rejection","__commonJSMin","exports","types_1","createRejection","error","beforeErrorGroups","promise","hooks","hook","error_","returnPromise","require_deep_freeze","__commonJSMin","exports","is_1","deepFreeze","object","value","require_types","__commonJSMin","exports","require_create","__commonJSMin","exports","__createBinding","o","m","k","k2","__exportStar","p","is_1","as_promise_1","create_rejection_1","core_1","deep_freeze_1","errors","delay","ms","resolve","normalizeArguments","mergeOptions","sources","mergedOptions","source","getPromiseOrStream","options","isGotInstance","value","aliases","next","callInitHooks","hooks","hook","create","defaults","fn","root","result","newOptions","typedResult","promiseThen","promiseCatch","promiseFianlly","got","url","_defaults","_a","_b","iteration","iterateHandlers","initHookError","error","normalizedOptions","instancesOrOptions","optionsArray","handlers","isMutableDefaults","handler","paginateEach","pagination","all","countLimit","numberOfRequests","parsed","current","item","optionsToMerge","results","method","require_source","__commonJSMin","exports","module","__createBinding","o","m","k","k2","__exportStar","p","url_1","create_1","defaults","computedValue","response","items","next","item","parsed","text","object","got","import_chain","ParsingError","message","invalidReason","init_utils","HexInvalidReason","Hex","_Hex","data","bytesToHex","str","input","ParsingError","hexToBytes","error","hexInput","other","value","index","MAX_U8_NUMBER","MAX_U16_NUMBER","MAX_U32_NUMBER","MAX_U64_BIG_INT","MAX_U128_BIG_INT","MAX_U256_BIG_INT","h","i","j","g","b","d","c","a","e","f","Serializable","serializer","Serializer","bcsBytes","Hex","length","bytes","newBuffer","values","fn","bytesLength","value","dv","textEncoder","ensureBoolean","byteValue","low","MAX_U32_NUMBER","high","MAX_U64_BIG_INT","MAX_U128_BIG_INT","val","valueArray","item","__decorateClass","checkNumberRange","MAX_U8_NUMBER","MAX_U16_NUMBER","MAX_U256_BIG_INT","outOfRangeErrorMessage","min","max","validateNumberInRange","minValue","maxValue","valueBigInt","target","propertyKey","descriptor","childFunction","init_utils","AddressInvalidReason","_AccountAddress","Serializable","input","ParsingError","byte","hex","bytesToHex","serializer","bcsBytes","deserializer","bytes","address","parsedInput","addressBytes","hexToBytes","error","args","other","value","index","AccountAddress","TokenActivitiesFieldsFragmentDoc","AnsTokenFragmentFragmentDoc","CurrentTokenOwnershipFieldsFragmentDoc","GetAccountCoinsCount","GetAccountCoinsData","GetAccountCollectionsWithOwnedTokens","GetAccountOwnedObjects","GetAccountOwnedTokens","GetAccountOwnedTokensByTokenData","GetAccountOwnedTokensFromCollection","GetAccountTokensCount","GetAccountTransactionsCount","GetChainTopUserTransactions","GetCollectionData","GetCurrentFungibleAssetBalances","GetDelegatedStakingActivities","GetEvents","GetFungibleAssetActivities","GetFungibleAssetMetadata","GetNames","GetNumberOfDelegators","GetProcessorStatus","GetTokenActivity","GetCurrentTokenOwnership","GetTokenData","AptosApiError","request","response","message","VERSION","errors","request","options","client","url","method","body","contentType","params","overrides","originMethod","headers","VERSION","aptosRequest","aptosConfig","apiType","path","fullUrl","response","result","AptosApiError","indexerResponse","errorMessage","get","options","aptosConfig","overrides","params","contentType","acceptType","path","originMethod","type","url","aptosRequest","getAptosFullNode","paginateWithCursor","out","cursor","requestParams","response","post","options","type","originMethod","path","body","acceptType","contentType","params","aptosConfig","overrides","url","aptosRequest","postAptosFullNode","postAptosIndexer","postAptosFaucet","modifiedAptosConfig","getLedgerInfo","args","aptosConfig","data","getAptosFullNode","getBlockByVersion","ledgerVersion","options","getBlockByHeight","blockHeight","getTableItem","handle","postAptosFullNode","getChainTopUserTransactions","limit","queryIndexer","GetChainTopUserTransactions","query","originMethod","postAptosIndexer","getProcessorStatuses","GetProcessorStatus","getIndexerLastSuccessVersion","response","getProcessorStatus","processorType","getNumberOfDelegators","args","aptosConfig","poolAddress","address","AccountAddress","data","queryIndexer","GetNumberOfDelegators","getNumberOfDelegatorsForAllPools","options","query","getDelegatedStakingActivities","delegatorAddress","GetDelegatedStakingActivities","sleep","timeMs","resolve","cache","memoizeAsync","func","key","ttlMs","args","value","timestamp","result","AptosApiType","APTOS_COIN","RAW_TRANSACTION_SALT","RAW_TRANSACTION_WITH_DATA_SALT","ProcessorType","getTransactions","args","aptosConfig","options","paginateWithCursor","getGasPriceEstimation","memoizeAsync","data","getAptosFullNode","getTransactionByVersion","ledgerVersion","getTransactionByHash","transactionHash","isTransactionPending","e","longWaitForTransaction","waitForTransaction","timeoutSecs","checkSuccess","isPending","timeElapsed","lastTxn","lastError","backoffIntervalMs","backoffMultiplier","handleAPIError","AptosApiError","startTime","sleep","WaitForTransactionError","FailedTransactionError","waitForIndexer","processorType","minimumLedgerVersion","timeoutMilliseconds","indexerVersion","getIndexerLastSuccessVersion","getProcessorStatus","message","lastSubmittedTransaction","transaction","waitForIndexerOnVersion","args","waitForIndexer","Staking","config","args","waitForIndexerOnVersion","getNumberOfDelegators","getNumberOfDelegatorsForAllPools","getDelegatedStakingActivities","Identifier","_Identifier","Serializable","identifier","serializer","deserializer","TypeTag","Serializable","deserializer","index","TypeTagBool","TypeTagU8","TypeTagU64","TypeTagU128","TypeTagAddress","TypeTagSigner","TypeTagVector","TypeTagStruct","TypeTagU16","TypeTagU32","TypeTagU256","TypeTagGeneric","_TypeTagBool","serializer","_deserializer","_TypeTagU8","_TypeTagU16","_TypeTagU32","_TypeTagU64","_TypeTagU128","_TypeTagU256","_TypeTagAddress","_TypeTagSigner","TypeTagReference","_TypeTagReference","value","_TypeTagGeneric","_TypeTagVector","_TypeTagStruct","typePredicate","typeArg","StructTag","address","moduleName","structName","AccountAddress","_StructTag","module_name","name","type_args","Identifier","typeArgs","stringStructTag","StructTag","AccountAddress","Identifier","objectStructTag","typeArg","StructTag","AccountAddress","Identifier","isValidIdentifier","str","isValidWhitespaceCharacter","char","isGeneric","consumeWhitespace","tagStr","pos","i","innerChar","TypeTagParserErrorType","TypeTagParserError","typeTagStr","invalidReason","parseTypeTag","typeStr","options","allowGenerics","saved","innerTypes","curTypes","cur","currentStr","expectedTypes","newType","parseTypeTagInner","savedPop","savedStr","savedTypes","savedExpectedTypes","parsedTypeTag","nextChar","types","TypeTagReference","TypeTagSigner","TypeTagBool","TypeTagAddress","TypeTagU8","TypeTagU16","TypeTagU32","TypeTagU64","TypeTagU128","TypeTagU256","TypeTagVector","TypeTagGeneric","structParts","TypeTagStruct","StructTag","AccountAddress","Identifier","Bool","_Bool","Serializable","value","ensureBoolean","serializer","bcsBytes","deserializer","U8","_U8","validateNumberInRange","MAX_U8_NUMBER","U16","_U16","MAX_U16_NUMBER","U32","_U32","MAX_U32_NUMBER","U64","_U64","MAX_U64_BIG_INT","U128","_U128","MAX_U128_BIG_INT","U256","_U256","MAX_U256_BIG_INT","MoveVector","_MoveVector","Serializable","values","serializer","bcsBytes","U8","numbers","hex","Hex","v","U16","U32","U64","U128","U256","Bool","MoveString","deserializer","cls","length","i","_MoveString","value","fixedStringBytes","MoveOption","_MoveOption","vector","FixedBytes","_FixedBytes","Serializable","value","Hex","serializer","deserializer","length","bytes","isBool","arg","isString","isNumber","isLargeNumber","isNull","isEncodedEntryFunctionArgument","isBcsBool","isBcsU8","isBcsU16","isBcsU32","isBcsU64","isBcsU128","isBcsU256","isBcsAddress","isBcsString","isBcsFixedBytes","MoveVector","MoveOption","Bool","AccountAddress","MoveString","FixedBytes","U8","U16","U32","U64","U128","U256","isScriptDataInput","throwTypeMismatch","expectedType","position","findFirstNonSignerArg","functionAbi","index","param","getFunctionParts","functionArg","funcNameParts","moduleAddress","moduleName","functionName","Signature","Serializable","bytes","Hex","convertSigningMessage","message","Hex","init_hmac","init_sha512","init_sha512","nfkd","str","normalize","norm","words","salt","passphrase","nfkd","mnemonicToSeedSync","mnemonic","passphrase","pbkdf2","sha512","normalize","salt","APTOS_HARDENED_REGEX","APTOS_BIP44_REGEX","KeyType","HARDENED_OFFSET","isValidBIP44Path","path","isValidHardenedPath","deriveKey","hashSeed","data","digest","hmac","sha512","CKDPriv","key","chainCode","index","buffer","indexBytes","zero","removeApostrophes","val","splitPath","mnemonicToSeed","mnemonic","normalizedMnemonic","part","mnemonicToSeedSync","PublicKey","Serializable","bytes","Hex","AccountPublicKey","init_sha3","_AuthenticationKey","Serializable","args","data","hex","Hex","serializer","deserializer","bytes","scheme","input","inputBytes","hashInput","hash","sha3Hash","hashDigest","publicKey","AccountAddress","AuthenticationKey","init_ed25519","L","_Ed25519PublicKey","AccountPublicKey","hexInput","hex","Hex","args","message","signature","Ed25519Signature","messageToVerify","convertSigningMessage","messageBytes","signatureBytes","publicKeyBytes","ed25519","AuthenticationKey","serializer","deserializer","bytes","publicKey","Ed25519PublicKey","_Ed25519PrivateKey","Serializable","privateKeyHex","keyPair","path","mnemonics","isValidHardenedPath","mnemonicToSeed","seed","offset","HARDENED_OFFSET","key","chainCode","deriveKey","segments","splitPath","el","privateKey","parentKeys","segment","CKDPriv","messageToSign","Ed25519PrivateKey","_Ed25519Signature","Signature","data","s","i","_MultiEd25519PublicKey","AccountPublicKey","args","publicKeys","threshold","message","signature","MultiEd25519Signature","indices","i","j","index","AuthenticationKey","bytes","Ed25519PublicKey","k","serializer","deserializer","keys","begin","MultiEd25519PublicKey","_MultiEd25519Signature","Signature","signatures","bitmap","Ed25519Signature","bits","firstBitInByte","dupCheckSet","bit","byteOffset","byte","init_sha3","init_secp256k1","init_hmac","init_sha256","init_sha512","init_assert","init_utils","init_secp256k1","init_modular","Point","secp256k1","base58check","createBase58check","sha256","bytesToNumber","bytes","bytesToHex","numberToBytes","num","hexToBytes","MASTER_SECRET","utf8ToBytes","BITCOIN_VERSIONS","HARDENED_OFFSET","hash160","data","ripemd160","fromU32","createView","toU32","n","buf","HDKey","priv","concatBytes","seed","versions","I","hmac","sha512","base58key","keyBuffer","keyView","version","opt","key","isPriv","json","path","parts","child","c","m","m1","idx","index","childTweak","chainCode","added","mod","hash","signature","sig","_Secp256k1PublicKey","PublicKey","hexInput","hex","Hex","args","message","signature","Secp256k1Signature","messageToVerify","convertSigningMessage","messageBytes","messageSha3Bytes","sha3_256","signatureBytes","secp256k1","serializer","deserializer","bytes","publicKey","Secp256k1PublicKey","_Secp256k1PrivateKey","Serializable","privateKeyHex","path","mnemonics","isValidBIP44Path","mnemonicToSeed","seed","privateKey","HDKey","messageToSign","messageHashBytes","Secp256k1PrivateKey","_Secp256k1Signature","Signature","data","AnyPublicKey","_AnyPublicKey","AccountPublicKey","publicKey","Ed25519PublicKey","Secp256k1PublicKey","args","message","signature","AnySignature","AuthenticationKey","serializer","deserializer","variantIndex","_AnySignature","Signature","Ed25519Signature","Secp256k1Signature","bitCount","byte","n","MultiKey","_MultiKey","AccountPublicKey","args","publicKeys","signaturesRequired","publicKey","AnyPublicKey","AuthenticationKey","serializer","deserializer","keys","bits","firstBitInByte","bitmap","dupCheckSet","bit","idx","byteOffset","_MultiKeySignature","Signature","signatures","signature","AnySignature","nSignatures","acc","i","AccountAuthenticator","Serializable","deserializer","index","AccountAuthenticatorEd25519","AccountAuthenticatorMultiEd25519","AccountAuthenticatorSingleKey","AccountAuthenticatorMultiKey","_AccountAuthenticatorEd25519","public_key","signature","serializer","Ed25519PublicKey","Ed25519Signature","_AccountAuthenticatorMultiEd25519","MultiEd25519PublicKey","MultiEd25519Signature","_AccountAuthenticatorSingleKey","AnyPublicKey","AnySignature","_AccountAuthenticatorMultiKey","public_keys","signatures","signatures_bitmap","MultiKey","Ed25519Account","_Ed25519Account","args","privateKey","address","AccountAddress","Ed25519PrivateKey","path","mnemonic","message","signature","AccountAuthenticatorEd25519","SingleKeyAccount","_SingleKeyAccount","args","privateKey","address","AnyPublicKey","AccountAddress","scheme","Ed25519PrivateKey","Secp256k1PrivateKey","path","mnemonic","message","innerSignature","signature","AnySignature","AccountAuthenticatorSingleKey","Account","args","scheme","legacy","Ed25519Account","SingleKeyAccount","privateKey","address","Ed25519PrivateKey","mnemonic","path","publicKey","getInfo","args","aptosConfig","accountAddress","data","getAptosFullNode","AccountAddress","getModules","options","paginateWithCursor","getModule","getModuleInner","memoizeAsync","moduleName","getTransactions","getResources","getResource","resourceType","lookupOriginalAccountAddress","authenticationKey","resource","handle","authKeyAddress","originalAddress","getTableItem","err","AptosApiError","getAccountTokensCount","whereCondition","queryIndexer","GetAccountTokensCount","getAccountOwnedTokens","graphqlQuery","GetAccountOwnedTokens","getAccountOwnedTokensFromCollectionAddress","collectionAddress","ownerAddress","collAddress","GetAccountOwnedTokensFromCollection","getAccountCollectionsWithOwnedTokens","GetAccountCollectionsWithOwnedTokens","getAccountTransactionsCount","address","GetAccountTransactionsCount","getAccountCoinAmount","coinType","getAccountCoinsData","GetAccountCoinsData","getAccountCoinsCount","GetAccountCoinsCount","getAccountOwnedObjects","GetAccountOwnedObjects","deriveAccountFromPrivateKey","privateKey","publicKey","AnyPublicKey","Secp256k1PrivateKey","AuthenticationKey","Account","Ed25519PrivateKey","singleSenderTransactionAuthenticatorAuthKey","isAccountExist","legacyAuthKey","authKey","error","TEXT_ENCODER","standardizeTypeTags","typeArguments","typeArg","isString","parseTypeTag","fetchFunctionAbi","moduleAddress","moduleName","functionName","aptosConfig","module","getModule","func","fetchEntryFunctionAbi","functionAbi","numSigners","findFirstNonSignerArg","params","i","fetchViewFunctionAbi","returnTypes","convertArgument","arg","position","genericTypeParams","param","checkOrConvertArgument","isEncodedEntryFunctionArgument","checkType","parseArg","isBool","Bool","throwTypeMismatch","AccountAddress","isNumber","U8","U16","U32","isLargeNumber","U64","U128","U256","genericIndex","MoveVector","item","MoveString","isNull","MoveOption","isBcsBool","isBcsAddress","isBcsU8","isBcsU16","isBcsU32","isBcsU64","isBcsU128","isBcsU256","TypeTagStruct","isBcsString","ModuleId","_ModuleId","Serializable","address","name","moduleId","parts","AccountAddress","Identifier","serializer","deserializer","EntryFunctionBytes","_EntryFunctionBytes","Serializable","value","FixedBytes","serializer","deserializer","length","fixedBytes","deserializeFromScriptArgument","deserializer","index","U8","U64","U128","AccountAddress","MoveVector","Bool","U16","U32","U256","TransactionPayload","Serializable","TransactionPayloadScript","TransactionPayloadEntryFunction","TransactionPayloadMultiSig","_TransactionPayloadScript","script","serializer","Script","_TransactionPayloadEntryFunction","entryFunction","EntryFunction","_TransactionPayloadMultiSig","multiSig","value","MultiSig","_EntryFunction","module_name","function_name","type_args","args","module_id","ModuleId","Identifier","item","TypeTag","length","i","fixedBytesLength","fixedBytes","EntryFunctionBytes","_Script","bytecode","scriptArgument","_MultiSig","multisig_address","transaction_payload","payloadPresent","MultiSigTransactionPayload","_MultiSigTransactionPayload","ChainId","_ChainId","Serializable","chainId","serializer","deserializer","RawTransaction","_RawTransaction","Serializable","sender","sequence_number","payload","max_gas_amount","gas_unit_price","expiration_timestamp_secs","chain_id","serializer","deserializer","AccountAddress","TransactionPayload","ChainId","RawTransactionWithData","index","MultiAgentRawTransaction","FeePayerRawTransaction","_MultiAgentRawTransaction","raw_txn","secondary_signer_addresses","rawTxn","secondarySignerAddresses","_FeePayerRawTransaction","fee_payer_address","feePayerAddress","MultiAgentTransaction","_MultiAgentTransaction","Serializable","rawTransaction","secondarySignerAddresses","feePayerAddress","serializer","deserializer","RawTransaction","AccountAddress","feepayerPresent","TransactionAuthenticator","Serializable","deserializer","index","TransactionAuthenticatorEd25519","TransactionAuthenticatorMultiEd25519","TransactionAuthenticatorMultiAgent","TransactionAuthenticatorFeePayer","TransactionAuthenticatorSingleSender","_TransactionAuthenticatorEd25519","public_key","signature","serializer","Ed25519PublicKey","Ed25519Signature","_TransactionAuthenticatorMultiEd25519","MultiEd25519PublicKey","MultiEd25519Signature","_TransactionAuthenticatorMultiAgent","sender","secondary_signer_addresses","secondary_signers","AccountAuthenticator","AccountAddress","_TransactionAuthenticatorFeePayer","fee_payer","address","authenticator","_TransactionAuthenticatorSingleSender","SignedTransaction","_SignedTransaction","Serializable","raw_txn","authenticator","serializer","deserializer","RawTransaction","TransactionAuthenticator","SimpleTransaction","_SimpleTransaction","Serializable","rawTransaction","feePayerAddress","serializer","deserializer","RawTransaction","feepayerPresent","AccountAddress","Deserializer","data","length","bytes","value","len","bool","low","high","shift","MAX_U32_NUMBER","byte","cls","vector","i","normalizeBundle","cls","value","serializedBytes","deserializer","Deserializer","NetworkToIndexerAPI","NetworkToNodeAPI","NetworkToFaucetAPI","Network","NetworkToChainId","init_sha3","generateTransactionPayload","args","isScriptDataInput","generateTransactionPayloadScript","moduleAddress","moduleName","functionName","getFunctionParts","functionAbi","fetchAbi","fetchEntryFunctionAbi","generateTransactionPayloadWithABI","typeArguments","standardizeTypeTags","functionArguments","arg","i","convertArgument","entryFunctionPayload","EntryFunction","multisigAddress","AccountAddress","TransactionPayloadMultiSig","MultiSig","MultiSigTransactionPayload","TransactionPayloadEntryFunction","generateViewFunctionPayload","fetchViewFunctionAbi","generateViewFunctionPayloadWithABI","TransactionPayloadScript","Script","Hex","generateRawTransaction","aptosConfig","sender","payload","options","feePayerAddress","getChainId","NetworkToChainId","getLedgerInfo","getGasUnitPrice","getGasPriceEstimation","getSequenceNumberForAny","getSequenceNumber","getInfo","chainId","gasEstimate","sequenceNumber","maxGasAmount","gasUnitPrice","expireTimestamp","RawTransaction","ChainId","buildTransaction","rawTxn","signers","signer","MultiAgentTransaction","SimpleTransaction","generateSignedTransactionForSimulation","signerPublicKey","transaction","secondarySignersPublicKeys","feePayerPublicKey","accountAuthenticator","getAuthenticatorForSimulation","transactionToSign","FeePayerRawTransaction","secondaryAccountAuthenticators","publicKey","feePayerAuthenticator","transactionAuthenticator","TransactionAuthenticatorFeePayer","SignedTransaction","MultiAgentRawTransaction","TransactionAuthenticatorMultiAgent","AccountAuthenticatorEd25519","TransactionAuthenticatorEd25519","AccountAuthenticatorSingleKey","TransactionAuthenticatorSingleSender","AnyPublicKey","Ed25519PublicKey","AnySignature","Ed25519Signature","Secp256k1PublicKey","Secp256k1Signature","sign","message","generateSigningMessage","generateSignedTransaction","additionalSignersAuthenticators","senderAuthenticator","normalizeBundle","AccountAuthenticator","txnAuthenticator","hashValues","input","hash","sha3Hash","item","TRANSACTION_PREFIX","deriveTransactionType","transaction","FeePayerRawTransaction","MultiAgentRawTransaction","generateSigningMessage","hash","sha3Hash","RAW_TRANSACTION_WITH_DATA_SALT","RAW_TRANSACTION_SALT","prefix","body","mergedArray","fetchAbi","key","moduleAddress","moduleName","functionName","aptosConfig","abi","fetch","memoizeAsync","RotationProofChallenge","Serializable","args","AccountAddress","MoveString","U64","MoveVector","serializer","generateTransaction","args","payload","buildTransactionPayload","buildRawTransaction","aptosConfig","data","generateTransactionPayloadData","generateTransactionPayload","sender","options","feePayerAddress","isFeePayerTransactionInput","AccountAddress","isMultiAgentTransactionInput","secondarySignerAddresses","buildTransaction","getSigningMessage","transaction","generateSigningMessage","signTransaction","sign","simulateTransaction","signerPublicKey","secondarySignersPublicKeys","feePayerPublicKey","signedTransaction","generateSignedTransactionForSimulation","postAptosFullNode","submitTransaction","generateSignedTransaction","signAndSubmitTransaction","signer","authenticator","packagePublishAbi","TypeTagVector","publicPackageTransaction","account","metadataBytes","moduleBytecode","totalByteCode","bytecode","MoveVector","rotateAuthKeyAbi","TypeTagU8","rotateAuthKey","fromAccount","toNewPrivateKey","accountInfo","getInfo","newAccount","Account","challengeHex","RotationProofChallenge","proofSignedByCurrentPrivateKey","proofSignedByNewPrivateKey","rawTxn","U8","Build","config","args","generateTransaction","now","AccountSequenceNumber","aptosConfig","account","maxWaitTime","maximumInFlight","sleepTime","sleep","nextNumber","startTime","e","sequenceNumber","getInfo","AsyncQueue","item","resolve","reject","AsyncQueueCancelledError","import_index","eventemitter3_default","EventEmitter","promiseFulfilledStatus","TransactionWorkerEventsEnum","TransactionWorker","EventEmitter","aptosConfig","account","maxWaitTime","maximumInFlight","sleepTime","AsyncQueue","AccountSequenceNumber","sequenceNumber","transaction","pendingTransaction","signAndSubmitTransaction","error","AsyncQueueCancelledError","awaitingTransactions","sequenceNumbers","sentTransactions","i","sentTransaction","waitFor","waitForTransaction","executedTransaction","transactionData","options","generateTransaction","TransactionManagement","EventEmitter","config","args","sender","TransactionWorker","data","options","d","error","ValidateFeePayerDataOnSubmission","target","propertyKey","descriptor","originalMethod","args","methodArgs","ValidateFeePayerDataOnSimulation","Simulate","config","args","simulateTransaction","__decorateClass","ValidateFeePayerDataOnSimulation","Submit","config","args","submitTransaction","__decorateClass","ValidateFeePayerDataOnSubmission","Transaction","config","Build","Simulate","Submit","TransactionManagement","args","getTransactions","getTransactionByVersion","getTransactionByHash","isTransactionPending","waitForTransaction","getGasPriceEstimation","getSigningMessage","publicPackageTransaction","rotateAuthKey","signTransaction","signer","transaction","sender","data","options","error","signAndSubmitTransaction","import_got","CookieJar","_CookieJar","jar","url","cookieStr","_a","key","cookie","c","str","parts","part","name","value","nameLow","val","cookieJar","aptosClient","requestOptions","params","method","headers","body","request","convertBigIntToString","options","cookies","response","got","parseResponse","error","gotError","obj","result","AptosConfig","settings","aptosClient","apiType","NetworkToNodeAPI","NetworkToFaucetAPI","NetworkToIndexerAPI","coinTransferAbi","TypeTagAddress","TypeTagU64","transferCoinTransaction","args","aptosConfig","sender","recipient","amount","coinType","options","generateTransaction","APTOS_COIN","Coin","config","args","transferCoinTransaction","PropertyTypeMap","defaultDigitalAssetType","getDigitalAssetData","args","aptosConfig","digitalAssetAddress","whereCondition","AccountAddress","queryIndexer","GetTokenData","getCurrentDigitalAssetOwnership","GetCurrentTokenOwnership","getOwnedDigitalAssets","ownerAddress","options","graphqlQuery","getDigitalAssetActivity","GetTokenActivity","createCollectionAbi","TypeTagStruct","stringStructTag","TypeTagU64","TypeTagBool","createCollectionTransaction","creator","generateTransaction","MoveString","U64","MAX_U64_BIG_INT","Bool","getCollectionData","creatorAddress","collectionName","address","GetCollectionData","getCollectionDataByCollectionId","collectionId","getCollectionId","mintDigitalAssetAbi","TypeTagVector","mintDigitalAssetTransaction","collection","description","name","uri","propertyKeys","propertyTypes","propertyValues","convertedPropertyType","type","MoveVector","getPropertyValueRaw","transferDigitalAssetAbi","objectStructTag","TypeTagGeneric","TypeTagAddress","transferDigitalAssetTransaction","sender","recipient","digitalAssetType","mintSoulBoundAbi","mintSoulBoundTransaction","account","burnDigitalAssetAbi","burnDigitalAssetTransaction","freezeDigitalAssetAbi","freezeDigitalAssetTransferTransaction","unfreezeDigitalAssetAbi","unfreezeDigitalAssetTransferTransaction","setDigitalAssetDescriptionAbi","setDigitalAssetDescriptionTransaction","setDigitalAssetNameAbi","setDigitalAssetNameTransaction","setDigitalAssetURIAbi","setDigitalAssetURITransaction","addDigitalAssetPropertyAbi","addDigitalAssetPropertyTransaction","propertyKey","propertyType","propertyValue","getSinglePropertyValueRaw","removeDigitalAssetPropertyAbi","removeDigitalAssetPropertyTransaction","updateDigitalAssetPropertyAbi","updateDigitalAssetPropertyTransaction","addDigitalAssetTypedPropertyAbi","addDigitalAssetTypedPropertyTransaction","updateDigitalAssetTypedPropertyAbi","updateDigitalAssetTypedPropertyTransaction","results","typ","index","typeTag","parseTypeTag","checkOrConvertArgument","DigitalAsset","config","args","waitForIndexerOnVersion","getCollectionData","getCollectionDataByCollectionId","getCollectionId","getDigitalAssetData","getCurrentDigitalAssetOwnership","getOwnedDigitalAssets","getDigitalAssetActivity","createCollectionTransaction","mintDigitalAssetTransaction","transferDigitalAssetTransaction","mintSoulBoundTransaction","burnDigitalAssetTransaction","freezeDigitalAssetTransferTransaction","unfreezeDigitalAssetTransferTransaction","setDigitalAssetDescriptionTransaction","setDigitalAssetNameTransaction","setDigitalAssetURITransaction","addDigitalAssetPropertyTransaction","removeDigitalAssetPropertyTransaction","updateDigitalAssetPropertyTransaction","addDigitalAssetTypedPropertyTransaction","updateDigitalAssetTypedPropertyTransaction","MAX_EVENT_TYPE_LENGTH","checkEventTypeLength","eventType","getModuleEventsByEventType","args","aptosConfig","options","customOptions","getEvents","getAccountEventsByCreationNumber","accountAddress","creationNumber","AccountAddress","getAccountEventsByEventType","graphqlQuery","GetEvents","queryIndexer","Event","config","args","waitForIndexerOnVersion","getModuleEventsByEventType","getAccountEventsByCreationNumber","getAccountEventsByEventType","getEvents","fundAccount","args","aptosConfig","accountAddress","amount","options","timeout","data","postAptosFaucet","AccountAddress","txnHash","res","waitForTransaction","Faucet","config","args","fundTxn","fundAccount","waitForIndexer","getFungibleAssetMetadata","args","aptosConfig","options","graphqlQuery","GetFungibleAssetMetadata","queryIndexer","getFungibleAssetActivities","GetFungibleAssetActivities","getCurrentFungibleAssetBalances","GetCurrentFungibleAssetBalances","faTransferAbi","parseTypeTag","TypeTagAddress","TypeTagU64","transferFungibleAsset","sender","fungibleAssetMetadataAddress","recipient","amount","generateTransaction","FungibleAsset","config","args","waitForIndexerOnVersion","getFungibleAssetMetadata","getFungibleAssetActivities","getCurrentFungibleAssetBalances","transferFungibleAsset","view","args","aptosConfig","payload","options","viewFunctionPayload","generateViewFunctionPayload","serializer","Serializer","bytes","data","postAptosFullNode","General","config","getLedgerInfo","args","getBlockByVersion","getBlockByHeight","getTableItem","view","getChainTopUserTransactions","queryIndexer","getIndexerLastSuccessVersion","processorType","getProcessorStatus","Account","config","args","getInfo","getModules","getModule","getTransactions","getResources","getResource","lookupOriginalAccountAddress","waitForIndexerOnVersion","getAccountTokensCount","getAccountOwnedTokens","getAccountOwnedTokensFromCollectionAddress","getAccountCollectionsWithOwnedTokens","getAccountTransactionsCount","getAccountCoinsData","getAccountCoinsCount","APTOS_COIN","getAccountCoinAmount","getAccountOwnedObjects","deriveAccountFromPrivateKey","VALIDATION_RULES_DESCRIPTION","isValidANSSegment","fragment","isValidANSName","name","first","second","rest","LOCAL_ANS_ACCOUNT_ADDRESS","NetworkToAnsContract","getRouterAddress","aptosConfig","address","unwrapOption","option","getOwnerAddress","args","name","routerAddress","domainName","subdomainName","isValidANSName","res","view","owner","AccountAddress","registerName","expiration","sender","targetAddress","toAddress","options","transferable","hasSubdomainPolicy","years","registrationDuration","generateTransaction","tldExpiration","getExpiration","expirationDateInMillisecondsSinceEpoch","getPrimaryName","setPrimaryName","getTargetAddress","target","setTargetAddress","getName","queryIndexer","GetNames","sanitizeANSName","getAccountNames","accountAddress","expirationDate","getANSExpirationDate","getAccountDomains","getAccountSubdomains","getDomainSubdomains","domain","gracePeriodInSeconds","gracePeriodInDays","now","renewDomain","renewalDuration","ANS","config","args","getOwnerAddress","getExpiration","getTargetAddress","setTargetAddress","getPrimaryName","setPrimaryName","registerName","renewDomain","getName","getAccountNames","getAccountDomains","getAccountSubdomains","getDomainSubdomains","Aptos","settings","AptosConfig","Account","ANS","Coin","DigitalAsset","Event","Faucet","FungibleAsset","General","Staking","Transaction","applyMixin","targetClass","baseClass","baseClassProp","propertyName","propertyDescriptor","args","MimeType","TypeTagVariants","ScriptTransactionArgumentVariants","TransactionPayloadVariants","TransactionVariants","TransactionAuthenticatorVariant","AccountAuthenticatorVariant","AnyPublicKeyVariant","AnySignatureVariant","TransactionResponseType","MoveFunctionVisibility","MoveAbility","RoleType","SigningScheme","SigningSchemeInput","DeriveScheme","Endpoints","process","AptosNetwork","AptosBindOptions","getRpcEndpoint","network","getClient","chainServer","t","toInternalModule","module","abi","toInternalFunction","toInternalStruct","func","visibility","v","InternalMoveFunctionVisibility","parseMoveType","struct","toInternalField","AptosChainAdapter","ChainAdapter","client","account","module","modules","m","toInternalModule","params","eventMap","qname","moduleQname","struct","abilities","SPLITTER","data"]}
|