@aptos-labs/ts-sdk 4.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/common/{account-CmEgDBH6.d.ts → account-BW99GTa5.d.ts} +35 -4
- package/dist/common/chunk-A2XB7TVI.js +4 -0
- package/dist/common/chunk-A2XB7TVI.js.map +1 -0
- package/dist/common/cli/index.d.ts +1 -1
- package/dist/common/cli/index.js +1 -1
- package/dist/common/cli/index.js.map +1 -1
- package/dist/common/index.d.ts +381 -47
- package/dist/common/index.js +34 -36
- package/dist/common/index.js.map +1 -1
- package/dist/esm/{Ed25519Account-ndmdpFe9.d.mts → Ed25519Account-CPwej6wB.d.mts} +1 -1
- package/dist/esm/account/AbstractKeylessAccount.d.mts +3 -3
- package/dist/esm/account/AbstractKeylessAccount.mjs +1 -1
- package/dist/esm/account/AbstractedAccount.d.mts +3 -2
- package/dist/esm/account/AbstractedAccount.mjs +1 -1
- package/dist/esm/account/Account.d.mts +2 -2
- package/dist/esm/account/Account.mjs +1 -1
- package/dist/esm/account/AccountUtils.d.mts +3 -3
- package/dist/esm/account/AccountUtils.mjs +1 -1
- package/dist/esm/account/DerivableAbstractedAccount.d.mts +2 -2
- package/dist/esm/account/DerivableAbstractedAccount.mjs +1 -1
- package/dist/esm/account/Ed25519Account.d.mts +2 -2
- package/dist/esm/account/Ed25519Account.mjs +1 -1
- package/dist/esm/account/EphemeralKeyPair.d.mts +1 -1
- package/dist/esm/account/EphemeralKeyPair.mjs +1 -1
- package/dist/esm/account/FederatedKeylessAccount.d.mts +3 -3
- package/dist/esm/account/FederatedKeylessAccount.mjs +1 -1
- package/dist/esm/account/KeylessAccount.d.mts +3 -3
- package/dist/esm/account/KeylessAccount.mjs +1 -1
- package/dist/esm/account/MultiEd25519Account.d.mts +2 -2
- package/dist/esm/account/MultiEd25519Account.mjs +1 -1
- package/dist/esm/account/MultiKeyAccount.d.mts +3 -3
- package/dist/esm/account/MultiKeyAccount.mjs +1 -1
- package/dist/esm/account/SingleKeyAccount.d.mts +2 -2
- package/dist/esm/account/SingleKeyAccount.mjs +1 -1
- package/dist/esm/account/index.d.mts +3 -3
- package/dist/esm/account/index.mjs +1 -1
- package/dist/esm/account/utils.d.mts +1 -1
- package/dist/esm/account/utils.mjs +1 -1
- package/dist/esm/{account--Q9z_xMN.d.mts → account-BortO8g2.d.mts} +34 -4
- package/dist/esm/api/account/abstraction.d.mts +1 -1
- package/dist/esm/api/account/abstraction.mjs +1 -1
- package/dist/esm/api/account.d.mts +31 -13
- package/dist/esm/api/account.mjs +1 -1
- package/dist/esm/api/ans.d.mts +2 -2
- package/dist/esm/api/ans.mjs +1 -1
- package/dist/esm/api/aptos.d.mts +4 -3
- package/dist/esm/api/aptos.mjs +1 -1
- package/dist/esm/api/aptosConfig.d.mts +1 -1
- package/dist/esm/api/aptosConfig.mjs +1 -1
- package/dist/esm/api/coin.d.mts +1 -1
- package/dist/esm/api/coin.mjs +1 -1
- package/dist/esm/api/digitalAsset.d.mts +2 -2
- package/dist/esm/api/digitalAsset.mjs +1 -1
- package/dist/esm/api/faucet.d.mts +1 -1
- package/dist/esm/api/faucet.mjs +1 -1
- package/dist/esm/api/fungibleAsset.d.mts +2 -2
- package/dist/esm/api/fungibleAsset.mjs +1 -1
- package/dist/esm/api/general.d.mts +1 -1
- package/dist/esm/api/general.mjs +1 -1
- package/dist/esm/api/index.d.mts +4 -3
- package/dist/esm/api/index.mjs +1 -1
- package/dist/esm/api/keyless.d.mts +3 -3
- package/dist/esm/api/keyless.mjs +1 -1
- package/dist/esm/api/object.d.mts +1 -1
- package/dist/esm/api/object.mjs +1 -1
- package/dist/esm/api/staking.d.mts +1 -1
- package/dist/esm/api/staking.mjs +1 -1
- package/dist/esm/api/table.d.mts +1 -1
- package/dist/esm/api/table.mjs +1 -1
- package/dist/esm/api/transaction.d.mts +56 -36
- package/dist/esm/api/transaction.mjs +1 -1
- package/dist/esm/api/transactionSubmission/build.d.mts +1 -1
- package/dist/esm/api/transactionSubmission/build.mjs +1 -1
- package/dist/esm/api/transactionSubmission/helpers.d.mts +1 -1
- package/dist/esm/api/transactionSubmission/management.d.mts +2 -2
- package/dist/esm/api/transactionSubmission/management.mjs +1 -1
- package/dist/esm/api/transactionSubmission/sign.d.mts +2 -2
- package/dist/esm/api/transactionSubmission/sign.mjs +1 -1
- package/dist/esm/api/transactionSubmission/sign.mjs.map +1 -1
- package/dist/esm/api/transactionSubmission/simulate.d.mts +1 -1
- package/dist/esm/api/transactionSubmission/simulate.mjs +1 -1
- package/dist/esm/api/transactionSubmission/submit.d.mts +1 -1
- package/dist/esm/api/transactionSubmission/submit.mjs +1 -1
- package/dist/esm/api/utils.d.mts +1 -1
- package/dist/esm/api/utils.mjs +1 -1
- package/dist/esm/bcs/consts.d.mts +1 -1
- package/dist/esm/bcs/deserializer.d.mts +1 -1
- package/dist/esm/bcs/index.d.mts +1 -1
- package/dist/esm/bcs/index.mjs +1 -1
- package/dist/esm/bcs/serializable/entryFunctionBytes.d.mts +1 -1
- package/dist/esm/bcs/serializable/fixedBytes.d.mts +1 -1
- package/dist/esm/bcs/serializable/movePrimitives.d.mts +1 -1
- package/dist/esm/bcs/serializable/movePrimitives.mjs +1 -1
- package/dist/esm/bcs/serializable/moveStructs.d.mts +1 -1
- package/dist/esm/bcs/serializable/moveStructs.mjs +1 -1
- package/dist/esm/bcs/serializer.d.mts +1 -1
- package/dist/esm/chunk-2PASUPUO.mjs +2 -0
- package/dist/esm/chunk-2PASUPUO.mjs.map +1 -0
- package/dist/esm/{chunk-6JYQ5P36.mjs → chunk-4AI7KQQ7.mjs} +2 -2
- package/dist/esm/{chunk-V6C6NWFU.mjs → chunk-6OWBKU7N.mjs} +2 -2
- package/dist/esm/{chunk-BPWSOC2Y.mjs → chunk-7EER7GWV.mjs} +2 -2
- package/dist/esm/{chunk-PLI53ZU6.mjs → chunk-AMXZQPUQ.mjs} +2 -2
- package/dist/esm/chunk-CIJA7ONS.mjs +2 -0
- package/dist/esm/{chunk-6SLY7UV2.mjs.map → chunk-CIJA7ONS.mjs.map} +1 -1
- package/dist/esm/chunk-I7XT6L7S.mjs +2 -0
- package/dist/esm/chunk-I7XT6L7S.mjs.map +1 -0
- package/dist/esm/{chunk-UQZTHVWC.mjs → chunk-JABP65XD.mjs} +2 -2
- package/dist/esm/chunk-L72TIN7T.mjs +4 -0
- package/dist/esm/chunk-L72TIN7T.mjs.map +1 -0
- package/dist/esm/{chunk-3BMZKCLH.mjs → chunk-M3AO73ZL.mjs} +2 -2
- package/dist/esm/chunk-MCFQE4GC.mjs +2 -0
- package/dist/esm/chunk-MCFQE4GC.mjs.map +1 -0
- package/dist/esm/chunk-OLILO7VD.mjs +2 -0
- package/dist/esm/{chunk-JCFTAG5Z.mjs.map → chunk-OLILO7VD.mjs.map} +1 -1
- package/dist/esm/{chunk-NF73V673.mjs → chunk-QP2BY4PK.mjs} +2 -2
- package/dist/esm/{chunk-Y7ZQTLH4.mjs → chunk-RCSJFTST.mjs} +2 -2
- package/dist/esm/{chunk-XYXBAU4J.mjs → chunk-SJDCGNWU.mjs} +2 -2
- package/dist/esm/{chunk-HZVN4JSO.mjs → chunk-WHSTLR3F.mjs} +2 -2
- package/dist/esm/chunk-ZP4DWSQA.mjs +2 -0
- package/dist/esm/chunk-ZP4DWSQA.mjs.map +1 -0
- package/dist/esm/cli/index.d.mts +1 -1
- package/dist/esm/cli/index.mjs +1 -1
- package/dist/esm/cli/localNode.mjs +1 -1
- package/dist/esm/cli/move.d.mts +1 -1
- package/dist/esm/client/core.d.mts +1 -1
- package/dist/esm/client/core.mjs +1 -1
- package/dist/esm/client/get.d.mts +1 -1
- package/dist/esm/client/get.mjs +1 -1
- package/dist/esm/client/index.d.mts +1 -1
- package/dist/esm/client/index.mjs +1 -1
- package/dist/esm/client/post.d.mts +1 -1
- package/dist/esm/client/post.mjs +1 -1
- package/dist/esm/core/account/index.d.mts +1 -1
- package/dist/esm/core/account/index.mjs +1 -1
- package/dist/esm/core/account/utils/address.d.mts +1 -1
- package/dist/esm/core/account/utils/address.mjs +1 -1
- package/dist/esm/core/account/utils/index.d.mts +1 -1
- package/dist/esm/core/account/utils/index.mjs +1 -1
- package/dist/esm/core/accountAddress.d.mts +1 -1
- package/dist/esm/core/accountAddress.mjs +1 -1
- package/dist/esm/core/authenticationKey.d.mts +1 -1
- package/dist/esm/core/authenticationKey.mjs +1 -1
- package/dist/esm/core/crypto/abstraction.d.mts +1 -1
- package/dist/esm/core/crypto/abstraction.mjs +1 -1
- package/dist/esm/core/crypto/deserializationUtils.d.mts +1 -1
- package/dist/esm/core/crypto/deserializationUtils.mjs +1 -1
- package/dist/esm/core/crypto/ed25519.d.mts +1 -1
- package/dist/esm/core/crypto/ed25519.mjs +1 -1
- package/dist/esm/core/crypto/ephemeral.d.mts +1 -1
- package/dist/esm/core/crypto/ephemeral.mjs +1 -1
- package/dist/esm/core/crypto/federatedKeyless.d.mts +2 -2
- package/dist/esm/core/crypto/federatedKeyless.mjs +1 -1
- package/dist/esm/core/crypto/index.d.mts +3 -2
- package/dist/esm/core/crypto/index.mjs +1 -1
- package/dist/esm/core/crypto/keyless.d.mts +2 -2
- package/dist/esm/core/crypto/keyless.mjs +1 -1
- package/dist/esm/core/crypto/multiEd25519.d.mts +1 -1
- package/dist/esm/core/crypto/multiEd25519.mjs +1 -1
- package/dist/esm/core/crypto/multiKey.d.mts +1 -1
- package/dist/esm/core/crypto/multiKey.mjs +1 -1
- package/dist/esm/core/crypto/privateKey.d.mts +1 -1
- package/dist/esm/core/crypto/privateKey.mjs +1 -1
- package/dist/esm/core/crypto/proof.d.mts +1 -1
- package/dist/esm/core/crypto/proof.mjs +1 -1
- package/dist/esm/core/crypto/publicKey.d.mts +1 -1
- package/dist/esm/core/crypto/publicKey.mjs +1 -1
- package/dist/esm/core/crypto/secp256k1.d.mts +1 -1
- package/dist/esm/core/crypto/secp256k1.mjs +1 -1
- package/dist/esm/core/crypto/secp256r1.d.mts +306 -0
- package/dist/esm/core/crypto/secp256r1.mjs +2 -0
- package/dist/esm/core/crypto/secp256r1.mjs.map +1 -0
- package/dist/esm/core/crypto/signature.d.mts +1 -1
- package/dist/esm/core/crypto/signature.mjs +1 -1
- package/dist/esm/core/crypto/singleKey.d.mts +1 -1
- package/dist/esm/core/crypto/singleKey.mjs +1 -1
- package/dist/esm/core/crypto/types.d.mts +1 -1
- package/dist/esm/core/crypto/utils.d.mts +5 -2
- package/dist/esm/core/crypto/utils.mjs +1 -1
- package/dist/esm/core/hex.d.mts +1 -1
- package/dist/esm/core/index.d.mts +3 -2
- package/dist/esm/core/index.mjs +1 -1
- package/dist/esm/errors/index.d.mts +1 -1
- package/dist/esm/errors/index.mjs +1 -1
- package/dist/esm/{federatedKeyless-CiyplsOB.d.mts → federatedKeyless-CTzDAQTu.d.mts} +1 -1
- package/dist/esm/index.d.mts +5 -4
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/internal/abstraction.d.mts +1 -1
- package/dist/esm/internal/abstraction.mjs +1 -1
- package/dist/esm/internal/account.d.mts +45 -21
- package/dist/esm/internal/account.mjs +1 -1
- package/dist/esm/internal/ans.d.mts +2 -2
- package/dist/esm/internal/ans.mjs +1 -1
- package/dist/esm/internal/coin.d.mts +1 -1
- package/dist/esm/internal/coin.mjs +1 -1
- package/dist/esm/internal/digitalAsset.d.mts +2 -2
- package/dist/esm/internal/digitalAsset.mjs +1 -1
- package/dist/esm/internal/faucet.d.mts +1 -1
- package/dist/esm/internal/faucet.mjs +1 -1
- package/dist/esm/internal/fungibleAsset.d.mts +2 -2
- package/dist/esm/internal/fungibleAsset.mjs +1 -1
- package/dist/esm/internal/general.d.mts +1 -1
- package/dist/esm/internal/general.mjs +1 -1
- package/dist/esm/internal/keyless.d.mts +3 -3
- package/dist/esm/internal/keyless.mjs +1 -1
- package/dist/esm/internal/object.d.mts +1 -1
- package/dist/esm/internal/object.mjs +1 -1
- package/dist/esm/internal/staking.d.mts +1 -1
- package/dist/esm/internal/staking.mjs +1 -1
- package/dist/esm/internal/table.d.mts +1 -1
- package/dist/esm/internal/table.mjs +1 -1
- package/dist/esm/internal/transaction.d.mts +1 -1
- package/dist/esm/internal/transaction.mjs +1 -1
- package/dist/esm/internal/transactionSubmission.d.mts +2 -2
- package/dist/esm/internal/transactionSubmission.mjs +1 -1
- package/dist/esm/internal/utils/index.d.mts +1 -1
- package/dist/esm/internal/utils/index.mjs +1 -1
- package/dist/esm/internal/utils/utils.d.mts +1 -1
- package/dist/esm/internal/utils/utils.mjs +1 -1
- package/dist/esm/internal/view.d.mts +1 -1
- package/dist/esm/internal/view.mjs +1 -1
- package/dist/esm/transactions/authenticator/account.d.mts +1 -1
- package/dist/esm/transactions/authenticator/account.mjs +1 -1
- package/dist/esm/transactions/authenticator/index.d.mts +1 -1
- package/dist/esm/transactions/authenticator/index.mjs +1 -1
- package/dist/esm/transactions/authenticator/transaction.d.mts +1 -1
- package/dist/esm/transactions/authenticator/transaction.mjs +1 -1
- package/dist/esm/transactions/index.d.mts +1 -1
- package/dist/esm/transactions/index.mjs +1 -1
- package/dist/esm/transactions/instances/chainId.d.mts +1 -1
- package/dist/esm/transactions/instances/identifier.d.mts +1 -1
- package/dist/esm/transactions/instances/index.d.mts +1 -1
- package/dist/esm/transactions/instances/index.mjs +1 -1
- package/dist/esm/transactions/instances/moduleId.d.mts +1 -1
- package/dist/esm/transactions/instances/moduleId.mjs +1 -1
- package/dist/esm/transactions/instances/multiAgentTransaction.d.mts +1 -1
- package/dist/esm/transactions/instances/multiAgentTransaction.mjs +1 -1
- package/dist/esm/transactions/instances/rawTransaction.d.mts +1 -1
- package/dist/esm/transactions/instances/rawTransaction.mjs +1 -1
- package/dist/esm/transactions/instances/rotationProofChallenge.d.mts +1 -1
- package/dist/esm/transactions/instances/rotationProofChallenge.mjs +1 -1
- package/dist/esm/transactions/instances/signedTransaction.d.mts +1 -1
- package/dist/esm/transactions/instances/signedTransaction.mjs +1 -1
- package/dist/esm/transactions/instances/simpleTransaction.d.mts +1 -1
- package/dist/esm/transactions/instances/simpleTransaction.mjs +1 -1
- package/dist/esm/transactions/instances/transactionArgument.d.mts +1 -1
- package/dist/esm/transactions/instances/transactionPayload.d.mts +1 -1
- package/dist/esm/transactions/instances/transactionPayload.mjs +1 -1
- package/dist/esm/transactions/management/accountSequenceNumber.d.mts +2 -2
- package/dist/esm/transactions/management/accountSequenceNumber.mjs +1 -1
- package/dist/esm/transactions/management/index.d.mts +2 -2
- package/dist/esm/transactions/management/index.mjs +1 -1
- package/dist/esm/transactions/management/transactionWorker.d.mts +2 -2
- package/dist/esm/transactions/management/transactionWorker.mjs +1 -1
- package/dist/esm/transactions/transactionBuilder/helpers.d.mts +1 -1
- package/dist/esm/transactions/transactionBuilder/helpers.mjs +1 -1
- package/dist/esm/transactions/transactionBuilder/index.d.mts +1 -1
- package/dist/esm/transactions/transactionBuilder/index.mjs +1 -1
- package/dist/esm/transactions/transactionBuilder/remoteAbi.d.mts +1 -1
- package/dist/esm/transactions/transactionBuilder/remoteAbi.mjs +1 -1
- package/dist/esm/transactions/transactionBuilder/signingMessage.d.mts +1 -1
- package/dist/esm/transactions/transactionBuilder/signingMessage.mjs +1 -1
- package/dist/esm/transactions/transactionBuilder/transactionBuilder.d.mts +2 -2
- package/dist/esm/transactions/transactionBuilder/transactionBuilder.mjs +1 -1
- package/dist/esm/transactions/typeTag/index.d.mts +1 -1
- package/dist/esm/transactions/typeTag/index.mjs +1 -1
- package/dist/esm/transactions/typeTag/parser.d.mts +1 -1
- package/dist/esm/transactions/typeTag/parser.mjs +1 -1
- package/dist/esm/transactions/types.d.mts +1 -1
- package/dist/esm/types/abstraction.d.mts +9 -3
- package/dist/esm/types/abstraction.mjs +1 -1
- package/dist/esm/types/index.d.mts +1 -1
- package/dist/esm/types/index.mjs +1 -1
- package/dist/esm/types/types.d.mts +1 -1
- package/dist/esm/types/types.mjs +1 -1
- package/dist/esm/utils/const.d.mts +2 -1
- package/dist/esm/utils/const.mjs +1 -1
- package/dist/esm/utils/helpers.d.mts +1 -1
- package/dist/esm/utils/helpers.mjs +1 -1
- package/dist/esm/utils/index.d.mts +2 -2
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/normalizeBundle.d.mts +1 -1
- package/dist/esm/utils/normalizeBundle.mjs +1 -1
- package/dist/esm/version.d.mts +1 -1
- package/dist/esm/version.mjs +1 -1
- package/package.json +27 -28
- package/src/account/AbstractedAccount.ts +16 -3
- package/src/account/DerivableAbstractedAccount.ts +3 -1
- package/src/api/account.ts +36 -23
- package/src/api/transaction.ts +59 -36
- package/src/core/crypto/index.ts +1 -0
- package/src/core/crypto/privateKey.ts +1 -0
- package/src/core/crypto/secp256k1.ts +9 -1
- package/src/core/crypto/secp256r1.ts +495 -0
- package/src/core/crypto/singleKey.ts +11 -0
- package/src/core/crypto/utils.ts +38 -1
- package/src/internal/account.ts +69 -83
- package/src/transactions/authenticator/account.ts +71 -17
- package/src/types/abstraction.ts +9 -2
- package/src/types/types.ts +5 -0
- package/src/utils/const.ts +2 -0
- package/src/version.ts +1 -1
- package/dist/common/chunk-6MMUUJHX.js +0 -4
- package/dist/common/chunk-6MMUUJHX.js.map +0 -1
- package/dist/esm/chunk-4JT5AESZ.mjs +0 -2
- package/dist/esm/chunk-4JT5AESZ.mjs.map +0 -1
- package/dist/esm/chunk-55Q7BSZT.mjs +0 -6
- package/dist/esm/chunk-55Q7BSZT.mjs.map +0 -1
- package/dist/esm/chunk-6SLY7UV2.mjs +0 -2
- package/dist/esm/chunk-DPW6ELCQ.mjs +0 -2
- package/dist/esm/chunk-DPW6ELCQ.mjs.map +0 -1
- package/dist/esm/chunk-IJE2LVZG.mjs +0 -2
- package/dist/esm/chunk-IJE2LVZG.mjs.map +0 -1
- package/dist/esm/chunk-JCFTAG5Z.mjs +0 -2
- package/dist/esm/chunk-K43K3YG7.mjs +0 -2
- package/dist/esm/chunk-K43K3YG7.mjs.map +0 -1
- package/dist/esm/chunk-KJH4KKG6.mjs +0 -2
- package/dist/esm/chunk-KJH4KKG6.mjs.map +0 -1
- package/dist/esm/chunk-MSMFHPDT.mjs +0 -2
- package/dist/esm/chunk-MSMFHPDT.mjs.map +0 -1
- package/dist/esm/chunk-ROT6S6BM.mjs +0 -2
- package/dist/esm/chunk-ROT6S6BM.mjs.map +0 -1
- /package/dist/esm/{chunk-6JYQ5P36.mjs.map → chunk-4AI7KQQ7.mjs.map} +0 -0
- /package/dist/esm/{chunk-V6C6NWFU.mjs.map → chunk-6OWBKU7N.mjs.map} +0 -0
- /package/dist/esm/{chunk-BPWSOC2Y.mjs.map → chunk-7EER7GWV.mjs.map} +0 -0
- /package/dist/esm/{chunk-PLI53ZU6.mjs.map → chunk-AMXZQPUQ.mjs.map} +0 -0
- /package/dist/esm/{chunk-UQZTHVWC.mjs.map → chunk-JABP65XD.mjs.map} +0 -0
- /package/dist/esm/{chunk-3BMZKCLH.mjs.map → chunk-M3AO73ZL.mjs.map} +0 -0
- /package/dist/esm/{chunk-NF73V673.mjs.map → chunk-QP2BY4PK.mjs.map} +0 -0
- /package/dist/esm/{chunk-Y7ZQTLH4.mjs.map → chunk-RCSJFTST.mjs.map} +0 -0
- /package/dist/esm/{chunk-XYXBAU4J.mjs.map → chunk-SJDCGNWU.mjs.map} +0 -0
- /package/dist/esm/{chunk-HZVN4JSO.mjs.map → chunk-WHSTLR3F.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/crypto/ed25519.ts","../../src/core/crypto/keyless.ts","../../src/core/crypto/secp256k1.ts","../../src/core/crypto/singleKey.ts","../../src/core/crypto/multiKey.ts","../../src/core/crypto/multiEd25519.ts","../../src/core/crypto/deserializationUtils.ts","../../src/transactions/authenticator/account.ts","../../src/transactions/transactionBuilder/signingMessage.ts","../../src/transactions/instances/moduleId.ts","../../src/transactions/typeTag/index.ts","../../src/transactions/instances/transactionPayload.ts","../../src/transactions/instances/rawTransaction.ts","../../src/transactions/authenticator/transaction.ts","../../src/transactions/instances/signedTransaction.ts","../../src/transactions/instances/simpleTransaction.ts","../../src/transactions/instances/multiAgentTransaction.ts","../../src/account/Ed25519Account.ts","../../src/account/SingleKeyAccount.ts","../../src/account/Account.ts","../../src/account/EphemeralKeyPair.ts","../../src/account/AbstractKeylessAccount.ts","../../src/account/KeylessAccount.ts","../../src/account/FederatedKeylessAccount.ts","../../src/account/MultiKeyAccount.ts","../../src/account/MultiEd25519Account.ts","../../src/account/utils.ts","../../src/account/AccountUtils.ts","../../src/account/AbstractedAccount.ts","../../src/account/DerivableAbstractedAccount.ts","../../src/transactions/transactionBuilder/transactionBuilder.ts","../../src/transactions/typeTag/parser.ts","../../src/transactions/transactionBuilder/helpers.ts","../../src/transactions/transactionBuilder/remoteAbi.ts","../../src/internal/transactionSubmission.ts","../../src/internal/account.ts","../../src/internal/view.ts","../../src/internal/abstraction.ts","../../src/api/account/abstraction.ts","../../src/api/account.ts","../../src/internal/coin.ts","../../src/api/coin.ts","../../src/internal/digitalAsset.ts","../../src/api/digitalAsset.ts","../../src/internal/faucet.ts","../../src/api/faucet.ts","../../src/internal/fungibleAsset.ts","../../src/api/fungibleAsset.ts","../../src/api/general.ts","../../src/internal/ans.ts","../../src/api/ans.ts","../../src/internal/staking.ts","../../src/api/staking.ts","../../src/api/transactionSubmission/build.ts","../../src/api/transactionSubmission/simulate.ts","../../src/api/transactionSubmission/submit.ts","../../src/api/transactionSubmission/management.ts","../../src/transactions/management/accountSequenceNumber.ts","../../src/transactions/management/transactionWorker.ts","../../src/api/transaction.ts","../../src/internal/keyless.ts","../../src/api/keyless.ts","../../src/internal/object.ts","../../src/api/object.ts","../../src/api/aptos.ts","../../src/core/crypto/federatedKeyless.ts","../../src/core/crypto/utils.ts","../../src/core/crypto/ephemeral.ts"],"sourcesContent":["// 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, PrivateKeyVariants } from \"../../types\";\nimport { CKDPriv, deriveKey, HARDENED_OFFSET, isValidHardenedPath, mnemonicToSeed, splitPath } from \"./hdKey\";\nimport { PrivateKey } from \"./privateKey\";\nimport { AccountPublicKey, PublicKey, VerifySignatureArgs, VerifySignatureAsyncArgs } 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 * @group Implementation\n * @category Serialization\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 * Checks if an ED25519 signature is non-canonical.\n * This function helps determine the validity of a signature by verifying its canonical form.\n *\n * @param signature - The signature to be checked for canonicality.\n * @returns A boolean indicating whether the 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 * @group Implementation\n * @category Serialization\n */\nexport function isCanonicalEd25519Signature(signature: Signature): boolean {\n const s = signature.toUint8Array().slice(32);\n for (let i = L.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/**\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 * @group Implementation\n * @category Serialization\n */\nexport class Ed25519PublicKey extends AccountPublicKey {\n /**\n * Length of an Ed25519 public key\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH: number = 32;\n\n /**\n * Bytes of the public key\n * @private\n * @group Implementation\n * @category Serialization\n */\n private readonly key: Hex;\n\n /**\n * Creates an instance of the Ed25519Signature class from a hex input.\n * This constructor validates the length of the signature to ensure it meets the required specifications.\n *\n * @param hexInput - The hex input representing the Ed25519 signature.\n * @throws Error if the signature length is not equal to Ed25519Signature.LENGTH.\n * @group Implementation\n * @category Serialization\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 message using a public key.\n *\n * @param args - The arguments for verification.\n * @param args.message - A signed message as a Hex string or Uint8Array.\n * @param args.signature - The signature of the message.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: VerifySignatureArgs): boolean {\n const { message, signature } = args;\n // Verify malleability\n if (!isCanonicalEd25519Signature(signature)) {\n return false;\n }\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 return ed25519.verify(signatureBytes, messageBytes, publicKeyBytes);\n }\n\n /**\n * Note: Ed25519Signatures can be verified syncronously.\n *\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by confirming that the signature is valid.\n *\n * @param args - The arguments for signature verification.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify, which must be an instance of Secp256k1Signature.\n * @returns A boolean indicating whether the signature is valid for the given message.\n * @group Implementation\n * @category Serialization\n */\n async verifySignatureAsync(args: VerifySignatureAsyncArgs): Promise<boolean> {\n return this.verifySignature(args);\n }\n\n /**\n * Generates an authentication key from the public key using the Ed25519 scheme.\n * This function is essential for creating a secure authentication key that can be used for further cryptographic operations.\n *\n * @returns {AuthenticationKey} The generated authentication key.\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.Ed25519,\n input: this.toUint8Array(),\n });\n }\n\n /**\n * Convert the internal data representation to a Uint8Array.\n *\n * @returns Uint8Array representation of the data.\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n /**\n * Serializes the data into a byte array using the provided serializer.\n * This allows for the conversion of data into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.key.toUint8Array());\n }\n\n /**\n * Deserialize bytes into an Ed25519Signature object.\n * This function is used to convert serialized byte data into a usable Ed25519Signature instance.\n *\n * @param deserializer - The deserializer instance used to read the byte data.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): Ed25519PublicKey {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519PublicKey(bytes);\n }\n\n // endregion\n\n /**\n * Determine if the provided public key is an instance of Ed25519PublicKey.\n *\n * @param publicKey - The public key to check.\n * @returns True if the public key is an instance of Ed25519PublicKey, otherwise false.\n * @deprecated use `instanceof Ed25519PublicKey` instead.\n * @group Implementation\n * @category Serialization\n */\n static isPublicKey(publicKey: AccountPublicKey): publicKey is Ed25519PublicKey {\n return publicKey instanceof Ed25519PublicKey;\n }\n\n /**\n * Determines if the provided public key is a valid Ed25519 public key.\n * This function checks for the presence of the \"key\" property and verifies that its data length matches the expected length\n * for Ed25519 public keys.\n *\n * @param publicKey - The public key to validate.\n * @returns A boolean indicating whether the public key is a valid Ed25519 public key.\n * @group Implementation\n * @category Serialization\n */\n static isInstance(publicKey: PublicKey): publicKey is Ed25519PublicKey {\n return \"key\" in publicKey && (publicKey.key as any)?.data?.length === Ed25519PublicKey.LENGTH;\n }\n}\n\n/**\n * Represents the private key of an Ed25519 key pair.\n * @group Implementation\n * @category Serialization\n */\nexport class Ed25519PrivateKey extends Serializable implements PrivateKey {\n /**\n * Length of an Ed25519 private key\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\n */\n static readonly SLIP_0010_SEED = \"ed25519 seed\";\n\n /**\n * The Ed25519 signing key\n * @private\n * @group Implementation\n * @category Serialization\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 * [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)\n *\n * @param hexInput HexInput (string or Uint8Array)\n * @param strict If true, private key must AIP-80 compliant.\n * @group Implementation\n * @category Serialization\n */\n constructor(hexInput: HexInput, strict?: boolean) {\n super();\n\n const privateKeyHex = PrivateKey.parseHexInput(hexInput, PrivateKeyVariants.Ed25519, strict);\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 A newly generated Ed25519 private key.\n * @group Implementation\n * @category Serialization\n */\n static generate(): Ed25519PrivateKey {\n const keyPair = ed25519.utils.randomPrivateKey();\n return new Ed25519PrivateKey(keyPair, false);\n }\n\n /**\n * Derives a private key from a mnemonic seed phrase using a specified BIP44 path.\n * To derive multiple keys from the same phrase, change the path\n *\n * IMPORTANT: Ed25519 supports hardened derivation only, as it lacks a key homomorphism, making non-hardened derivation impossible.\n *\n * @param path - The BIP44 path used for key derivation.\n * @param mnemonics - The mnemonic seed phrase from which the key will be derived.\n * @throws Error if the provided path is not a valid hardened path.\n * @group Implementation\n * @category Serialization\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 * Derives a child private key from a given BIP44 path and seed.\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 used for key derivation.\n * @param seed - The seed phrase created by the mnemonics, represented as a Uint8Array.\n * @param offset - The offset used for key derivation, defaults to HARDENED_OFFSET.\n * @returns An instance of Ed25519PrivateKey derived from the specified path and seed.\n * @group Implementation\n * @category Serialization\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, false);\n }\n\n // endregion\n\n // region PrivateKey\n\n /**\n * Derive the Ed25519PublicKey for this private key.\n *\n * @returns Ed25519PublicKey - The derived public key corresponding to the private key.\n * @group Implementation\n * @category Serialization\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 * This function generates a digital signature for the specified message, ensuring its authenticity and integrity.\n *\n * @param message - A message as a string or Uint8Array in HexInput format.\n * @returns A digital signature for the provided message.\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\n */\n toString(): string {\n return this.toAIP80String();\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 toHexString(): string {\n return this.signingKey.toString();\n }\n\n /**\n * Get the private key as a AIP-80 compliant hex string.\n *\n * [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)\n *\n * @returns AIP-80 compliant string representation of the private key.\n */\n toAIP80String(): string {\n return PrivateKey.formatPrivateKey(this.signingKey.toString(), PrivateKeyVariants.Ed25519);\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, false);\n }\n\n // endregion\n\n /**\n * Determines if the provided private key is an instance of Ed25519PrivateKey.\n *\n * @param privateKey - The private key to check.\n * @returns A boolean indicating whether the private key is an Ed25519PrivateKey.\n *\n * @deprecated Use `instanceof Ed25519PrivateKey` instead.\n * @group Implementation\n * @category Serialization\n */\n static isPrivateKey(privateKey: PrivateKey): privateKey is Ed25519PrivateKey {\n return privateKey instanceof Ed25519PrivateKey;\n }\n}\n\n/**\n * Represents a signature of a message signed using an Ed25519 private key.\n * @group Implementation\n * @category Serialization\n */\nexport class Ed25519Signature extends Signature {\n /**\n * Length of an Ed25519 signature, which is 64 bytes.\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH = 64;\n\n /**\n * The signature bytes\n * @private\n * @group Implementation\n * @category Serialization\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 // endregion\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n// eslint-disable-next-line max-classes-per-file\nimport { JwtPayload, jwtDecode } from \"jwt-decode\";\nimport { sha3_256 } from \"@noble/hashes/sha3\";\nimport { AccountPublicKey, PublicKey } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { Deserializer, Serializable, Serializer } from \"../../bcs\";\nimport { Hex, hexToAsciiString } from \"../hex\";\nimport {\n HexInput,\n EphemeralCertificateVariant,\n AnyPublicKeyVariant,\n SigningScheme,\n ZkpVariant,\n LedgerVersionArg,\n MoveResource,\n} from \"../../types\";\nimport { EphemeralPublicKey, EphemeralSignature } from \"./ephemeral\";\nimport { bigIntToBytesLE, bytesToBigIntLE, hashStrToField, padAndPackBytesWithLen, poseidonHash } from \"./poseidon\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Proof } from \"./proof\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"./ed25519\";\nimport {\n Groth16VerificationKeyResponse,\n KeylessConfigurationResponse,\n MoveAnyStruct,\n PatchedJWKsResponse,\n} from \"../../types/keyless\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport { getAptosFullNode } from \"../../client\";\nimport { memoizeAsync } from \"../../utils/memoize\";\nimport { AccountAddress, AccountAddressInput } from \"../accountAddress\";\nimport { base64UrlToBytes, getErrorMessage, nowInSeconds } from \"../../utils\";\nimport { KeylessError, KeylessErrorType } from \"../../errors\";\nimport { bn254 } from \"@noble/curves/bn254\";\nimport { bytesToNumberBE } from \"@noble/curves/abstract/utils\";\nimport { FederatedKeylessPublicKey } from \"./federatedKeyless\";\nimport { encode } from \"js-base64\";\nimport { generateSigningMessage } from \"../..\";\nimport { ProjPointType } from \"@noble/curves/abstract/weierstrass\";\nimport { Fp2 } from \"@noble/curves/abstract/tower\";\n\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const EPK_HORIZON_SECS = 10000000;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_AUD_VAL_BYTES = 120;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_UID_KEY_BYTES = 30;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_UID_VAL_BYTES = 330;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_ISS_VAL_BYTES = 120;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_EXTRA_FIELD_BYTES = 350;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_JWT_HEADER_B64_BYTES = 300;\n/**\n * @group Implementation\n * @category Serialization\n */\nexport const MAX_COMMITED_EPK_BYTES = 93;\n\n/**\n * Represents a Keyless Public Key used for authentication.\n *\n * This class encapsulates the public key functionality for keyless authentication,\n * including methods for generating and verifying signatures, as well as serialization\n * and deserialization of the key. The KeylessPublicKey is represented in the SDK\n * as `AnyPublicKey`.\n * @group Implementation\n * @category Serialization\n */\nexport class KeylessPublicKey extends AccountPublicKey {\n /**\n * The number of bytes that `idCommitment` should be\n * @group Implementation\n * @category Serialization\n */\n static readonly ID_COMMITMENT_LENGTH: number = 32;\n\n /**\n * The value of the 'iss' claim on the JWT which identifies the OIDC provider.\n * @group Implementation\n * @category Serialization\n */\n readonly iss: string;\n\n /**\n * A value representing a cryptographic commitment to a user identity.\n *\n * It is calculated from the aud, uidKey, uidVal, pepper.\n * @group Implementation\n * @category Serialization\n */\n readonly idCommitment: Uint8Array;\n\n /**\n * Constructs an instance with the specified parameters for cryptographic operations.\n *\n * @param args - The parameters required to initialize the instance.\n * @param args.alphaG1 - The hex representation of the alpha G1 value.\n * @param args.betaG2 - The hex representation of the beta G2 value.\n * @param args.deltaG2 - The hex representation of the delta G2 value.\n * @param args.gammaAbcG1 - An array containing two hex representations for gamma ABC G1 values.\n * @param args.gammaG2 - The hex representation of the gamma G2 value.\n * @group Implementation\n * @category Serialization\n */\n // TODO: Fix the JSDoc for the below values\n constructor(iss: string, idCommitment: HexInput) {\n super();\n const idcBytes = Hex.fromHexInput(idCommitment).toUint8Array();\n if (idcBytes.length !== KeylessPublicKey.ID_COMMITMENT_LENGTH) {\n throw new Error(`Id Commitment length in bytes should be ${KeylessPublicKey.ID_COMMITMENT_LENGTH}`);\n }\n this.iss = iss;\n this.idCommitment = idcBytes;\n }\n\n /**\n * Get the authentication key for the keyless public key.\n *\n * @returns AuthenticationKey - The authentication key derived from the keyless public key.\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n const serializer = new Serializer();\n serializer.serializeU32AsUleb128(AnyPublicKeyVariant.Keyless);\n serializer.serializeFixedBytes(this.bcsToBytes());\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: SigningScheme.SingleKey,\n input: serializer.toUint8Array(),\n });\n }\n\n /**\n * Verifies the validity of a signature for a given message.\n *\n * @param args - The arguments for signature verification.\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify against the message.\n * @param args.jwk - The JWK to use for verification.\n * @param args.keylessConfig - The keyless configuration to use for verification.\n * @returns true if the signature is valid; otherwise, false.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: {\n message: HexInput;\n signature: Signature;\n jwk: MoveJWK;\n keylessConfig: KeylessConfiguration;\n }): boolean {\n try {\n verifyKeylessSignatureWithJwkAndConfig({ ...args, publicKey: this });\n return true;\n } catch (error) {\n if (error instanceof KeylessError) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Verifies a keyless signature for a given message. It will fetch the keyless configuration and the JWK to\n * use for verification from the appropriate network as defined by the aptosConfig.\n *\n * @param args.aptosConfig The aptos config to use for fetching the keyless configuration.\n * @param args.message The message to verify the signature against.\n * @param args.signature The signature to verify.\n * @param args.options.throwErrorWithReason Whether to throw an error with the reason for the failure instead of returning false.\n * @returns true if the signature is valid\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n return verifyKeylessSignature({\n ...args,\n publicKey: this,\n });\n }\n\n /**\n * Serializes the current instance into a format suitable for transmission or storage.\n * This function ensures that all relevant fields are properly serialized, including the proof and optional fields.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @param serializer.proof - The proof to be serialized.\n * @param serializer.expHorizonSecs - The expiration horizon in seconds.\n * @param serializer.extraField - An optional additional field for serialization.\n * @param serializer.overrideAudVal - An optional override value for auditing.\n * @param serializer.trainingWheelsSignature - An optional signature for training wheels.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeStr(this.iss);\n serializer.serializeBytes(this.idCommitment);\n }\n\n /**\n * Deserializes a ZeroKnowledgeSig object from the provided deserializer.\n * This function allows you to reconstruct a ZeroKnowledgeSig instance from its serialized form.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @returns A new instance of ZeroKnowledgeSig.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): KeylessPublicKey {\n const iss = deserializer.deserializeStr();\n const addressSeed = deserializer.deserializeBytes();\n return new KeylessPublicKey(iss, addressSeed);\n }\n\n /**\n * Loads a KeylessPublicKey instance from the provided deserializer.\n * This function is used to deserialize the necessary components to create a KeylessPublicKey.\n *\n * @param deserializer - The deserializer used to extract the string and byte data.\n * @param deserializer.deserializeStr - A method to deserialize a string value.\n * @param deserializer.deserializeBytes - A method to deserialize byte data.\n * @returns A new instance of KeylessPublicKey.\n * @group Implementation\n * @category Serialization\n */\n static load(deserializer: Deserializer): KeylessPublicKey {\n const iss = deserializer.deserializeStr();\n const addressSeed = deserializer.deserializeBytes();\n return new KeylessPublicKey(iss, addressSeed);\n }\n\n /**\n * Determines if the provided public key is an instance of KeylessPublicKey.\n *\n * @param publicKey - The public key to check.\n * @returns A boolean indicating whether the public key is a KeylessPublicKey instance.\n * @group Implementation\n * @category Serialization\n */\n static isPublicKey(publicKey: PublicKey): publicKey is KeylessPublicKey {\n return publicKey instanceof KeylessPublicKey;\n }\n\n /**\n * Creates a KeylessPublicKey from the JWT components plus pepper\n *\n * @param args.iss the iss of the identity\n * @param args.uidKey the key to use to get the uidVal in the JWT token\n * @param args.uidVal the value of the uidKey in the JWT token\n * @param args.aud the client ID of the application\n * @param args.pepper The pepper used to maintain privacy of the account\n * @returns KeylessPublicKey\n * @group Implementation\n * @category Serialization\n */\n static create(args: {\n iss: string;\n uidKey: string;\n uidVal: string;\n aud: string;\n pepper: HexInput;\n }): KeylessPublicKey {\n computeIdCommitment(args);\n return new KeylessPublicKey(args.iss, computeIdCommitment(args));\n }\n\n /**\n * Creates a KeylessPublicKey instance from a JWT and a pepper value.\n * This function is useful for generating a public key that can be used for authentication based on the provided JWT claims and pepper.\n *\n * @param args - The arguments for creating the KeylessPublicKey.\n * @param args.jwt - The JSON Web Token to decode.\n * @param args.pepper - The pepper value used in the key creation process.\n * @param args.uidKey - An optional key to retrieve the unique identifier from the JWT payload, defaults to \"sub\".\n * @returns A KeylessPublicKey instance created from the provided JWT and pepper.\n * @group Implementation\n * @category Serialization\n */\n static fromJwtAndPepper(args: { jwt: string; pepper: HexInput; uidKey?: string }): KeylessPublicKey {\n const { jwt, pepper, uidKey = \"sub\" } = args;\n const jwtPayload = jwtDecode<JwtPayload & { [key: string]: string }>(jwt);\n if (typeof jwtPayload.iss !== \"string\") {\n throw new Error(\"iss was not found\");\n }\n if (typeof jwtPayload.aud !== \"string\") {\n throw new Error(\"aud was not found or an array of values\");\n }\n const uidVal = jwtPayload[uidKey];\n return KeylessPublicKey.create({ iss: jwtPayload.iss, uidKey, uidVal, aud: jwtPayload.aud, pepper });\n }\n\n /**\n * Checks if the provided public key is a valid instance by verifying its structure and types.\n *\n * @param publicKey - The public key to validate.\n * @returns A boolean indicating whether the public key is a valid instance.\n * @group Implementation\n * @category Serialization\n */\n static isInstance(publicKey: PublicKey) {\n return (\n \"iss\" in publicKey &&\n typeof publicKey.iss === \"string\" &&\n \"idCommitment\" in publicKey &&\n publicKey.idCommitment instanceof Uint8Array\n );\n }\n}\n\nexport async function verifyKeylessSignature(args: {\n publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n keylessConfig?: KeylessConfiguration;\n jwk?: MoveJWK;\n options?: { throwErrorWithReason?: boolean };\n}): Promise<boolean> {\n const {\n aptosConfig,\n publicKey,\n message,\n signature,\n jwk,\n keylessConfig = await getKeylessConfig({ aptosConfig }),\n options,\n } = args;\n try {\n if (!(signature instanceof KeylessSignature)) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.SIGNATURE_TYPE_INVALID,\n details: \"Not a keyless signature\",\n });\n }\n verifyKeylessSignatureWithJwkAndConfig({\n message,\n publicKey,\n signature,\n jwk: jwk ? jwk : await fetchJWK({ aptosConfig, publicKey, kid: signature.getJwkKid() }),\n keylessConfig,\n });\n return true;\n } catch (error) {\n if (options?.throwErrorWithReason) {\n throw error;\n }\n return false;\n }\n}\n\n/**\n * Syncronously verifies a keyless signature for a given message. You need to provide the keyless configuration and the\n * JWK to use for verification.\n *\n * @param args.message The message to verify the signature against.\n * @param args.signature The signature to verify.\n * @param args.keylessConfig The keyless configuration.\n * @param args.jwk The JWK to use for verification.\n * @returns true if the signature is valid\n * @throws KeylessError if the signature is invalid\n */\nexport function verifyKeylessSignatureWithJwkAndConfig(args: {\n publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n message: HexInput;\n signature: Signature;\n keylessConfig: KeylessConfiguration;\n jwk: MoveJWK;\n}): void {\n const { publicKey, message, signature, keylessConfig, jwk } = args;\n const { verificationKey, maxExpHorizonSecs, trainingWheelsPubkey } = keylessConfig;\n if (!(signature instanceof KeylessSignature)) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.SIGNATURE_TYPE_INVALID,\n details: \"Not a keyless signature\",\n });\n }\n if (!(signature.ephemeralCertificate.signature instanceof ZeroKnowledgeSig)) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.SIGNATURE_TYPE_INVALID,\n details: \"Unsupported ephemeral certificate variant\",\n });\n }\n const zkSig = signature.ephemeralCertificate.signature;\n if (!(zkSig.proof.proof instanceof Groth16Zkp)) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.SIGNATURE_TYPE_INVALID,\n details: \"Unsupported proof variant for ZeroKnowledgeSig\",\n });\n }\n const groth16Proof = zkSig.proof.proof;\n if (signature.expiryDateSecs < nowInSeconds()) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.SIGNATURE_EXPIRED,\n details: \"The expiryDateSecs is in the past\",\n });\n }\n if (zkSig.expHorizonSecs > maxExpHorizonSecs) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.MAX_EXPIRY_HORIZON_EXCEEDED,\n });\n }\n if (!signature.ephemeralPublicKey.verifySignature({ message, signature: signature.ephemeralSignature })) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.EPHEMERAL_SIGNATURE_VERIFICATION_FAILED,\n });\n }\n const publicInputsHash = getPublicInputsHash({ publicKey, signature, jwk, keylessConfig });\n if (!verificationKey.verifyProof({ publicInputsHash, groth16Proof })) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.PROOF_VERIFICATION_FAILED,\n });\n }\n if (trainingWheelsPubkey) {\n if (!zkSig.trainingWheelsSignature) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.TRAINING_WHEELS_SIGNATURE_MISSING,\n });\n }\n const proofAndStatement = new Groth16ProofAndStatement(groth16Proof, publicInputsHash);\n if (\n !trainingWheelsPubkey.verifySignature({\n message: proofAndStatement.hash(),\n signature: zkSig.trainingWheelsSignature,\n })\n ) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.TRAINING_WHEELS_SIGNATURE_VERIFICATION_FAILED,\n });\n }\n }\n}\n\n/**\n * Get the public inputs hash for the keyless signature.\n *\n * @param args.signature The signature\n * @param args.jwk The JWK to use for the public inputs hash\n * @param args.keylessConfig The keyless configuration which defines the byte lengths to use when hashing fields.\n * @returns The public inputs hash\n */\nfunction getPublicInputsHash(args: {\n publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n signature: KeylessSignature;\n jwk: MoveJWK;\n keylessConfig: KeylessConfiguration;\n}): bigint {\n const { publicKey, signature, jwk, keylessConfig } = args;\n const innerKeylessPublicKey = publicKey instanceof KeylessPublicKey ? publicKey : publicKey.keylessPublicKey;\n if (!(signature.ephemeralCertificate.signature instanceof ZeroKnowledgeSig)) {\n throw new Error(\"Signature is not a ZeroKnowledgeSig\");\n }\n const proof = signature.ephemeralCertificate.signature;\n const fields = [];\n fields.push(\n ...padAndPackBytesWithLen(signature.ephemeralPublicKey.toUint8Array(), keylessConfig.maxCommitedEpkBytes),\n );\n fields.push(bytesToBigIntLE(innerKeylessPublicKey.idCommitment));\n fields.push(signature.expiryDateSecs);\n fields.push(proof.expHorizonSecs);\n fields.push(hashStrToField(innerKeylessPublicKey.iss, keylessConfig.maxIssValBytes));\n if (!proof.extraField) {\n fields.push(0n);\n fields.push(hashStrToField(\" \", keylessConfig.maxExtraFieldBytes));\n } else {\n fields.push(1n);\n fields.push(hashStrToField(proof.extraField, keylessConfig.maxExtraFieldBytes));\n }\n fields.push(hashStrToField(encode(signature.jwtHeader, true) + \".\", keylessConfig.maxJwtHeaderB64Bytes));\n fields.push(jwk.toScalar());\n if (!proof.overrideAudVal) {\n fields.push(hashStrToField(\"\", MAX_AUD_VAL_BYTES));\n fields.push(0n);\n } else {\n fields.push(hashStrToField(proof.overrideAudVal, MAX_AUD_VAL_BYTES));\n fields.push(1n);\n }\n return poseidonHash(fields);\n}\n\n/**\n * Fetches the JWK from the issuer's well-known JWKS endpoint.\n *\n * @param args.publicKey The keyless public key which contains the issuer the address to fetch the JWK from (0x1 if not federated).\n * @param args.kid The kid of the JWK to fetch\n * @returns A JWK matching the `kid` in the JWT header.\n * @throws {KeylessError} If the JWK cannot be fetched\n */\nexport async function fetchJWK(args: {\n aptosConfig: AptosConfig;\n publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n kid: string;\n}): Promise<MoveJWK> {\n const { aptosConfig, publicKey, kid } = args;\n const keylessPubKey = publicKey instanceof KeylessPublicKey ? publicKey : publicKey.keylessPublicKey;\n const { iss } = keylessPubKey;\n\n let allJWKs: Map<string, MoveJWK[]>;\n const jwkAddr = publicKey instanceof FederatedKeylessPublicKey ? publicKey.jwkAddress : undefined;\n try {\n allJWKs = await getKeylessJWKs({ aptosConfig, jwkAddr });\n } catch (error) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.FULL_NODE_JWKS_LOOKUP_ERROR,\n error,\n details: `Failed to fetch ${jwkAddr ? \"Federated\" : \"Patched\"}JWKs ${jwkAddr ? `for address ${jwkAddr}` : \"0x1\"}`,\n });\n }\n\n // Find the corresponding JWK set by `iss`\n const jwksForIssuer = allJWKs.get(iss);\n\n if (jwksForIssuer === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.INVALID_JWT_ISS_NOT_RECOGNIZED,\n details: `JWKs for issuer ${iss} not found.`,\n });\n }\n\n // Find the corresponding JWK by `kid`\n const jwk = jwksForIssuer.find((key) => key.kid === kid);\n\n if (jwk === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.INVALID_JWT_JWK_NOT_FOUND,\n details: `JWK with kid '${kid}' for issuer '${iss}' not found.`,\n });\n }\n\n return jwk;\n}\n\nfunction computeIdCommitment(args: { uidKey: string; uidVal: string; aud: string; pepper: HexInput }): Uint8Array {\n const { uidKey, uidVal, aud, pepper } = args;\n\n const fields = [\n bytesToBigIntLE(Hex.fromHexInput(pepper).toUint8Array()),\n hashStrToField(aud, MAX_AUD_VAL_BYTES),\n hashStrToField(uidVal, MAX_UID_VAL_BYTES),\n hashStrToField(uidKey, MAX_UID_KEY_BYTES),\n ];\n\n return bigIntToBytesLE(poseidonHash(fields), KeylessPublicKey.ID_COMMITMENT_LENGTH);\n}\n\n/**\n * Represents a signature of a message signed via a Keyless Account, utilizing proofs or a JWT token for authentication.\n * @group Implementation\n * @category Serialization\n */\nexport class KeylessSignature extends Signature {\n /**\n * The inner signature ZeroKnowledgeSignature or OpenIdSignature\n * @group Implementation\n * @category Serialization\n */\n readonly ephemeralCertificate: EphemeralCertificate;\n\n /**\n * The jwt header in the token used to create the proof/signature. In json string representation.\n * @group Implementation\n * @category Serialization\n */\n readonly jwtHeader: string;\n\n /**\n * The expiry timestamp in seconds of the EphemeralKeyPair used to sign\n * @group Implementation\n * @category Serialization\n */\n readonly expiryDateSecs: number;\n\n /**\n * The ephemeral public key used to verify the signature\n * @group Implementation\n * @category Serialization\n */\n readonly ephemeralPublicKey: EphemeralPublicKey;\n\n /**\n * The signature resulting from signing with the private key of the EphemeralKeyPair\n * @group Implementation\n * @category Serialization\n */\n readonly ephemeralSignature: EphemeralSignature;\n\n constructor(args: {\n jwtHeader: string;\n ephemeralCertificate: EphemeralCertificate;\n expiryDateSecs: number;\n ephemeralPublicKey: EphemeralPublicKey;\n ephemeralSignature: EphemeralSignature;\n }) {\n super();\n const { jwtHeader, ephemeralCertificate, expiryDateSecs, ephemeralPublicKey, ephemeralSignature } = args;\n this.jwtHeader = jwtHeader;\n this.ephemeralCertificate = ephemeralCertificate;\n this.expiryDateSecs = expiryDateSecs;\n this.ephemeralPublicKey = ephemeralPublicKey;\n this.ephemeralSignature = ephemeralSignature;\n }\n\n /**\n * Get the kid of the JWT used to derive the Keyless Account used to sign.\n *\n * @returns the kid as a string\n */\n getJwkKid(): string {\n return parseJwtHeader(this.jwtHeader).kid;\n }\n\n serialize(serializer: Serializer): void {\n this.ephemeralCertificate.serialize(serializer);\n serializer.serializeStr(this.jwtHeader);\n serializer.serializeU64(this.expiryDateSecs);\n this.ephemeralPublicKey.serialize(serializer);\n this.ephemeralSignature.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): KeylessSignature {\n const ephemeralCertificate = EphemeralCertificate.deserialize(deserializer);\n const jwtHeader = deserializer.deserializeStr();\n const expiryDateSecs = deserializer.deserializeU64();\n const ephemeralPublicKey = EphemeralPublicKey.deserialize(deserializer);\n const ephemeralSignature = EphemeralSignature.deserialize(deserializer);\n return new KeylessSignature({\n jwtHeader,\n expiryDateSecs: Number(expiryDateSecs),\n ephemeralCertificate,\n ephemeralPublicKey,\n ephemeralSignature,\n });\n }\n\n static getSimulationSignature(): KeylessSignature {\n return new KeylessSignature({\n jwtHeader: \"{}\",\n ephemeralCertificate: new EphemeralCertificate(\n new ZeroKnowledgeSig({\n proof: new ZkProof(\n new Groth16Zkp({ a: new Uint8Array(32), b: new Uint8Array(64), c: new Uint8Array(32) }),\n ZkpVariant.Groth16,\n ),\n expHorizonSecs: 0,\n }),\n EphemeralCertificateVariant.ZkProof,\n ),\n expiryDateSecs: 0,\n ephemeralPublicKey: new EphemeralPublicKey(new Ed25519PublicKey(new Uint8Array(32))),\n ephemeralSignature: new EphemeralSignature(new Ed25519Signature(new Uint8Array(64))),\n });\n }\n\n static isSignature(signature: Signature): signature is KeylessSignature {\n return signature instanceof KeylessSignature;\n }\n}\n\n/**\n * Represents an ephemeral certificate containing a signature, specifically a ZeroKnowledgeSig.\n * This class can be extended to support additional signature types, such as OpenIdSignature.\n *\n * @extends Signature\n * @group Implementation\n * @category Serialization\n */\nexport class EphemeralCertificate extends Signature {\n public readonly signature: Signature;\n\n /**\n * Index of the underlying enum variant\n * @group Implementation\n * @category Serialization\n */\n readonly variant: EphemeralCertificateVariant;\n\n constructor(signature: Signature, variant: EphemeralCertificateVariant) {\n super();\n this.signature = signature;\n this.variant = variant;\n }\n\n /**\n * Get the public key in bytes (Uint8Array).\n *\n * @returns Uint8Array representation of the public key\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.signature.toUint8Array();\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.variant);\n this.signature.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): EphemeralCertificate {\n const variant = deserializer.deserializeUleb128AsU32();\n switch (variant) {\n case EphemeralCertificateVariant.ZkProof:\n return new EphemeralCertificate(ZeroKnowledgeSig.deserialize(deserializer), variant);\n default:\n throw new Error(`Unknown variant index for EphemeralCertificate: ${variant}`);\n }\n }\n}\n\n/**\n * Represents a fixed-size byte array of 32 bytes, extending the Serializable class.\n * This class is used for handling and serializing G1 bytes in cryptographic operations.\n *\n * @extends Serializable\n * @group Implementation\n * @category Serialization\n */\nclass G1Bytes extends Serializable {\n private static readonly B = bn254.fields.Fp.create(3n);\n\n data: Uint8Array;\n\n constructor(data: HexInput) {\n super();\n this.data = Hex.fromHexInput(data).toUint8Array();\n if (this.data.length !== 32) {\n throw new Error(\"Input needs to be 32 bytes\");\n }\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.data);\n }\n\n static deserialize(deserializer: Deserializer): G1Bytes {\n const bytes = deserializer.deserializeFixedBytes(32);\n return new G1Bytes(bytes);\n }\n\n // Convert the projective coordinates to strings\n toArray(): string[] {\n const point = this.toProjectivePoint();\n return [point.x.toString(), point.y.toString(), point.pz.toString()];\n }\n\n /**\n * Converts the G1 bytes to a projective point.\n * @returns The projective point.\n */\n toProjectivePoint(): ProjPointType<bigint> {\n const bytes = new Uint8Array(this.data);\n // Reverse the bytes to convert from little-endian to big-endian.\n bytes.reverse();\n // This gets the flag bit to determine which y to use.\n const yFlag = (bytes[0] & 0x80) >> 7;\n const { Fp } = bn254.fields;\n const x = Fp.create(bytesToBn254FpBE(bytes));\n const y = Fp.sqrt(Fp.add(Fp.pow(x, 3n), G1Bytes.B));\n const negY = Fp.neg(y);\n const yToUse = y > negY === (yFlag === 1) ? y : negY;\n return bn254.G1.ProjectivePoint.fromAffine({\n x: x,\n y: yToUse,\n });\n }\n}\n\nfunction bytesToBn254FpBE(bytes: Uint8Array): bigint {\n if (bytes.length !== 32) {\n throw new Error(\"Input should be 32 bytes\");\n }\n // Clear the first two bits of the first byte which removes any flags.\n const result = new Uint8Array(bytes);\n result[0] = result[0] & 0x3f; // 0x3F = 00111111 in binary\n return bytesToNumberBE(result);\n}\n\n/**\n * Represents a 64-byte G2 element in a cryptographic context.\n * This class provides methods for serialization and deserialization of G2 bytes.\n *\n * @extends Serializable\n * @group Implementation\n * @category Serialization\n */\nclass G2Bytes extends Serializable {\n /**\n * The constant b value used in G2 point calculations\n */\n private static readonly B = bn254.fields.Fp2.fromBigTuple([\n 19485874751759354771024239261021720505790618469301721065564631296452457478373n,\n 266929791119991161246907387137283842545076965332900288569378510910307636690n,\n ]);\n\n data: Uint8Array;\n\n constructor(data: HexInput) {\n super();\n this.data = Hex.fromHexInput(data).toUint8Array();\n if (this.data.length !== 64) {\n throw new Error(\"Input needs to be 64 bytes\");\n }\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.data);\n }\n\n static deserialize(deserializer: Deserializer): G2Bytes {\n const bytes = deserializer.deserializeFixedBytes(64);\n return new G2Bytes(bytes);\n }\n\n // Convert the projective coordinates to strings\n toArray(): [string, string][] {\n const point = this.toProjectivePoint();\n return [\n [\n point.x.c0.toString(), // x real part\n point.x.c1.toString(),\n ], // x imaginary part\n [\n point.y.c0.toString(), // y real part\n point.y.c1.toString(),\n ], // y imaginary part\n [\n point.pz.c0.toString(), // z real part\n point.pz.c1.toString(),\n ], // z imaginary part\n ];\n }\n\n toProjectivePoint(): ProjPointType<Fp2> {\n const bytes = new Uint8Array(this.data);\n // Reverse the bytes to convert from little-endian to big-endian for each part of x.\n const x0 = bytes.slice(0, 32).reverse();\n const x1 = bytes.slice(32, 64).reverse();\n // This gets the flag bit to determine which y to use.\n const yFlag = (x1[0] & 0x80) >> 7;\n const { Fp2 } = bn254.fields;\n const x = Fp2.fromBigTuple([bytesToBn254FpBE(x0), bytesToBn254FpBE(x1)]);\n const y = Fp2.sqrt(Fp2.add(Fp2.pow(x, 3n), G2Bytes.B));\n const negY = Fp2.neg(y);\n const isYGreaterThanNegY = y.c1 > negY.c1 || (y.c1 === negY.c1 && y.c0 > negY.c0);\n const yToUse = isYGreaterThanNegY === (yFlag === 1) ? y : negY;\n return bn254.G2.ProjectivePoint.fromAffine({\n x: x,\n y: yToUse,\n });\n }\n}\n\n/**\n * Represents a Groth16 zero-knowledge proof, consisting of three proof points in compressed serialization format.\n * The points are the compressed serialization of affine representation of the proof.\n *\n * @extends Proof\n * @group Implementation\n * @category Serialization\n */\nexport class Groth16Zkp extends Proof {\n /**\n * The bytes of G1 proof point a\n * @group Implementation\n * @category Serialization\n */\n a: G1Bytes;\n\n /**\n * The bytes of G2 proof point b\n * @group Implementation\n * @category Serialization\n */\n b: G2Bytes;\n\n /**\n * The bytes of G1 proof point c\n * @group Implementation\n * @category Serialization\n */\n c: G1Bytes;\n\n constructor(args: { a: HexInput; b: HexInput; c: HexInput }) {\n super();\n const { a, b, c } = args;\n this.a = new G1Bytes(a);\n this.b = new G2Bytes(b);\n this.c = new G1Bytes(c);\n }\n\n serialize(serializer: Serializer): void {\n this.a.serialize(serializer);\n this.b.serialize(serializer);\n this.c.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): Groth16Zkp {\n const a = G1Bytes.deserialize(deserializer).bcsToBytes();\n const b = G2Bytes.deserialize(deserializer).bcsToBytes();\n const c = G1Bytes.deserialize(deserializer).bcsToBytes();\n return new Groth16Zkp({ a, b, c });\n }\n\n toSnarkJsJson() {\n return {\n protocol: \"groth16\",\n curve: \"bn128\",\n pi_a: this.a.toArray(),\n pi_b: this.b.toArray(),\n pi_c: this.c.toArray(),\n };\n }\n}\n\n/**\n * Represents a Groth16 proof and statement, consisting of a Groth16 proof and a public inputs hash.\n * This is used to generate the signing message for the training wheels signature.\n *\n * @extends Serializable\n * @group Implementation\n * @category Serialization\n */\nexport class Groth16ProofAndStatement extends Serializable {\n /**\n * The Groth16 proof\n * @group Implementation\n * @category Serialization\n */\n proof: Groth16Zkp;\n\n /**\n * The public inputs hash as a 32 byte Uint8Array\n * @group Implementation\n * @category Serialization\n */\n publicInputsHash: Uint8Array;\n\n /**\n * The domain separator prefix used when hashing.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly domainSeparator = \"APTOS::Groth16ProofAndStatement\";\n\n constructor(proof: Groth16Zkp, publicInputsHash: HexInput | bigint) {\n super();\n this.proof = proof;\n this.publicInputsHash =\n typeof publicInputsHash === \"bigint\"\n ? bigIntToBytesLE(publicInputsHash, 32)\n : Hex.fromHexInput(publicInputsHash).toUint8Array();\n if (this.publicInputsHash.length !== 32) {\n throw new Error(\"Invalid public inputs hash\");\n }\n }\n\n serialize(serializer: Serializer): void {\n this.proof.serialize(serializer);\n serializer.serializeFixedBytes(this.publicInputsHash);\n }\n\n static deserialize(deserializer: Deserializer): Groth16ProofAndStatement {\n return new Groth16ProofAndStatement(Groth16Zkp.deserialize(deserializer), deserializer.deserializeFixedBytes(32));\n }\n\n hash(): Uint8Array {\n return generateSigningMessage(this.bcsToBytes(), this.domainSeparator);\n }\n}\n\n/**\n * Represents a container for different types of zero-knowledge proofs.\n *\n * @extends Serializable\n * @group Implementation\n * @category Serialization\n */\nexport class ZkProof extends Serializable {\n public readonly proof: Proof;\n\n /**\n * Index of the underlying enum variant\n * @group Implementation\n * @category Serialization\n */\n readonly variant: ZkpVariant;\n\n constructor(proof: Proof, variant: ZkpVariant) {\n super();\n this.proof = proof;\n this.variant = variant;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.variant);\n this.proof.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): ZkProof {\n const variant = deserializer.deserializeUleb128AsU32();\n switch (variant) {\n case ZkpVariant.Groth16:\n return new ZkProof(Groth16Zkp.deserialize(deserializer), variant);\n default:\n throw new Error(`Unknown variant index for ZkProof: ${variant}`);\n }\n }\n}\n\n/**\n * Represents a zero-knowledge signature, encapsulating the proof and its associated metadata.\n *\n * @extends Signature\n * @group Implementation\n * @category Serialization\n */\nexport class ZeroKnowledgeSig extends Signature {\n /**\n * The proof\n * @group Implementation\n * @category Serialization\n */\n readonly proof: ZkProof;\n\n /**\n * The max lifespan of the proof\n * @group Implementation\n * @category Serialization\n */\n readonly expHorizonSecs: number;\n\n /**\n * A key value pair on the JWT token that can be specified on the signature which would reveal the value on chain.\n * Can be used to assert identity or other attributes.\n * @group Implementation\n * @category Serialization\n */\n readonly extraField?: string;\n\n /**\n * The 'aud' value of the recovery service which is set when recovering an account.\n * @group Implementation\n * @category Serialization\n */\n readonly overrideAudVal?: string;\n\n /**\n * The training wheels signature\n * @group Implementation\n * @category Serialization\n */\n readonly trainingWheelsSignature?: EphemeralSignature;\n\n constructor(args: {\n proof: ZkProof;\n expHorizonSecs: number;\n extraField?: string;\n overrideAudVal?: string;\n trainingWheelsSignature?: EphemeralSignature;\n }) {\n super();\n const { proof, expHorizonSecs, trainingWheelsSignature, extraField, overrideAudVal } = args;\n this.proof = proof;\n this.expHorizonSecs = expHorizonSecs;\n this.trainingWheelsSignature = trainingWheelsSignature;\n this.extraField = extraField;\n this.overrideAudVal = overrideAudVal;\n }\n\n /**\n * Deserialize a ZeroKnowledgeSig object from its BCS serialization in bytes.\n *\n * @param bytes - The bytes representing the serialized ZeroKnowledgeSig.\n * @returns ZeroKnowledgeSig - The deserialized ZeroKnowledgeSig object.\n * @group Implementation\n * @category Serialization\n */\n static fromBytes(bytes: Uint8Array): ZeroKnowledgeSig {\n return ZeroKnowledgeSig.deserialize(new Deserializer(bytes));\n }\n\n serialize(serializer: Serializer): void {\n this.proof.serialize(serializer);\n serializer.serializeU64(this.expHorizonSecs);\n serializer.serializeOption(this.extraField);\n serializer.serializeOption(this.overrideAudVal);\n serializer.serializeOption(this.trainingWheelsSignature);\n }\n\n static deserialize(deserializer: Deserializer): ZeroKnowledgeSig {\n const proof = ZkProof.deserialize(deserializer);\n const expHorizonSecs = Number(deserializer.deserializeU64());\n const extraField = deserializer.deserializeOption(\"string\");\n const overrideAudVal = deserializer.deserializeOption(\"string\");\n const trainingWheelsSignature = deserializer.deserializeOption(EphemeralSignature);\n return new ZeroKnowledgeSig({ proof, expHorizonSecs, trainingWheelsSignature, extraField, overrideAudVal });\n }\n}\n\n/**\n * Represents the on-chain configuration for how Keyless accounts operate.\n *\n * @remarks\n * This class encapsulates the verification key and the maximum lifespan of ephemeral key pairs,\n * which are essential for the functionality of Keyless accounts.\n * @group Implementation\n * @category Serialization\n */\nexport class KeylessConfiguration {\n /**\n * The verification key used to verify Groth16 proofs on chain\n * @group Implementation\n * @category Serialization\n */\n readonly verificationKey: Groth16VerificationKey;\n\n /**\n * The maximum lifespan of an ephemeral key pair. This is configured on chain.\n * @group Implementation\n * @category Serialization\n */\n readonly maxExpHorizonSecs: number;\n\n /**\n * The public key of the training wheels account.\n * @group Implementation\n * @category Serialization\n */\n readonly trainingWheelsPubkey?: EphemeralPublicKey;\n\n /**\n * The maximum number of bytes that can be used for the extra field.\n * @group Implementation\n * @category Serialization\n */\n readonly maxExtraFieldBytes: number;\n\n /**\n * The maximum number of bytes that can be used for the JWT header.\n * @group Implementation\n * @category Serialization\n */\n readonly maxJwtHeaderB64Bytes: number;\n\n /**\n * The maximum number of bytes that can be used for the issuer value.\n * @group Implementation\n * @category Serialization\n */\n readonly maxIssValBytes: number;\n\n /**\n * The maximum number of bytes that can be used for the committed ephemeral public key.\n * @group Implementation\n * @category Serialization\n */\n readonly maxCommitedEpkBytes: number;\n\n constructor(args: {\n verificationKey: Groth16VerificationKey;\n trainingWheelsPubkey?: HexInput;\n maxExpHorizonSecs?: number;\n maxExtraFieldBytes?: number;\n maxJwtHeaderB64Bytes?: number;\n maxIssValBytes?: number;\n maxCommitedEpkBytes?: number;\n }) {\n const {\n verificationKey,\n trainingWheelsPubkey,\n maxExpHorizonSecs = EPK_HORIZON_SECS,\n maxExtraFieldBytes = MAX_EXTRA_FIELD_BYTES,\n maxJwtHeaderB64Bytes = MAX_JWT_HEADER_B64_BYTES,\n maxIssValBytes = MAX_ISS_VAL_BYTES,\n maxCommitedEpkBytes = MAX_COMMITED_EPK_BYTES,\n } = args;\n\n this.verificationKey = verificationKey;\n this.maxExpHorizonSecs = maxExpHorizonSecs;\n if (trainingWheelsPubkey) {\n this.trainingWheelsPubkey = new EphemeralPublicKey(new Ed25519PublicKey(trainingWheelsPubkey));\n }\n this.maxExtraFieldBytes = maxExtraFieldBytes;\n this.maxJwtHeaderB64Bytes = maxJwtHeaderB64Bytes;\n this.maxIssValBytes = maxIssValBytes;\n this.maxCommitedEpkBytes = maxCommitedEpkBytes;\n }\n\n /**\n * Creates a new KeylessConfiguration instance from a Groth16VerificationKeyResponse and a KeylessConfigurationResponse.\n * @param res - The Groth16VerificationKeyResponse object containing the verification key data.\n * @param config - The KeylessConfigurationResponse object containing the configuration data.\n * @returns A new KeylessConfiguration instance.\n */\n static create(res: Groth16VerificationKeyResponse, config: KeylessConfigurationResponse): KeylessConfiguration {\n return new KeylessConfiguration({\n verificationKey: new Groth16VerificationKey({\n alphaG1: res.alpha_g1,\n betaG2: res.beta_g2,\n deltaG2: res.delta_g2,\n gammaAbcG1: res.gamma_abc_g1,\n gammaG2: res.gamma_g2,\n }),\n maxExpHorizonSecs: Number(config.max_exp_horizon_secs),\n trainingWheelsPubkey: config.training_wheels_pubkey.vec[0],\n maxExtraFieldBytes: config.max_extra_field_bytes,\n maxJwtHeaderB64Bytes: config.max_jwt_header_b64_bytes,\n maxIssValBytes: config.max_iss_val_bytes,\n maxCommitedEpkBytes: config.max_commited_epk_bytes,\n });\n }\n}\n\n/**\n * Represents the verification key stored on-chain used to verify Groth16 proofs.\n * @group Implementation\n * @category Serialization\n */\nexport class Groth16VerificationKey {\n // The docstrings below are borrowed from ark-groth16\n\n /**\n * The `alpha * G`, where `G` is the generator of G1\n * @group Implementation\n * @category Serialization\n */\n readonly alphaG1: G1Bytes;\n\n /**\n * The `alpha * H`, where `H` is the generator of G2\n * @group Implementation\n * @category Serialization\n */\n readonly betaG2: G2Bytes;\n\n /**\n * The `delta * H`, where `H` is the generator of G2\n * @group Implementation\n * @category Serialization\n */\n readonly deltaG2: G2Bytes;\n\n /**\n * The `gamma^{-1} * (beta * a_i + alpha * b_i + c_i) * H`, where H is the generator of G1\n * @group Implementation\n * @category Serialization\n */\n readonly gammaAbcG1: [G1Bytes, G1Bytes];\n\n /**\n * The `gamma * H`, where `H` is the generator of G2\n * @group Implementation\n * @category Serialization\n */\n readonly gammaG2: G2Bytes;\n\n constructor(args: {\n alphaG1: HexInput;\n betaG2: HexInput;\n deltaG2: HexInput;\n gammaAbcG1: [HexInput, HexInput];\n gammaG2: HexInput;\n }) {\n const { alphaG1, betaG2, deltaG2, gammaAbcG1, gammaG2 } = args;\n this.alphaG1 = new G1Bytes(alphaG1);\n this.betaG2 = new G2Bytes(betaG2);\n this.deltaG2 = new G2Bytes(deltaG2);\n this.gammaAbcG1 = [new G1Bytes(gammaAbcG1[0]), new G1Bytes(gammaAbcG1[1])];\n this.gammaG2 = new G2Bytes(gammaG2);\n }\n\n /**\n * Calculates the hash of the serialized form of the verification key.\n * This is useful for comparing verification keys or using them as unique identifiers.\n *\n * @returns The SHA3-256 hash of the serialized verification key as a Uint8Array\n */\n public hash(): Uint8Array {\n const serializer = new Serializer();\n this.serialize(serializer);\n return sha3_256.create().update(serializer.toUint8Array()).digest();\n }\n\n serialize(serializer: Serializer): void {\n this.alphaG1.serialize(serializer);\n this.betaG2.serialize(serializer);\n this.deltaG2.serialize(serializer);\n this.gammaAbcG1[0].serialize(serializer);\n this.gammaAbcG1[1].serialize(serializer);\n this.gammaG2.serialize(serializer);\n }\n\n /**\n * Converts a Groth16VerificationKeyResponse object into a Groth16VerificationKey instance.\n *\n * @param res - The Groth16VerificationKeyResponse object containing the verification key data.\n * @param res.alpha_g1 - The alpha G1 value from the response.\n * @param res.beta_g2 - The beta G2 value from the response.\n * @param res.delta_g2 - The delta G2 value from the response.\n * @param res.gamma_abc_g1 - The gamma ABC G1 value from the response.\n * @param res.gamma_g2 - The gamma G2 value from the response.\n * @returns A Groth16VerificationKey instance constructed from the provided response data.\n * @group Implementation\n * @category Serialization\n */\n static fromGroth16VerificationKeyResponse(res: Groth16VerificationKeyResponse): Groth16VerificationKey {\n return new Groth16VerificationKey({\n alphaG1: res.alpha_g1,\n betaG2: res.beta_g2,\n deltaG2: res.delta_g2,\n gammaAbcG1: res.gamma_abc_g1,\n gammaG2: res.gamma_g2,\n });\n }\n\n /**\n * Verifies a Groth16 proof using the verification key given the public inputs hash and the proof.\n *\n * @param args.publicInputsHash The public inputs hash\n * @param args.groth16Proof The Groth16 proof\n * @returns true if the proof is valid\n */\n verifyProof(args: { publicInputsHash: bigint; groth16Proof: Groth16Zkp }): boolean {\n const { publicInputsHash, groth16Proof } = args;\n\n try {\n // Get proof points\n const proofA = groth16Proof.a.toProjectivePoint();\n const proofB = groth16Proof.b.toProjectivePoint();\n const proofC = groth16Proof.c.toProjectivePoint();\n\n // Get verification key points\n const vkAlpha1 = this.alphaG1.toProjectivePoint();\n const vkBeta2 = this.betaG2.toProjectivePoint();\n const vkGamma2 = this.gammaG2.toProjectivePoint();\n const vkDelta2 = this.deltaG2.toProjectivePoint();\n const vkIC = this.gammaAbcG1.map((g1) => g1.toProjectivePoint());\n\n const { Fp12 } = bn254.fields;\n\n // Check that the following pairing equation holds:\n // e(A_1, B_2) = e(\\alpha_1, \\beta_2) + e(\\ic_0 + public_inputs_hash \\ic_1, \\gamma_2) + e(C_1, \\delta_2)\n // Where A_1, B_2, C_1 are the proof points and \\alpha_1, \\beta_2, \\gamma_2, \\delta_2, \\ic_0, \\ic_1\n // are the verification key points\n\n // \\ic_0 + public_inputs_hash \\ic_1\n let accum = vkIC[0].add(vkIC[1].multiply(publicInputsHash));\n // e(\\ic_0 + public_inputs_hash \\ic_1, \\gamma_2)\n const pairingAccumGamma = bn254.pairing(accum, vkGamma2);\n // e(A_1, B_2)\n const pairingAB = bn254.pairing(proofA, proofB);\n // e(\\alpha_1, \\beta_2)\n const pairingAlphaBeta = bn254.pairing(vkAlpha1, vkBeta2);\n // e(C_1, \\delta_2)\n const pairingCDelta = bn254.pairing(proofC, vkDelta2);\n // Get the result of the right hand side of the pairing equation\n const product = Fp12.mul(pairingAlphaBeta, Fp12.mul(pairingAccumGamma, pairingCDelta));\n // Check if the left hand side equals the right hand side\n return Fp12.eql(pairingAB, product);\n } catch (error) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.PROOF_VERIFICATION_FAILED,\n error,\n details: \"Error encountered when checking zero knowledge relation\",\n });\n }\n }\n\n /**\n * Converts the verification key to a JSON format compatible with snarkjs groth16.verify\n *\n * @returns An object containing the verification key in snarkjs format\n * @group Implementation\n * @category Serialization\n */\n toSnarkJsJson() {\n return {\n protocol: \"groth16\",\n curve: \"bn128\",\n nPublic: 1,\n vk_alpha_1: this.alphaG1.toArray(),\n vk_beta_2: this.betaG2.toArray(),\n vk_gamma_2: this.gammaG2.toArray(),\n vk_delta_2: this.deltaG2.toArray(),\n IC: this.gammaAbcG1.map((g1) => g1.toArray()),\n };\n }\n}\n\n/**\n * Retrieves the configuration parameters for Keyless Accounts on the blockchain, including the verifying key and the maximum\n * expiry horizon.\n *\n * @param args - The arguments for retrieving the keyless configuration.\n * @param args.aptosConfig - The Aptos configuration object containing network details.\n * @param args.options - Optional parameters for the request.\n * @param args.options.ledgerVersion - The ledger version to query; if not provided, the latest version will be used.\n * @returns KeylessConfiguration - The configuration object containing the verifying key and maximum expiry horizon.\n * @group Implementation\n * @category Serialization\n */\nexport async function getKeylessConfig(args: {\n aptosConfig: AptosConfig;\n options?: LedgerVersionArg;\n}): Promise<KeylessConfiguration> {\n const { aptosConfig } = args;\n try {\n return await memoizeAsync(\n async () => {\n const [config, vk] = await Promise.all([\n getKeylessConfigurationResource(args),\n getGroth16VerificationKeyResource(args),\n ]);\n return KeylessConfiguration.create(vk, config);\n },\n `keyless-configuration-${aptosConfig.network}`,\n 1000 * 60 * 5, // 5 minutes\n )();\n } catch (error) {\n if (error instanceof KeylessError) {\n throw error;\n }\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.FULL_NODE_OTHER,\n error,\n });\n }\n}\n\n/**\n * Parses a JWT and returns the 'iss', 'aud', and 'uid' values.\n *\n * @param args - The arguments for parsing the JWT.\n * @param args.jwt - The JWT to parse.\n * @param args.uidKey - The key to use for the 'uid' value; defaults to 'sub'.\n * @returns The 'iss', 'aud', and 'uid' values from the JWT.\n */\nexport function getIssAudAndUidVal(args: { jwt: string; uidKey?: string }): {\n iss: string;\n aud: string;\n uidVal: string;\n} {\n const { jwt, uidKey = \"sub\" } = args;\n let jwtPayload: JwtPayload & { [key: string]: string };\n try {\n jwtPayload = jwtDecode<JwtPayload & { [key: string]: string }>(jwt);\n } catch (error) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.JWT_PARSING_ERROR,\n details: `Failed to parse JWT - ${getErrorMessage(error)}`,\n });\n }\n if (typeof jwtPayload.iss !== \"string\") {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.JWT_PARSING_ERROR,\n details: \"JWT is missing 'iss' in the payload. This should never happen.\",\n });\n }\n if (typeof jwtPayload.aud !== \"string\") {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.JWT_PARSING_ERROR,\n details: \"JWT is missing 'aud' in the payload or 'aud' is an array of values.\",\n });\n }\n const uidVal = jwtPayload[uidKey];\n return { iss: jwtPayload.iss, aud: jwtPayload.aud, uidVal };\n}\n\n/**\n * Retrieves the KeylessConfiguration set on chain.\n *\n * @param args - The arguments for retrieving the configuration.\n * @param args.aptosConfig - The configuration for connecting to the Aptos network.\n * @param args.options - Optional parameters for the request.\n * @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.\n * @returns KeylessConfigurationResponse - The response containing the keyless configuration data.\n * @group Implementation\n * @category Serialization\n */\nasync function getKeylessConfigurationResource(args: {\n aptosConfig: AptosConfig;\n options?: LedgerVersionArg;\n}): Promise<KeylessConfigurationResponse> {\n const { aptosConfig, options } = args;\n const resourceType = \"0x1::keyless_account::Configuration\";\n try {\n const { data } = await getAptosFullNode<{}, MoveResource<KeylessConfigurationResponse>>({\n aptosConfig,\n originMethod: \"getKeylessConfigurationResource\",\n path: `accounts/${AccountAddress.from(\"0x1\").toString()}/resource/${resourceType}`,\n params: { ledger_version: options?.ledgerVersion },\n });\n return data.data;\n } catch (error) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.FULL_NODE_CONFIG_LOOKUP_ERROR,\n error,\n });\n }\n}\n\n/**\n * Retrieves the Groth16VerificationKey set on the blockchain.\n *\n * @param args - The arguments for retrieving the verification key.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.options - Optional parameters for the request.\n * @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.\n * @returns Groth16VerificationKeyResponse - The response containing the Groth16 verification key data.\n * @group Implementation\n * @category Serialization\n */\nasync function getGroth16VerificationKeyResource(args: {\n aptosConfig: AptosConfig;\n options?: LedgerVersionArg;\n}): Promise<Groth16VerificationKeyResponse> {\n const { aptosConfig, options } = args;\n const resourceType = \"0x1::keyless_account::Groth16VerificationKey\";\n try {\n const { data } = await getAptosFullNode<{}, MoveResource<Groth16VerificationKeyResponse>>({\n aptosConfig,\n originMethod: \"getGroth16VerificationKeyResource\",\n path: `accounts/${AccountAddress.from(\"0x1\").toString()}/resource/${resourceType}`,\n params: { ledger_version: options?.ledgerVersion },\n });\n return data.data;\n } catch (error) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.FULL_NODE_VERIFICATION_KEY_LOOKUP_ERROR,\n error,\n });\n }\n}\n\nexport async function getKeylessJWKs(args: {\n aptosConfig: AptosConfig;\n jwkAddr?: AccountAddressInput;\n options?: LedgerVersionArg;\n}): Promise<Map<string, MoveJWK[]>> {\n const { aptosConfig, jwkAddr, options } = args;\n let resource: MoveResource<PatchedJWKsResponse>;\n if (!jwkAddr) {\n const resourceType = \"0x1::jwks::PatchedJWKs\";\n const { data } = await getAptosFullNode<{}, MoveResource<PatchedJWKsResponse>>({\n aptosConfig,\n originMethod: \"getKeylessJWKs\",\n path: `accounts/0x1/resource/${resourceType}`,\n params: { ledger_version: options?.ledgerVersion },\n });\n resource = data;\n } else {\n const resourceType = \"0x1::jwks::FederatedJWKs\";\n const { data } = await getAptosFullNode<{}, MoveResource<PatchedJWKsResponse>>({\n aptosConfig,\n originMethod: \"getKeylessJWKs\",\n path: `accounts/${AccountAddress.from(jwkAddr).toString()}/resource/${resourceType}`,\n params: { ledger_version: options?.ledgerVersion },\n });\n resource = data;\n }\n\n // Create a map of issuer to JWK arrays\n const jwkMap = new Map<string, MoveJWK[]>();\n for (const entry of resource.data.jwks.entries) {\n const jwks: MoveJWK[] = [];\n for (const jwkStruct of entry.jwks) {\n const { data: jwkData } = jwkStruct.variant;\n const deserializer = new Deserializer(Hex.fromHexInput(jwkData).toUint8Array());\n const jwk = MoveJWK.deserialize(deserializer);\n jwks.push(jwk);\n }\n jwkMap.set(hexToAsciiString(entry.issuer), jwks);\n }\n\n return jwkMap;\n}\n\nexport class MoveJWK extends Serializable {\n public kid: string;\n\n public kty: string;\n\n public alg: string;\n\n public e: string;\n\n public n: string;\n\n constructor(args: { kid: string; kty: string; alg: string; e: string; n: string }) {\n super();\n const { kid, kty, alg, e, n } = args;\n this.kid = kid;\n this.kty = kty;\n this.alg = alg;\n this.e = e;\n this.n = n;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeStr(this.kid);\n serializer.serializeStr(this.kty);\n serializer.serializeStr(this.alg);\n serializer.serializeStr(this.e);\n serializer.serializeStr(this.n);\n }\n\n static fromMoveStruct(struct: MoveAnyStruct): MoveJWK {\n const { data } = struct.variant;\n const deserializer = new Deserializer(Hex.fromHexInput(data).toUint8Array());\n return MoveJWK.deserialize(deserializer);\n }\n\n toScalar(): bigint {\n if (this.alg !== \"RS256\") {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.PROOF_VERIFICATION_FAILED,\n details:\n \"Failed to convert JWK to scalar when calculating the public inputs hash. Only RSA 256 is supported currently\",\n });\n }\n const uint8Array = base64UrlToBytes(this.n);\n const chunks = chunkInto24Bytes(uint8Array.reverse());\n const scalars = chunks.map((chunk) => bytesToBigIntLE(chunk));\n scalars.push(256n); // Add the modulus size\n return poseidonHash(scalars);\n }\n\n static deserialize(deserializer: Deserializer): MoveJWK {\n const kid = deserializer.deserializeStr();\n const kty = deserializer.deserializeStr();\n const alg = deserializer.deserializeStr();\n const e = deserializer.deserializeStr();\n const n = deserializer.deserializeStr();\n return new MoveJWK({ kid, kty, alg, n, e });\n }\n}\n\nfunction chunkInto24Bytes(data: Uint8Array): Uint8Array[] {\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < data.length; i += 24) {\n const chunk = data.slice(i, Math.min(i + 24, data.length));\n // Pad last chunk with zeros if needed\n if (chunk.length < 24) {\n const paddedChunk = new Uint8Array(24);\n paddedChunk.set(chunk);\n chunks.push(paddedChunk);\n } else {\n chunks.push(chunk);\n }\n }\n return chunks;\n}\n\ninterface JwtHeader {\n kid: string; // Key ID\n}\n/**\n * Safely parses the JWT header.\n * @param jwtHeader The JWT header string\n * @returns Parsed JWT header as an object.\n */\nexport function parseJwtHeader(jwtHeader: string): JwtHeader {\n try {\n const header = JSON.parse(jwtHeader);\n if (header.kid === undefined) {\n throw new Error(\"JWT header missing kid\");\n }\n return header;\n } catch (error) {\n throw new Error(\"Failed to parse JWT header.\");\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, PrivateKeyVariants } from \"../../types\";\nimport { isValidBIP44Path, mnemonicToSeed } from \"./hdKey\";\nimport { PrivateKey } from \"./privateKey\";\nimport { PublicKey } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { convertSigningMessage } from \"./utils\";\nimport { AptosConfig } from \"../../api\";\n\n/**\n * Represents a Secp256k1 ECDSA public key.\n *\n * @extends PublicKey\n * @property LENGTH - The length of the Secp256k1 public key in bytes.\n * @group Implementation\n * @category Serialization\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 // If it's compressed, it is only 33 bytes\n static readonly COMPRESSED_LENGTH: number = 33;\n\n // Hex value of the public key\n private readonly key: Hex;\n\n // Identifier to distinguish from Secp256k1PublicKey\n public readonly keyType: string = \"secp256k1\";\n\n /**\n * Create a new PublicKey instance from a HexInput, which can be a string or Uint8Array.\n * This constructor validates the length of the provided signature data.\n *\n * @param hexInput - A HexInput (string or Uint8Array) representing the signature data.\n * @throws Error if the length of the signature data is not equal to Secp256k1Signature.LENGTH.\n * @group Implementation\n * @category Serialization\n */\n constructor(hexInput: HexInput) {\n super();\n\n const hex = Hex.fromHexInput(hexInput);\n const { length } = hex.toUint8Array();\n if (length === Secp256k1PublicKey.LENGTH) {\n this.key = hex;\n } else if (length === Secp256k1PublicKey.COMPRESSED_LENGTH) {\n const point = secp256k1.ProjectivePoint.fromHex(hex.toUint8Array());\n this.key = Hex.fromHexInput(point.toRawBytes(false));\n } else {\n throw new Error(\n `PublicKey length should be ${Secp256k1PublicKey.LENGTH} or ${Secp256k1PublicKey.COMPRESSED_LENGTH}, received ${length}`,\n );\n }\n }\n\n // region PublicKey\n /**\n * Verifies a Secp256k1 signature against the public key.\n *\n * This function checks the validity of a signature for a given message, ensuring that the signature is canonical as a malleability check.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify against the public key.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: { message: HexInput; signature: Secp256k1Signature }): boolean {\n const { message, signature } = args;\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 /**\n * Note: Secp256k1Signatures can be verified syncronously.\n *\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by confirming that the signature is valid.\n *\n * @param args - The arguments for signature verification.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify, which must be an instance of Secp256k1Signature.\n * @returns A boolean indicating whether the signature is valid for the given message.\n * @group Implementation\n * @category Serialization\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Secp256k1Signature;\n }): Promise<boolean> {\n return this.verifySignature(args);\n }\n\n /**\n * Get the data as a Uint8Array representation.\n *\n * @returns Uint8Array representation of the data.\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n /**\n * Serializes the data into a byte array using the provided serializer.\n * This function is essential for converting data into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to convert the data.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.key.toUint8Array());\n }\n\n /**\n * Deserializes a Secp256k1Signature from the provided deserializer.\n * This function allows you to reconstruct a Secp256k1Signature object from its serialized byte representation.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\n */\n // eslint-disable-next-line class-methods-use-this\n deserialize(deserializer: Deserializer) {\n const hex = deserializer.deserializeBytes();\n return new Secp256k1Signature(hex);\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 * Determine if the provided public key is an instance of Secp256k1PublicKey.\n *\n * @deprecated use `instanceof Secp256k1PublicKey` instead\n * @param publicKey - The public key to check.\n * @group Implementation\n * @category Serialization\n */\n static isPublicKey(publicKey: PublicKey): publicKey is Secp256k1PublicKey {\n return publicKey instanceof Secp256k1PublicKey;\n }\n\n /**\n * Determines if the provided public key is a valid instance of a Secp256k1 public key.\n * This function checks for the presence of a \"key\" property and validates the length of the key data.\n *\n * @param publicKey - The public key to validate.\n * @returns A boolean indicating whether the public key is a valid Secp256k1 public key.\n * @group Implementation\n * @category Serialization\n */\n static isInstance(publicKey: PublicKey): publicKey is Secp256k1PublicKey {\n return (\n \"key\" in publicKey &&\n (publicKey.key as any)?.data?.length === Secp256k1PublicKey.LENGTH &&\n \"keyType\" in publicKey &&\n (publicKey as any).keyType === \"secp256k1\"\n );\n }\n}\n\n/**\n * Represents a Secp256k1 ECDSA private key, providing functionality to create, sign messages,\n * derive public keys, and serialize/deserialize the key.\n * @group Implementation\n * @category Serialization\n */\nexport class Secp256k1PrivateKey extends Serializable implements PrivateKey {\n /**\n * Length of Secp256k1 ecdsa private key\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The private key bytes\n * @private\n * @group Implementation\n * @category Serialization\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 * [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)\n *\n * @param hexInput A HexInput (string or Uint8Array)\n * @param strict If true, private key must AIP-80 compliant.\n * @group Implementation\n * @category Serialization\n */\n constructor(hexInput: HexInput, strict?: boolean) {\n super();\n\n const privateKeyHex = PrivateKey.parseHexInput(hexInput, PrivateKeyVariants.Secp256k1, strict);\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 - A newly generated Secp256k1 private key.\n * @group Implementation\n * @category Serialization\n */\n static generate(): Secp256k1PrivateKey {\n const hexInput = secp256k1.utils.randomPrivateKey();\n return new Secp256k1PrivateKey(hexInput, false);\n }\n\n /**\n * Derives a private key from a mnemonic seed phrase using a specified BIP44 path.\n *\n * @param path - The BIP44 path to derive the key from.\n * @param mnemonics - The mnemonic seed phrase used for key generation.\n *\n * @returns The generated private key.\n *\n * @throws Error if the provided path is not a valid BIP44 path.\n * @group Implementation\n * @category Serialization\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 * Derives a private key from a specified BIP44 path using a given seed.\n * This function is essential for generating keys that follow the hierarchical deterministic (HD) wallet structure.\n *\n * @param path - The BIP44 path used for key derivation.\n * @param seed - The seed phrase created by the mnemonics, represented as a Uint8Array.\n * @returns The generated private key as an instance of Secp256k1PrivateKey.\n * @throws Error if the derived private key is invalid.\n * @group Implementation\n * @category Serialization\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, false);\n }\n\n // endregion\n\n // region PrivateKey\n\n /**\n * Sign the given message with the private key.\n * This function generates a cryptographic signature for the provided message, ensuring the signature is canonical and non-malleable.\n *\n * @param message - A message in HexInput format to be signed.\n * @returns Signature - The generated signature for the provided message.\n * @group Implementation\n * @category Serialization\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 The derived public key.\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n /**\n * Get the private key as a string representation.\n *\n * @returns string representation of the private key\n * @group Implementation\n * @category Serialization\n */\n toString(): string {\n return this.toAIP80String();\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 toHexString(): string {\n return this.key.toString();\n }\n\n /**\n * Get the private key as a AIP-80 compliant hex string.\n *\n * [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)\n *\n * @returns AIP-80 compliant string representation of the private key.\n */\n toAIP80String(): string {\n return PrivateKey.formatPrivateKey(this.key.toString(), PrivateKeyVariants.Secp256k1);\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, false);\n }\n\n // endregion\n\n /**\n * Determines if the provided private key is an instance of Secp256k1PrivateKey.\n *\n * @param privateKey - The private key to be checked.\n *\n * @deprecated use `instanceof Secp256k1PrivateKey` instead\n * @group Implementation\n * @category Serialization\n */\n static isPrivateKey(privateKey: PrivateKey): privateKey is Secp256k1PrivateKey {\n return privateKey instanceof Secp256k1PrivateKey;\n }\n}\n\n/**\n * Represents a signature of a message signed using a Secp256k1 ECDSA private key.\n *\n * @group Implementation\n * @category Serialization\n */\nexport class Secp256k1Signature extends Signature {\n /**\n * Secp256k1 ecdsa signatures are 256-bit.\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH = 64;\n\n /**\n * The signature bytes\n * @private\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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","import { Deserializer, Serializer } from \"../../bcs\";\nimport {\n AnyPublicKeyVariant,\n AnySignatureVariant,\n SigningScheme as AuthenticationKeyScheme,\n HexInput,\n} from \"../../types\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature } from \"./ed25519\";\nimport { AccountPublicKey, PublicKey } from \"./publicKey\";\nimport { Secp256k1PrivateKey, Secp256k1PublicKey, Secp256k1Signature } from \"./secp256k1\";\nimport { KeylessPublicKey, KeylessSignature } from \"./keyless\";\nimport { Signature } from \"./signature\";\nimport { FederatedKeylessPublicKey } from \"./federatedKeyless\";\nimport { AptosConfig } from \"../../api\";\nimport { Secp256r1PublicKey, WebAuthnSignature } from \"./secp256r1\";\n\nexport type PrivateKeyInput = Ed25519PrivateKey | Secp256k1PrivateKey;\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 * @group Implementation\n * @category Serialization\n */\nexport class AnyPublicKey extends AccountPublicKey {\n /**\n * Reference to the inner public key\n * @group Implementation\n * @category Serialization\n */\n public readonly publicKey: PublicKey;\n\n /**\n * Index of the underlying enum variant\n * @group Implementation\n * @category Serialization\n */\n public readonly variant: AnyPublicKeyVariant;\n\n // region Constructors\n\n /**\n * Creates an instance of the signature class based on the provided signature type.\n * This allows for the handling of different signature variants such as Ed25519, Secp256k1, and Keyless.\n *\n * @param publicKey - The publicKey object which determines the variant to be used.\n * @throws Error if the provided signature type is unsupported.\n * @group Implementation\n * @category Serialization\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 if (publicKey instanceof Secp256r1PublicKey) {\n this.variant = AnyPublicKeyVariant.Secp256r1;\n } else if (publicKey instanceof KeylessPublicKey) {\n this.variant = AnyPublicKeyVariant.Keyless;\n } else if (publicKey instanceof FederatedKeylessPublicKey) {\n this.variant = AnyPublicKeyVariant.FederatedKeyless;\n } else {\n throw new Error(\"Unsupported public key type\");\n }\n }\n\n // endregion\n\n // region AccountPublicKey\n\n /**\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by confirming that the signature is valid.\n *\n * @param args - The arguments for signature verification.\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify, which must be an instance of AnySignature.\n * @returns A boolean indicating whether the signature is valid for the given message.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: { message: HexInput; signature: AnySignature }): boolean {\n const { message, signature } = args;\n if (this.publicKey instanceof KeylessPublicKey) {\n throw new Error(\"Use verifySignatureAsync to verify Keyless signatures\");\n }\n return this.publicKey.verifySignature({\n message,\n signature: signature.signature,\n });\n }\n\n /**\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by confirming that the signature is valid.\n *\n * @param args - The arguments for signature verification.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify, which must be an instance of AnySignature.\n * @returns A boolean indicating whether the signature is valid for the given message.\n * @group Implementation\n * @category Serialization\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n if (!(args.signature instanceof AnySignature)) {\n if (args.options?.throwErrorWithReason) {\n throw new Error(\"Signature must be an instance of AnySignature\");\n }\n return false;\n }\n return await this.publicKey.verifySignatureAsync({\n ...args,\n signature: args.signature.signature,\n });\n }\n\n /**\n * Generates an authentication key from the current instance's byte representation.\n * This function is essential for creating a unique identifier for authentication purposes.\n *\n * @returns {AuthenticationKey} The generated authentication key.\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.SingleKey,\n input: this.toUint8Array(),\n });\n }\n\n /**\n * Get the signature in bytes (Uint8Array).\n *\n * This function is a warning that it will soon return the underlying signature bytes directly.\n * Use AnySignature.bcsToBytes() instead.\n *\n * @returns Uint8Array representation of the signature.\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.bcsToBytes();\n }\n\n // endregion\n\n // region Serializable\n\n /**\n * Serializes the current object using the provided serializer.\n * This function helps in converting the object into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.variant);\n this.publicKey.serialize(serializer);\n }\n\n /**\n * Deserializes an AnySignature from the provided deserializer.\n * This function helps in reconstructing the AnySignature object from its serialized form, allowing for further processing or validation.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\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 case AnyPublicKeyVariant.Secp256r1:\n publicKey = Secp256r1PublicKey.deserialize(deserializer);\n break;\n case AnyPublicKeyVariant.Keyless:\n publicKey = KeylessPublicKey.deserialize(deserializer);\n break;\n case AnyPublicKeyVariant.FederatedKeyless:\n publicKey = FederatedKeylessPublicKey.deserialize(deserializer);\n break;\n default:\n throw new Error(`Unknown variant index for AnyPublicKey: ${variantIndex}`);\n }\n return new AnyPublicKey(publicKey);\n }\n // endregion\n\n /**\n * Determines if the provided public key is an instance of AnyPublicKey.\n *\n * @param publicKey - The public key to check.\n * @deprecated Use `instanceof AnyPublicKey` instead.\n * @group Implementation\n * @category Serialization\n */\n static isPublicKey(publicKey: AccountPublicKey): publicKey is AnyPublicKey {\n return publicKey instanceof AnyPublicKey;\n }\n\n /**\n * Determines if the current public key is an instance of Ed25519PublicKey.\n *\n * @deprecated use `publicKey instanceof Ed25519PublicKey` instead.\n * @group Implementation\n * @category Serialization\n */\n isEd25519(): boolean {\n return this.publicKey instanceof Ed25519PublicKey;\n }\n\n /**\n * Checks if the public key is an instance of Secp256k1PublicKey.\n *\n * @deprecated use `publicKey instanceof Secp256k1PublicKey` instead.\n * @group Implementation\n * @category Serialization\n */\n isSecp256k1PublicKey(): boolean {\n return this.publicKey instanceof Secp256k1PublicKey;\n }\n\n /**\n * Determines if the provided publicKey is an instance of a valid PublicKey object.\n *\n * @param publicKey - The publicKey to be checked for validity.\n * @param publicKey.publicKey - The actual publicKey object that needs to be validated.\n * @returns True if the signature is a valid instance; otherwise, false.\n * @group Implementation\n * @category Serialization\n */\n static isInstance(publicKey: PublicKey): publicKey is AnyPublicKey {\n return \"publicKey\" in publicKey && \"variant\" in publicKey;\n }\n}\n\n/**\n * Represents a signature that utilizes the SingleKey authentication scheme.\n * This class is designed to encapsulate various types of signatures, which can\n * only be generated by a `SingleKeySigner` due to the shared authentication mechanism.\n *\n * @extends Signature\n * @group Implementation\n * @category Serialization\n */\nexport class AnySignature extends Signature {\n public readonly signature: Signature;\n\n /**\n * Index of the underlying enum variant\n * @group Implementation\n * @category Serialization\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 if (signature instanceof WebAuthnSignature) {\n this.variant = AnySignatureVariant.WebAuthn;\n } else if (signature instanceof KeylessSignature) {\n this.variant = AnySignatureVariant.Keyless;\n } else {\n throw new Error(\"Unsupported signature type\");\n }\n }\n\n // endregion\n\n // region AccountSignature\n\n toUint8Array(): Uint8Array {\n // TODO: keep this warning around for a bit, and eventually change this to return `this.signature.toUint8Array()`.\n // eslint-disable-next-line no-console\n console.warn(\n \"[Aptos SDK] Calls to AnySignature.toUint8Array() will soon return the underlying signature bytes. \" +\n \"Use AnySignature.bcsToBytes() instead.\",\n );\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 case AnySignatureVariant.WebAuthn:\n signature = WebAuthnSignature.deserialize(deserializer);\n break;\n case AnySignatureVariant.Keyless:\n signature = KeylessSignature.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 static isInstance(signature: Signature): signature is AnySignature {\n return (\n \"signature\" in signature &&\n typeof signature.signature === \"object\" &&\n signature.signature !== null &&\n \"toUint8Array\" in signature.signature\n );\n }\n}\n","import { AnyPublicKeyVariant, SigningScheme as AuthenticationKeyScheme, HexInput } from \"../../types\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializer } from \"../../bcs/serializer\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { AccountPublicKey, PublicKey, VerifySignatureAsyncArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { AnyPublicKey, AnySignature } from \"./singleKey\";\nimport { AptosConfig } from \"../../api\";\n\n/**\n * Counts the number of set bits (1s) in a byte.\n * This function can help you determine the population count of a given byte value.\n *\n * @param byte - The byte value for which to count the number of set bits.\n * @group Implementation\n * @category Serialization\n */\n/* eslint-disable no-bitwise */\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/* eslint-enable no-bitwise */\n\nconst MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY = 3;\nexport abstract class AbstractMultiKey extends AccountPublicKey {\n publicKeys: PublicKey[];\n\n constructor(args: { publicKeys: PublicKey[] }) {\n super();\n this.publicKeys = args.publicKeys;\n }\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 * @group Implementation\n * @category Serialization\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 /**\n * Get the index of the provided public key.\n *\n * This function retrieves the index of a specified public key within the MultiKey.\n * If the public key does not exist, it throws an error.\n *\n * @param publicKey - The public key to find the index for.\n * @returns The corresponding index of the public key, if it exists.\n * @throws Error - If the public key is not found in the MultiKey.\n * @group Implementation\n * @category Serialization\n */\n getIndex(publicKey: PublicKey): number {\n const index = this.publicKeys.findIndex((pk) => pk.toString() === publicKey.toString());\n\n if (index !== -1) {\n return index;\n }\n throw new Error(`Public key ${publicKey} not found in multi key set ${this.publicKeys}`);\n }\n\n abstract getSignaturesRequired(): number;\n}\n\n/**\n * Represents a multi-key authentication scheme for accounts, allowing multiple public keys\n * to be associated with a single account. This class enforces a minimum number of valid signatures\n * required to authorize actions, ensuring enhanced security for multi-agent accounts.\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 * @group Implementation\n * @category Serialization\n */\nexport class MultiKey extends AbstractMultiKey {\n /**\n * List of any public keys\n * @group Implementation\n * @category Serialization\n */\n public readonly publicKeys: AnyPublicKey[];\n\n /**\n * The minimum number of valid signatures required, for the number of public keys specified\n * @group Implementation\n * @category Serialization\n */\n public readonly signaturesRequired: number;\n\n /**\n * Signature for a K-of-N multi-sig transaction.\n * This constructor initializes a multi-signature transaction with the provided signatures and bitmap.\n *\n * @param args An object containing the parameters for the multi-signature transaction.\n * @param args.signatures A list of signatures.\n * @param args.bitmap A bitmap represented as a Uint8Array or an array of numbers, where each bit indicates whether a\n * corresponding signature is present. A maximum of 32 signatures is supported, and the length of the bitmap must be 4 bytes.\n *\n * @throws Error if the number of signatures exceeds the maximum supported, if the bitmap length is incorrect, or if the number\n * of signatures does not match the bitmap.\n * @group Implementation\n * @category Serialization\n */\n // region Constructors\n constructor(args: { publicKeys: Array<PublicKey>; signaturesRequired: number }) {\n const { publicKeys, signaturesRequired } = args;\n super({ publicKeys });\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 if (signaturesRequired > MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY) {\n const keylessCount = this.publicKeys.filter(\n (pk) => pk.variant === AnyPublicKeyVariant.Keyless || pk.variant === AnyPublicKeyVariant.FederatedKeyless,\n ).length;\n if (keylessCount > MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY) {\n throw new Error(\n `Construction of MultiKey with more than ${MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY} keyless public keys is not allowed when signaturesRequired \n is greater than ${MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY}. This is because a maximum of 3 keyless signatures are supported for a \n K-of-N MultiKey transaction.`,\n );\n }\n }\n\n this.signaturesRequired = signaturesRequired;\n }\n\n getSignaturesRequired(): number {\n return this.signaturesRequired;\n }\n\n // endregion\n\n // region AccountPublicKey\n\n /**\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by checking if the signature is valid.\n *\n * Note: This function will fail if a keyless signature is used. Use `verifySignatureAsync` instead.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: { message: HexInput; signature: MultiKeySignature }): boolean {\n const { message, signature } = args;\n if (signature.signatures.length !== this.signaturesRequired) {\n throw new Error(\"The number of signatures does not match the number of required signatures\");\n }\n const signerIndices = signature.bitMapToSignerIndices();\n for (let i = 0; i < signature.signatures.length; i += 1) {\n const singleSignature = signature.signatures[i];\n const publicKey = this.publicKeys[signerIndices[i]];\n if (!publicKey.verifySignature({ message, signature: singleSignature })) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by checking if the signature is valid.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.aptosConfig - The Aptos configuration to use\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify.\n * @group Implementation\n * @category Serialization\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n const { signature } = args;\n try {\n if (!(signature instanceof MultiKeySignature)) {\n throw new Error(\"Signature is not a MultiKeySignature\");\n }\n if (signature.signatures.length !== this.signaturesRequired) {\n throw new Error(\"The number of signatures does not match the number of required signatures\");\n }\n const signerIndices = signature.bitMapToSignerIndices();\n for (let i = 0; i < signature.signatures.length; i += 1) {\n const singleSignature = signature.signatures[i];\n const publicKey = this.publicKeys[signerIndices[i]];\n if (!(await publicKey.verifySignatureAsync({ ...args, signature: singleSignature }))) {\n return false;\n }\n }\n return true;\n } catch (error) {\n if (args.options?.throwErrorWithReason) {\n throw error;\n }\n return false;\n }\n }\n\n /**\n * Generates an authentication key based on the current instance's byte representation.\n * This key can be used for secure authentication processes within the system.\n *\n * @returns {AuthenticationKey} The generated authentication key.\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.MultiKey,\n input: this.toUint8Array(),\n });\n }\n\n // endregion\n\n // region Serializable\n\n /**\n * Serializes the object by writing its signatures and bitmap to the provided serializer.\n * This allows the object to be converted into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeVector(this.publicKeys);\n serializer.serializeU8(this.signaturesRequired);\n }\n\n /**\n * Deserializes a MultiKeySignature from the provided deserializer.\n * This function retrieves the signatures and bitmap necessary for creating a MultiKeySignature object.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\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 * Get the index of the provided public key.\n *\n * This function retrieves the index of a specified public key within the MultiKey.\n * If the public key does not exist, it throws an error.\n *\n * @param publicKey - The public key to find the index for.\n * @returns The corresponding index of the public key, if it exists.\n * @throws Error - If the public key is not found in the MultiKey.\n * @group Implementation\n */\n getIndex(publicKey: PublicKey): number {\n const anyPublicKey = publicKey instanceof AnyPublicKey ? publicKey : new AnyPublicKey(publicKey);\n return super.getIndex(anyPublicKey);\n }\n\n public static isInstance(value: PublicKey): value is MultiKey {\n return \"publicKeys\" in value && \"signaturesRequired\" in value;\n }\n}\n\n/**\n * Represents a multi-signature transaction using Ed25519 signatures.\n * This class allows for the creation and management of a K-of-N multi-signature scheme,\n * where a specified number of signatures are required to authorize a transaction.\n *\n * It includes functionality to validate the number of signatures against a bitmap,\n * which indicates which public keys have signed the transaction.\n * @group Implementation\n * @category Serialization\n */\nexport class MultiKeySignature extends Signature {\n /**\n * Number of bytes in the bitmap representing who signed the transaction (32-bits)\n * @group Implementation\n * @category Serialization\n */\n static BITMAP_LEN: number = 4;\n\n /**\n * Maximum number of Ed25519 signatures supported\n * @group Implementation\n * @category Serialization\n */\n static MAX_SIGNATURES_SUPPORTED = MultiKeySignature.BITMAP_LEN * 8;\n\n /**\n * The list of underlying Ed25519 signatures\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 /**\n * Converts the bitmap to an array of signer indices.\n *\n * Example:\n *\n * bitmap: [0b10001000, 0b01000000, 0b00000000, 0b00000000]\n * signerIndices: [0, 4, 9]\n *\n * @returns An array of signer indices.\n * @group Implementation\n * @category Serialization\n */\n bitMapToSignerIndices(): number[] {\n const signerIndices: number[] = [];\n for (let i = 0; i < this.bitmap.length; i += 1) {\n const byte = this.bitmap[i];\n for (let bit = 0; bit < 8; bit += 1) {\n if ((byte & (128 >> bit)) !== 0) {\n signerIndices.push(i * 8 + bit);\n }\n }\n }\n return signerIndices;\n }\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 signatures = deserializer.deserializeVector(AnySignature);\n const bitmap = deserializer.deserializeBytes();\n return new MultiKeySignature({ signatures, bitmap });\n }\n\n // endregion\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosConfig } from \"../../api\";\nimport { Deserializer, Serializer } from \"../../bcs\";\nimport { SigningScheme as AuthenticationKeyScheme, HexInput } from \"../../types\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"./ed25519\";\nimport { AbstractMultiKey } from \"./multiKey\";\nimport { Signature } from \"./signature\";\n\n/**\n * Represents the public key of a K-of-N Ed25519 multi-sig transaction.\n *\n * A K-of-N multi-sig transaction requires at least K out of N authorized signers to sign the transaction\n * for it to be executed. This class encapsulates the logic for managing the public keys and the threshold\n * for valid signatures.\n *\n * @see {@link https://aptos.dev/integration/creating-a-signed-transaction/ | Creating a Signed Transaction}\n * @group Implementation\n * @category Serialization\n */\nexport class MultiEd25519PublicKey extends AbstractMultiKey {\n /**\n * Maximum number of public keys supported\n * @group Implementation\n * @category Serialization\n */\n static readonly MAX_KEYS = 32;\n\n /**\n * Minimum number of public keys needed\n * @group Implementation\n * @category Serialization\n */\n static readonly MIN_KEYS = 2;\n\n /**\n * Minimum threshold for the number of valid signatures required\n * @group Implementation\n * @category Serialization\n */\n static readonly MIN_THRESHOLD = 1;\n\n /**\n * List of Ed25519 public keys for this LegacyMultiEd25519PublicKey\n * @group Implementation\n * @category Serialization\n */\n public readonly publicKeys: Ed25519PublicKey[];\n\n /**\n * The minimum number of valid signatures required, for the number of public keys specified\n * @group Implementation\n * @category Serialization\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 * @param args - A wrapper to let you choose the param order.\n * @param args.publicKeys A list of public keys\n * @param args.threshold At least \"threshold\" signatures must be valid\n * @group Implementation\n * @category Serialization\n */\n constructor(args: { publicKeys: Ed25519PublicKey[]; threshold: number }) {\n const { publicKeys, threshold } = args;\n super({ publicKeys });\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 getSignaturesRequired(): number {\n return this.threshold;\n }\n\n // region AccountPublicKey\n\n /**\n * Verifies a multi-signature against a given message.\n * This function ensures that the provided signatures meet the required threshold and are valid for the given message.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The message that was signed.\n * @param args.signature - The multi-signature containing multiple signatures and a bitmap indicating which signatures are valid.\n * @returns True if the signature is valid; otherwise, false.\n * @throws Error if the bitmap and signatures length mismatch or if there are not enough valid signatures.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: { message: HexInput; signature: Signature }): 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 async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n }): Promise<boolean> {\n return this.verifySignature(args);\n }\n\n /**\n * Generates an authentication key based on the current instance's byte representation.\n * This function is essential for creating a secure authentication key that can be used for various cryptographic operations.\n *\n * @returns {AuthenticationKey} The generated authentication key.\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 /**\n * Serializes the current instance into bytes using the provided serializer.\n * This allows for the conversion of the instance's data into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer used to convert the instance into bytes.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.toUint8Array());\n }\n\n /**\n * Deserializes a MultiEd25519Signature from the provided deserializer.\n * This function helps in reconstructing a MultiEd25519Signature object from its serialized byte representation.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\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 /**\n * Deserializes a MultiEd25519Signature from the provided deserializer.\n * This function helps in reconstructing a MultiEd25519Signature object from its serialized byte representation.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\n */\n static deserializeWithoutLength(deserializer: Deserializer): MultiEd25519PublicKey {\n const length = deserializer.remaining();\n const bytes = deserializer.deserializeFixedBytes(length);\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 * Get the index of the provided public key.\n *\n * This function retrieves the index of a specified public key within the MultiKey.\n * If the public key does not exist, it throws an error.\n *\n * @param publicKey - The public key to find the index for.\n * @returns The corresponding index of the public key, if it exists.\n * @throws Error - If the public key is not found in the MultiKey.\n * @group Implementation\n */\n getIndex(publicKey: Ed25519PublicKey): number {\n return super.getIndex(publicKey);\n }\n}\n\n/**\n * Represents the signature of a K-of-N Ed25519 multi-sig transaction.\n *\n * @see {@link https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}\n * @group Implementation\n * @category Serialization\n */\nexport class MultiEd25519Signature extends Signature {\n /**\n * Maximum number of Ed25519 signatures supported\n * @group Implementation\n * @category Serialization\n */\n static MAX_SIGNATURES_SUPPORTED = 32;\n\n /**\n * Number of bytes in the bitmap representing who signed the transaction (32-bits)\n * @group Implementation\n * @category Serialization\n */\n static BITMAP_LEN: number = 4;\n\n /**\n * The list of underlying Ed25519 signatures\n * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 * @group Implementation\n * @category Serialization\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 * This function allows you to set specific bits in a 32-bit long bitmap based on the provided positions.\n *\n * @param args The arguments for creating the bitmap.\n * @param args.bits The bitmap positions that should be set. A position starts at index 0. Valid positions should range between 0 and 31.\n *\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 32 bits long.\n * @group Implementation\n * @category Serialization\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","import {\n AnyPublicKey,\n Ed25519PublicKey,\n MultiKey,\n KeylessPublicKey,\n MultiEd25519PublicKey,\n FederatedKeylessPublicKey,\n Secp256k1PublicKey,\n Signature,\n PublicKey,\n Ed25519Signature,\n Secp256k1Signature,\n KeylessSignature,\n AnySignature,\n MultiEd25519Signature,\n MultiKeySignature,\n} from \"..\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { HexInput } from \"../../types\";\n\nconst MULTIPLE_DESERIALIZATIONS_ERROR_MSG = \"Multiple possible deserializations found\";\n\n/**\n * Deserializes a public key from a hex string.\n * Attempts to deserialize using various public key types in sequence until one succeeds.\n *\n * @param publicKey - The hex string representation of the public key to deserialize\n * @returns The deserialized public key\n * @throws Error if deserialization fails for all supported key types or if multiple deserializations are found\n */\nexport function deserializePublicKey(publicKey: HexInput): PublicKey {\n const publicKeyTypes = [\n Ed25519PublicKey,\n AnyPublicKey,\n MultiEd25519PublicKey,\n MultiKey,\n KeylessPublicKey,\n FederatedKeylessPublicKey,\n Secp256k1PublicKey,\n ];\n\n let result: PublicKey | undefined;\n for (const KeyType of publicKeyTypes) {\n try {\n const deserializer = Deserializer.fromHex(publicKey);\n const key = KeyType.deserialize(deserializer);\n deserializer.assertFinished();\n if (result) {\n throw new Error(`${MULTIPLE_DESERIALIZATIONS_ERROR_MSG}: ${publicKey}`);\n }\n result = key;\n } catch (error) {\n if (error instanceof Error && error.message.includes(MULTIPLE_DESERIALIZATIONS_ERROR_MSG)) {\n throw error;\n }\n }\n }\n\n if (!result) {\n throw new Error(`Failed to deserialize public key: ${publicKey}`);\n }\n\n return result;\n}\n\n/**\n * Deserializes a signature from a hex string.\n * Attempts to deserialize using various signature types in sequence until one succeeds.\n *\n * @param signature - The hex string representation of the signature to deserialize\n * @returns The deserialized signature\n * @throws Error if deserialization fails for all supported signature types or if multiple deserializations are found\n */\nexport function deserializeSignature(signature: HexInput): Signature {\n const signatureTypes = [\n Ed25519Signature,\n AnySignature,\n MultiEd25519Signature,\n MultiKeySignature,\n KeylessSignature,\n Secp256k1Signature,\n ];\n\n let result: Signature | undefined;\n for (const SignatureType of signatureTypes) {\n try {\n const deserializer = Deserializer.fromHex(signature);\n const sig = SignatureType.deserialize(deserializer);\n deserializer.assertFinished();\n if (result) {\n throw new Error(`${MULTIPLE_DESERIALIZATIONS_ERROR_MSG}: ${signature}`);\n }\n result = sig;\n } catch (error) {\n if (error instanceof Error && error.message.includes(MULTIPLE_DESERIALIZATIONS_ERROR_MSG)) {\n throw error;\n }\n }\n }\n\n if (!result) {\n throw new Error(`Failed to deserialize signature: ${signature}`);\n }\n\n return result;\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, MultiKeySignature } from \"../../core/crypto/multiKey\";\nimport { AccountAuthenticatorVariant, HexInput, MoveFunctionId } from \"../../types\";\nimport { AASigningDataVariant, AbstractAuthenticationDataVariant } from \"../../types/abstraction\";\nimport { AccountAddress, Hex } from \"../../core\";\nimport { getFunctionParts, isValidFunctionInfo } from \"../../utils/helpers\";\n\n/**\n * Represents an account authenticator that can handle multiple authentication variants.\n * This class serves as a base for different types of account authenticators, allowing for serialization\n * and deserialization of various authenticator types.\n *\n * @extends Serializable\n * @group Implementation\n * @category Transactions\n */\nexport abstract class AccountAuthenticator extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserializes an AccountAuthenticator from the provided deserializer.\n * This function helps in reconstructing the AccountAuthenticator object based on the variant index.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\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 case AccountAuthenticatorVariant.NoAccountAuthenticator:\n return AccountAuthenticatorNoAccountAuthenticator.load(deserializer);\n case AccountAuthenticatorVariant.Abstraction:\n return AccountAuthenticatorAbstraction.load(deserializer);\n default:\n throw new Error(`Unknown variant index for AccountAuthenticator: ${index}`);\n }\n }\n\n /**\n * Determines if the current instance is an Ed25519 account authenticator.\n *\n * @returns {boolean} True if the instance is of type AccountAuthenticatorEd25519, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isEd25519(): this is AccountAuthenticatorEd25519 {\n return this instanceof AccountAuthenticatorEd25519;\n }\n\n /**\n * Determines if the current instance is of type AccountAuthenticatorMultiEd25519.\n *\n * @returns {boolean} True if the instance is a multi-signature Ed25519 account authenticator, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isMultiEd25519(): this is AccountAuthenticatorMultiEd25519 {\n return this instanceof AccountAuthenticatorMultiEd25519;\n }\n\n /**\n * Determines if the current instance is of the type AccountAuthenticatorSingleKey.\n *\n * @returns {boolean} True if the instance is an AccountAuthenticatorSingleKey, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isSingleKey(): this is AccountAuthenticatorSingleKey {\n return this instanceof AccountAuthenticatorSingleKey;\n }\n\n /**\n * Determine if the current instance is of type AccountAuthenticatorMultiKey.\n *\n * @returns {boolean} Returns true if the instance is an AccountAuthenticatorMultiKey, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isMultiKey(): this is AccountAuthenticatorMultiKey {\n return this instanceof AccountAuthenticatorMultiKey;\n }\n}\n\n/**\n * Represents an Ed25519 transaction authenticator for multi-signer transactions.\n * This class encapsulates the account's Ed25519 public key and signature.\n *\n * @param public_key - The Ed25519 public key associated with the account.\n * @param signature - The Ed25519 signature for the account.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorEd25519 extends AccountAuthenticator {\n public readonly public_key: Ed25519PublicKey;\n\n public readonly signature: Ed25519Signature;\n\n /**\n * Creates an instance of the class with the specified public keys and signatures.\n *\n * @param public_key The public key used for verification.\n * @param signature The signatures corresponding to the public keys.\n * @group Implementation\n * @category Transactions\n */\n constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n /**\n * Serializes the account authenticator data into the provided serializer.\n * This function captures the multi-key variant, public keys, and signatures for serialization.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Transactions\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 /**\n * Loads an instance of AccountAuthenticatorMultiKey from the provided deserializer.\n * This function helps in reconstructing the authenticator object using the deserialized public keys and signatures.\n *\n * @param deserializer - The deserializer used to extract the necessary data for loading the authenticator.\n * @group Implementation\n * @category Transactions\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 * Represents a transaction authenticator for Multi Ed25519, designed for multi-signer transactions.\n *\n * @param public_key - The MultiEd25519 public key of the account.\n * @param signature - The MultiEd25519 signature of the account.\n * @group Implementation\n * @category Transactions\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 * Represents an account authenticator that utilizes a single key for signing.\n * This class is designed to handle authentication using a public key and its corresponding signature.\n *\n * @param public_key - The public key used for authentication.\n * @param signature - The signature associated with the public key.\n * @group Implementation\n * @category Transactions\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 * Represents an account authenticator that supports multiple keys and signatures for multi-signature scenarios.\n *\n * @param public_keys - The public keys used for authentication.\n * @param signatures - The signatures corresponding to the public keys.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorMultiKey extends AccountAuthenticator {\n public readonly public_keys: MultiKey;\n\n public readonly signatures: MultiKeySignature;\n\n constructor(public_keys: MultiKey, signatures: MultiKeySignature) {\n super();\n this.public_keys = public_keys;\n this.signatures = signatures;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.MultiKey);\n this.public_keys.serialize(serializer);\n this.signatures.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorMultiKey {\n const public_keys = MultiKey.deserialize(deserializer);\n const signatures = MultiKeySignature.deserialize(deserializer);\n return new AccountAuthenticatorMultiKey(public_keys, signatures);\n }\n}\n\n/**\n * AccountAuthenticatorNoAccountAuthenticator for no account authenticator\n * It represents the absence of a public key for transaction simulation.\n * It allows skipping the public/auth key check during the simulation.\n */\nexport class AccountAuthenticatorNoAccountAuthenticator extends AccountAuthenticator {\n // eslint-disable-next-line class-methods-use-this\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.NoAccountAuthenticator);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static load(deserializer: Deserializer): AccountAuthenticatorNoAccountAuthenticator {\n return new AccountAuthenticatorNoAccountAuthenticator();\n }\n}\n\n/**\n * Represents an account authenticator that supports abstract authentication.\n *\n * @param functionInfo - The function info of the authentication function.\n * @param signingMessageDigest - The digest of the signing message.\n * @param abstractionSignature - The signature of the authentication function.\n * @param accountIdentity - optional. The account identity for DAA.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorAbstraction extends AccountAuthenticator {\n public readonly functionInfo: string;\n\n public readonly signingMessageDigest: Hex;\n\n public readonly abstractionSignature: Uint8Array;\n\n /**\n * DAA, which is extended of the AA module, requires an account identity\n */\n public readonly accountIdentity?: Uint8Array;\n\n constructor(\n functionInfo: string,\n signingMessageDigest: HexInput,\n abstractionSignature: Uint8Array,\n accountIdentity?: Uint8Array,\n ) {\n super();\n if (!isValidFunctionInfo(functionInfo)) {\n throw new Error(`Invalid function info ${functionInfo} passed into AccountAuthenticatorAbstraction`);\n }\n this.functionInfo = functionInfo;\n this.abstractionSignature = abstractionSignature;\n this.signingMessageDigest = Hex.fromHexInput(Hex.fromHexInput(signingMessageDigest).toUint8Array());\n this.accountIdentity = accountIdentity;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.Abstraction);\n const { moduleAddress, moduleName, functionName } = getFunctionParts(this.functionInfo as MoveFunctionId);\n AccountAddress.fromString(moduleAddress).serialize(serializer);\n serializer.serializeStr(moduleName);\n serializer.serializeStr(functionName);\n if (this.accountIdentity) {\n serializer.serializeU32AsUleb128(AbstractAuthenticationDataVariant.DerivableV1);\n } else {\n serializer.serializeU32AsUleb128(AbstractAuthenticationDataVariant.V1);\n }\n serializer.serializeBytes(this.signingMessageDigest.toUint8Array());\n if (this.accountIdentity) {\n serializer.serializeBytes(this.abstractionSignature);\n } else {\n serializer.serializeFixedBytes(this.abstractionSignature);\n }\n\n if (this.accountIdentity) {\n serializer.serializeBytes(this.accountIdentity);\n }\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorAbstraction {\n // deserialize the function info\n const moduleAddress = AccountAddress.deserialize(deserializer);\n const moduleName = deserializer.deserializeStr();\n const functionName = deserializer.deserializeStr();\n // deserialize the variant\n const variant = deserializer.deserializeUleb128AsU32();\n // deserialize the signing message digest\n const signingMessageDigest = deserializer.deserializeBytes();\n\n if (variant === AbstractAuthenticationDataVariant.V1) {\n const abstractionSignature = deserializer.deserializeFixedBytes(deserializer.remaining());\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n abstractionSignature,\n );\n }\n if (variant === AbstractAuthenticationDataVariant.DerivableV1) {\n const abstractionSignature = deserializer.deserializeBytes();\n const abstractPublicKey = deserializer.deserializeBytes();\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n abstractionSignature,\n abstractPublicKey,\n );\n }\n throw new Error(`Unknown variant index for AccountAuthenticatorAbstraction: ${variant}`);\n }\n}\n\n/**\n * Represents an account abstraction message that contains the original signing message and the function info.\n *\n * @param originalSigningMessage - The original signing message.\n * @param functionInfo - The function info of the authentication function.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAbstractionMessage extends Serializable {\n public readonly originalSigningMessage: Hex;\n\n public readonly functionInfo: string;\n\n constructor(originalSigningMessage: HexInput, functionInfo: string) {\n super();\n this.originalSigningMessage = Hex.fromHexInput(Hex.fromHexInput(originalSigningMessage).toUint8Array());\n this.functionInfo = functionInfo;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AASigningDataVariant.V1);\n serializer.serializeBytes(this.originalSigningMessage.toUint8Array());\n const { moduleAddress, moduleName, functionName } = getFunctionParts(this.functionInfo as MoveFunctionId);\n AccountAddress.fromString(moduleAddress).serialize(serializer);\n serializer.serializeStr(moduleName);\n serializer.serializeStr(functionName);\n }\n\n static deserialize(deserializer: Deserializer): AccountAbstractionMessage {\n const variant = deserializer.deserializeUleb128AsU32();\n if (variant !== AASigningDataVariant.V1) {\n throw new Error(`Unknown variant index for AccountAbstractionMessage: ${variant}`);\n }\n const originalSigningMessage = deserializer.deserializeBytes();\n const functionInfoModuleAddress = AccountAddress.deserialize(deserializer);\n const functionInfoModuleName = deserializer.deserializeStr();\n const functionInfoFunctionName = deserializer.deserializeStr();\n const functionInfo = `${functionInfoModuleAddress}::${functionInfoModuleName}::${functionInfoFunctionName}`;\n return new AccountAbstractionMessage(originalSigningMessage, functionInfo);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file handles the generation of the signing message.\n * @group Implementation\n * @category Transactions\n */\nimport { sha3_256 as sha3Hash } from \"@noble/hashes/sha3\";\nimport { RAW_TRANSACTION_SALT, RAW_TRANSACTION_WITH_DATA_SALT } from \"../../utils/const\";\nimport { FeePayerRawTransaction, MultiAgentRawTransaction } from \"../instances\";\nimport { AnyRawTransaction, AnyRawTransactionInstance } from \"../types\";\nimport { Serializable } from \"../../bcs\";\n\n/**\n * Derives the appropriate raw transaction type based on the provided transaction details.\n * This function helps in identifying whether the transaction is a FeePayerRawTransaction,\n * MultiAgentRawTransaction, or a standard RawTransaction.\n *\n * @param transaction - An object representing an Aptos transaction, which may include:\n * - feePayerAddress - The address of the fee payer (optional).\n * - secondarySignerAddresses - An array of secondary signer addresses (optional).\n * - rawTransaction - The raw transaction data.\n *\n * @returns FeePayerRawTransaction | MultiAgentRawTransaction | RawTransaction\n * @group Implementation\n * @category Transactions\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\n/**\n * Generates the 'signing message' form of a message to be signed.\n * This function combines a domain separator with the byte representation of the message to create a signing message.\n *\n * @param bytes - The byte representation of the message to be signed and sent to the chain.\n * @param domainSeparator - A domain separator that starts with 'APTOS::'.\n *\n * @returns The Uint8Array of the signing message.\n * @group Implementation\n * @category Transactions\n */\nexport function generateSigningMessage(bytes: Uint8Array, domainSeparator: string): Uint8Array {\n const hash = sha3Hash.create();\n\n if (!domainSeparator.startsWith(\"APTOS::\")) {\n throw new Error(`Domain separator needs to start with 'APTOS::'. Provided - ${domainSeparator}`);\n }\n\n hash.update(domainSeparator);\n\n const prefix = hash.digest();\n\n const body = bytes;\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 * @deprecated\n * Use CryptoHashable instead by having your class implement it and call hash() to get the signing message.\n *\n * Generates the 'signing message' form of a serializable value by serializing it and using the constructor name as the domain\n * separator.\n *\n * @param serializable - An object that has a BCS serialized form.\n *\n * @returns The Uint8Array of the signing message.\n * @group Implementation\n * @category Transactions\n */\nexport function generateSigningMessageForSerializable(serializable: Serializable): Uint8Array {\n return generateSigningMessage(serializable.bcsToBytes(), `APTOS::${serializable.constructor.name}`);\n}\n\n/**\n * Generates the 'signing message' form of a transaction by deriving the type of transaction and applying the appropriate domain\n * separator based on the presence of a fee payer or secondary signers.\n *\n * @param transaction - A transaction that is to be signed, which can include a fee payer address or secondary signer addresses.\n *\n * @returns The Uint8Array of the signing message.\n * @group Implementation\n * @category Transactions\n */\nexport function generateSigningMessageForTransaction(transaction: AnyRawTransaction): Uint8Array {\n const rawTxn = deriveTransactionType(transaction);\n if (transaction.feePayerAddress) {\n return generateSigningMessage(rawTxn.bcsToBytes(), RAW_TRANSACTION_WITH_DATA_SALT);\n }\n if (transaction.secondarySignerAddresses) {\n return generateSigningMessage(rawTxn.bcsToBytes(), RAW_TRANSACTION_WITH_DATA_SALT);\n }\n return generateSigningMessage(rawTxn.bcsToBytes(), RAW_TRANSACTION_SALT);\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 * Represents a ModuleId that can be serialized and deserialized.\n * A ModuleId consists of a module address (e.g., \"0x1\") and a module name (e.g., \"coin\").\n * @group Implementation\n * @category Transactions\n */\nexport class ModuleId extends Serializable {\n public readonly address: AccountAddress;\n\n public readonly name: Identifier;\n\n /**\n * Initializes a new instance of the module with the specified account address and name.\n *\n * @param address - The account address, e.g., \"0x1\".\n * @param name - The module name under the specified address, e.g., \"coin\".\n * @group Implementation\n * @category Transactions\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 in the format \"account_address::module_name\" to a ModuleId.\n * @param moduleId - A string literal representing the module identifier.\n * @throws Error if the provided moduleId is not in the correct format.\n * @returns ModuleId - The corresponding ModuleId object.\n * @group Implementation\n * @category Transactions\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 /**\n * Serializes the address and name properties using the provided serializer.\n * This function is essential for converting the object's data into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Transactions\n */\n serialize(serializer: Serializer): void {\n this.address.serialize(serializer);\n this.name.serialize(serializer);\n }\n\n /**\n * Deserializes a ModuleId from the provided deserializer.\n * This function retrieves the account address and identifier to construct a ModuleId instance.\n *\n * @param deserializer - The deserializer instance used to read the data.\n * @group Implementation\n * @category Transactions\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\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\n/**\n * Represents a type tag in the serialization framework, serving as a base class for various specific type tags.\n * This class provides methods for serialization and deserialization of type tags, as well as type checking methods\n * to determine the specific type of the tag at runtime.\n *\n * @extends Serializable\n * @group Implementation\n * @category Transactions\n */\nexport abstract class TypeTag extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserializes a StructTag from the provided deserializer.\n * This function allows you to reconstruct a StructTag object from its serialized form.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\n */\n 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 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 /**\n * Determines if the current instance is of type TypeTagBool.\n *\n * @returns {boolean} True if the instance is a TypeTagBool, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isBool(): this is TypeTagBool {\n return this instanceof TypeTagBool;\n }\n\n /**\n * Determines if the current instance is of type TypeTagAddress.\n *\n * @returns {boolean} True if the instance is a TypeTagAddress, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isAddress(): this is TypeTagAddress {\n return this instanceof TypeTagAddress;\n }\n\n /**\n * Determines if the current instance is of type TypeTagGeneric.\n *\n * @returns {boolean} Returns true if the instance is a TypeTagGeneric, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isGeneric(): this is TypeTagGeneric {\n return this instanceof TypeTagGeneric;\n }\n\n /**\n * Determine if the current instance is a TypeTagSigner.\n *\n * @returns {boolean} Returns true if the instance is a TypeTagSigner, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isSigner(): this is TypeTagSigner {\n return this instanceof TypeTagSigner;\n }\n\n /**\n * Checks if the current instance is a vector type.\n * This can help determine the specific type of data structure being used.\n *\n * @returns {boolean} True if the instance is of type TypeTagVector, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isVector(): this is TypeTagVector {\n return this instanceof TypeTagVector;\n }\n\n /**\n * Determines if the current instance is a structure type.\n *\n * @returns {boolean} True if the instance is of type TypeTagStruct, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isStruct(): this is TypeTagStruct {\n return this instanceof TypeTagStruct;\n }\n\n /**\n * Determines if the current instance is of type `TypeTagU8`.\n *\n * @returns {boolean} Returns true if the instance is of type `TypeTagU8`, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isU8(): this is TypeTagU8 {\n return this instanceof TypeTagU8;\n }\n\n /**\n * Checks if the current instance is of type TypeTagU16.\n *\n * @returns {boolean} True if the instance is TypeTagU16, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isU16(): this is TypeTagU16 {\n return this instanceof TypeTagU16;\n }\n\n /**\n * Checks if the current instance is of type TypeTagU32.\n *\n * @returns {boolean} Returns true if the instance is TypeTagU32, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isU32(): this is TypeTagU32 {\n return this instanceof TypeTagU32;\n }\n\n /**\n * Checks if the current instance is of type TypeTagU64.\n *\n * @returns {boolean} True if the instance is a TypeTagU64, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isU64(): this is TypeTagU64 {\n return this instanceof TypeTagU64;\n }\n\n /**\n * Determines if the current instance is of the TypeTagU128 type.\n *\n * @returns {boolean} True if the instance is of TypeTagU128, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isU128(): this is TypeTagU128 {\n return this instanceof TypeTagU128;\n }\n\n /**\n * Checks if the current instance is of type TypeTagU256.\n *\n * @returns {boolean} Returns true if the instance is of type TypeTagU256, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isU256(): this is TypeTagU256 {\n return this instanceof TypeTagU256;\n }\n\n isPrimitive(): boolean {\n return (\n this instanceof TypeTagSigner ||\n this instanceof TypeTagAddress ||\n this instanceof TypeTagBool ||\n this instanceof TypeTagU8 ||\n this instanceof TypeTagU16 ||\n this instanceof TypeTagU32 ||\n this instanceof TypeTagU64 ||\n this instanceof TypeTagU128 ||\n this instanceof TypeTagU256\n );\n }\n}\n\n/**\n * Represents a boolean type tag in the type system.\n * This class extends the base TypeTag class and provides\n * methods for serialization and deserialization of the boolean\n * type tag.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\n */\nexport class TypeTagBool extends TypeTag {\n /**\n * Returns the string representation of the object.\n *\n * @returns {string} The string representation of the object.\n * @group Implementation\n * @category Transactions\n */\n toString(): string {\n return \"bool\";\n }\n\n /**\n * Serializes the current instance's properties into a provided serializer.\n * This function ensures that the address, module name, name, and type arguments are properly serialized.\n *\n * @param serializer - The serializer instance used to serialize the properties.\n * @group Implementation\n * @category Transactions\n */\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TypeTagVariants.Bool);\n }\n\n /**\n * Deserializes a StructTag and returns a new TypeTagStruct instance.\n *\n * @param _deserializer - The deserializer used to read the StructTag data.\n * @group Implementation\n * @category Transactions\n */\n static load(_deserializer: Deserializer): TypeTagBool {\n return new TypeTagBool();\n }\n}\n\n/**\n * Represents a type tag for an 8-bit unsigned integer (u8).\n * This class extends the base TypeTag class and provides methods\n * for serialization and deserialization specific to the u8 type.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for unsigned 16-bit integers (u16).\n * This class extends the base TypeTag class and provides methods for serialization and deserialization.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for a 32-bit unsigned integer (u32).\n * This class extends the base TypeTag class and provides methods for serialization\n * and deserialization specific to the u32 type.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for 64-bit unsigned integers (u64).\n * This class extends the base TypeTag class and provides methods for serialization and deserialization.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for the u128 data type.\n * This class extends the base TypeTag class and provides methods for serialization and deserialization.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for the U256 data type.\n * This class extends the base TypeTag class and provides methods for serialization and deserialization.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for an address in the system.\n * This class extends the TypeTag class and provides functionality\n * to serialize the address type and load it from a deserializer.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a type tag for a signer in the system.\n * This class extends the base TypeTag and provides specific functionality\n * related to the signer type.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a reference to a type tag in the type system.\n * This class extends the TypeTag class and provides functionality\n * to serialize and deserialize type tag references.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\n */\nexport class TypeTagReference extends TypeTag {\n toString(): `&${string}` {\n return `&${this.value.toString()}`;\n }\n\n /**\n * Initializes a new instance of the class with the specified parameters.\n *\n * @param value - The TypeTag to reference.\n * @group Implementation\n * @category Transactions\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 * Represents a generic type tag used for type parameters in entry functions.\n * Generics are not serialized into a real type, so they cannot be used as a type directly.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a vector type tag, which encapsulates a single type tag value.\n * This class extends the base TypeTag class and provides methods for serialization,\n * deserialization, and string representation of the vector type tag.\n *\n * @extends TypeTag\n * @group Implementation\n * @category Transactions\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 /**\n * Creates a new TypeTagVector instance with a TypeTagU8 type.\n *\n * @returns {TypeTagVector} A new TypeTagVector initialized with TypeTagU8.\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a structured type tag in the system, extending the base TypeTag class.\n * This class encapsulates information about a specific structure, including its address,\n * module name, and type arguments, and provides methods for serialization and type checking.\n *\n * @param value - The StructTag instance containing the details of the structured type.\n * @group Implementation\n * @category Transactions\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 /**\n * Determines if the provided address, module name, and struct name match the current type tag.\n *\n * @param address - The account address to compare against the type tag.\n * @param moduleName - The name of the module to compare against the type tag.\n * @param structName - The name of the struct to compare against the type tag.\n * @returns True if the address, module name, and struct name match the type tag; otherwise, false.\n * @group Implementation\n * @category Transactions\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 /**\n * Checks if the provided value is of type string.\n * This function can help ensure that the data being processed is in the correct format before further operations.\n *\n * @returns {boolean} Returns true if the value is a string, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isString(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"string\", \"String\");\n }\n\n /**\n * Checks if the specified account address is of type \"option\".\n *\n * @returns {boolean} Returns true if the account address is an option type, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isOption(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"option\", \"Option\");\n }\n\n /**\n * Checks if the provided value is of type 'object'.\n * This function helps determine if a value can be treated as an object type in the context of the SDK.\n *\n * @returns {boolean} Returns true if the value is an object, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isObject(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"object\", \"Object\");\n }\n\n /**\n * Checks if the provided value is a 'DelegationKey' for permissioned signers.\n *\n * @returns {boolean} Returns true if the value is a DelegationKey, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isDelegationKey(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"permissioned_delegation\", \"DelegationKey\");\n }\n\n /**\n * Checks if the provided value is of type `RateLimiter`.\n *\n * @returns {boolean} Returns true if the value is a RateLimiter, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isRateLimiter(): boolean {\n return this.isTypeTag(AccountAddress.ONE, \"rate_limiter\", \"RateLimiter\");\n }\n}\n\n/**\n * Represents a structured tag that includes an address, module name,\n * name, and type arguments. This class is used to define and manage\n * structured data types within the SDK.\n *\n * @property {AccountAddress} address - The address associated with the struct tag.\n * @property {Identifier} moduleName - The name of the module that contains the struct.\n * @property {Identifier} name - The name of the struct.\n * @property {Array<TypeTag>} typeArgs - An array of type arguments associated with the struct.\n * @group Implementation\n * @category Transactions\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\n/**\n * Retrieves the StructTag for the AptosCoin, which represents the Aptos Coin in the Aptos blockchain.\n *\n * @returns {StructTag} The StructTag for the AptosCoin.\n * @group Implementation\n * @category Transactions\n */\nexport function aptosCoinStructTag(): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"aptos_coin\"), new Identifier(\"AptosCoin\"), []);\n}\n\n/**\n * Returns a new StructTag representing a string type.\n *\n * @returns {StructTag} A StructTag for the string type.\n * @group Implementation\n * @category Transactions\n */\nexport function stringStructTag(): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"string\"), new Identifier(\"String\"), []);\n}\n\n/**\n * Creates a new StructTag for the Option type with the specified type argument.\n * This can help in defining a specific instance of an Option type in your application.\n *\n * @param typeArg - The type tag that specifies the type of the value contained in the Option.\n * @group Implementation\n * @category Transactions\n */\nexport function optionStructTag(typeArg: TypeTag): StructTag {\n return new StructTag(AccountAddress.ONE, new Identifier(\"option\"), new Identifier(\"Option\"), [typeArg]);\n}\n\n/**\n * Creates a new StructTag for the Object type with the specified type argument.\n * This function helps in defining a structured representation of an Object with a specific type.\n *\n * @param typeArg - The type tag that specifies the type of the Object.\n * @group Implementation\n * @category Transactions\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\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, Serialized } from \"../../bcs/serializable/moveStructs\";\nimport { AccountAddress, Hex } from \"../../core\";\nimport { Identifier } from \"./identifier\";\nimport { ModuleId } from \"./moduleId\";\nimport type { EntryFunctionArgument, ScriptFunctionArgument, TransactionArgument } from \"./transactionArgument\";\nimport {\n AnyNumber,\n MoveModuleId,\n ScriptTransactionArgumentVariants,\n TransactionExecutableVariants,\n TransactionExtraConfigVariants,\n TransactionInnerPayloadVariants,\n TransactionPayloadVariants,\n} from \"../../types\";\nimport { TypeTag } from \"../typeTag\";\n\n/**\n * Deserialize a Script Transaction Argument.\n * This function retrieves and deserializes various types of script transaction arguments based on the provided deserializer.\n *\n * @param deserializer - The deserializer used to read the script transaction argument.\n * @returns The deserialized script transaction argument.\n * @throws Error if the variant index is unknown.\n * @group Implementation\n * @category Transactions\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 case ScriptTransactionArgumentVariants.Serialized:\n return Serialized.deserialize(deserializer);\n default:\n throw new Error(`Unknown variant index for ScriptTransactionArgument: ${index}`);\n }\n}\n\n/**\n * Represents a supported Transaction Payload that can be serialized and deserialized.\n *\n * This class serves as a base for different types of transaction payloads, allowing for\n * their serialization into a format suitable for transmission and deserialization back\n * into their original form.\n * @group Implementation\n * @category Transactions\n */\nexport abstract class TransactionPayload extends Serializable {\n /**\n * Serialize a Transaction Payload\n * @group Implementation\n * @category Transactions\n */\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserialize a Transaction Payload\n * @group Implementation\n * @category Transactions\n */\n\n /**\n * Deserializes a multisig transaction payload from the provided deserializer.\n * This function enables the reconstruction of a MultiSigTransactionPayload object from its serialized form.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\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 case TransactionPayloadVariants.Payload:\n return TransactionInnerPayload.deserialize(deserializer);\n default:\n throw new Error(`Unknown variant index for TransactionPayload: ${index}`);\n }\n }\n}\n\n/**\n * Represents a transaction payload script that can be serialized and deserialized.\n *\n * This class encapsulates a script that defines the logic for a transaction payload.\n *\n * @extends TransactionPayload\n * @group Implementation\n * @category Transactions\n */\nexport class TransactionPayloadScript extends TransactionPayload {\n public readonly script: Script;\n\n /**\n * Initializes a multi-sig account transaction with the provided payload.\n *\n * @param script - The payload of the multi-sig transaction. This can only be an EntryFunction for now, but Script might be\n * supported in the future.\n * @group Implementation\n * @category Transactions\n */\n constructor(script: Script) {\n super();\n this.script = script;\n }\n\n /**\n * Serializes the transaction payload, enabling future support for multiple types of inner transaction payloads.\n *\n * @param serializer - The serializer instance used to serialize the transaction data.\n * @group Implementation\n * @category Transactions\n */\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionPayloadVariants.Script);\n this.script.serialize(serializer);\n }\n\n /**\n * Loads a MultiSig transaction payload from the provided deserializer.\n * This function helps in reconstructing a MultiSig transaction payload from its serialized form.\n *\n * @param deserializer - The deserializer used to read the serialized data.\n * @group Implementation\n * @category Transactions\n */\n static load(deserializer: Deserializer): TransactionPayloadScript {\n const script = Script.deserialize(deserializer);\n return new TransactionPayloadScript(script);\n }\n}\n\n/**\n * Represents a transaction payload entry function that can be serialized and deserialized.\n *\n * @extends TransactionPayload\n * @group Implementation\n * @category Transactions\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 * Represents a multi-signature transaction payload that can be serialized and deserialized.\n * @group Implementation\n * @category Transactions\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 * Represents an entry function that can be serialized and deserialized.\n * This class encapsulates the details required to invoke a function within a module,\n * including the module name, function name, type arguments, and function arguments.\n *\n * @param module_name - Fully qualified module name in the format \"account_address::module_name\" (e.g., \"0x1::coin\").\n * @param function_name - The name of the function (e.g., \"transfer\").\n * @param type_args - Type arguments required by the Move function.\n * @param args - Arguments to the Move function.\n * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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 * Build an EntryFunction payload from raw primitive values.\n *\n * @param module_id - Fully qualified module name in the format \"AccountAddress::module_id\", e.g., \"0x1::coin\".\n * @param function_name - The name of the function to be called.\n * @param type_args - Type arguments that the Move function requires.\n * @param args - Arguments to the Move function.\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 *\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 * @returns EntryFunction\n * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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 * Represents a Script that can be serialized and deserialized.\n * Scripts contain the Move bytecode payload that can be submitted to the Aptos chain for execution.\n * @group Implementation\n * @category Transactions\n */\nexport class Script {\n /**\n * The move module bytecode\n * @group Implementation\n * @category Transactions\n */\n public readonly bytecode: Uint8Array;\n\n /**\n * The type arguments that the bytecode function requires.\n * @group Implementation\n * @category Transactions\n */\n public readonly type_args: Array<TypeTag>;\n\n /**\n * The arguments that the bytecode function requires.\n * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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 * Represents a MultiSig account that can be serialized and deserialized.\n *\n * This class encapsulates the functionality to manage multi-signature transactions, including the address of the\n * multi-sig account and the associated transaction payload.\n * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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 * Represents a multi-signature transaction payload that can be serialized and deserialized.\n * This class is designed to encapsulate the transaction payload for multi-sig account transactions\n * as defined in the `multisig_account.move` module. Future enhancements may allow support for script\n * payloads as the `multisig_account.move` module evolves.\n * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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\n/**\n * Represents any transaction payload that can be submitted to the Aptos chain for execution.\n *\n * This is specifically required for orderless transactions, but can be used for any transaction payload.\n */\nexport abstract class TransactionInnerPayload extends TransactionPayload {\n abstract serialize(serializer: Serializer): void;\n\n static deserialize(deserializer: Deserializer): TransactionInnerPayload {\n // index enum variant\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TransactionInnerPayloadVariants.V1:\n return TransactionInnerPayloadV1.load(deserializer);\n default:\n throw new Error(`Unknown variant index for TransactionInnerPayload: ${index}`);\n }\n }\n}\n\nexport class TransactionInnerPayloadV1 extends TransactionInnerPayload {\n executable: TransactionExecutable;\n extra_config: TransactionExtraConfig;\n\n constructor(executable: TransactionExecutable, extra_config: TransactionExtraConfig) {\n super();\n this.executable = executable;\n this.extra_config = extra_config;\n }\n\n serialize(serializer: Serializer): void {\n // This payload must be serialized as a top level TransactionPayload, so we add that here\n serializer.serializeU32AsUleb128(TransactionPayloadVariants.Payload);\n // V1 is serialized as 0\n serializer.serializeU32AsUleb128(TransactionInnerPayloadVariants.V1);\n this.executable.serialize(serializer);\n this.extra_config.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionInnerPayloadV1 {\n let executable = TransactionExecutable.deserialize(deserializer);\n let extra_config = TransactionExtraConfig.deserialize(deserializer);\n return new TransactionInnerPayloadV1(executable, extra_config);\n }\n}\n\nexport abstract class TransactionExecutable {\n abstract serialize(serializer: Serializer): void;\n\n static deserialize(deserializer: Deserializer): TransactionExecutable {\n // index enum variant\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TransactionExecutableVariants.Script:\n return TransactionExecutableScript.load(deserializer);\n case TransactionExecutableVariants.EntryFunction:\n return TransactionExecutableEntryFunction.load(deserializer);\n case TransactionExecutableVariants.Empty:\n return TransactionExecutableEmpty.load(deserializer);\n default:\n throw new Error(`Unknown variant index for TransactionExecutable: ${index}`);\n }\n }\n}\n\nexport class TransactionExecutableScript extends TransactionExecutable {\n script: Script;\n\n constructor(script: Script) {\n super();\n this.script = script;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionExecutableVariants.Script);\n this.script.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionExecutableScript {\n let script = Script.deserialize(deserializer);\n return new TransactionExecutableScript(script);\n }\n}\n\nexport class TransactionExecutableEntryFunction extends TransactionExecutable {\n entryFunction: EntryFunction;\n\n constructor(entryFunction: EntryFunction) {\n super();\n this.entryFunction = entryFunction;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionExecutableVariants.EntryFunction);\n this.entryFunction.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): TransactionExecutableEntryFunction {\n let entryFunction = EntryFunction.deserialize(deserializer);\n return new TransactionExecutableEntryFunction(entryFunction);\n }\n}\n\nexport class TransactionExecutableEmpty extends TransactionExecutable {\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionExecutableVariants.Empty);\n }\n\n static load(_: Deserializer): TransactionExecutableEmpty {\n return new TransactionExecutableEmpty();\n }\n}\n\nexport abstract class TransactionExtraConfig {\n abstract serialize(serializer: Serializer): void;\n\n static deserialize(deserializer: Deserializer): TransactionExtraConfig {\n // index enum variant\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case TransactionExtraConfigVariants.V1:\n return TransactionExtraConfigV1.load(deserializer);\n default:\n throw new Error(`Unknown variant index for TransactionExtraConfig: ${index}`);\n }\n }\n}\n\nexport class TransactionExtraConfigV1 extends TransactionExtraConfig {\n multisigAddress?: AccountAddress;\n replayProtectionNonce?: bigint;\n\n constructor(multisigAddress?: AccountAddress, replayProtectionNonce?: AnyNumber) {\n super();\n this.multisigAddress = multisigAddress;\n this.replayProtectionNonce = replayProtectionNonce !== undefined ? BigInt(replayProtectionNonce) : undefined;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(TransactionExtraConfigVariants.V1);\n serializer.serializeOption<AccountAddress>(this.multisigAddress);\n serializer.serializeOption<U64>(\n this.replayProtectionNonce !== undefined ? new U64(this.replayProtectionNonce) : undefined,\n );\n }\n\n static load(deserializer: Deserializer): TransactionExtraConfigV1 {\n const multisigAddress = deserializer.deserializeOption(AccountAddress);\n const replayProtectionNonce = deserializer.deserializeOption(U64);\n return new TransactionExtraConfigV1(multisigAddress, replayProtectionNonce?.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 { ChainId } from \"./chainId\";\nimport { AccountAddress } from \"../../core\";\nimport { TransactionPayload } from \"./transactionPayload\";\nimport { TransactionVariants } from \"../../types\";\n\n/**\n * Represents a raw transaction that can be serialized and deserialized.\n * Raw transactions contain the metadata and payloads that can be submitted to the Aptos chain for execution.\n * They must be signed before the Aptos chain can execute them.\n * @group Implementation\n * @category Transactions\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 * @group Implementation\n * @category Transactions\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 /**\n * Serializes the transaction data, including the fee payer transaction type, raw transaction, secondary signer addresses,\n * and fee payer address.\n * This function is essential for preparing the transaction for transmission or storage in a serialized format.\n *\n * @param serializer - The serializer instance used to serialize the transaction data.\n * @group Implementation\n * @category Transactions\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 /**\n * Deserialize a Raw Transaction With Data.\n * This function retrieves the appropriate raw transaction based on the variant index provided by the deserializer.\n *\n * @param deserializer - An instance of the Deserializer used to read the serialized data.\n * @group Implementation\n * @category Transactions\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 * Represents a raw transaction with associated data that can be serialized and deserialized.\n *\n * @extends Serializable\n * @group Implementation\n * @category Transactions\n */\nexport abstract class RawTransactionWithData extends Serializable {\n /**\n * Serialize a Raw Transaction With Data\n * @group Implementation\n * @category Transactions\n */\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserialize a Raw Transaction With Data\n * @group Implementation\n * @category Transactions\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 * Represents a multi-agent transaction that can be serialized and deserialized.\n *\n * @extends RawTransactionWithData\n * @group Implementation\n * @category Transactions\n */\nexport class MultiAgentRawTransaction extends RawTransactionWithData {\n /**\n * The raw transaction\n * @group Implementation\n * @category Transactions\n */\n public readonly raw_txn: RawTransaction;\n\n /**\n * The secondary signers on this transaction\n * @group Implementation\n * @category Transactions\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 /**\n * Deserializes a Fee Payer Raw Transaction from the provided deserializer.\n * This function allows you to reconstruct a Fee Payer Raw Transaction object, which includes the raw transaction data,\n * secondary signer addresses, and the fee payer address.\n *\n * @param deserializer - The deserializer used to read the raw transaction data.\n * @returns A FeePayerRawTransaction object constructed from the deserialized data.\n * @group Implementation\n * @category Transactions\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 * Represents a Fee Payer Transaction that can be serialized and deserialized.\n * @group Implementation\n * @category Transactions\n */\nexport class FeePayerRawTransaction extends RawTransactionWithData {\n /**\n * The raw transaction\n * @group Implementation\n * @category Transactions\n */\n public readonly raw_txn: RawTransaction;\n\n /**\n * The secondary signers on this transaction - optional and can be empty\n * @group Implementation\n * @category Transactions\n */\n public readonly secondary_signer_addresses: Array<AccountAddress>;\n\n /**\n * The fee payer account address\n * @group Implementation\n * @category Transactions\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 { 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\n/**\n * Represents an abstract base class for transaction authenticators.\n * This class provides methods for serializing and deserializing different types of transaction authenticators.\n *\n * @extends Serializable\n * @group Implementation\n * @category Transactions\n */\nexport abstract class TransactionAuthenticator extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserializes a TransactionAuthenticator from the provided deserializer.\n * This function helps in reconstructing the TransactionAuthenticator based on the variant index found in the serialized data.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\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 isEd25519(): this is TransactionAuthenticatorEd25519 {\n return this instanceof TransactionAuthenticatorEd25519;\n }\n\n isMultiEd25519(): this is TransactionAuthenticatorMultiEd25519 {\n return this instanceof TransactionAuthenticatorMultiEd25519;\n }\n\n isMultiAgent(): this is TransactionAuthenticatorMultiAgent {\n return this instanceof TransactionAuthenticatorMultiAgent;\n }\n\n isFeePayer(): this is TransactionAuthenticatorFeePayer {\n return this instanceof TransactionAuthenticatorFeePayer;\n }\n\n isSingleSender(): this is TransactionAuthenticatorSingleSender {\n return this instanceof TransactionAuthenticatorSingleSender;\n }\n}\n\n/**\n * Represents a transaction authenticator using Ed25519 for a single signer transaction.\n * This class encapsulates the client's public key and the Ed25519 signature of a raw transaction.\n *\n * @param public_key - The client's public key.\n * @param signature - The 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 * @group Implementation\n * @category Transactions\n */\nexport class TransactionAuthenticatorEd25519 extends TransactionAuthenticator {\n public readonly public_key: Ed25519PublicKey;\n\n public readonly signature: Ed25519Signature;\n\n /**\n * Creates an instance of the class with the specified account authenticator.\n *\n * @param public_key - The Ed25519PublicKey that will be used for authentication.\n * @param signature - The Ed25519Signature that will be used for authentication.\n * @group Implementation\n * @category Transactions\n */\n constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n /**\n * Serializes the transaction authenticator by encoding the sender information.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Transactions\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 /**\n * Loads a TransactionAuthenticatorSingleSender instance from the provided deserializer.\n * This function helps in deserializing the sender information to create a transaction authenticator.\n *\n * @param deserializer - The deserializer used to extract the sender data.\n * @group Implementation\n * @category Transactions\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 * Represents a transaction authenticator for multi-signature transactions using Ed25519.\n * This class is used to validate transactions that require multiple signatures from different signers.\n *\n * @param public_key - The public key of the client involved in the transaction.\n * @param signature - The multi-signature of the raw transaction.\n * @group Implementation\n * @category Transactions\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 * Represents a transaction authenticator for a multi-agent transaction.\n *\n * This class manages the authentication process involving a primary sender and multiple secondary signers.\n *\n * @param sender - The authenticator for the sender account.\n * @param secondary_signer_addresses - An array of addresses for the secondary signers.\n * @param secondary_signers - An array of authenticators for the secondary signer accounts.\n * @group Implementation\n * @category Transactions\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 * Represents a transaction authenticator specifically for fee payer transactions.\n * It encapsulates the sender's account authenticator, addresses of secondary signers,\n * their respective authenticators, and the fee payer's account information.\n *\n * @param sender - The authenticator for the sender's account.\n * @param secondary_signer_addresses - An array of addresses for secondary signers.\n * @param secondary_signers - An array of authenticators for secondary signers' accounts.\n * @param fee_payer - An object containing the fee payer's account address and authenticator.\n * @group Implementation\n * @category Transactions\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 * Represents a single sender authenticator for transactions that require a single signer.\n * This class is responsible for managing the authentication of a transaction initiated by a single sender.\n *\n * @param sender - An instance of AccountAuthenticator that represents the account of the sender.\n * @group Implementation\n * @category Transactions\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\n/**\n * Represents a signed transaction that includes a raw transaction and an authenticator.\n * The authenticator 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 * @param raw_txn - The raw transaction to be signed.\n * @param authenticator - Contains a client's public key and the signature of the raw transaction.\n * Authenticator can have three variations: 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 * @group Implementation\n * @category Transactions\n */\nexport class SignedTransaction extends Serializable {\n public readonly raw_txn: RawTransaction;\n\n public readonly authenticator: TransactionAuthenticator;\n\n /**\n * Represents a signed transaction that includes a raw transaction and an authenticator.\n * The authenticator contains a client's public key and the signature of the raw transaction,\n * which can be of three types: single signature, multi-signature, and multi-agent.\n *\n * @param raw_txn The raw transaction to be signed.\n * @param authenticator Contains a client's public key and the signature of the raw transaction. The authenticator has 3\n * flavors: single signature, multi-signature and multi-agent.\n * @see {@link https://aptos.dev/integration/creating-a-signed-transaction | Creating a Signed Transaction}\n * @see {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/authenticator.rs} for details.\n * @group Implementation\n * @category Transactions\n */\n constructor(raw_txn: RawTransaction, authenticator: TransactionAuthenticator) {\n super();\n this.raw_txn = raw_txn;\n this.authenticator = authenticator;\n }\n\n /**\n * Serializes the raw transaction and its authenticator using the provided serializer.\n * This function is essential for preparing the transaction data for transmission or storage.\n *\n * @param serializer - The serializer instance used to serialize the transaction and authenticator.\n * @group Implementation\n * @category Transactions\n */\n serialize(serializer: Serializer): void {\n this.raw_txn.serialize(serializer);\n this.authenticator.serialize(serializer);\n }\n\n /**\n * Deserializes a signed transaction from the provided deserializer.\n * This function allows you to reconstruct a SignedTransaction object from its serialized form, enabling further processing or validation.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\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 * Represents a simple transaction type that can be submitted to the Aptos chain for execution.\n *\n * This transaction type is designed for a single signer and includes metadata such as the Raw Transaction\n * and an optional sponsor Account Address to cover gas fees.\n *\n * @param rawTransaction - The Raw Transaction.\n * @param feePayerAddress - The optional sponsor Account Address.\n * @group Implementation\n * @category Transactions\n */\nexport class SimpleTransaction extends Serializable {\n public rawTransaction: RawTransaction;\n\n public feePayerAddress?: AccountAddress | undefined;\n\n // We don't really need it, we add it for type checking we do\n // throughout the SDK\n public readonly secondarySignerAddresses: undefined;\n\n /**\n * SimpleTransaction represents a transaction signed by a single account that\n * can be submitted to the Aptos chain for execution.\n *\n * @param rawTransaction The Raw Transaction.\n * @param feePayerAddress The optional sponsor Account Address to pay the gas fees.\n * @group Implementation\n * @category Transactions\n */\n constructor(rawTransaction: RawTransaction, feePayerAddress?: AccountAddress) {\n super();\n this.rawTransaction = rawTransaction;\n this.feePayerAddress = feePayerAddress;\n }\n\n /**\n * Serializes the transaction data using the provided serializer.\n * This function ensures that the raw transaction and fee payer address are properly serialized for further processing.\n *\n * @param serializer - The serializer instance used to serialize the transaction data.\n * @group Implementation\n * @category Transactions\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 /**\n * Deserializes a SimpleTransaction from the given deserializer.\n * This function helps in reconstructing a SimpleTransaction object from its serialized form.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\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 @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 * Represents a multi-agent transaction that can be serialized and deserialized.\n * This transaction includes a raw transaction, optional fee payer address, and multiple secondary signer addresses.\n *\n * @param rawTransaction The raw transaction to be executed.\n * @param secondarySignerAddresses An array of secondary signer addresses involved in the transaction.\n * @param feePayerAddress An optional account address that sponsors the transaction's gas fees.\n * @group Implementation\n * @category Transactions\n */\nexport class MultiAgentTransaction extends Serializable {\n public rawTransaction: RawTransaction;\n\n public feePayerAddress?: AccountAddress | undefined;\n\n public secondarySignerAddresses: AccountAddress[];\n\n /**\n * Represents a MultiAgentTransaction that can be submitted to the Aptos chain for execution.\n * This class encapsulates the raw transaction data, the secondary signer addresses, and an optional fee payer address.\n *\n * @param rawTransaction The raw transaction data.\n * @param secondarySignerAddresses An array of secondary signer addresses.\n * @param feePayerAddress An optional account address that sponsors the gas fees.\n * @group Implementation\n * @category Transactions\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 /**\n * Serializes the transaction data, including the raw transaction, secondary signer addresses, and fee payer address.\n * This function is essential for preparing the transaction for transmission or storage in a serialized format.\n *\n * @param serializer - The serializer instance used to serialize the transaction data.\n * @group Implementation\n * @category Transactions\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 /**\n * Deserializes a MultiAgentTransaction from the provided deserializer.\n * This function allows you to reconstruct a MultiAgentTransaction object from its serialized form, including any secondary\n * signer addresses and the fee payer address if present.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\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","import { AccountAuthenticatorEd25519 } from \"../transactions/authenticator/account\";\nimport { HexInput, SigningScheme } from \"../types\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature, Signature } from \"../core/crypto\";\nimport type { Account } from \"./Account\";\nimport { AnyRawTransaction } from \"../transactions/types\";\nimport { generateSigningMessageForTransaction } from \"../transactions/transactionBuilder/signingMessage\";\nimport { AptosConfig } from \"../api\";\n\n/**\n * Arguments required to create an instance of an Ed25519 signer.\n *\n * @param privateKey - The private key used for signing.\n * @param address - Optional account address associated with the signer.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface Ed25519SignerConstructorArgs {\n privateKey: Ed25519PrivateKey;\n address?: AccountAddressInput;\n}\n\n/**\n * Arguments for creating an Ed25519 signer from a derivation path.\n *\n * @param path - The derivation path for the Ed25519 key.\n * @param mnemonic - The mnemonic phrase used to generate the key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface Ed25519SignerFromDerivationPathArgs {\n path: string;\n mnemonic: string;\n}\n\n/**\n * Arguments required to verify an Ed25519 signature against a given message.\n *\n * @param message - The message to be verified, represented in hexadecimal format.\n * @param signature - The Ed25519 signature to validate.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface VerifyEd25519SignatureArgs {\n message: HexInput;\n signature: Ed25519Signature;\n}\n\n/**\n * Represents an Ed25519 account that provides signing capabilities through an Ed25519 private key.\n * This class allows for the creation of accounts, signing messages and transactions, and verifying signatures.\n *\n * Note: Generating an instance of this class does not create the account on-chain.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class Ed25519Account implements Account {\n /**\n * Private key associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\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 /**\n * Creates an instance of the Ed25519Signer with the specified parameters.\n * This constructor initializes the private key, public key, and account address for the signer.\n *\n * @param args - The constructor arguments for the Ed25519Signer.\n * @param args.privateKey - The private key used for signing.\n * @param args.address - The optional account address; if not provided, it will derive the address from the public key.\n * @group Implementation\n * @category Account (On-Chain Model)\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 * Generates a new Ed25519 account using a randomly generated private key.\n * This function is useful for creating a signer that can be used for cryptographic operations.\n *\n * @returns {Ed25519Account} The newly generated Ed25519 account.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static generate(): Ed25519Account {\n const privateKey = Ed25519PrivateKey.generate();\n return new Ed25519Account({ privateKey });\n }\n\n /**\n * Derives an Ed25519 account using a specified BIP44 path and mnemonic seed phrase.\n *\n * @param args - The arguments for deriving the account.\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 * @group Implementation\n * @category Account (On-Chain Model)\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 // endregion\n\n // region Account\n /**\n * Verify the given message and signature with the public key.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - Raw message data in HexInput format.\n * @param args.signature - Signed message signature.\n * @returns A boolean indicating whether the signature is valid.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n verifySignature(args: VerifyEd25519SignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n /**\n * Verify the given message and signature with the public key.\n *\n * Ed25519 signatures do not depend on chain state, so this function is equivalent to the synchronous verifySignature method.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - Raw message data in HexInput format.\n * @param args.signature - Signed message signature.\n * @returns A boolean indicating whether the signature is valid.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n }): Promise<boolean> {\n return this.publicKey.verifySignatureAsync({\n ...args,\n signature: args.signature,\n });\n }\n\n /**\n * Sign a message using the account's Ed25519 private key.\n * This function returns an AccountAuthenticator containing the signature along with the account's public key.\n *\n * @param message - The signing message, represented as hexadecimal input.\n * @returns An AccountAuthenticator containing the signature and the account's public key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signWithAuthenticator(message: HexInput): AccountAuthenticatorEd25519 {\n return new AccountAuthenticatorEd25519(this.publicKey, this.privateKey.sign(message));\n }\n\n /**\n * Sign a transaction using the account's Ed25519 private key.\n * This function returns an AccountAuthenticator that contains the signature of the transaction along with the account's public key.\n *\n * @param transaction - The raw transaction to be signed.\n * @returns An AccountAuthenticator containing the signature and the public key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorEd25519 {\n return new AccountAuthenticatorEd25519(this.publicKey, this.signTransaction(transaction));\n }\n\n /**\n * Sign the given message using the account's Ed25519 private key.\n * @param message - The message to be signed in HexInput format.\n * @returns Signature - The resulting signature of the signed message.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n sign(message: HexInput): Ed25519Signature {\n return this.privateKey.sign(message);\n }\n\n /**\n * Sign the given transaction using the available signing capabilities.\n * This function helps ensure that the transaction is properly authenticated before submission.\n *\n * @param transaction - The transaction to be signed.\n * @returns Signature - The resulting signature for the transaction.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransaction(transaction: AnyRawTransaction): Ed25519Signature {\n return this.sign(generateSigningMessageForTransaction(transaction));\n }\n\n // endregion\n}\n","import { AccountAuthenticatorSingleKey } from \"../transactions/authenticator/account\";\nimport { type HexInput, SigningScheme, SigningSchemeInput } from \"../types\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport {\n AnyPublicKey,\n AnySignature,\n Ed25519PrivateKey,\n KeylessSignature,\n PrivateKeyInput,\n Secp256k1PrivateKey,\n Signature,\n} from \"../core/crypto\";\nimport type { Account } from \"./Account\";\nimport { generateSigningMessageForTransaction } from \"../transactions/transactionBuilder/signingMessage\";\nimport { AnyRawTransaction } from \"../transactions/types\";\nimport { Ed25519Account } from \"./Ed25519Account\";\nimport { AptosConfig } from \"../api\";\n\n/**\n * An interface which defines if an Account utilizes SingleKey signing.\n *\n * Such an account will use the AnyPublicKey enum to represent its public key when deriving the auth key.\n */\nexport interface SingleKeySigner extends Account {\n getAnyPublicKey(): AnyPublicKey;\n}\n\nexport function isSingleKeySigner(obj: unknown): obj is SingleKeySigner {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"getAnyPublicKey\" in obj &&\n typeof (obj as any).getAnyPublicKey === \"function\"\n );\n}\n\nexport type SingleKeySignerOrLegacyEd25519Account = SingleKeySigner | Ed25519Account;\n\n/**\n * Arguments required to create a single key signer.\n *\n * @param privateKey - The private key used for signing.\n * @param address - Optional account address associated with the signer.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface SingleKeySignerConstructorArgs {\n privateKey: PrivateKeyInput;\n address?: AccountAddressInput;\n}\n\n/**\n * Arguments for generating a single key signer.\n *\n * @param scheme - The signing scheme to be used.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface SingleKeySignerGenerateArgs {\n scheme?: SigningSchemeInput;\n}\n\n/**\n * The arguments for generating a single key signer from a specified derivation path.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport type SingleKeySignerFromDerivationPathArgs = SingleKeySignerGenerateArgs & {\n path: string;\n mnemonic: string;\n};\n\n/**\n * Arguments required to verify a single key signature for a given message.\n *\n * @param message - The message to be verified, represented in hexadecimal format.\n * @param signature - The signature that corresponds to the message.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface VerifySingleKeySignatureArgs {\n message: HexInput;\n signature: AnySignature;\n}\n\n/**\n * Signer implementation for the SingleKey authentication scheme.\n * This class 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 * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class SingleKeyAccount implements Account, SingleKeySigner {\n /**\n * Private key associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly privateKey: PrivateKeyInput;\n\n readonly publicKey: AnyPublicKey;\n\n readonly accountAddress: AccountAddress;\n\n readonly signingScheme = SigningScheme.SingleKey;\n\n /**\n * Creates an instance of the SingleKeySigner using the provided private key and address.\n * This allows for signing transactions and messages with the specified private key.\n *\n * @param args - The constructor arguments for initializing the SingleKeySigner.\n * @param args.privateKey - The private key used for signing.\n * @param args.address - The optional account address; if not provided, it will derive the address from the public key.\n * @group Implementation\n * @category Account (On-Chain Model)\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 getAnyPublicKey(): AnyPublicKey {\n return this.publicKey;\n }\n\n /**\n * Derives an account from a randomly generated private key based on the specified signing scheme.\n * The default generation scheme is Ed25519, but it can also support Secp256k1Ecdsa.\n *\n * @param args - The arguments for generating the account.\n * @param args.scheme - The signing scheme to use for generating the private key. Defaults to SigningSchemeInput.Ed25519.\n * @returns An account with the generated private key based on the specified signing scheme.\n * @throws Error if an unsupported signature scheme is provided.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static generate(args: SingleKeySignerGenerateArgs = {}) {\n const { scheme = SigningSchemeInput.Ed25519 } = args;\n let privateKey: PrivateKeyInput;\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 using a specified BIP44 path and mnemonic seed phrase, defaulting to the Ed25519 signature scheme.\n * This function allows you to create a single key account based on the provided derivation path and mnemonic.\n *\n * @param args - The arguments for deriving the account.\n * @param args.scheme - The signature scheme to derive the private key with. Defaults to Ed25519.\n * @param args.path - The BIP44 derive hardened path (e.g. m/44'/637'/0'/0'/0') for Ed25519, or non-hardened path\n * (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 * @group Implementation\n * @category Account (On-Chain Model)\n */\n static fromDerivationPath(args: SingleKeySignerFromDerivationPathArgs) {\n const { scheme = SigningSchemeInput.Ed25519, path, mnemonic } = args;\n let privateKey: PrivateKeyInput;\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 /**\n * Verify the given message and signature with the public key.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The raw message data in HexInput format.\n * @param args.signature - The signed message signature.\n * @returns A boolean indicating whether the signature is valid.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n verifySignature(args: VerifySingleKeySignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n /**\n * Verify the given message and signature with the account's public key.\n *\n * This function checks if the provided signature is valid for the given message using the account's public key.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The raw message data in HexInput format.\n * @param args.signature - The signed message signature.\n * @param args.options.throwErrorWithReason - Whether to throw an error with the reason for the verification failure.\n * @returns A boolean indicating whether the signature is valid for the message.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n return this.publicKey.verifySignatureAsync({\n ...args,\n signature: args.signature,\n });\n }\n\n /**\n * Sign a message using the account's private key and return an AccountAuthenticator containing the signature along with the\n * account's public key.\n * @param message - The signing message, represented as binary input in hexadecimal format.\n * @returns An instance of AccountAuthenticatorSingleKey containing the signature and the public key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signWithAuthenticator(message: HexInput): AccountAuthenticatorSingleKey {\n return new AccountAuthenticatorSingleKey(this.publicKey, this.sign(message));\n }\n\n /**\n * Sign a transaction using the account's private key.\n * This function returns an AccountAuthenticator that contains the signature of the transaction along with the account's public key.\n * @param transaction - The raw transaction to be signed.\n * @returns An AccountAuthenticatorSingleKey containing the signature of the transaction and the account's public key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorSingleKey {\n return new AccountAuthenticatorSingleKey(this.publicKey, this.signTransaction(transaction));\n }\n\n /**\n * Sign the given message using the account's private key.\n * @param message - The message to be signed in HexInput format.\n * @returns A new AnySignature containing the signature of the message.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n sign(message: HexInput): AnySignature {\n return new AnySignature(this.privateKey.sign(message));\n }\n\n /**\n * Sign the given transaction using the account's private key.\n * This function generates a signing message for the transaction and then signs it.\n *\n * @param transaction - The transaction to be signed.\n * @returns Signature - The resulting signature for the signed transaction.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransaction(transaction: AnyRawTransaction): AnySignature {\n return this.sign(generateSigningMessageForTransaction(transaction));\n }\n\n // endregion\n\n static fromEd25519Account(account: Ed25519Account): SingleKeyAccount {\n return new SingleKeyAccount({ privateKey: account.privateKey, address: account.accountAddress });\n }\n}\n","import type { AccountAuthenticator } from \"../transactions/authenticator/account\";\nimport { HexInput, SigningScheme, SigningSchemeInput } from \"../types\";\nimport type { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { AuthenticationKey } from \"../core/authenticationKey\";\nimport { AccountPublicKey, Ed25519PrivateKey, PrivateKeyInput, Signature, VerifySignatureArgs } from \"../core/crypto\";\nimport { Ed25519Account } from \"./Ed25519Account\";\nimport { SingleKeyAccount } from \"./SingleKeyAccount\";\nimport { AnyRawTransaction } from \"../transactions/types\";\nimport { AptosConfig } from \"../api\";\n\n/**\n * Arguments for creating an `Ed25519Account` from an `Ed25519PrivateKey`.\n * To use the SingleKey authentication scheme, set `legacy` to false.\n *\n * @param privateKey - The private key used to create the account.\n * @param address - Optional address for the account.\n * @param legacy - Indicates whether to use legacy authentication (default is true).\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface CreateEd25519AccountFromPrivateKeyArgs {\n privateKey: Ed25519PrivateKey;\n address?: AccountAddressInput;\n legacy?: true;\n}\n\n/**\n * Arguments for creating a `SingleKeyAccount` using an `Ed25519PrivateKey`.\n * The `legacy` property must be set to false to utilize the `SingleKey` authentication scheme.\n *\n * @param privateKey - The Ed25519 private key used for account creation.\n * @param address - Optional account address input.\n * @param legacy - Must be false to enable the `SingleKey` authentication scheme.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface CreateEd25519SingleKeyAccountFromPrivateKeyArgs {\n privateKey: Ed25519PrivateKey;\n address?: AccountAddressInput;\n legacy: false;\n}\n\n/**\n * Arguments for creating a `SingleKeyAccount` from a supported private key, excluding `Ed25519PrivateKey`.\n * The `legacy` argument is always false and cannot be set to true.\n *\n * @param privateKey - The private key used to create the account.\n * @param address - Optional address input for the account.\n * @param legacy - Always false; cannot be explicitly set to true.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface CreateSingleKeyAccountFromPrivateKeyArgs {\n privateKey: PrivateKeyInput;\n address?: AccountAddressInput;\n legacy?: false;\n}\n\n/**\n * Arguments for creating an `Account` from a private key when the key type is unknown at compile time.\n *\n * @param privateKey - The private key used to create the account.\n * @param address - Optional address for the account.\n * @param legacy - Optional flag indicating if the account is a legacy account.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface CreateAccountFromPrivateKeyArgs {\n privateKey: PrivateKeyInput;\n address?: AccountAddressInput;\n legacy?: boolean;\n}\n\n/**\n * Arguments for generating an Ed25519 account, specifying the signing scheme and legacy option.\n *\n * @param scheme - The signing scheme to use for the account.\n * @param legacy - Indicates if the account should be created in legacy mode.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface GenerateEd25519AccountArgs {\n scheme?: SigningSchemeInput.Ed25519;\n legacy?: true;\n}\n\n/**\n * Arguments for generating a `SingleKeyAccount` with an underlying `Ed25519PrivateKey`.\n * The `legacy` argument must be set to false to ensure an `Ed25519SingleKeyAccount` is returned.\n *\n * @param scheme - Optional signing scheme input for the account.\n * @param legacy - Indicates whether to use legacy account generation.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface GenerateEd25519SingleKeyAccountArgs {\n scheme?: SigningSchemeInput.Ed25519;\n legacy: false;\n}\n\n/**\n * Arguments for generating a `SingleKeyAccount` using a supported private key other than `Ed25519PrivateKey`.\n * The `legacy` argument is optional and defaults to false, and cannot be set to true.\n *\n * @param scheme - The signing scheme to use for the account.\n * @param legacy - Indicates whether to use legacy account generation (defaults to false).\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface GenerateSingleKeyAccountArgs {\n scheme: Exclude<SigningSchemeInput, SigningSchemeInput.Ed25519>;\n legacy?: false;\n}\n\n/**\n * Arguments for generating an opaque `Account` when the input signature scheme is unknown at compile time.\n *\n * @param scheme - The signing scheme to use for account generation.\n * @param legacy - Indicates whether to use legacy account generation methods.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface GenerateAccountArgs {\n scheme?: SigningSchemeInput;\n legacy?: boolean;\n}\n\n/**\n * Arguments for deriving a private key using a mnemonic phrase and a specified BIP44 path.\n *\n * @param path - The BIP44 derivation path for the key.\n * @param mnemonic - The mnemonic phrase used for key generation.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface PrivateKeyFromDerivationPathArgs {\n path: string;\n mnemonic: string;\n}\n\n/**\n * Abstract class representing a generic Aptos account.\n *\n * This class serves as a single entry point for account generation, allowing accounts to be created\n * either through `Account.generate()` or `Account.fromDerivationPath`. Although it is defined as an\n * abstract class, it should be treated as an interface and enforced using the `implements` keyword.\n *\n * Note: Generating an account instance does not create the account on-chain.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport abstract class Account {\n /**\n * Public key associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract readonly publicKey: AccountPublicKey;\n\n /**\n * Account address associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract readonly accountAddress: AccountAddress;\n\n /**\n * Signing scheme used to sign transactions\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract signingScheme: SigningScheme;\n\n /**\n * Generates a new account based on the specified signing scheme and legacy option.\n * This function allows you to create an account with either the Ed25519 signing scheme or a different scheme as specified.\n *\n * @param args - The arguments for generating the account.\n * @param args.scheme - The signing scheme to use for account generation. Defaults to Ed25519.\n * @param args.legacy - Indicates whether to use the legacy account generation method. Defaults to true.\n * @group Implementation\n * @category Account (On-Chain Model)\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 a given private key and address.\n * This function allows you to instantiate an account based on the provided private key,\n * and it can differentiate between legacy and non-legacy accounts.\n *\n * @param args - The arguments for creating the account.\n * @param args.privateKey - The private key used to create the account.\n * @param args.address - The address associated with the account.\n * @param args.legacy - A boolean indicating whether to create a legacy account (default is true).\n * @returns An instance of either Ed25519Account or SingleKeyAccount based on the provided private key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static fromPrivateKey(args: CreateEd25519AccountFromPrivateKeyArgs): Ed25519Account;\n static fromPrivateKey(args: CreateSingleKeyAccountFromPrivateKeyArgs): SingleKeyAccount;\n static fromPrivateKey(args: CreateAccountFromPrivateKeyArgs): SingleKeyAccount;\n static fromPrivateKey(args: CreateAccountFromPrivateKeyArgs): Ed25519Account | SingleKeyAccount {\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 using a private key and a specified account address. This is primarily used to instantiate an\n * `Account` that has had its authentication key rotated.\n *\n * @param args - The arguments required to create an account from a private key.\n * @param args.privateKey - The underlying private key for the account.\n * @param args.address - 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 to generating a Legacy\n * Ed25519 keypair.\n *\n * @returns Account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static fromPrivateKeyAndAddress(args: CreateAccountFromPrivateKeyArgs) {\n return this.fromPrivateKey(args);\n }\n\n /**\n * Generates an account from a specified derivation path and mnemonic.\n * This function allows you to create an account using different signing schemes based on the provided arguments.\n *\n * @param args - The arguments for generating the account.\n * @param args.scheme - The signing scheme to use for account generation. Defaults to Ed25519.\n * @param args.mnemonic - The mnemonic phrase used to derive the account.\n * @param args.path - The derivation path used to generate the account.\n * @param args.legacy - A boolean indicating whether to use the legacy account generation method. Defaults to true.\n * @group Implementation\n * @category Account (On-Chain Model)\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 * Retrieve the authentication key for the associated account using the provided public key.\n * This key enables account owners to rotate their private key(s) associated with the account without changing the address that\n * hosts their account.\n * See here for more info: {@link https://aptos.dev/concepts/accounts#single-signer-authentication}\n *\n * @param args - The arguments for retrieving the authentication key.\n * @param args.publicKey - The public key of the account.\n * @returns The authentication key for the associated account.\n * @group Implementation\n * @category Account (On-Chain Model)\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 * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract signWithAuthenticator(message: HexInput): AccountAuthenticator;\n\n /**\n * Sign a transaction using the available signing capabilities.\n * @param transaction the raw transaction\n * @return the AccountAuthenticator containing the signature of the transaction, together with the account's public key\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticator;\n\n /**\n * Sign the given message using the available signing capabilities.\n * @param message in HexInput format\n * @returns Signature\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract sign(message: HexInput): Signature;\n\n /**\n * Sign the given transaction using the available signing capabilities.\n * @param transaction the transaction to be signed\n * @returns Signature\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n abstract signTransaction(transaction: AnyRawTransaction): Signature;\n\n /**\n * Verify the given message and signature with the public key.\n * This function helps ensure the integrity and authenticity of a message by validating its signature.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The raw message data in HexInput format.\n * @param args.signature - The signed message signature.\n * @returns A boolean indicating whether the signature is valid.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n verifySignature(args: VerifySignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n /**\n * Verify the given message and signature with the public key. It fetches any on chain state if needed for verification.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - Raw message data in HexInput format.\n * @param args.signature - Signed message signature.\n * @returns A boolean indicating whether the signature is valid.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n }): Promise<boolean> {\n return this.publicKey.verifySignatureAsync(args);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { randomBytes } from \"@noble/hashes/utils\";\n\nimport {\n bytesToBigIntLE,\n padAndPackBytesWithLen,\n poseidonHash,\n Ed25519PrivateKey,\n EphemeralPublicKey,\n EphemeralSignature,\n PrivateKey,\n} from \"../core/crypto\";\nimport { Hex } from \"../core/hex\";\nimport { EphemeralPublicKeyVariant, HexInput } from \"../types\";\nimport { Deserializer, Serializable, Serializer } from \"../bcs\";\nimport { floorToWholeHour, nowInSeconds } from \"../utils/helpers\";\n\nconst TWO_WEEKS_IN_SECONDS = 1_209_600;\n\n/**\n * Represents an ephemeral key pair used for signing transactions via the Keyless authentication scheme.\n * This key pair is temporary and includes an expiration time.\n * For more details on how this class is used, refer to the documentation:\n * https://aptos.dev/guides/keyless-accounts/#1-present-the-user-with-a-sign-in-with-idp-button-on-the-ui\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class EphemeralKeyPair extends Serializable {\n static readonly BLINDER_LENGTH: number = 31;\n\n /**\n * A byte array of length BLINDER_LENGTH used to obfuscate the public key from the IdP.\n * Used in calculating the nonce passed to the IdP and as a secret witness in proof generation.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly blinder: Uint8Array;\n\n /**\n * A timestamp in seconds indicating when the ephemeral key pair is expired. After expiry, a new\n * EphemeralKeyPair must be generated and a new JWT needs to be created.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly expiryDateSecs: number;\n\n /**\n * The value passed to the IdP when the user authenticates. It consists of a hash of the\n * ephemeral public key, expiry date, and blinder.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly nonce: string;\n\n /**\n * A private key used to sign transactions. This private key is not tied to any account on the chain as it\n * is ephemeral (not permanent) in nature.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n private privateKey: PrivateKey;\n\n /**\n * A public key used to verify transactions. This public key is not tied to any account on the chain as it\n * is ephemeral (not permanent) in nature.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n private publicKey: EphemeralPublicKey;\n\n /**\n * Creates an instance of the class with a specified private key, optional expiry date, and optional blinder.\n * This constructor initializes the public key, sets the expiry date to a default value if not provided,\n * generates a blinder if not supplied, and calculates the nonce based on the public key, expiry date, and blinder.\n *\n * @param args - The parameters for constructing the instance.\n * @param args.privateKey - The private key used for creating the instance.\n * @param args.expiryDateSecs - Optional expiry date in seconds from the current time. Defaults to two weeks from now.\n * @param args.blinder - Optional blinder value. If not provided, a new blinder will be generated.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n constructor(args: { privateKey: PrivateKey; expiryDateSecs?: number; blinder?: HexInput }) {\n super();\n const { privateKey, expiryDateSecs, blinder } = args;\n this.privateKey = privateKey;\n this.publicKey = new EphemeralPublicKey(privateKey.publicKey());\n // By default, we set the expiry date to be two weeks in the future floored to the nearest hour\n this.expiryDateSecs = expiryDateSecs || floorToWholeHour(nowInSeconds() + TWO_WEEKS_IN_SECONDS);\n // Generate the blinder if not provided\n this.blinder = blinder !== undefined ? Hex.fromHexInput(blinder).toUint8Array() : generateBlinder();\n // Calculate the nonce\n const fields = padAndPackBytesWithLen(this.publicKey.bcsToBytes(), 93);\n fields.push(BigInt(this.expiryDateSecs));\n fields.push(bytesToBigIntLE(this.blinder));\n const nonceHash = poseidonHash(fields);\n this.nonce = nonceHash.toString();\n }\n\n /**\n * Returns the public key of the key pair.\n * @return EphemeralPublicKey\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n getPublicKey(): EphemeralPublicKey {\n return this.publicKey;\n }\n\n /**\n * Checks if the current time has surpassed the expiry date of the key pair.\n * @return boolean - Returns true if the key pair is expired, otherwise false.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n isExpired(): boolean {\n const currentTimeSecs: number = Math.floor(Date.now() / 1000);\n return currentTimeSecs > this.expiryDateSecs;\n }\n\n /**\n * Serializes the object's properties into a format suitable for transmission or storage.\n * This function is essential for preparing the object data for serialization processes.\n *\n * @param serializer - The serializer instance used to serialize the object's properties.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.publicKey.variant);\n serializer.serializeBytes(this.privateKey.toUint8Array());\n serializer.serializeU64(this.expiryDateSecs);\n serializer.serializeFixedBytes(this.blinder);\n }\n\n /**\n * Deserializes an ephemeral key pair from the provided deserializer.\n * This function helps in reconstructing an ephemeral key pair, which is essential for cryptographic operations.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static deserialize(deserializer: Deserializer): EphemeralKeyPair {\n const variantIndex = deserializer.deserializeUleb128AsU32();\n let privateKey: PrivateKey;\n switch (variantIndex) {\n case EphemeralPublicKeyVariant.Ed25519:\n privateKey = Ed25519PrivateKey.deserialize(deserializer);\n break;\n default:\n throw new Error(`Unknown variant index for EphemeralPublicKey: ${variantIndex}`);\n }\n const expiryDateSecs = deserializer.deserializeU64();\n const blinder = deserializer.deserializeFixedBytes(31);\n return new EphemeralKeyPair({ privateKey, expiryDateSecs: Number(expiryDateSecs), blinder });\n }\n\n /**\n * Deserialize a byte array into an EphemeralKeyPair object.\n * This function allows you to reconstruct an EphemeralKeyPair from its serialized byte representation.\n *\n * @param bytes - The byte array representing the serialized EphemeralKeyPair.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static fromBytes(bytes: Uint8Array): EphemeralKeyPair {\n return EphemeralKeyPair.deserialize(new Deserializer(bytes));\n }\n\n /**\n * Generates a new ephemeral key pair with an optional expiry date.\n * This function allows you to create a temporary key pair for secure operations.\n *\n * @param args - Optional parameters for key pair generation.\n * @param args.scheme - The type of key pair to use for the EphemeralKeyPair. Only Ed25519 is supported for now.\n * @param args.expiryDateSecs - The date of expiry for the key pair in seconds.\n * @returns An instance of EphemeralKeyPair containing the generated private key and expiry date.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static generate(args?: { scheme?: EphemeralPublicKeyVariant; expiryDateSecs?: number }): EphemeralKeyPair {\n let privateKey: PrivateKey;\n\n switch (args?.scheme) {\n case EphemeralPublicKeyVariant.Ed25519:\n default:\n privateKey = Ed25519PrivateKey.generate();\n }\n\n return new EphemeralKeyPair({ privateKey, expiryDateSecs: args?.expiryDateSecs });\n }\n\n /**\n * Sign the given data using the private key, returning an ephemeral signature.\n * This function is essential for creating a secure signature that can be used for authentication or verification purposes.\n *\n * @param data - The data to be signed, provided in HexInput format.\n * @returns EphemeralSignature - The resulting ephemeral signature.\n * @throws Error - Throws an error if the EphemeralKeyPair has expired.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n sign(data: HexInput): EphemeralSignature {\n if (this.isExpired()) {\n throw new Error(\"EphemeralKeyPair has expired\");\n }\n return new EphemeralSignature(this.privateKey.sign(data));\n }\n}\n\n/**\n * Generates a random byte array of length EphemeralKeyPair.BLINDER_LENGTH.\n * @returns Uint8Array A random byte array used for blinding.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nfunction generateBlinder(): Uint8Array {\n return randomBytes(EphemeralKeyPair.BLINDER_LENGTH);\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { EphemeralCertificateVariant, HexInput, SigningScheme } from \"../types\";\nimport { AccountAddress } from \"../core/accountAddress\";\nimport {\n AnyPublicKey,\n AnySignature,\n KeylessPublicKey,\n KeylessSignature,\n EphemeralCertificate,\n ZeroKnowledgeSig,\n ZkProof,\n MoveJWK,\n getKeylessConfig,\n fetchJWK,\n KeylessConfiguration,\n} from \"../core/crypto\";\n\nimport { EphemeralKeyPair } from \"./EphemeralKeyPair\";\nimport { Hex } from \"../core/hex\";\nimport { AccountAuthenticatorSingleKey } from \"../transactions/authenticator/account\";\nimport { Deserializer, Serializable, Serializer } from \"../bcs\";\nimport { deriveTransactionType, generateSigningMessage } from \"../transactions/transactionBuilder/signingMessage\";\nimport { AnyRawTransaction, AnyRawTransactionInstance } from \"../transactions/types\";\nimport { base64UrlDecode } from \"../utils/helpers\";\nimport { FederatedKeylessPublicKey } from \"../core/crypto/federatedKeyless\";\nimport { Account } from \"./Account\";\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { KeylessError, KeylessErrorType } from \"../errors\";\nimport type { SingleKeySigner } from \"./SingleKeyAccount\";\n\n/**\n * An interface which defines if an Account utilizes Keyless signing.\n */\nexport interface KeylessSigner extends Account {\n checkKeylessAccountValidity(aptosConfig: AptosConfig): Promise<void>;\n}\n\nexport function isKeylessSigner(obj: any): obj is KeylessSigner {\n return obj !== null && obj !== undefined && typeof obj.checkKeylessAccountValidity === \"function\";\n}\n\n/**\n * Account implementation for the Keyless authentication scheme. This abstract class is used for standard Keyless Accounts\n * and Federated Keyless Accounts.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport abstract class AbstractKeylessAccount extends Serializable implements KeylessSigner, SingleKeySigner {\n static readonly PEPPER_LENGTH: number = 31;\n\n /**\n * The KeylessPublicKey associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n\n /**\n * The EphemeralKeyPair used to generate sign.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly ephemeralKeyPair: EphemeralKeyPair;\n\n /**\n * The claim on the JWT to identify a user. This is typically 'sub' or 'email'.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly uidKey: string;\n\n /**\n * The value of the uidKey claim on the JWT. This intended to be a stable user identifier.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly uidVal: string;\n\n /**\n * The value of the 'aud' claim on the JWT, also known as client ID. This is the identifier for the dApp's\n * OIDC registration with the identity provider.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly aud: string;\n\n /**\n * A value contains 31 bytes of entropy that preserves privacy of the account. Typically fetched from a pepper provider.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly pepper: Uint8Array;\n\n /**\n * Account address associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly accountAddress: AccountAddress;\n\n /**\n * The zero knowledge signature (if ready) which contains the proof used to validate the EphemeralKeyPair.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n proof: ZeroKnowledgeSig | undefined;\n\n /**\n * The proof of the EphemeralKeyPair or a promise that provides the proof. This is used to allow for awaiting on\n * fetching the proof.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly proofOrPromise: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;\n\n /**\n * Signing scheme used to sign transactions\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly signingScheme: SigningScheme = SigningScheme.SingleKey;\n\n /**\n * The JWT token used to derive the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly jwt: string;\n\n /**\n * The hash of the verification key used to verify the proof. This is optional and can be used to check verifying key\n * rotations which may invalidate the proof.\n */\n readonly verificationKeyHash?: Uint8Array;\n\n /**\n * An event emitter used to assist in handling asynchronous proof fetching.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n private readonly emitter: EventEmitter<ProofFetchEvents>;\n\n /**\n * Use the static generator `create(...)` instead.\n * Creates an instance of the KeylessAccount with an optional proof.\n *\n * @param args - The parameters for creating a KeylessAccount.\n * @param args.address - Optional account address associated with the KeylessAccount.\n * @param args.publicKey - A KeylessPublicKey or FederatedKeylessPublicKey.\n * @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.\n * @param args.iss - A JWT issuer.\n * @param args.uidKey - The claim on the JWT to identify a user. This is typically 'sub' or 'email'.\n * @param args.uidVal - The unique id for this user, intended to be a stable user identifier.\n * @param args.aud - The value of the 'aud' claim on the JWT, also known as client ID. This is the identifier for the dApp's\n * OIDC registration with the identity provider.\n * @param args.pepper - A hexadecimal input used for additional security.\n * @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.\n * @param args.proofFetchCallback - Optional callback function for fetching proof.\n * @param args.jwt - A JSON Web Token used for authentication.\n * @param args.verificationKeyHash Optional 32-byte verification key hash as hex input used to check proof validity.\n */\n protected constructor(args: {\n address?: AccountAddress;\n publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n ephemeralKeyPair: EphemeralKeyPair;\n iss: string;\n uidKey: string;\n uidVal: string;\n aud: string;\n pepper: HexInput;\n proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;\n proofFetchCallback?: ProofFetchCallback;\n jwt: string;\n verificationKeyHash?: HexInput;\n }) {\n super();\n const {\n address,\n ephemeralKeyPair,\n publicKey,\n uidKey,\n uidVal,\n aud,\n pepper,\n proof,\n proofFetchCallback,\n jwt,\n verificationKeyHash,\n } = args;\n this.ephemeralKeyPair = ephemeralKeyPair;\n this.publicKey = publicKey;\n this.accountAddress = address ? AccountAddress.from(address) : this.publicKey.authKey().derivedAddress();\n this.uidKey = uidKey;\n this.uidVal = uidVal;\n this.aud = aud;\n this.jwt = jwt;\n this.emitter = new EventEmitter<ProofFetchEvents>();\n this.proofOrPromise = proof;\n if (proof instanceof ZeroKnowledgeSig) {\n this.proof = proof;\n } else {\n if (proofFetchCallback === undefined) {\n throw new Error(\"Must provide callback for async proof fetch\");\n }\n this.emitter.on(\"proofFetchFinish\", async (status) => {\n await proofFetchCallback(status);\n this.emitter.removeAllListeners();\n });\n // Note, this is purposely not awaited to be non-blocking. The caller should await on the proofFetchCallback.\n this.init(proof);\n }\n const pepperBytes = Hex.fromHexInput(pepper).toUint8Array();\n if (pepperBytes.length !== AbstractKeylessAccount.PEPPER_LENGTH) {\n throw new Error(`Pepper length in bytes should be ${AbstractKeylessAccount.PEPPER_LENGTH}`);\n }\n this.pepper = pepperBytes;\n if (verificationKeyHash !== undefined) {\n if (Hex.hexInputToUint8Array(verificationKeyHash).length !== 32) {\n throw new Error(\"verificationKeyHash must be 32 bytes\");\n }\n this.verificationKeyHash = Hex.hexInputToUint8Array(verificationKeyHash);\n }\n }\n\n getAnyPublicKey(): AnyPublicKey {\n return new AnyPublicKey(this.publicKey);\n }\n\n /**\n * This initializes the asynchronous proof fetch\n * @return Emits whether the proof succeeds or fails, but has no return.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async init(promise: Promise<ZeroKnowledgeSig>) {\n try {\n this.proof = await promise;\n this.emitter.emit(\"proofFetchFinish\", { status: \"Success\" });\n } catch (error) {\n if (error instanceof Error) {\n this.emitter.emit(\"proofFetchFinish\", { status: \"Failed\", error: error.toString() });\n } else {\n this.emitter.emit(\"proofFetchFinish\", { status: \"Failed\", error: \"Unknown\" });\n }\n }\n }\n\n /**\n * Serializes the jwt data into a format suitable for transmission or storage.\n * This function ensures that both the jwt data and the proof are properly serialized.\n *\n * @param serializer - The serializer instance used to convert the jwt data into bytes.\n */\n serialize(serializer: Serializer): void {\n this.accountAddress.serialize(serializer);\n serializer.serializeStr(this.jwt);\n serializer.serializeStr(this.uidKey);\n serializer.serializeFixedBytes(this.pepper);\n this.ephemeralKeyPair.serialize(serializer);\n if (this.proof === undefined) {\n throw new Error(\"Cannot serialize - proof undefined\");\n }\n this.proof.serialize(serializer);\n serializer.serializeOption(this.verificationKeyHash, 32);\n }\n\n static partialDeserialize(deserializer: Deserializer): {\n address: AccountAddress;\n jwt: string;\n uidKey: string;\n pepper: Uint8Array;\n ephemeralKeyPair: EphemeralKeyPair;\n proof: ZeroKnowledgeSig;\n verificationKeyHash?: Uint8Array;\n } {\n const address = AccountAddress.deserialize(deserializer);\n const jwt = deserializer.deserializeStr();\n const uidKey = deserializer.deserializeStr();\n const pepper = deserializer.deserializeFixedBytes(31);\n const ephemeralKeyPair = EphemeralKeyPair.deserialize(deserializer);\n const proof = ZeroKnowledgeSig.deserialize(deserializer);\n const verificationKeyHash = deserializer.deserializeOption(\"fixedBytes\", 32);\n\n return { address, jwt, uidKey, pepper, ephemeralKeyPair, proof, verificationKeyHash };\n }\n\n /**\n * Checks if the proof is expired. If so the account must be re-derived with a new EphemeralKeyPair\n * and JWT token.\n * @return boolean\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n isExpired(): boolean {\n return this.ephemeralKeyPair.isExpired();\n }\n\n /**\n * Sign a message using Keyless.\n * @param message the message to sign, as binary input\n * @return the AccountAuthenticator containing the signature, together with the account's public key\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signWithAuthenticator(message: HexInput): AccountAuthenticatorSingleKey {\n const signature = new AnySignature(this.sign(message));\n const publicKey = new AnyPublicKey(this.publicKey);\n return new AccountAuthenticatorSingleKey(publicKey, signature);\n }\n\n /**\n * Sign a transaction using Keyless.\n * @param transaction the raw transaction\n * @return the AccountAuthenticator containing the signature of the transaction, together with the account's public key\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorSingleKey {\n const signature = new AnySignature(this.signTransaction(transaction));\n const publicKey = new AnyPublicKey(this.publicKey);\n return new AccountAuthenticatorSingleKey(publicKey, signature);\n }\n\n /**\n * Waits for asynchronous proof fetching to finish.\n * @return\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async waitForProofFetch() {\n if (this.proofOrPromise instanceof Promise) {\n await this.proofOrPromise;\n }\n }\n\n /**\n * Validates that the Keyless Account can be used to sign transactions.\n * @return\n */\n async checkKeylessAccountValidity(aptosConfig: AptosConfig): Promise<void> {\n if (this.isExpired()) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.EPHEMERAL_KEY_PAIR_EXPIRED,\n });\n }\n await this.waitForProofFetch();\n if (this.proof === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.ASYNC_PROOF_FETCH_FAILED,\n });\n }\n const header = jwtDecode(this.jwt, { header: true });\n if (header.kid === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.JWT_PARSING_ERROR,\n details: \"checkKeylessAccountValidity failed. JWT is missing 'kid' in header. This should never happen.\",\n });\n }\n if (this.verificationKeyHash !== undefined) {\n const { verificationKey } = await getKeylessConfig({ aptosConfig });\n if (Hex.hexInputToString(verificationKey.hash()) !== Hex.hexInputToString(this.verificationKeyHash)) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.INVALID_PROOF_VERIFICATION_KEY_NOT_FOUND,\n });\n }\n } else {\n // eslint-disable-next-line no-console\n console.warn(\n \"[Aptos SDK] The verification key hash was not set. Proof may be invalid if the verification key has rotated.\",\n );\n }\n await AbstractKeylessAccount.fetchJWK({ aptosConfig, publicKey: this.publicKey, kid: header.kid });\n }\n\n /**\n * Sign the given message using Keyless.\n * @param message in HexInput format\n * @returns Signature\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n sign(message: HexInput): KeylessSignature {\n const { expiryDateSecs } = this.ephemeralKeyPair;\n if (this.isExpired()) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.EPHEMERAL_KEY_PAIR_EXPIRED,\n });\n }\n if (this.proof === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.PROOF_NOT_FOUND,\n details: \"Proof not found - make sure to call `await account.checkKeylessAccountValidity()` before signing.\",\n });\n }\n const ephemeralPublicKey = this.ephemeralKeyPair.getPublicKey();\n const ephemeralSignature = this.ephemeralKeyPair.sign(message);\n\n return new KeylessSignature({\n jwtHeader: base64UrlDecode(this.jwt.split(\".\")[0]),\n ephemeralCertificate: new EphemeralCertificate(this.proof, EphemeralCertificateVariant.ZkProof),\n expiryDateSecs,\n ephemeralPublicKey,\n ephemeralSignature,\n });\n }\n\n /**\n * Sign the given transaction with Keyless.\n * Signs the transaction and proof to guard against proof malleability.\n * @param transaction the transaction to be signed\n * @returns KeylessSignature\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransaction(transaction: AnyRawTransaction): KeylessSignature {\n if (this.proof === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.PROOF_NOT_FOUND,\n details: \"Proof not found - make sure to call `await account.checkKeylessAccountValidity()` before signing.\",\n });\n }\n const raw = deriveTransactionType(transaction);\n const txnAndProof = new TransactionAndProof(raw, this.proof.proof);\n const signMess = txnAndProof.hash();\n return this.sign(signMess);\n }\n\n getSigningMessage(transaction: AnyRawTransaction): Uint8Array {\n if (this.proof === undefined) {\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.PROOF_NOT_FOUND,\n details: \"Proof not found - make sure to call `await account.checkKeylessAccountValidity()` before signing.\",\n });\n }\n const raw = deriveTransactionType(transaction);\n const txnAndProof = new TransactionAndProof(raw, this.proof.proof);\n return txnAndProof.hash();\n }\n\n /**\n * Note - This function is currently incomplete and should only be used to verify ownership of the KeylessAccount\n *\n * Verifies a signature given the message.\n *\n * @param args.message the message that was signed.\n * @param args.signature the KeylessSignature to verify\n * @returns boolean\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n verifySignature(args: {\n message: HexInput;\n signature: KeylessSignature;\n jwk: MoveJWK;\n keylessConfig: KeylessConfiguration;\n }): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: KeylessSignature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n return this.publicKey.verifySignatureAsync({\n ...args,\n });\n }\n\n /**\n * Fetches the JWK from the issuer's well-known JWKS endpoint.\n *\n * @param args.publicKey The keyless public key to query\n * @param args.kid The kid of the JWK to fetch\n * @returns A JWK matching the `kid` in the JWT header.\n * @throws {KeylessError} If the JWK cannot be fetched\n */\n static async fetchJWK(args: {\n aptosConfig: AptosConfig;\n publicKey: KeylessPublicKey | FederatedKeylessPublicKey;\n kid: string;\n }): Promise<MoveJWK> {\n return fetchJWK(args);\n }\n}\n\n/**\n * A container class to hold a transaction and a proof. It implements CryptoHashable which is used to create\n * the signing message for Keyless transactions. We sign over the proof to ensure non-malleability.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class TransactionAndProof extends Serializable {\n /**\n * The transaction to sign.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n transaction: AnyRawTransactionInstance;\n\n /**\n * The zero knowledge proof used in signing the transaction.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n proof?: ZkProof;\n\n /**\n * The domain separator prefix used when hashing.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly domainSeparator = \"APTOS::TransactionAndProof\";\n\n constructor(transaction: AnyRawTransactionInstance, proof?: ZkProof) {\n super();\n this.transaction = transaction;\n this.proof = proof;\n }\n\n /**\n * Serializes the transaction data into a format suitable for transmission or storage.\n * This function ensures that both the transaction bytes and the proof are properly serialized.\n *\n * @param serializer - The serializer instance used to convert the transaction data into bytes.\n */\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.transaction.bcsToBytes());\n serializer.serializeOption(this.proof);\n }\n\n /**\n * Hashes the bcs serialized from of the class. This is the typescript corollary to the BCSCryptoHash macro in aptos-core.\n *\n * @returns Uint8Array\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n hash(): Uint8Array {\n return generateSigningMessage(this.bcsToBytes(), this.domainSeparator);\n }\n}\n/**\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport type ProofFetchSuccess = {\n status: \"Success\";\n};\n/**\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport type ProofFetchFailure = {\n status: \"Failed\";\n error: string;\n};\n/**\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport type ProofFetchStatus = ProofFetchSuccess | ProofFetchFailure;\n/**\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport type ProofFetchCallback = (status: ProofFetchStatus) => Promise<void>;\n/**\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface ProofFetchEvents {\n proofFetchFinish: (status: ProofFetchStatus) => void;\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { HexInput } from \"../types\";\nimport { AccountAddress } from \"../core/accountAddress\";\nimport { getIssAudAndUidVal, Groth16VerificationKey, KeylessPublicKey, ZeroKnowledgeSig } from \"../core/crypto\";\n\nimport { EphemeralKeyPair } from \"./EphemeralKeyPair\";\nimport { Deserializer, Serializer } from \"../bcs\";\nimport { AbstractKeylessAccount, ProofFetchCallback } from \"./AbstractKeylessAccount\";\nimport { Hex } from \"../core/hex\";\n\n/**\n * Account implementation for the Keyless authentication scheme.\n *\n * Used to represent a Keyless based account and sign transactions with it.\n *\n * Use `KeylessAccount.create()` to instantiate a KeylessAccount with a JWT, proof and EphemeralKeyPair.\n *\n * When the proof expires or the JWT becomes invalid, the KeylessAccount must be instantiated again with a new JWT,\n * EphemeralKeyPair, and corresponding proof.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class KeylessAccount extends AbstractKeylessAccount {\n /**\n * The KeylessPublicKey associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly publicKey: KeylessPublicKey;\n\n // Use the static constructor 'create' instead.\n\n /**\n * Use the static generator `create(...)` instead.\n * Creates an instance of the KeylessAccount with an optional proof.\n *\n * @param args - The parameters for creating a KeylessAccount.\n * @param args.address - Optional account address associated with the KeylessAccount.\n * @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.\n * @param args.iss - A JWT issuer.\n * @param args.uidKey - The claim on the JWT to identify a user. This is typically 'sub' or 'email'.\n * @param args.uidVal - The unique id for this user, intended to be a stable user identifier.\n * @param args.aud - The value of the 'aud' claim on the JWT, also known as client ID. This is the identifier for the dApp's\n * OIDC registration with the identity provider.\n * @param args.pepper - A hexadecimal input used for additional security.\n * @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.\n * @param args.proofFetchCallback - Optional callback function for fetching proof.\n * @param args.jwt - A JSON Web Token used for authentication.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n constructor(args: {\n address?: AccountAddress;\n ephemeralKeyPair: EphemeralKeyPair;\n iss: string;\n uidKey: string;\n uidVal: string;\n aud: string;\n pepper: HexInput;\n proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;\n proofFetchCallback?: ProofFetchCallback;\n jwt: string;\n verificationKeyHash?: HexInput;\n }) {\n const publicKey = KeylessPublicKey.create(args);\n super({ publicKey, ...args });\n this.publicKey = publicKey;\n }\n\n /**\n * Serializes the transaction data into a format suitable for transmission or storage.\n * This function ensures that both the transaction bytes and the proof are properly serialized.\n *\n * @param serializer - The serializer instance used to convert the transaction data into bytes.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n serialize(serializer: Serializer): void {\n super.serialize(serializer);\n }\n\n /**\n * Deserializes the provided deserializer to create a KeylessAccount instance.\n * This function extracts necessary components such as the JWT, UID key, pepper, ephemeral key pair, and proof from the deserializer.\n *\n * @param deserializer - The deserializer instance used to retrieve the serialized data.\n * @returns A KeylessAccount instance created from the deserialized data.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static deserialize(deserializer: Deserializer): KeylessAccount {\n const { address, proof, ephemeralKeyPair, jwt, uidKey, pepper, verificationKeyHash } =\n AbstractKeylessAccount.partialDeserialize(deserializer);\n const { iss, aud, uidVal } = getIssAudAndUidVal({ jwt, uidKey });\n return new KeylessAccount({\n address,\n proof,\n ephemeralKeyPair,\n iss,\n uidKey,\n uidVal,\n aud,\n pepper,\n jwt,\n verificationKeyHash,\n });\n }\n\n /**\n * Deserialize bytes using this account's information.\n *\n * @param bytes The bytes being interpreted.\n * @returns\n */\n static fromBytes(bytes: HexInput): KeylessAccount {\n return KeylessAccount.deserialize(new Deserializer(Hex.hexInputToUint8Array(bytes)));\n }\n\n /**\n * Creates a KeylessAccount instance using the provided parameters.\n * This function allows you to set up a KeylessAccount with specific attributes such as address, proof, and JWT.\n * This is used instead of the KeylessAccount constructor.\n *\n * @param args - The parameters for creating a KeylessAccount.\n * @param args.address - Optional account address associated with the KeylessAccount.\n * @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.\n * @param args.jwt - A JSON Web Token used for authentication.\n * @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.\n * @param args.pepper - A hexadecimal input used for additional security.\n * @param args.uidKey - Optional key for user identification, defaults to \"sub\".\n * @param args.proofFetchCallback - Optional callback function for fetching proof.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static create(args: {\n address?: AccountAddress;\n proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n pepper: HexInput;\n uidKey?: string;\n proofFetchCallback?: ProofFetchCallback;\n verificationKey?: Groth16VerificationKey;\n verificationKeyHash?: Uint8Array;\n }): KeylessAccount {\n const {\n address,\n proof,\n jwt,\n ephemeralKeyPair,\n pepper,\n uidKey = \"sub\",\n proofFetchCallback,\n verificationKey,\n verificationKeyHash,\n } = args;\n\n if (verificationKeyHash && verificationKey) {\n throw new Error(\"Cannot provide both verificationKey and verificationKeyHash\");\n }\n\n const { iss, aud, uidVal } = getIssAudAndUidVal({ jwt, uidKey });\n return new KeylessAccount({\n address,\n proof,\n ephemeralKeyPair,\n iss,\n uidKey,\n uidVal,\n aud,\n pepper,\n jwt,\n proofFetchCallback,\n verificationKeyHash: verificationKeyHash ?? (verificationKey ? verificationKey.hash() : undefined),\n });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { HexInput } from \"../types\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { getIssAudAndUidVal, Groth16VerificationKey, ZeroKnowledgeSig } from \"../core/crypto\";\n\nimport { EphemeralKeyPair } from \"./EphemeralKeyPair\";\nimport { Deserializer, Serializer } from \"../bcs\";\nimport { FederatedKeylessPublicKey } from \"../core/crypto/federatedKeyless\";\nimport { AbstractKeylessAccount, ProofFetchCallback } from \"./AbstractKeylessAccount\";\n\n/**\n * Account implementation for the FederatedKeyless authentication scheme.\n *\n * Used to represent a FederatedKeyless based account and sign transactions with it.\n *\n * Use `FederatedKeylessAccount.create()` to instantiate a KeylessAccount with a JSON Web Token (JWT), proof, EphemeralKeyPair and the\n * address the JSON Web Key Set (JWKS) are installed that will be used to verify the JWT.\n *\n * When the proof expires or the JWT becomes invalid, the KeylessAccount must be instantiated again with a new JWT,\n * EphemeralKeyPair, and corresponding proof.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class FederatedKeylessAccount extends AbstractKeylessAccount {\n /**\n * The FederatedKeylessPublicKey associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly publicKey: FederatedKeylessPublicKey;\n\n readonly audless: boolean;\n\n /**\n * Use the static generator `FederatedKeylessAccount.create(...)` instead.\n * Creates a KeylessAccount instance using the provided parameters.\n * This function allows you to set up a KeylessAccount with specific attributes such as address, proof, and JWT.\n *\n * @param args - The parameters for creating a KeylessAccount.\n * @param args.address - Optional account address associated with the KeylessAccount.\n * @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.\n * @param args.jwt - A JSON Web Token used for authentication.\n * @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.\n * @param args.jwkAddress - The address which stores the JSON Web Key Set (JWKS) used to verify the JWT.\n * @param args.uidKey - Optional key for user identification, defaults to \"sub\".\n * @param args.proofFetchCallback - Optional callback function for fetching proof.\n */\n constructor(args: {\n address?: AccountAddress;\n ephemeralKeyPair: EphemeralKeyPair;\n iss: string;\n uidKey: string;\n uidVal: string;\n aud: string;\n pepper: HexInput;\n jwkAddress: AccountAddress;\n proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;\n proofFetchCallback?: ProofFetchCallback;\n jwt: string;\n verificationKeyHash?: HexInput;\n audless?: boolean;\n }) {\n const publicKey = FederatedKeylessPublicKey.create(args);\n super({ publicKey, ...args });\n this.publicKey = publicKey;\n this.audless = args.audless ?? false;\n }\n\n /**\n * Serializes the transaction data into a format suitable for transmission or storage.\n * This function ensures that both the transaction bytes and the proof are properly serialized.\n *\n * @param serializer - The serializer instance used to convert the transaction data into bytes.\n */\n serialize(serializer: Serializer): void {\n super.serialize(serializer);\n this.publicKey.jwkAddress.serialize(serializer);\n }\n\n /**\n * Deserializes the provided deserializer to create a KeylessAccount instance.\n * This function extracts necessary components such as the JWT, UID key, pepper, ephemeral key pair, and proof from the deserializer.\n *\n * @param deserializer - The deserializer instance used to retrieve the serialized data.\n * @returns A KeylessAccount instance created from the deserialized data.\n */\n static deserialize(deserializer: Deserializer): FederatedKeylessAccount {\n const { address, proof, ephemeralKeyPair, jwt, uidKey, pepper, verificationKeyHash } =\n AbstractKeylessAccount.partialDeserialize(deserializer);\n const jwkAddress = AccountAddress.deserialize(deserializer);\n const { iss, aud, uidVal } = getIssAudAndUidVal({ jwt, uidKey });\n return new FederatedKeylessAccount({\n address,\n proof,\n ephemeralKeyPair,\n iss,\n uidKey,\n uidVal,\n aud,\n pepper,\n jwt,\n verificationKeyHash,\n jwkAddress,\n });\n }\n\n /**\n * Deserialize bytes using this account's information.\n *\n * @param bytes The bytes being interpreted.\n * @returns\n */\n static fromBytes(bytes: HexInput): FederatedKeylessAccount {\n return FederatedKeylessAccount.deserialize(Deserializer.fromHex(bytes));\n }\n\n /**\n * Creates a KeylessAccount instance using the provided parameters.\n * This function allows you to set up a KeylessAccount with specific attributes such as address, proof, and JWT.\n * This is used instead of the KeylessAccount constructor.\n *\n * @param args - The parameters for creating a KeylessAccount.\n * @param args.address - Optional account address associated with the KeylessAccount.\n * @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.\n * @param args.jwt - A JSON Web Token used for authentication.\n * @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.\n * @param args.jwkAddress - The address which stores the JSON Web Key Set (JWKS) used to verify the JWT.\n * @param args.uidKey - Optional key for user identification, defaults to \"sub\".\n * @param args.proofFetchCallback - Optional callback function for fetching proof.\n */\n static create(args: {\n address?: AccountAddress;\n proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n pepper: HexInput;\n jwkAddress: AccountAddressInput;\n uidKey?: string;\n proofFetchCallback?: ProofFetchCallback;\n verificationKey?: Groth16VerificationKey;\n verificationKeyHash?: Uint8Array;\n }): FederatedKeylessAccount {\n const {\n address,\n proof,\n jwt,\n ephemeralKeyPair,\n pepper,\n jwkAddress,\n uidKey = \"sub\",\n proofFetchCallback,\n verificationKey,\n verificationKeyHash,\n } = args;\n\n if (verificationKeyHash && verificationKey) {\n throw new Error(\"Cannot provide both verificationKey and verificationKeyHash\");\n }\n\n const { iss, aud, uidVal } = getIssAudAndUidVal({ jwt, uidKey });\n return new FederatedKeylessAccount({\n address,\n proof,\n ephemeralKeyPair,\n iss,\n uidKey,\n uidVal,\n aud,\n pepper,\n jwkAddress: AccountAddress.from(jwkAddress),\n jwt,\n proofFetchCallback,\n verificationKeyHash: verificationKeyHash ?? (verificationKey ? verificationKey.hash() : undefined),\n });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Account } from \"./Account\";\nimport { MultiKey, MultiKeySignature, PublicKey } from \"../core/crypto\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { HexInput, SigningScheme } from \"../types\";\nimport { AccountAuthenticatorMultiKey } from \"../transactions/authenticator/account\";\nimport { AnyRawTransaction } from \"../transactions/types\";\nimport { AbstractKeylessAccount, KeylessSigner } from \"./AbstractKeylessAccount\";\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { SingleKeyAccount, SingleKeySigner, SingleKeySignerOrLegacyEd25519Account } from \"./SingleKeyAccount\";\nimport { Ed25519Account } from \"./Ed25519Account\";\n\n/**\n * Arguments required to verify a multi-key signature against a given message.\n *\n * @param message - The original message that was signed.\n * @param signature - The multi-key signature to be verified.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport interface VerifyMultiKeySignatureArgs {\n message: HexInput;\n signature: MultiKeySignature;\n}\n\n/**\n * Signer implementation for the MultiKey authentication scheme.\n *\n * This account utilizes an M of N signing scheme, where M and N are specified in the {@link MultiKey}.\n * It signs messages using an array of M accounts, each corresponding to a public key in the {@link MultiKey}.\n *\n * Note: Generating a signer instance does not create the account on-chain.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\nexport class MultiKeyAccount implements Account, KeylessSigner {\n /**\n * Public key associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly publicKey: MultiKey;\n\n /**\n * Account address associated with the account\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly accountAddress: AccountAddress;\n\n /**\n * Signing scheme used to sign transactions\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly signingScheme: SigningScheme = SigningScheme.MultiKey;\n\n /**\n * The signers used to sign messages. These signers should correspond to public keys in the\n * MultiKeyAccount's public key. The number of signers should be equal to this.publicKey.signaturesRequired.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly signers: Account[];\n\n /**\n * An array of indices where for signer[i], signerIndicies[i] is the index of the corresponding public key in\n * publicKey.publicKeys. Used to derive the right public key to use for verification.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n // TODO: Rename Indicies to Indices\n readonly signerIndicies: number[];\n\n readonly signaturesBitmap: Uint8Array;\n\n /**\n * Constructs a MultiKeyAccount instance, which requires multiple signatures for transactions.\n *\n * @param args - The arguments for creating a MultiKeyAccount.\n * @param args.multiKey - The multikey of the account consisting of N public keys and a number M representing the required signatures.\n * @param args.signers - An array of M signers that will be used to sign the transaction.\n * @param args.address - An optional account address input. If not provided, the derived address from the public key will be used.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n constructor(args: {\n multiKey: MultiKey;\n signers: SingleKeySignerOrLegacyEd25519Account[];\n address?: AccountAddressInput;\n }) {\n const { multiKey, address } = args;\n\n const signers: SingleKeySigner[] = args.signers.map((signer) =>\n signer instanceof Ed25519Account ? SingleKeyAccount.fromEd25519Account(signer) : signer,\n );\n\n if (multiKey.signaturesRequired > signers.length) {\n throw new Error(\n // eslint-disable-next-line max-len\n `Not enough signers provided to satisfy the required signatures. Need ${multiKey.signaturesRequired} signers, but only ${signers.length} provided`,\n );\n } else if (multiKey.signaturesRequired < signers.length) {\n throw new Error(\n // eslint-disable-next-line max-len\n `More signers provided than required. Need ${multiKey.signaturesRequired} signers, but ${signers.length} provided`,\n );\n }\n\n this.publicKey = multiKey;\n\n this.accountAddress = address ? AccountAddress.from(address) : this.publicKey.authKey().derivedAddress();\n\n // For each signer, find its corresponding position in the MultiKey's public keys array\n const bitPositions: number[] = [];\n for (const signer of signers) {\n bitPositions.push(this.publicKey.getIndex(signer.getAnyPublicKey()));\n }\n\n // Create pairs of [signer, position] and sort them by position\n // This sorting is critical because:\n // 1. The on-chain verification expects signatures to be in ascending order by bit position\n // 2. The bitmap must match the order of signatures when verifying\n const signersAndBitPosition: [Account, number][] = signers.map((signer, index) => [signer, bitPositions[index]]);\n signersAndBitPosition.sort((a, b) => a[1] - b[1]);\n\n // Extract the sorted signers and their positions into separate arrays\n this.signers = signersAndBitPosition.map((value) => value[0]);\n this.signerIndicies = signersAndBitPosition.map((value) => value[1]);\n\n // Create a bitmap representing which public keys from the MultiKey are being used\n // This bitmap is used during signature verification to identify which public keys\n // should be used to verify each signature\n this.signaturesBitmap = this.publicKey.createBitmap({ bits: bitPositions });\n }\n\n /**\n * Static constructor to create a MultiKeyAccount using the provided public keys and signers.\n *\n * @param args - The arguments for creating a MultiKeyAccount.\n * @param args.publicKeys - The N public keys of the MultiKeyAccount.\n * @param args.signaturesRequired - The number of signatures required to authorize a transaction.\n * @param args.signers - An array of M signers that will be used to sign the transaction.\n * @returns MultiKeyAccount - The newly created MultiKeyAccount.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static fromPublicKeysAndSigners(args: {\n address?: AccountAddressInput;\n publicKeys: PublicKey[];\n signaturesRequired: number;\n signers: SingleKeySignerOrLegacyEd25519Account[];\n }): MultiKeyAccount {\n const { address, publicKeys, signaturesRequired, signers } = args;\n const multiKey = new MultiKey({ publicKeys, signaturesRequired });\n return new MultiKeyAccount({ multiKey, signers, address });\n }\n\n /**\n * Determines if the provided account is a multi-key account.\n *\n * @param account - The account to check.\n * @returns A boolean indicating whether the account is a multi-key account.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n static isMultiKeySigner(account: Account): account is MultiKeyAccount {\n return account instanceof MultiKeyAccount;\n }\n\n /**\n * Sign a message using the account's signers and return an AccountAuthenticator containing the signature along with the\n * account's public key.\n * @param message - The signing message, represented as binary input in hexadecimal format.\n * @returns An instance of AccountAuthenticatorMultiKey that includes the signature and the public key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signWithAuthenticator(message: HexInput): AccountAuthenticatorMultiKey {\n return new AccountAuthenticatorMultiKey(this.publicKey, this.sign(message));\n }\n\n /**\n * Sign a transaction using the account's signers, returning an AccountAuthenticator that contains the signature and the\n * account's public key.\n * @param transaction - The raw transaction to be signed.\n * @returns An AccountAuthenticatorMultiKey containing the signature of the transaction along with the account's public key.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorMultiKey {\n return new AccountAuthenticatorMultiKey(this.publicKey, this.signTransaction(transaction));\n }\n\n /**\n * Waits for any proofs on KeylessAccount signers to be fetched. This ensures that signing with the KeylessAccount does not\n * fail due to missing proofs.\n * @return {Promise<void>} A promise that resolves when all proofs have been fetched.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async waitForProofFetch(): Promise<void> {\n const keylessSigners = this.signers.filter(\n (signer) => signer instanceof AbstractKeylessAccount,\n ) as AbstractKeylessAccount[];\n const promises = keylessSigners.map(async (signer) => signer.waitForProofFetch());\n await Promise.all(promises);\n }\n\n /**\n * Validates that the Keyless Account can be used to sign transactions.\n * @return\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async checkKeylessAccountValidity(aptosConfig: AptosConfig): Promise<void> {\n const keylessSigners = this.signers.filter(\n (signer) => signer instanceof AbstractKeylessAccount,\n ) as AbstractKeylessAccount[];\n const promises = keylessSigners.map((signer) => signer.checkKeylessAccountValidity(aptosConfig));\n await Promise.all(promises);\n }\n\n /**\n * Sign the given message using the MultiKeyAccount's signers\n * @param data - The data to be signed in HexInput format.\n * @returns MultiKeySignature\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n sign(data: HexInput): MultiKeySignature {\n const signatures = [];\n for (const signer of this.signers) {\n signatures.push(signer.sign(data));\n }\n return new MultiKeySignature({ signatures, bitmap: this.signaturesBitmap });\n }\n\n /**\n * Sign the given transaction using the MultiKeyAccount's signers.\n * This function aggregates signatures from all signers associated with the MultiKeyAccount.\n *\n * @param transaction - The transaction to be signed.\n * @returns MultiKeySignature - An object containing the aggregated signatures and a bitmap of the signatures.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n signTransaction(transaction: AnyRawTransaction): MultiKeySignature {\n const signatures = [];\n for (const signer of this.signers) {\n signatures.push(signer.signTransaction(transaction));\n }\n return new MultiKeySignature({ signatures, bitmap: this.signaturesBitmap });\n }\n\n /**\n * Verify the given message and signature with the public keys.\n *\n * This function checks if the provided signatures are valid for the given message using the corresponding public keys.\n * Note: If you are using KeylessAccounts, you must use `verifySignatureAsync` instead.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The raw message data in HexInput format.\n * @param args.signature - The signed message MultiKeySignature containing multiple signatures.\n * @returns A boolean indicating whether the signatures are valid for the message.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n verifySignature(args: { message: HexInput; signature: MultiKeySignature }): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n /**\n * Verify the given message and signature with the public keys.\n *\n * This function checks if the provided signatures are valid for the given message using the corresponding public keys.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The raw message data in HexInput format.\n * @param args.signature - The signed message MultiKeySignature containing multiple signatures.\n * @param args.options.throwErrorWithReason - Whether to throw an error with the reason for the verification failure.\n * @returns A boolean indicating whether the signatures are valid for the message.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: MultiKeySignature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n return await this.publicKey.verifySignatureAsync(args);\n }\n}\n","import { AptosConfig } from \"../api\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { Ed25519PrivateKey, Signature } from \"../core/crypto\";\nimport { MultiEd25519PublicKey, MultiEd25519Signature } from \"../core/crypto/multiEd25519\";\nimport { AccountAuthenticatorMultiEd25519 } from \"../transactions/authenticator/account\";\nimport { generateSigningMessageForTransaction } from \"../transactions/transactionBuilder/signingMessage\";\nimport { AnyRawTransaction } from \"../transactions/types\";\nimport { HexInput, SigningScheme } from \"../types\";\nimport type { Account } from \"./Account\";\n\nexport interface MultiEd25519SignerConstructorArgs {\n publicKey: MultiEd25519PublicKey;\n signers: Ed25519PrivateKey[];\n address?: AccountAddressInput;\n}\n\nexport interface VerifyMultiEd25519SignatureArgs {\n message: HexInput;\n signature: MultiEd25519Signature;\n}\n\n/**\n * Signer implementation for the Multi-Ed25519 authentication scheme.\n *\n * Note: This authentication scheme is a legacy authentication scheme. Prefer using MultiKeyAccounts as a\n * MultiKeyAccount can support any type of signer, not just Ed25519. Generating a signer instance does not\n * create the account on-chain.\n */\nexport class MultiEd25519Account implements Account {\n readonly publicKey: MultiEd25519PublicKey;\n\n readonly accountAddress: AccountAddress;\n\n readonly signingScheme = SigningScheme.MultiEd25519;\n\n /**\n * The signers used to sign messages. These signers should correspond to public keys in the\n * MultiEd25519Account. The number of signers should be equal to this.publicKey.threshold.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly signers: Ed25519PrivateKey[];\n\n /**\n * An array of indices where for signer[i], signerIndicies[i] is the index of the corresponding public key in\n * publicKey.publicKeys. Used to derive the right public key to use for verification.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n readonly signerIndices: number[];\n\n readonly signaturesBitmap: Uint8Array;\n\n // region Constructors\n\n constructor(args: MultiEd25519SignerConstructorArgs) {\n const { signers, publicKey, address } = args;\n this.publicKey = publicKey;\n this.accountAddress = address ? AccountAddress.from(address) : this.publicKey.authKey().derivedAddress();\n\n if (publicKey.threshold > signers.length) {\n throw new Error(\n // eslint-disable-next-line max-len\n `Not enough signers provided to satisfy the required signatures. Need ${publicKey.threshold} signers, but only ${signers.length} provided`,\n );\n } else if (publicKey.threshold < signers.length) {\n throw new Error(\n // eslint-disable-next-line max-len\n `More signers provided than required. Need ${publicKey.threshold} signers, but ${signers.length} provided`,\n );\n }\n\n // For each signer, find its corresponding position in the public keys array\n const bitPositions: number[] = [];\n for (const signer of signers) {\n bitPositions.push(this.publicKey.getIndex(signer.publicKey()));\n }\n\n // Create pairs of [signer, position] and sort them by position\n // This sorting is critical because:\n // 1. The on-chain verification expects signatures to be in ascending order by bit position\n // 2. The bitmap must match the order of signatures when verifying\n const signersAndBitPosition: [Ed25519PrivateKey, number][] = signers.map((signer, index) => [\n signer,\n bitPositions[index],\n ]);\n signersAndBitPosition.sort((a, b) => a[1] - b[1]);\n\n // Extract the sorted signers and their positions into separate arrays\n this.signers = signersAndBitPosition.map((value) => value[0]);\n this.signerIndices = signersAndBitPosition.map((value) => value[1]);\n\n // Create a bitmap representing which public keys from the MultiEd25519PublicKey are being used\n // This bitmap is used during signature verification to identify which public keys\n // should be used to verify each signature\n this.signaturesBitmap = this.publicKey.createBitmap({ bits: bitPositions });\n }\n\n // endregion\n\n // region Account\n\n /**\n * Verify the given message and signature with the public key.\n *\n * @param args.message raw message data in HexInput format\n * @param args.signature signed message Signature\n * @returns\n */\n verifySignature(args: VerifyMultiEd25519SignatureArgs): boolean {\n return this.publicKey.verifySignature(args);\n }\n\n /**\n * Verify the given message and signature with the public key.\n *\n * MultiEd25519 signatures do not depend on chain state, so this function is\n * equivalent to the synchronous verifySignature method.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - Raw message data in HexInput format.\n * @param args.signature - Signed message signature.\n * @returns A boolean indicating whether the signature is valid.\n * @group Implementation\n * @category Account (On-Chain Model)\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n return this.publicKey.verifySignatureAsync({\n ...args,\n signature: args.signature,\n });\n }\n\n /**\n * Sign a message using the account's Ed25519 private key.\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 signWithAuthenticator(message: HexInput): AccountAuthenticatorMultiEd25519 {\n return new AccountAuthenticatorMultiEd25519(this.publicKey, this.sign(message));\n }\n\n /**\n * Sign a transaction using the account's Ed25519 private keys.\n * @param transaction the raw transaction\n * @return the AccountAuthenticator containing the signature of the transaction, together with the account's public key\n */\n signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorMultiEd25519 {\n return new AccountAuthenticatorMultiEd25519(this.publicKey, this.signTransaction(transaction));\n }\n\n /**\n * Sign the given message using the account's Ed25519 private keys.\n * @param message in HexInput format\n * @returns MultiEd25519Signature\n */\n sign(message: HexInput): MultiEd25519Signature {\n const signatures = [];\n for (const signer of this.signers) {\n signatures.push(signer.sign(message));\n }\n return new MultiEd25519Signature({ signatures, bitmap: this.signaturesBitmap });\n }\n\n /**\n * Sign the given transaction using the available signing capabilities.\n * @param transaction the transaction to be signed\n * @returns Signature\n */\n signTransaction(transaction: AnyRawTransaction): MultiEd25519Signature {\n return this.sign(generateSigningMessageForTransaction(transaction));\n }\n\n // endregion\n}\n","import { SigningScheme } from \"../types\";\nimport { AccountAddress } from \"../core\";\nimport { Deserializer } from \"../bcs/deserializer\";\n\nexport function deserializeSchemeAndAddress(deserializer: Deserializer): {\n address: AccountAddress;\n signingScheme: SigningScheme;\n} {\n const signingScheme = deserializer.deserializeUleb128AsU32();\n // Validate that signingScheme is a valid SigningScheme value\n if (!Object.values(SigningScheme).includes(signingScheme)) {\n throw new Error(`Deserialization of Account failed: SigningScheme variant ${signingScheme} is invalid`);\n }\n const address = AccountAddress.deserialize(deserializer);\n return { address, signingScheme };\n}\n","import { Deserializer, Serializer } from \"../bcs\";\nimport { AnyPublicKeyVariant, HexInput, SigningScheme } from \"../types\";\nimport { MultiKeyAccount } from \"./MultiKeyAccount\";\nimport { Account } from \"./Account\";\nimport { Ed25519Account } from \"./Ed25519Account\";\nimport { isSingleKeySigner, SingleKeyAccount, SingleKeySignerOrLegacyEd25519Account } from \"./SingleKeyAccount\";\nimport { KeylessAccount } from \"./KeylessAccount\";\nimport { FederatedKeylessAccount } from \"./FederatedKeylessAccount\";\nimport { AbstractKeylessAccount } from \"./AbstractKeylessAccount\";\nimport {\n AccountAddress,\n Ed25519PrivateKey,\n getIssAudAndUidVal,\n Hex,\n MultiKey,\n Secp256k1PrivateKey,\n ZeroKnowledgeSig,\n} from \"../core\";\nimport { deserializeSchemeAndAddress } from \"./utils\";\nimport { EphemeralKeyPair } from \"./EphemeralKeyPair\";\n\nfunction serializeKeylessAccountCommon(account: AbstractKeylessAccount, serializer: Serializer): void {\n serializer.serializeStr(account.jwt);\n serializer.serializeStr(account.uidKey);\n serializer.serializeFixedBytes(account.pepper);\n account.ephemeralKeyPair.serialize(serializer);\n if (account.proof === undefined) {\n throw new Error(\"Cannot serialize - proof undefined\");\n }\n account.proof.serialize(serializer);\n serializer.serializeOption(account.verificationKeyHash, 32);\n}\n\nfunction deserializeKeylessAccountCommon(deserializer: Deserializer): {\n jwt: string;\n uidKey: string;\n pepper: Uint8Array;\n ephemeralKeyPair: EphemeralKeyPair;\n proof: ZeroKnowledgeSig;\n verificationKeyHash?: Uint8Array;\n} {\n const jwt = deserializer.deserializeStr();\n const uidKey = deserializer.deserializeStr();\n const pepper = deserializer.deserializeFixedBytes(31);\n const ephemeralKeyPair = EphemeralKeyPair.deserialize(deserializer);\n const proof = ZeroKnowledgeSig.deserialize(deserializer);\n const verificationKeyHash = deserializer.deserializeOption(\"fixedBytes\", 32);\n return { jwt, uidKey, pepper, ephemeralKeyPair, proof, verificationKeyHash };\n}\n\n/**\n * Utility functions for working with accounts.\n */\nexport namespace AccountUtils {\n export function toBytes(account: Account): Uint8Array {\n const serializer = new Serializer();\n serializer.serializeU32AsUleb128(account.signingScheme);\n account.accountAddress.serialize(serializer);\n switch (account.signingScheme) {\n case SigningScheme.Ed25519:\n (account as Ed25519Account).privateKey.serialize(serializer);\n return serializer.toUint8Array();\n case SigningScheme.SingleKey: {\n if (!isSingleKeySigner(account)) {\n throw new Error(\"Account is not a SingleKeySigner\");\n }\n const anyPublicKey = account.getAnyPublicKey();\n serializer.serializeU32AsUleb128(anyPublicKey.variant);\n switch (anyPublicKey.variant) {\n case AnyPublicKeyVariant.Keyless: {\n const keylessAccount = account as KeylessAccount;\n serializeKeylessAccountCommon(keylessAccount, serializer);\n return serializer.toUint8Array();\n }\n case AnyPublicKeyVariant.FederatedKeyless: {\n const federatedKeylessAccount = account as FederatedKeylessAccount;\n serializeKeylessAccountCommon(federatedKeylessAccount, serializer);\n federatedKeylessAccount.publicKey.jwkAddress.serialize(serializer);\n serializer.serializeBool(federatedKeylessAccount.audless);\n return serializer.toUint8Array();\n }\n case AnyPublicKeyVariant.Secp256k1:\n case AnyPublicKeyVariant.Ed25519: {\n const singleKeyAccount = account as SingleKeyAccount;\n singleKeyAccount.privateKey.serialize(serializer);\n return serializer.toUint8Array();\n }\n default: {\n throw new Error(`Invalid public key variant: ${anyPublicKey.variant}`);\n }\n }\n }\n case SigningScheme.MultiKey: {\n const multiKeyAccount = account as MultiKeyAccount;\n multiKeyAccount.publicKey.serialize(serializer);\n serializer.serializeU32AsUleb128(multiKeyAccount.signers.length);\n multiKeyAccount.signers.forEach((signer) => {\n serializer.serializeFixedBytes(toBytes(signer));\n });\n return serializer.toUint8Array();\n }\n default:\n throw new Error(`Deserialization of Account failed: invalid signingScheme value ${account.signingScheme}`);\n }\n }\n\n export function toHexStringWithoutPrefix(account: Account): string {\n return Hex.hexInputToStringWithoutPrefix(toBytes(account));\n }\n\n export function toHexString(account: Account): string {\n return Hex.hexInputToString(toBytes(account));\n }\n\n export function deserialize(deserializer: Deserializer): Account {\n const { address, signingScheme } = deserializeSchemeAndAddress(deserializer);\n switch (signingScheme) {\n case SigningScheme.Ed25519: {\n const privateKey = Ed25519PrivateKey.deserialize(deserializer);\n return new Ed25519Account({ privateKey, address });\n }\n case SigningScheme.SingleKey: {\n const variantIndex = deserializer.deserializeUleb128AsU32();\n switch (variantIndex) {\n case AnyPublicKeyVariant.Ed25519: {\n const privateKey = Ed25519PrivateKey.deserialize(deserializer);\n return new SingleKeyAccount({ privateKey, address });\n }\n case AnyPublicKeyVariant.Secp256k1: {\n const privateKey = Secp256k1PrivateKey.deserialize(deserializer);\n return new SingleKeyAccount({ privateKey, address });\n }\n case AnyPublicKeyVariant.Keyless: {\n const keylessComponents = deserializeKeylessAccountCommon(deserializer);\n const jwtClaims = getIssAudAndUidVal(keylessComponents);\n return new KeylessAccount({ ...keylessComponents, ...jwtClaims });\n }\n case AnyPublicKeyVariant.FederatedKeyless: {\n const keylessComponents = deserializeKeylessAccountCommon(deserializer);\n const jwkAddress = AccountAddress.deserialize(deserializer);\n const audless = deserializer.deserializeBool();\n const jwtClaims = getIssAudAndUidVal(keylessComponents);\n return new FederatedKeylessAccount({ ...keylessComponents, ...jwtClaims, jwkAddress, audless });\n }\n default:\n throw new Error(`Unsupported public key variant ${variantIndex}`);\n }\n }\n case SigningScheme.MultiKey: {\n const multiKey = MultiKey.deserialize(deserializer);\n const length = deserializer.deserializeUleb128AsU32();\n const signers = new Array<SingleKeySignerOrLegacyEd25519Account>();\n for (let i = 0; i < length; i += 1) {\n const signer = deserialize(deserializer);\n if (!isSingleKeySigner(signer) && !(signer instanceof Ed25519Account)) {\n throw new Error(\n \"Deserialization of MultiKeyAccount failed. Signer is not a SingleKeySigner or Ed25519Account\",\n );\n }\n signers.push(signer);\n }\n return new MultiKeyAccount({ multiKey, signers, address });\n }\n default:\n throw new Error(`Deserialization of Account failed: invalid signingScheme value ${signingScheme}`);\n }\n }\n\n export function keylessAccountFromHex(hex: HexInput): KeylessAccount {\n const account = fromHex(hex);\n if (!(account instanceof KeylessAccount)) {\n throw new Error(\"Deserialization of KeylessAccount failed\");\n }\n return account;\n }\n\n export function federatedKeylessAccountFromHex(hex: HexInput): FederatedKeylessAccount {\n const account = fromHex(hex);\n if (!(account instanceof FederatedKeylessAccount)) {\n throw new Error(\"Deserialization of FederatedKeylessAccount failed\");\n }\n return account;\n }\n\n export function multiKeyAccountFromHex(hex: HexInput): MultiKeyAccount {\n const account = fromHex(hex);\n if (!(account instanceof MultiKeyAccount)) {\n throw new Error(\"Deserialization of MultiKeyAccount failed\");\n }\n return account;\n }\n\n export function singleKeyAccountFromHex(hex: HexInput): SingleKeyAccount {\n const account = fromHex(hex);\n if (!(account instanceof SingleKeyAccount)) {\n throw new Error(\"Deserialization of SingleKeyAccount failed\");\n }\n return account;\n }\n\n export function ed25519AccountFromHex(hex: HexInput): Ed25519Account {\n const account = fromHex(hex);\n if (!(account instanceof Ed25519Account)) {\n throw new Error(\"Deserialization of Ed25519Account failed\");\n }\n return account;\n }\n\n export function fromHex(hex: HexInput): Account {\n return deserialize(Deserializer.fromHex(hex));\n }\n\n export function fromBytes(bytes: Uint8Array): Account {\n return fromHex(bytes);\n }\n}\n","import { sha3_256 } from \"@noble/hashes/sha3\";\nimport { AccountAddress } from \"../core\";\nimport { AbstractPublicKey, AbstractSignature } from \"../core/crypto/abstraction\";\nimport { SigningScheme, HexInput } from \"../types\";\nimport { Account } from \"./Account\";\nimport { AnyRawTransaction } from \"../transactions/types\";\nimport {\n generateSigningMessage,\n generateSigningMessageForTransaction,\n} from \"../transactions/transactionBuilder/signingMessage\";\nimport { AccountAbstractionMessage, AccountAuthenticatorAbstraction } from \"../transactions/authenticator/account\";\nimport { Ed25519Account } from \"./Ed25519Account\";\nimport { Serializer } from \"../bcs/serializer\";\nimport { isValidFunctionInfo } from \"../utils/helpers\";\nimport { ACCOUNT_ABSTRACTION_SIGNING_DATA_SALT } from \"../utils/const\";\n\ntype AbstractedAccountConstructorArgs = {\n /**\n * The account address of the account.\n */\n accountAddress: AccountAddress;\n /**\n * The signer function signs transactions and returns the `authenticator` bytes in the `AbstractionAuthData`.\n *\n * @param digest - The SHA256 hash of the transaction signing message\n * @returns The `authenticator` bytes that can be used to verify the signature.\n */\n signer: (digest: HexInput) => Uint8Array;\n /**\n * The authentication function that will be used to verify the signature.\n *\n * @example\n * ```ts\n * const authenticationFunction = `${accountAddress}::permissioned_delegation::authenticate`;\n * ```\n */\n authenticationFunction: string;\n};\n\nexport class AbstractedAccount extends Account {\n public readonly publicKey: AbstractPublicKey;\n\n readonly accountAddress: AccountAddress;\n\n readonly authenticationFunction: string;\n\n readonly signingScheme = SigningScheme.SingleKey;\n\n constructor({ signer, accountAddress, authenticationFunction }: AbstractedAccountConstructorArgs) {\n super();\n\n if (!isValidFunctionInfo(authenticationFunction)) {\n throw new Error(`Invalid authentication function ${authenticationFunction} passed into AbstractedAccount`);\n }\n\n this.authenticationFunction = authenticationFunction;\n this.accountAddress = accountAddress;\n this.publicKey = new AbstractPublicKey(this.accountAddress);\n this.sign = (digest: HexInput) => new AbstractSignature(signer(digest));\n }\n\n /**\n * Creates an `AbstractedAccount` from an `Ed25519Account` that has a permissioned signer function and\n * using the `0x1::permissioned_delegation::authenticate` function to verify the signature.\n *\n * @param signer - The `Ed25519Account` that can be used to sign permissioned transactions.\n * @returns The `AbstractedAccount`\n */\n public static fromPermissionedSigner({\n signer,\n accountAddress,\n }: {\n signer: Ed25519Account;\n accountAddress?: AccountAddress;\n }) {\n return new AbstractedAccount({\n signer: (digest: HexInput) => {\n const serializer = new Serializer();\n signer.publicKey.serialize(serializer);\n signer.sign(digest).serialize(serializer);\n return serializer.toUint8Array();\n },\n accountAddress: accountAddress ?? signer.accountAddress,\n authenticationFunction: \"0x1::permissioned_delegation::authenticate\",\n });\n }\n\n public static generateAccountAbstractionMessage(message: HexInput, functionInfo: string): HexInput {\n const accountAbstractionMessage = new AccountAbstractionMessage(message, functionInfo);\n return generateSigningMessage(accountAbstractionMessage.bcsToBytes(), ACCOUNT_ABSTRACTION_SIGNING_DATA_SALT);\n }\n\n signWithAuthenticator(message: HexInput): AccountAuthenticatorAbstraction {\n return new AccountAuthenticatorAbstraction(\n this.authenticationFunction,\n sha3_256(message),\n this.sign(sha3_256(message)).toUint8Array(),\n );\n }\n\n signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorAbstraction {\n const message = AbstractedAccount.generateAccountAbstractionMessage(\n generateSigningMessageForTransaction(transaction),\n this.authenticationFunction,\n );\n return this.signWithAuthenticator(message);\n }\n\n sign: (message: HexInput) => AbstractSignature;\n\n signTransaction(transaction: AnyRawTransaction): AbstractSignature {\n return this.sign(generateSigningMessageForTransaction(transaction));\n }\n\n /**\n * Update the signer function for the account. This can be done after asynchronous operations are complete\n * to update the context of the signer function.\n *\n * @param signer - The new signer function to use for the account.\n */\n public setSigner(signer: (digest: HexInput) => HexInput): void {\n this.sign = (digest: HexInput) => new AbstractSignature(signer(digest));\n }\n}\n","import { sha3_256 } from \"@noble/hashes/sha3\";\nimport { Serializer } from \"../bcs/serializer\";\nimport { AccountAddress } from \"../core/accountAddress\";\nimport { AccountAbstractionMessage, AccountAuthenticatorAbstraction } from \"../transactions/authenticator/account\";\nimport { HexInput } from \"../types\";\nimport { isValidFunctionInfo } from \"../utils/helpers\";\nimport { AbstractedAccount } from \"./AbstractedAccount\";\nimport { generateSigningMessage } from \"../transactions/transactionBuilder/signingMessage\";\nimport { ACCOUNT_ABSTRACTION_SIGNING_DATA_SALT } from \"../utils/const\";\n\ntype DerivableAbstractedAccountArgs = {\n /**\n * The signer function signs transactions and returns the `authenticator` bytes in the `AbstractionAuthData`.\n *\n * @param digest - The SHA256 hash of the transaction signing message\n * @returns The `authenticator` bytes that can be used to verify the signature.\n */\n signer: (digest: HexInput) => Uint8Array;\n\n /**\n * The authentication function that will be used to verify the signature.\n *\n * @example\n * ```ts\n * const authenticationFunction = `${accountAddress}::permissioned_delegation::authenticate`;\n * ```\n */\n authenticationFunction: string;\n\n /**\n * The abstract public key that is used to identify the account.\n * Depends on the use cases, most of the time it is the public key of the source wallet\n */\n abstractPublicKey: Uint8Array;\n};\n\nexport class DerivableAbstractedAccount extends AbstractedAccount {\n /**\n * The abstract public key that is used to identify the account.\n * Depends on the use cases, most of the time it is the public key of the source wallet\n */\n readonly abstractPublicKey: Uint8Array;\n\n /**\n * The domain separator used to calculate the DAA account address.\n */\n static readonly ADDRESS_DOMAIN_SEPERATOR: number = 5;\n\n constructor({ signer, authenticationFunction, abstractPublicKey }: DerivableAbstractedAccountArgs) {\n const daaAccountAddress = new AccountAddress(\n DerivableAbstractedAccount.computeAccountAddress(authenticationFunction, abstractPublicKey),\n );\n super({\n accountAddress: daaAccountAddress,\n signer,\n authenticationFunction,\n });\n this.abstractPublicKey = abstractPublicKey;\n }\n\n /**\n * Compute the account address of the DAA\n * The DAA account address is computed by hashing the function info and the account identity\n * and appending the domain separator (5)\n *\n * @param functionInfo - The authentication function\n * @param accountIdentifier - The account identity\n * @returns The account address\n */\n static computeAccountAddress(functionInfo: string, accountIdentifier: Uint8Array): Uint8Array {\n if (!isValidFunctionInfo(functionInfo)) {\n throw new Error(`Invalid authentication function ${functionInfo} passed into DerivableAbstractedAccount`);\n }\n const [moduleAddress, moduleName, functionName] = functionInfo.split(\"::\");\n\n const hash = sha3_256.create();\n // Serialize and append the function info\n const serializer = new Serializer();\n AccountAddress.fromString(moduleAddress).serialize(serializer);\n serializer.serializeStr(moduleName);\n serializer.serializeStr(functionName);\n hash.update(serializer.toUint8Array());\n\n // Serialize and append the account identity\n const s2 = new Serializer();\n s2.serializeBytes(accountIdentifier);\n hash.update(s2.toUint8Array());\n\n // Append the domain separator\n hash.update(new Uint8Array([DerivableAbstractedAccount.ADDRESS_DOMAIN_SEPERATOR]));\n\n return hash.digest();\n }\n\n signWithAuthenticator(message: HexInput): AccountAuthenticatorAbstraction {\n return new AccountAuthenticatorAbstraction(\n this.authenticationFunction,\n sha3_256(message),\n this.sign(sha3_256(message)).value,\n this.abstractPublicKey,\n );\n }\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 {\n AnyPublicKey,\n AnySignature,\n KeylessPublicKey,\n KeylessSignature,\n Secp256k1PublicKey,\n FederatedKeylessPublicKey,\n MultiKey,\n MultiKeySignature,\n} from \"../../core/crypto\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"../../core/crypto/ed25519\";\nimport { getInfo } from \"../../internal/utils\";\nimport { getLedgerInfo } from \"../../internal/general\";\nimport { getGasPriceEstimation } from \"../../internal/transaction\";\nimport { NetworkToChainId } from \"../../utils/apiEndpoints\";\nimport { normalizeBundle } from \"../../utils/normalizeBundle\";\nimport {\n AccountAuthenticator,\n AccountAuthenticatorEd25519,\n AccountAuthenticatorMultiEd25519,\n AccountAuthenticatorMultiKey,\n AccountAuthenticatorNoAccountAuthenticator,\n AccountAuthenticatorSingleKey,\n} from \"../authenticator/account\";\nimport {\n TransactionAuthenticator,\n TransactionAuthenticatorEd25519,\n TransactionAuthenticatorFeePayer,\n TransactionAuthenticatorMultiAgent,\n TransactionAuthenticatorMultiEd25519,\n TransactionAuthenticatorSingleSender,\n} from \"../authenticator/transaction\";\nimport {\n ChainId,\n EntryFunction,\n FeePayerRawTransaction,\n MultiAgentRawTransaction,\n MultiSig,\n MultiSigTransactionPayload,\n RawTransaction,\n Script,\n TransactionInnerPayload,\n TransactionPayloadEntryFunction,\n TransactionPayloadMultiSig,\n TransactionPayloadScript,\n} from \"../instances\";\nimport { SignedTransaction } from \"../instances/signedTransaction\";\nimport {\n AnyRawTransaction,\n AnyTransactionPayloadInstance,\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 { isScriptDataInput } from \"./helpers\";\nimport { SimpleTransaction } from \"../instances/simpleTransaction\";\nimport { MultiAgentTransaction } from \"../instances/multiAgentTransaction\";\nimport { getFunctionParts } from \"../../utils/helpers\";\nimport {\n TransactionExecutable,\n TransactionExecutableEmpty,\n TransactionExecutableEntryFunction,\n TransactionExecutableScript,\n TransactionExtraConfigV1,\n TransactionInnerPayloadV1,\n} from \"../instances/transactionPayload\";\n\n/**\n * Builds a transaction payload based on the provided arguments and returns a transaction payload.\n * This function uses the RemoteABI by default, but can also utilize a specified ABI.\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 * @param args - The input data for generating the transaction payload.\n * @param args.function - The function to be called, specified in the format \"moduleAddress::moduleName::functionName\".\n * @param args.functionArguments - The arguments to pass to the function.\n * @param args.typeArguments - The type arguments for the function.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.abi - The ABI to use for the transaction, if not using the RemoteABI.\n *\n * @returns TransactionPayload - The generated transaction payload, which can be of type TransactionPayloadScript,\n * TransactionPayloadMultiSig, or TransactionPayloadEntryFunction.\n * @group Implementation\n * @category Transactions\n */\nexport async function generateTransactionPayload(args: InputScriptData): Promise<TransactionPayloadScript>;\n/**\n * @group Implementation\n * @category Transactions\n */\nexport async function generateTransactionPayload(\n args: InputEntryFunctionDataWithRemoteABI,\n): Promise<TransactionPayloadEntryFunction>;\n/**\n * @group Implementation\n * @category Transactions\n */\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 * @group Implementation\n * @category Transactions\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\n/**\n * Generates a transaction payload using the provided ABI and function details.\n * This function helps create a properly structured transaction payload for executing a specific function on a module.\n *\n * @param args - The input data required to generate the transaction payload.\n * @param args.abi - The ABI of the function to be executed.\n * @param args.function - The fully qualified name of the function in the format `moduleAddress::moduleName::functionName`.\n * @param args.typeArguments - An array of type arguments that correspond to the function's type parameters.\n * @param args.functionArguments - An array of arguments to be passed to the function.\n * @param args.multisigAddress - (Optional) The address for a multisig transaction if applicable.\n *\n * @throws Error if the type argument count does not match the ABI or if the number of function arguments is incorrect.\n * @group Implementation\n * @category Transactions\n */\nexport function generateTransactionPayloadWithABI(args: InputEntryFunctionDataWithABI): TransactionPayloadEntryFunction;\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function generateTransactionPayloadWithABI(args: InputMultiSigDataWithABI): TransactionPayloadMultiSig;\n/**\n * @group Implementation\n * @category Transactions\n */\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 /**\n * Converts the argument for a specified function using its ABI and type arguments.\n * This function helps ensure that the correct number of arguments is provided for the function call.\n *\n * @param args - The arguments for the function call.\n * @param args.function - The specific function to be invoked.\n * @param functionAbi - The ABI (Application Binary Interface) of the function, which includes parameter details.\n * @param arg - The argument to be converted.\n * @param i - The index of the argument in the function call.\n * @param typeArguments - Additional type arguments that may be required for the conversion.\n * @group Implementation\n * @category Transactions\n */\n // TODO: Fix JSDoc\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\n/**\n * Generates the payload for a view function call using the provided arguments.\n * This function helps in preparing the necessary data to interact with a specific view function on the blockchain.\n *\n * @param args - The input data required to generate the view function payload.\n * @param args.function - The function identifier in the format \"moduleAddress::moduleName::functionName\".\n * @param args.aptosConfig - Configuration settings for the Aptos client.\n * @param args.abi - The ABI (Application Binary Interface) of the module.\n *\n * @returns The generated payload for the view function call.\n * @group Implementation\n * @category Transactions\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\n/**\n * Generates a payload for a view function call using the provided ABI and arguments.\n * This function ensures that the type arguments and function arguments are correctly formatted\n * and match the expected counts as defined in the ABI.\n *\n * @param args - The input data for generating the view function payload.\n * @param args.abi - The ABI of the function to be called.\n * @param args.function - The full name of the function in the format \"moduleAddress::moduleName::functionName\".\n * @param args.typeArguments - An array of type arguments to be used in the function call.\n * @param args.functionArguments - An array of arguments to be passed to the function.\n *\n * @throws Error if the type argument count does not match the ABI or if the function arguments\n * do not match the expected parameters defined in the ABI.\n * @group Implementation\n * @category Transactions\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\n/**\n * Generates a transaction payload script based on the provided input data.\n * This function helps in creating a structured script for transaction processing.\n *\n * @param args - The input data required to generate the transaction payload script.\n * @param args.bytecode - The bytecode to be converted into a Uint8Array.\n * @param args.typeArguments - The type arguments that will be standardized.\n * @param args.functionArguments - The arguments for the function being called.\n * @returns A new instance of TransactionPayloadScript.\n * @group Implementation\n * @category Transactions\n */\nfunction generateTransactionPayloadScript(args: InputScriptData) {\n return new TransactionPayloadScript(\n new Script(\n Hex.fromHexInput(args.bytecode).toUint8Array(),\n standardizeTypeTags(args.typeArguments),\n args.functionArguments,\n ),\n );\n}\n\n/**\n * Generates a raw transaction that can be sent to the Aptos network.\n *\n * @param args - The arguments for generating the raw transaction.\n * @param args.aptosConfig - The configuration for the Aptos network.\n * @param args.sender - The transaction's sender account address as a hex input.\n * @param args.payload - The transaction payload, which can be created using generateTransactionPayload().\n * @param args.options - Optional parameters for transaction generation.\n * @param args.feePayerAddress - The address of the fee payer for sponsored transactions.\n *\n * @returns RawTransaction - The generated raw transaction.\n * @group Implementation\n * @category Transactions\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 if (options?.replayProtectionNonce !== undefined && options?.accountSequenceNumber !== undefined) {\n throw new Error(\"Cannot specify both replayProtectionNonce and accountSequenceNumber in options.\");\n }\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 } else if (options?.replayProtectionNonce !== undefined) {\n // If replay nonce is provided, use it as the sequence number\n // This is an unused value, so it's specifically to show that the sequence number is not used\n return 0xdeadbeefn;\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 * @group Implementation\n * @category Transactions\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, replayProtectionNonce } = {\n maxGasAmount: options?.maxGasAmount ? BigInt(options.maxGasAmount) : BigInt(aptosConfig.getDefaultMaxGasAmount()),\n gasUnitPrice: options?.gasUnitPrice ?? BigInt(gasEstimate),\n expireTimestamp:\n options?.expireTimestamp ?? BigInt(Math.floor(Date.now() / 1000) + aptosConfig.getDefaultTxnExpirySecFromNow()),\n replayProtectionNonce: options?.replayProtectionNonce ? BigInt(options.replayProtectionNonce) : undefined,\n };\n\n // If we're using replay nonce, we must convert the original payload\n let txnPayload = payload;\n if (replayProtectionNonce !== undefined) {\n txnPayload = convertPayloadToInnerPayload(payload, replayProtectionNonce);\n }\n\n return new RawTransaction(\n AccountAddress.from(sender),\n BigInt(sequenceNumber),\n txnPayload,\n BigInt(maxGasAmount),\n BigInt(gasUnitPrice),\n BigInt(expireTimestamp),\n new ChainId(chainId),\n );\n}\n\nexport function convertPayloadToInnerPayload(\n payload: AnyTransactionPayloadInstance,\n replayProtectionNonce?: bigint,\n): TransactionInnerPayload {\n if (payload instanceof TransactionPayloadScript) {\n return new TransactionInnerPayloadV1(\n new TransactionExecutableScript(payload.script),\n new TransactionExtraConfigV1(undefined, replayProtectionNonce),\n );\n } else if (payload instanceof TransactionPayloadEntryFunction) {\n return new TransactionInnerPayloadV1(\n new TransactionExecutableEntryFunction(payload.entryFunction),\n new TransactionExtraConfigV1(undefined, replayProtectionNonce),\n );\n } else if (payload instanceof TransactionPayloadMultiSig) {\n const innerPayload = payload.multiSig.transaction_payload;\n let executable: TransactionExecutable;\n if (innerPayload === undefined || innerPayload?.transaction_payload === undefined) {\n executable = new TransactionExecutableEmpty();\n } else if (innerPayload.transaction_payload instanceof EntryFunction) {\n executable = new TransactionExecutableEntryFunction(innerPayload.transaction_payload);\n } else {\n // TODO For now, scripts are not supported in multi-sig transactions, so it's always entry function\n throw new Error(\"Scripts are not supported in multi-sig transactions.\");\n }\n\n return new TransactionInnerPayloadV1(\n executable,\n new TransactionExtraConfigV1(payload.multiSig.multisig_address, replayProtectionNonce),\n );\n } else {\n throw new Error(`Unsupported payload type: ${payload}`);\n }\n}\n\n/**\n * Generates a transaction based on the provided arguments.\n * This function can create both simple and multi-agent transactions, allowing for flexible transaction handling.\n *\n * @param args - The input arguments for generating the transaction.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.sender - The transaction's sender account address as a hex input.\n * @param args.payload - The transaction payload, which can be created using `generateTransactionPayload()`.\n * @param args.options - Optional. Transaction options object.\n * @param args.secondarySignerAddresses - Optional. An array of addresses for additional signers in a multi-signature transaction.\n * @param args.feePayerAddress - Optional. The address of the fee payer for sponsored transactions.\n * @returns An instance of a transaction, which may include secondary signer addresses and a fee payer address.\n * @group Implementation\n * @category Transactions\n */\nexport async function buildTransaction(args: InputGenerateSingleSignerRawTransactionArgs): Promise<SimpleTransaction>;\n/**\n * @group Implementation\n * @category Transactions\n */\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 * @group Implementation\n * @category Transactions\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 * Generate a signed transaction for simulation before submitting it to the chain.\n * This function helps in preparing a transaction that can be simulated, allowing users to verify its validity and expected behavior.\n *\n * @param args - The input data required to generate the signed transaction for simulation.\n * @param args.transaction - An Aptos transaction type to sign.\n * @param args.signerPublicKey - The public key of the signer.\n * @param args.secondarySignersPublicKeys - Optional. The public keys of secondary signers if it is a multi-signer transaction.\n * @param args.feePayerPublicKey - Optional. The public key of the fee payer in a sponsored transaction.\n * @param args.options - Optional. Additional options for simulating the transaction.\n *\n * @returns A signed serialized transaction that can be simulated.\n * @group Implementation\n * @category Transactions\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 (transaction.secondarySignerAddresses) {\n if (secondarySignersPublicKeys) {\n secondaryAccountAuthenticators = secondarySignersPublicKeys.map((publicKey) =>\n getAuthenticatorForSimulation(publicKey),\n );\n } else {\n secondaryAccountAuthenticators = Array.from({ length: transaction.secondarySignerAddresses.length }, () =>\n getAuthenticatorForSimulation(undefined),\n );\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 if (secondarySignersPublicKeys) {\n secondaryAccountAuthenticators = secondarySignersPublicKeys.map((publicKey) =>\n getAuthenticatorForSimulation(publicKey),\n );\n } else {\n secondaryAccountAuthenticators = Array.from({ length: transaction.secondarySignerAddresses.length }, () =>\n getAuthenticatorForSimulation(undefined),\n );\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 (\n accountAuthenticator instanceof AccountAuthenticatorSingleKey ||\n accountAuthenticator instanceof AccountAuthenticatorMultiKey\n ) {\n transactionAuthenticator = new TransactionAuthenticatorSingleSender(accountAuthenticator);\n } else if (accountAuthenticator instanceof AccountAuthenticatorNoAccountAuthenticator) {\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\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function getAuthenticatorForSimulation(publicKey?: PublicKey) {\n if (!publicKey) {\n return new AccountAuthenticatorNoAccountAuthenticator();\n }\n\n // Wrap the public key types below with AnyPublicKey as they are only support through single sender.\n // Learn more about AnyPublicKey here - https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-55.md\n const convertToAnyPublicKey =\n KeylessPublicKey.isInstance(publicKey) ||\n FederatedKeylessPublicKey.isInstance(publicKey) ||\n Secp256k1PublicKey.isInstance(publicKey);\n const accountPublicKey = convertToAnyPublicKey ? new AnyPublicKey(publicKey) : publicKey;\n\n // No need to for the signature to be matching in scheme. All that matters for simulations is that it's not valid\n const invalidSignature = new Ed25519Signature(new Uint8Array(64));\n\n if (Ed25519PublicKey.isInstance(accountPublicKey)) {\n return new AccountAuthenticatorEd25519(accountPublicKey, invalidSignature);\n }\n\n if (AnyPublicKey.isInstance(accountPublicKey)) {\n if (KeylessPublicKey.isInstance(accountPublicKey.publicKey)) {\n return new AccountAuthenticatorSingleKey(\n accountPublicKey,\n new AnySignature(KeylessSignature.getSimulationSignature()),\n );\n }\n return new AccountAuthenticatorSingleKey(accountPublicKey, new AnySignature(invalidSignature));\n }\n\n if (MultiKey.isInstance(accountPublicKey)) {\n return new AccountAuthenticatorMultiKey(\n accountPublicKey,\n new MultiKeySignature({\n signatures: accountPublicKey.publicKeys.map((pubKey) => {\n if (KeylessPublicKey.isInstance(pubKey.publicKey) || FederatedKeylessPublicKey.isInstance(pubKey.publicKey)) {\n return new AnySignature(KeylessSignature.getSimulationSignature());\n }\n return new AnySignature(invalidSignature);\n }),\n bitmap: accountPublicKey.createBitmap({\n bits: Array(accountPublicKey.publicKeys.length)\n .fill(0)\n .map((_, i) => i),\n }),\n }),\n );\n }\n\n throw new Error(\"Unsupported PublicKey used for simulations\");\n}\n\n/**\n * Generate a signed transaction ready for submission to the blockchain.\n * This function prepares the transaction by authenticating the sender and any additional signers based on the provided arguments.\n *\n * @param args - The input data required to generate the signed transaction.\n * @param args.transaction - An Aptos transaction type containing the details of the transaction.\n * @param args.senderAuthenticator - The account authenticator of the transaction sender.\n * @param args.feePayerAuthenticator - The authenticator for the fee payer, required if the transaction has a fee payer address.\n * @param args.additionalSignersAuthenticators - Optional authenticators for additional signers in a multi-signer transaction.\n *\n * @returns A Uint8Array representing the signed transaction in bytes.\n *\n * @throws Error if the feePayerAuthenticator is not provided for a fee payer transaction.\n * @throws Error if additionalSignersAuthenticators are not provided for a multi-signer transaction.\n * @group Implementation\n * @category Transactions\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 if (senderAuthenticator instanceof AccountAuthenticatorMultiEd25519) {\n txnAuthenticator = new TransactionAuthenticatorMultiEd25519(\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 using a SHA-3 256 hash algorithm.\n * @param input - An array of UTF-8 strings or Uint8Array byte arrays to be hashed.\n * @group Implementation\n * @category Transactions\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 transactions\n * @group Implementation\n * @category Transactions\n */\nconst TRANSACTION_PREFIX = hashValues([\"APTOS::Transaction\"]);\n\n/**\n * Generates a user transaction hash for the provided transaction payload, which must already have an authenticator.\n * This function helps ensure the integrity and uniqueness of the transaction by producing a hash based on the signed transaction data.\n *\n * @param args - The input data required to submit the transaction.\n * @param args.authenticator - The authenticator for the transaction.\n * @param args.payload - The payload containing the transaction details.\n * @param args.sender - The address of the sender initiating the transaction.\n * @param args.sequenceNumber - The sequence number of the transaction for the sender.\n * @group Implementation\n * @category Transactions\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 * Fetches and caches ABIs while allowing for pass-through on provided ABIs.\n *\n * @param key - A unique identifier for the cached ABI.\n * @param moduleAddress - The address of the module from which to fetch the ABI.\n * @param moduleName - The name of the module containing the function.\n * @param functionName - The name of the function whose ABI is being fetched.\n * @param aptosConfig - Configuration settings for Aptos.\n * @param abi - An optional ABI to use if already available.\n * @param fetch - A function to fetch the ABI if it is not provided.\n * @group Implementation\n * @category Transactions\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 {\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\n/**\n * Determines if the provided string is a valid Move identifier, which can only contain alphanumeric characters and underscores.\n * @param str - The string to validate as a Move identifier.\n * @group Implementation\n * @category Transactions\n */\nfunction isValidIdentifier(str: string) {\n return !!str.match(/^[_a-zA-Z0-9]+$/);\n}\n\n/**\n * Determines if the provided character is a whitespace character. This function only works for single characters.\n * @param char - The character to check for whitespace.\n * @group Implementation\n * @category Transactions\n */\nfunction isValidWhitespaceCharacter(char: string) {\n return !!char.match(/\\s/);\n}\n\n/**\n * Determines if a given string represents a generic type from the ABI, specifically in the format T0, T1, etc.\n * @param str - The string to evaluate for generic type format.\n * @group Implementation\n * @category Transactions\n */\nfunction isGeneric(str: string) {\n return !!str.match(/^T[0-9]+$/);\n}\n\n/**\n * Determines if the provided string is a reference type, which is indicated by starting with an ampersand (&).\n * @param str - The string to evaluate for reference type.\n * @group Implementation\n * @category Transactions\n */\nfunction isRef(str: string) {\n return !!str.match(/^&.+$/);\n}\n\n/**\n * Determines if the provided string represents a primitive type.\n * @param str - The string to evaluate as a potential primitive type.\n * @returns A boolean indicating whether the string is a primitive type.\n * @group Implementation\n * @category Transactions\n */\nfunction isPrimitive(str: string) {\n switch (str) {\n case \"signer\":\n case \"address\":\n case \"bool\":\n case \"u8\":\n case \"u16\":\n case \"u32\":\n case \"u64\":\n case \"u128\":\n case \"u256\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Consumes all whitespace characters in a string starting from a specified position.\n *\n * @param tagStr - The string from which to consume whitespace.\n * @param pos - The position in the string to start consuming whitespace from.\n * @returns The new position in the string after consuming whitespace.\n * @group Implementation\n * @category Transactions\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\n/**\n * State for TypeTag parsing, maintained on a stack to track the current parsing state.\n * @group Implementation\n * @category Transactions\n */\ntype TypeTagState = {\n savedExpectedTypes: number;\n savedStr: string;\n savedTypes: Array<TypeTag>;\n};\n\n/**\n * Error types related to parsing type tags, indicating various issues encountered during the parsing process.\n * @group Implementation\n * @category Transactions\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 MissingTypeArgument = \"no type argument before ','\",\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 InvalidAddress = \"struct address must be valid\",\n}\n\n/**\n * Represents an error that occurs during the parsing of a type tag.\n * This error extends the built-in Error class and provides additional context\n * regarding the specific type tag that failed to parse and the reason for the failure.\n *\n * @param typeTagStr - The type tag string that failed to be parsed.\n * @param invalidReason - The reason why the type tag string is considered invalid.\n * @group Implementation\n * @category Transactions\n */\nexport class TypeTagParserError extends Error {\n /**\n * Constructs an error indicating a failure to parse a type tag.\n * This error provides details about the specific type tag that could not be parsed and the reason for the failure.\n *\n * @param typeTagStr - The string representation of the type tag that failed to parse.\n * @param invalidReason - The reason why the type tag is considered invalid.\n * @group Implementation\n * @category Transactions\n */\n constructor(typeTagStr: string, invalidReason: TypeTagParserErrorType) {\n super(`Failed to parse typeTag '${typeTagStr}', ${invalidReason}`);\n }\n}\n\n/**\n * Parses a type string into a structured representation of type tags, accommodating various formats including generics and\n * nested types.\n *\n * This function can help you accurately interpret type strings, which can include simple types, standalone structs, and complex\n * nested generics.\n * It supports multiple generics, spacing within generics, and nested generics of varying depths.\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 * @param typeStr - The string representation of the type to be parsed.\n * @param options - Optional settings for parsing behavior.\n * @param options.allowGenerics - A flag indicating whether to allow generics in the parsing process.\n * @returns The parsed type tag representation.\n * @throws TypeTagParserError if the type string is malformed or does not conform to expected formats.\n * @group Implementation\n * @category Transactions\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\n // No top level commas (not in a type <> are allowed)\n if (saved.length === 0) {\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.UnexpectedComma);\n }\n // If there was no actual value before the comma, then it's missing a type argument\n if (currentStr.length === 0) {\n throw new TypeTagParserError(typeStr, TypeTagParserErrorType.MissingTypeArgument);\n }\n\n // Process characters before as a type\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 } 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, allowing for the inclusion of generics if specified. This function helps in\n * constructing the appropriate type tags based on the provided string representation and associated types.\n *\n * @param str - The string representation of the type tag to parse.\n * @param types - An array of TypeTag instances that represent internal types associated with the type tag.\n * @param allowGenerics - A boolean indicating whether generics are allowed in the parsing of the type tag.\n * @group Implementation\n * @category Transactions\n */\nfunction parseTypeTagInner(str: string, types: Array<TypeTag>, allowGenerics: boolean): TypeTag {\n const trimmedStr = str.trim();\n const lowerCaseTrimmed = trimmedStr.toLowerCase();\n if (isPrimitive(lowerCaseTrimmed)) {\n if (types.length > 0) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedPrimitiveTypeArguments);\n }\n }\n\n switch (trimmedStr.toLowerCase()) {\n case \"signer\":\n return new TypeTagSigner();\n case \"bool\":\n return new TypeTagBool();\n case \"address\":\n return new TypeTagAddress();\n case \"u8\":\n return new TypeTagU8();\n case \"u16\":\n return new TypeTagU16();\n case \"u32\":\n return new TypeTagU32();\n case \"u64\":\n return new TypeTagU64();\n case \"u128\":\n return new TypeTagU128();\n case \"u256\":\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 // Reference will have to handle the inner type\n if (isRef(trimmedStr)) {\n const actualType = trimmedStr.substring(1);\n return new TypeTagReference(parseTypeTagInner(actualType, types, allowGenerics));\n }\n\n // Generics are always expected to be T0 or T1\n if (isGeneric(trimmedStr)) {\n if (allowGenerics) {\n return new TypeTagGeneric(Number(trimmedStr.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 (!trimmedStr.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 = trimmedStr.split(\"::\");\n if (structParts.length !== 3) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.UnexpectedStructFormat);\n }\n\n // Validate struct address\n // eslint-disable-next-line no-case-declarations\n let address: AccountAddress;\n try {\n address = AccountAddress.fromString(structParts[0]);\n } catch (error: any) {\n throw new TypeTagParserError(str, TypeTagParserErrorType.InvalidAddress);\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(address, new Identifier(structParts[1]), new Identifier(structParts[2]), types),\n );\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 } from \"../../types\";\n\n/**\n * Determines if the provided argument is of type boolean.\n * This can help in validating input types before processing them further.\n *\n * @param arg - The argument to check, which can be of various types.\n * @returns A boolean indicating whether the argument is a boolean.\n * @group Implementation\n * @category Transactions\n */\nexport function isBool(arg: SimpleEntryFunctionArgumentTypes): arg is boolean {\n return typeof arg === \"boolean\";\n}\n\n/**\n * Checks if the provided argument is of type string.\n *\n * @param arg - The value to be checked for string type.\n * @returns A boolean indicating whether the argument is a string.\n * @group Implementation\n * @category Transactions\n */\nexport function isString(arg: any): arg is string {\n return typeof arg === \"string\";\n}\n\n/**\n * Determines if the provided argument is of type number.\n *\n * @param arg - The argument to check, which can be of various types.\n * @returns A boolean indicating whether the argument is a number.\n * @group Implementation\n * @category Transactions\n */\nexport function isNumber(arg: SimpleEntryFunctionArgumentTypes): arg is number {\n return typeof arg === \"number\";\n}\n\n/**\n * Converts a number or a string representation of a number into a number type.\n * This function is useful for ensuring that the input is in a consistent numeric format,\n * which can help prevent type mismatches in further processing.\n *\n * @param arg - The input value to be converted. This can be a number, a string representing a number, or any other type.\n * @returns Returns the converted number if the input is valid; otherwise, it returns undefined.\n * @group Implementation\n * @category Transactions\n */\nexport function convertNumber(arg: SimpleEntryFunctionArgumentTypes): number | undefined {\n if (isNumber(arg)) {\n return arg;\n }\n if (isString(arg) && arg !== \"\") {\n return Number.parseInt(arg, 10);\n }\n\n return undefined;\n}\n\n/**\n * Determines if the provided argument is a large number, which can be a number, bigint, or string representation of a number.\n *\n * @param arg - The argument to check, which can be of type number, bigint, or string.\n * @group Implementation\n * @category Transactions\n */\nexport function isLargeNumber(arg: SimpleEntryFunctionArgumentTypes): arg is number | bigint | string {\n return typeof arg === \"number\" || typeof arg === \"bigint\" || typeof arg === \"string\";\n}\n\n/**\n * Checks if the provided argument is empty, meaning it is either null or undefined.\n *\n * @param arg - The argument to check for emptiness.\n * @returns A boolean indicating whether the argument is empty.\n * @group Implementation\n * @category Transactions\n */\nexport function isEmptyOption(arg: SimpleEntryFunctionArgumentTypes): arg is null | undefined {\n return arg === null || arg === undefined;\n}\n\n/**\n * Determines if the provided argument is a valid encoded entry function argument type.\n * This function helps validate that the argument conforms to the expected types for entry function parameters.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\nexport function isEncodedEntryFunctionArgument(\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n): arg is EntryFunctionArgumentTypes {\n return (\n /**\n * Determines if the provided argument is an instance of the Bool class.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsBool(arg) ||\n /**\n * Determines if the provided argument is an instance of U8.\n * This function helps validate the type of the argument passed to ensure it is a U8 type.\n *\n * @param arg - The argument to be checked, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsU8(arg) ||\n /**\n * Determines if the provided argument is an instance of U16.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsU16(arg) ||\n /**\n * Determines if the provided argument is an instance of U32.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @returns A boolean indicating whether the argument is a U32 instance.\n * @group Implementation\n * @category Transactions\n */\n isBcsU32(arg) ||\n /**\n * Determine if the provided argument is an instance of U64.\n * This function helps validate that the argument conforms to the expected U64 type.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsU64(arg) ||\n /**\n * Determines if the provided argument is an instance of U128.\n * This function helps validate the type of the argument passed to ensure it is a U128 type.\n *\n * @param arg - The argument to be checked, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsU128(arg) ||\n /**\n * Determines if the provided argument is an instance of U256.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @returns A boolean indicating whether the argument is a U256 instance.\n * @group Implementation\n * @category Transactions\n */\n isBcsU256(arg) ||\n /**\n * Determines if the provided argument is an instance of AccountAddress.\n * This function helps validate whether a given input corresponds to a valid BCS address type.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsAddress(arg) ||\n /**\n * Determine if the provided argument is an instance of MoveString.\n *\n * @param arg - The argument to check, which can be of types EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsString(arg) ||\n /**\n * Determine if the provided argument is an instance of FixedBytes.\n * This function helps to validate the type of the argument being passed.\n *\n * @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.\n * @group Implementation\n * @category Transactions\n */\n isBcsFixedBytes(arg) ||\n arg instanceof MoveVector ||\n arg instanceof MoveOption\n );\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsBool(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is Bool {\n return arg instanceof Bool;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsAddress(\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n): arg is AccountAddress {\n return arg instanceof AccountAddress;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsString(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is MoveString {\n return arg instanceof MoveString;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsFixedBytes(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is FixedBytes {\n return arg instanceof FixedBytes;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsU8(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U8 {\n return arg instanceof U8;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsU16(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U16 {\n return arg instanceof U16;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsU32(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U32 {\n return arg instanceof U32;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsU64(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U64 {\n return arg instanceof U64;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsU128(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U128 {\n return arg instanceof U128;\n}\n/**\n * @group Implementation\n * @category Transactions\n */\nexport function isBcsU256(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U256 {\n return arg instanceof U256;\n}\n\n/**\n * Determines if the provided argument contains script data input by checking for the presence of bytecode.\n *\n * @param arg - The input data to be checked, which can either be a payload with remote ABI or a standard payload.\n * @param arg.bytecode - The bytecode of the script, present if the input is script data.\n * @param arg.function - The function associated with the transaction, which is relevant for standard payloads.\n * @param arg.args - The arguments for the function, applicable in the context of standard payloads.\n * @group Implementation\n * @category Transactions\n */\nexport function isScriptDataInput(\n arg: InputGenerateTransactionPayloadDataWithRemoteABI | InputGenerateTransactionPayloadData,\n): arg is InputScriptData {\n return \"bytecode\" in arg;\n}\n\n/**\n * Throws an error indicating a type mismatch for a specified argument position.\n * This function helps in debugging by providing clear feedback on expected types.\n *\n * @param expectedType - The type that was expected for the argument.\n * @param position - The position of the argument that caused the type mismatch.\n * @group Implementation\n * @category Transactions\n */\nexport function throwTypeMismatch(expectedType: string, position: number) {\n throw new Error(`Type mismatch for argument ${position}, expected '${expectedType}'`);\n}\n\n/**\n * Finds the index of the first non-signer argument in the function ABI parameters.\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. This function helps identify the position of the first argument that\n * can be provided by the caller, allowing for easier handling of function parameters.\n *\n * @param functionAbi - The ABI of the function to analyze.\n * @returns The index of the first non-signer argument, or the length of the parameters array if none are found.\n * @group Implementation\n * @category Transactions\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","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { parseTypeTag } from \"../typeTag/parser\";\nimport {\n TypeTag,\n TypeTagAddress,\n TypeTagBool,\n TypeTagStruct,\n TypeTagU128,\n TypeTagU16,\n TypeTagU256,\n TypeTagU32,\n TypeTagU64,\n TypeTagU8,\n} from \"../typeTag\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport {\n EntryFunctionArgumentTypes,\n SimpleEntryFunctionArgumentTypes,\n EntryFunctionABI,\n ViewFunctionABI,\n FunctionABI,\n TypeArgument,\n} from \"../types\";\nimport { Bool, FixedBytes, 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 isEmptyOption,\n isString,\n throwTypeMismatch,\n convertNumber,\n} from \"./helpers\";\nimport { MoveFunction, MoveModule } 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 *\n * @param typeArguments - An optional array of type arguments that may include string representations.\n * @returns An array of TypeTag objects derived from the provided type arguments.\n * @group Implementation\n * @category Transactions\n */\nexport function standardizeTypeTags(typeArguments?: Array<TypeArgument>): Array<TypeTag> {\n return (\n typeArguments?.map((typeArg: TypeArgument): 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 the ABI of a specified module from the on-chain module ABI.\n *\n * @param moduleAddress - The address of the module from which to fetch the ABI.\n * @param moduleName - The name of the module containing the ABI.\n * @param aptosConfig - The configuration settings for Aptos.\n * @group Implementation\n * @category Transactions\n */\nexport async function fetchModuleAbi(\n moduleAddress: string,\n moduleName: string,\n aptosConfig: AptosConfig,\n): Promise<MoveModule | undefined> {\n const moduleBytecode = await getModule({ aptosConfig, accountAddress: moduleAddress, moduleName });\n return moduleBytecode.abi;\n}\n\n/**\n * Fetches the ABI of a specified function from the on-chain module ABI. This function allows you to access the details of a\n * specific function within a module.\n *\n * @param moduleAddress - The address of the module from which to fetch the function ABI.\n * @param moduleName - The name of the module containing the function.\n * @param functionName - The name of the function whose ABI is to be fetched.\n * @param aptosConfig - The configuration settings for Aptos.\n * @group Implementation\n * @category Transactions\n */\nexport async function fetchFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<MoveFunction | undefined> {\n const moduleAbi = await fetchModuleAbi(moduleAddress, moduleName, aptosConfig);\n if (!moduleAbi) throw new Error(`Could not find module ABI for '${moduleAddress}::${moduleName}'`);\n return moduleAbi.exposed_functions.find((func) => func.name === functionName);\n}\n\n/**\n * @deprecated Use `fetchFunctionAbi` instead and manually parse the type tags.\n */\nexport async function fetchMoveFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<FunctionABI> {\n const functionAbi = await fetchFunctionAbi(moduleAddress, moduleName, functionName, aptosConfig);\n if (!functionAbi) {\n throw new Error(`Could not find function ABI for '${moduleAddress}::${moduleName}::${functionName}'`);\n }\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 return {\n typeParameters: functionAbi.generic_type_params,\n parameters: params,\n };\n}\n\n/**\n * Fetches the ABI for an entry function from the specified module address.\n * This function validates if the ABI corresponds to an entry function and retrieves its parameters.\n *\n * @param moduleAddress - The address of the module containing the entry function.\n * @param moduleName - The name of the module containing the entry function.\n * @param functionName - The name of the entry function to fetch the ABI for.\n * @param aptosConfig - The configuration settings for Aptos.\n * @returns An object containing the number of signers, type parameters, and function parameters.\n * @throws Error if the ABI cannot be found or if the function is not an entry function.\n * @group Implementation\n * @category Transactions\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 specified module address.\n * This function ensures that the ABI is valid and retrieves the type parameters, parameters, and return types for the view function.\n *\n * @param moduleAddress - The address of the module containing the view function.\n * @param moduleName - The name of the module containing the view function.\n * @param functionName - The name of the view function for which to fetch the ABI.\n * @param aptosConfig - The configuration settings for Aptos.\n * @returns An object containing the type parameters, parameters, and return types of the view function.\n * @throws Error if the ABI cannot be found or if the function is not a view function.\n * @group Implementation\n * @category Transactions\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 * This function checks the provided argument against the expected parameter type and converts it accordingly.\n *\n * @param functionName - The name of the function for which the argument is being converted.\n * @param functionAbiOrModuleAbi - The ABI (Application Binary Interface) of the function, which defines its parameters.\n * @param arg - The argument to be converted, which can be of various types.\n * @param position - The index of the argument in the function's parameter list.\n * @param genericTypeParams - An array of type tags for any generic type parameters.\n * @param options - Options for the conversion process.\n * @param options.allowUnknownStructs - If true, unknown structs will be allowed and converted to a `FixedBytes`.\n * @group Implementation\n * @category Transactions\n */\nexport function convertArgument(\n functionName: string,\n functionAbiOrModuleAbi: MoveModule | FunctionABI,\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n position: number,\n genericTypeParams: Array<TypeTag>,\n options?: { allowUnknownStructs?: boolean },\n) {\n let param: TypeTag;\n\n if (\"exposed_functions\" in functionAbiOrModuleAbi) {\n const functionAbi = functionAbiOrModuleAbi.exposed_functions.find((func) => func.name === functionName);\n if (!functionAbi) {\n throw new Error(\n `Could not find function ABI for '${functionAbiOrModuleAbi.address}::${functionAbiOrModuleAbi.name}::${functionName}'`,\n );\n }\n\n if (position >= functionAbi.params.length) {\n throw new Error(`Too many arguments for '${functionName}', expected ${functionAbi.params.length}`);\n }\n\n param = parseTypeTag(functionAbi.params[position], { allowGenerics: true });\n } else {\n if (position >= functionAbiOrModuleAbi.parameters.length) {\n throw new Error(`Too many arguments for '${functionName}', expected ${functionAbiOrModuleAbi.parameters.length}`);\n }\n\n param = functionAbiOrModuleAbi.parameters[position];\n }\n\n return checkOrConvertArgument(\n arg,\n param,\n position,\n genericTypeParams,\n \"exposed_functions\" in functionAbiOrModuleAbi ? functionAbiOrModuleAbi : undefined,\n options,\n );\n}\n\n/**\n * Checks if the provided argument is BCS encoded and converts it if necessary, ensuring type compatibility with the ABI.\n * This function helps in validating and converting arguments for entry functions based on their expected types.\n *\n * @param arg - The argument to check or convert, which can be either a simple or entry function argument type.\n * @param param - The expected type tag for the argument.\n * @param position - The position of the argument in the function call.\n * @param genericTypeParams - An array of generic type parameters that may be used for conversion.\n * @group Implementation\n * @category Transactions\n */\nexport function checkOrConvertArgument(\n arg: SimpleEntryFunctionArgumentTypes | EntryFunctionArgumentTypes,\n param: TypeTag,\n position: number,\n genericTypeParams: Array<TypeTag>,\n moduleAbi?: MoveModule,\n options?: { allowUnknownStructs?: boolean },\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\n /**\n * Checks the type of the provided argument against the expected type.\n * This function helps validate that the argument conforms to the specified type requirements.\n *\n * @param typeArgs - The expected type arguments.\n * @param arg - The argument to be checked.\n * @param position - The position of the argument in the context of the check.\n * @param moduleAbi - The ABI of the module containing the function, used for type checking.\n * This will typically have information about structs, enums, and other types.\n * @group Implementation\n * @category Transactions\n */\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, moduleAbi, options);\n}\n\n/**\n * Parses a non-BCS encoded argument into a BCS encoded argument recursively.\n * This function helps convert various types of input arguments into their corresponding BCS encoded formats based on the\n * specified parameter type.\n *\n * @param arg - The argument to be parsed, which can be of various types.\n * @param param - The type tag that defines the expected type of the argument.\n * @param position - The position of the argument in the function call, used for error reporting.\n * @param genericTypeParams - An array of type tags for generic type parameters, used when the parameter type is generic.\n * @param moduleAbi - The ABI of the module containing the function, used for type checking.\n * This will typically have information about structs, enums, and other types.\n * @param options - Options for the conversion process.\n * @param options.allowUnknownStructs - If true, unknown structs will be allowed and converted to a `FixedBytes`.\n * @group Implementation\n * @category Transactions\n */\nfunction parseArg(\n arg: SimpleEntryFunctionArgumentTypes,\n param: TypeTag,\n position: number,\n genericTypeParams: Array<TypeTag>,\n moduleAbi?: MoveModule,\n options?: { allowUnknownStructs?: boolean },\n): EntryFunctionArgumentTypes {\n if (param.isBool()) {\n if (isBool(arg)) {\n return new Bool(arg);\n }\n if (isString(arg)) {\n if (arg === \"true\") return new Bool(true);\n if (arg === \"false\") return new Bool(false);\n }\n\n /**\n * Throws a type mismatch error for the specified move option.\n *\n * @param moveOption - The name of the move option that caused the type mismatch.\n * @param position - The position where the error occurred.\n * @group Implementation\n * @category Transactions\n */\n throwTypeMismatch(\"boolean\", position);\n }\n if (param.isAddress()) {\n if (isString(arg)) {\n return AccountAddress.fromString(arg);\n }\n // Support for Uint8Array coming from external sources\n // Usually, dapps will be getting the account address as a Uint8Array from the wallet (following\n // the wallet standard).\n if (arg && typeof arg === \"object\" && \"data\" in arg && arg.data instanceof Uint8Array) {\n return new AccountAddress(arg.data);\n }\n throwTypeMismatch(\"string | AccountAddress\", position);\n }\n if (param.isU8()) {\n const num = convertNumber(arg);\n if (num !== undefined) {\n return new U8(num);\n }\n throwTypeMismatch(\"number | string\", position);\n }\n if (param.isU16()) {\n const num = convertNumber(arg);\n if (num !== undefined) {\n return new U16(num);\n }\n throwTypeMismatch(\"number | string\", position);\n }\n if (param.isU32()) {\n const num = convertNumber(arg);\n if (num !== undefined) {\n return new U32(num);\n }\n throwTypeMismatch(\"number | string\", 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 subtype\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, moduleAbi);\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 if (isString(arg)) {\n // In a web env, arguments are passing as strings\n if (arg.startsWith(\"[\")) {\n return checkOrConvertArgument(JSON.parse(arg), param, position, genericTypeParams);\n }\n }\n\n // TODO: Support Uint16Array, Uint32Array, BigUint64Array?\n\n if (Array.isArray(arg)) {\n return new MoveVector(\n arg.map((item) => checkOrConvertArgument(item, param.value, position, genericTypeParams, moduleAbi)),\n );\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 // Support for Uint8Array coming from external sources\n if (arg && typeof arg === \"object\" && \"data\" in arg && arg.data instanceof Uint8Array) {\n return new AccountAddress(arg.data);\n }\n throwTypeMismatch(\"string | AccountAddress\", position);\n }\n // Handle known enum types from Aptos framework\n if (param.isDelegationKey() || param.isRateLimiter()) {\n if (arg instanceof Uint8Array) {\n return new FixedBytes(arg);\n }\n throwTypeMismatch(\"Uint8Array\", position);\n }\n\n if (param.isOption()) {\n if (isEmptyOption(arg)) {\n // Here we attempt to reconstruct the underlying type\n // Note, for some reason the `isBool` etc. does not work with the compiler\n const innerParam = param.value.typeArgs[0];\n if (innerParam instanceof TypeTagBool) {\n return new MoveOption<Bool>(null);\n }\n if (innerParam instanceof TypeTagAddress) {\n return new MoveOption<AccountAddress>(null);\n }\n if (innerParam instanceof TypeTagU8) {\n return new MoveOption<U8>(null);\n }\n if (innerParam instanceof TypeTagU16) {\n return new MoveOption<U16>(null);\n }\n if (innerParam instanceof TypeTagU32) {\n return new MoveOption<U32>(null);\n }\n if (innerParam instanceof TypeTagU64) {\n return new MoveOption<U64>(null);\n }\n if (innerParam instanceof TypeTagU128) {\n return new MoveOption<U128>(null);\n }\n if (innerParam instanceof TypeTagU256) {\n return new MoveOption<U256>(null);\n }\n\n // In all other cases, we will use a placeholder, it doesn't actually matter what the type is, but it will be obvious\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<MoveString>(null);\n }\n\n return new MoveOption(\n checkOrConvertArgument(arg, param.value.typeArgs[0], position, genericTypeParams, moduleAbi),\n );\n }\n\n // We are assuming that fieldless structs are enums, and therefore we cannot typecheck any further due\n // to limited information from the ABI. This does not work for structs on other modules.\n const structDefinition = moduleAbi?.structs.find((s) => s.name === param.value.name.identifier);\n if (structDefinition?.fields.length === 0 && arg instanceof Uint8Array) {\n return new FixedBytes(arg);\n }\n\n if (arg instanceof Uint8Array && options?.allowUnknownStructs) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `Unsupported struct input type for argument ${position}. Continuing since 'allowUnknownStructs' is enabled.`,\n );\n return new FixedBytes(arg);\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 the BCS encoded argument matches the ABI\n * @param param\n * @param arg\n * @param position\n * @group Implementation\n * @category Transactions\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","/**\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 * @group Implementation\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { Deserializer, MoveVector } from \"../bcs\";\nimport { postAptosFullNode } from \"../client\";\nimport { Account, AbstractKeylessAccount, isKeylessSigner } from \"../account\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport { FederatedKeylessPublicKey, KeylessPublicKey, KeylessSignature } from \"../core/crypto\";\nimport { AccountAuthenticator } from \"../transactions/authenticator/account\";\nimport {\n buildTransaction,\n generateTransactionPayload,\n generateSignedTransactionForSimulation,\n generateSignedTransaction,\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 InputTransactionPluginData,\n} from \"../transactions/types\";\nimport { UserTransactionResponse, PendingTransactionResponse, MimeType, HexInput } from \"../types\";\nimport { SignedTransaction, TypeTagVector, generateSigningMessageForTransaction } 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 * @group Implementation\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 * @group Implementation\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\n/**\n * Builds a transaction payload based on the provided configuration and input data.\n * This function is essential for preparing transaction data for execution on the Aptos blockchain.\n *\n * @param args - The arguments for building the transaction payload.\n * @param args.aptosConfig - Configuration settings for the Aptos network.\n * @param args.data - Input data required to generate the transaction payload, which may include bytecode, multisig address,\n * function name, function arguments, type arguments, and ABI.\n * @returns A promise that resolves to the generated transaction payload instance.\n * @group Implementation\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\n/**\n * Builds a raw transaction based on the provided configuration and payload.\n * This function helps in creating a transaction that can be sent to the Aptos blockchain.\n *\n * @param args - The arguments for generating the transaction.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.sender - The address of the sender of the transaction.\n * @param args.options - Additional options for the transaction.\n * @param payload - The payload of the transaction, which defines the action to be performed.\n * @group Implementation\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\n/**\n * Determine if the transaction input includes a fee payer.\n *\n * @param data - The input data for generating a transaction.\n * @param data.withFeePayer - Indicates whether a fee payer is included in the transaction input.\n * @returns A boolean value indicating if the transaction input has a fee payer.\n * @group Implementation\n */\nfunction isFeePayerTransactionInput(data: InputGenerateTransactionData): boolean {\n return data.withFeePayer === true;\n}\n\n/**\n * Determines whether the provided transaction input data includes multiple agent signatures.\n *\n * @param data - The transaction input data to evaluate.\n * @param data.secondarySignerAddresses - An array of secondary signer addresses, indicating multiple agents.\n * @group Implementation\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 - The arguments for generating the signing message.\n * @param args.transaction - AnyRawTransaction, as generated by `generateTransaction()`.\n *\n * @returns The message to be signed.\n * @group Implementation\n */\nexport function getSigningMessage(args: { transaction: AnyRawTransaction }): Uint8Array {\n const { transaction } = args;\n return generateSigningMessageForTransaction(transaction);\n}\n\n/**\n * Sign a transaction that can later be submitted to the chain.\n *\n * @param args The arguments for signing the transaction.\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 * @return The signer AccountAuthenticator.\n * @group Implementation\n */\nexport function signTransaction(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n const { signer, transaction } = args;\n return signer.signTransactionWithAuthenticator(transaction);\n}\n\nexport function signAsFeePayer(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n const { signer, transaction } = args;\n\n // if transaction doesn't 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/**\n * Simulates a transaction before signing it to evaluate its potential outcome.\n *\n * @param args The arguments for simulating the transaction.\n * @param args.aptosConfig The configuration for the Aptos network.\n * @param args.transaction The raw transaction to simulate.\n * @param args.signerPublicKey Optional. The signer public key.\n * @param args.secondarySignersPublicKeys Optional. For when the transaction involves multiple signers.\n * @param args.feePayerPublicKey Optional. For when the transaction is sponsored by a fee payer.\n * @param args.options Optional. A configuration object to customize the simulation process.\n * @param args.options.estimateGasUnitPrice Optional. Indicates whether to estimate the gas unit price.\n * @param args.options.estimateMaxGasAmount Optional. Indicates whether to estimate the maximum gas amount.\n * @param args.options.estimatePrioritizedGasUnitPrice Optional. Indicates whether to estimate the prioritized gas unit price.\n * @group Implementation\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 a transaction to the Aptos blockchain.\n *\n * @param args - The arguments for submitting the transaction.\n * @param args.aptosConfig - The configuration for connecting to the Aptos network.\n * @param args.transaction - The Aptos transaction data to be submitted.\n * @param args.senderAuthenticator - The account authenticator of the transaction sender.\n * @param args.secondarySignerAuthenticators - Optional. Authenticators for additional signers in a multi-signer transaction.\n *\n * @returns PendingTransactionResponse - The response containing the status of the submitted transaction.\n * @group Implementation\n */\nexport async function submitTransaction(\n args: {\n aptosConfig: AptosConfig;\n } & InputSubmitTransactionData,\n): Promise<PendingTransactionResponse> {\n const { aptosConfig, transactionSubmitter } = args;\n const maybeTransactionSubmitter =\n transactionSubmitter === undefined ? aptosConfig.getTransactionSubmitter() : transactionSubmitter;\n if (maybeTransactionSubmitter) {\n return maybeTransactionSubmitter.submitTransaction(args);\n }\n const signedTransaction = generateSignedTransaction({ ...args });\n try {\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 } catch (e) {\n const signedTxn = SignedTransaction.deserialize(new Deserializer(signedTransaction));\n if (\n signedTxn.authenticator.isSingleSender() &&\n signedTxn.authenticator.sender.isSingleKey() &&\n (signedTxn.authenticator.sender.public_key.publicKey instanceof KeylessPublicKey ||\n signedTxn.authenticator.sender.public_key.publicKey instanceof FederatedKeylessPublicKey)\n ) {\n await AbstractKeylessAccount.fetchJWK({\n aptosConfig,\n publicKey: signedTxn.authenticator.sender.public_key.publicKey,\n kid: (signedTxn.authenticator.sender.signature.signature as KeylessSignature).getJwkKid(),\n });\n }\n throw e;\n }\n}\n\nexport type FeePayerOrFeePayerAuthenticatorOrNeither =\n | { feePayer: Account; feePayerAuthenticator?: never }\n | { feePayer?: never; feePayerAuthenticator: AccountAuthenticator }\n | { feePayer?: never; feePayerAuthenticator?: never };\n\nexport async function signAndSubmitTransaction(\n args: FeePayerOrFeePayerAuthenticatorOrNeither & {\n aptosConfig: AptosConfig;\n signer: Account;\n transaction: AnyRawTransaction;\n } & InputTransactionPluginData,\n): Promise<PendingTransactionResponse> {\n const { aptosConfig, signer, feePayer, transaction, ...rest } = args;\n // If the signer contains a KeylessAccount, await proof fetching in case the proof\n // was fetched asynchronously.\n if (isKeylessSigner(signer)) {\n await signer.checkKeylessAccountValidity(aptosConfig);\n }\n if (isKeylessSigner(feePayer)) {\n await feePayer.checkKeylessAccountValidity(aptosConfig);\n }\n const feePayerAuthenticator =\n args.feePayerAuthenticator || (feePayer && signAsFeePayer({ signer: feePayer, transaction }));\n\n const senderAuthenticator = signTransaction({ signer, transaction });\n return submitTransaction({\n aptosConfig,\n transaction,\n senderAuthenticator,\n feePayerAuthenticator,\n ...rest,\n });\n}\n\nexport async function signAndSubmitAsFeePayer(\n args: {\n aptosConfig: AptosConfig;\n feePayer: Account;\n senderAuthenticator: AccountAuthenticator;\n transaction: AnyRawTransaction;\n } & InputTransactionPluginData,\n): Promise<PendingTransactionResponse> {\n const { aptosConfig, senderAuthenticator, feePayer, transaction, ...rest } = args;\n\n if (isKeylessSigner(feePayer)) {\n await feePayer.checkKeylessAccountValidity(aptosConfig);\n }\n\n const feePayerAuthenticator = signAsFeePayer({ signer: feePayer, transaction });\n\n return submitTransaction({\n aptosConfig,\n transaction,\n senderAuthenticator,\n feePayerAuthenticator,\n ...rest,\n });\n}\n\nconst packagePublishAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [TypeTagVector.u8(), new TypeTagVector(TypeTagVector.u8())],\n};\n\n/**\n * Publishes a package transaction to the Aptos blockchain.\n * This function allows you to create and send a transaction that publishes a package with the specified metadata and bytecode.\n *\n * @param args - The arguments for the package transaction.\n * @param args.aptosConfig - The configuration settings for the Aptos client.\n * @param args.account - The address of the account sending the transaction.\n * @param args.metadataBytes - The metadata associated with the package, represented as hexadecimal input.\n * @param args.moduleBytecode - An array of module bytecode, each represented as hexadecimal input.\n * @param args.options - Optional parameters for generating the transaction.\n * @group Implementation\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","// 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 * @group Implementation\n */\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport {\n getAptosFullNode,\n getPageWithObfuscatedCursor,\n paginateWithCursor,\n paginateWithObfuscatedCursor,\n} from \"../client\";\nimport {\n AccountData,\n AnyNumber,\n anyPublicKeyVariantToString,\n CommittedTransactionResponse,\n CursorPaginationArgs,\n GetAccountCoinsDataResponse,\n GetAccountCollectionsWithOwnedTokenResponse,\n GetAccountOwnedTokensFromCollectionResponse,\n GetAccountOwnedTokensQueryResponse,\n GetObjectDataQueryResponse,\n LedgerVersionArg,\n MoveModuleBytecode,\n MoveResource,\n MoveStructId,\n OrderByArg,\n PaginationArgs,\n PendingTransactionResponse,\n TokenStandardArg,\n WhereArg,\n} from \"../types\";\nimport { AccountAddress, AccountAddressInput } from \"../core/accountAddress\";\nimport {\n Account,\n Ed25519Account,\n FederatedKeylessAccount,\n KeylessAccount,\n MultiEd25519Account,\n MultiKeyAccount,\n SingleKeyAccount,\n} from \"../account\";\nimport {\n AbstractMultiKey,\n AccountPublicKey,\n AnyPublicKey,\n BaseAccountPublicKey,\n Ed25519PublicKey,\n MultiEd25519PublicKey,\n MultiKey,\n PrivateKeyInput,\n} from \"../core/crypto\";\nimport { queryIndexer } from \"./general\";\nimport { getModule as getModuleUtil, getInfo as getInfoUtil } from \"./utils\";\nimport {\n GetAccountCoinsCountQuery,\n GetAccountCoinsDataQuery,\n GetAccountCollectionsWithOwnedTokensQuery,\n GetObjectDataQuery,\n GetAccountOwnedTokensFromCollectionQuery,\n GetAccountOwnedTokensQuery,\n GetAccountTokensCountQuery,\n GetAccountTransactionsCountQuery,\n GetAuthKeysForPublicKeyQuery,\n GetAccountAddressesForAuthKeyQuery,\n} from \"../types/generated/operations\";\nimport {\n GetAccountCoinsCount,\n GetAccountCoinsData,\n GetAccountCollectionsWithOwnedTokens,\n GetObjectData,\n GetAccountOwnedTokens,\n GetAccountOwnedTokensFromCollection,\n GetAccountTokensCount,\n GetAccountTransactionsCount,\n GetAuthKeysForPublicKey,\n GetAccountAddressesForAuthKey,\n} from \"../types/generated/queries\";\nimport { Secp256k1PrivateKey, AuthenticationKey, Ed25519PrivateKey, createObjectAddress, Hex } from \"../core\";\nimport { CurrentFungibleAssetBalancesBoolExp } from \"../types/generated/types\";\nimport { getTableItem } from \"./table\";\nimport { APTOS_COIN } from \"../utils\";\nimport { AptosApiError } from \"../errors\";\nimport { Deserializer } from \"../bcs\";\nimport { signAndSubmitTransaction, generateTransaction } from \"./transactionSubmission\";\nimport {\n EntryFunctionABI,\n InputGenerateTransactionOptions,\n RotationProofChallenge,\n SimpleTransaction,\n TypeTagU8,\n TypeTagVector,\n} from \"../transactions\";\nimport { U8, MoveVector } from \"../bcs\";\nimport { waitForTransaction, waitForIndexer } from \"./transaction\";\nimport { view } from \"./view\";\nimport { getLedgerInfo } from \"./general\";\nimport { accountPublicKeyToBaseAccountPublicKey, accountPublicKeyToSigningScheme } from \"../core/crypto/utils\";\n\n/**\n * Retrieves account information for a specified account address.\n *\n * @param args - The arguments for retrieving account information.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.accountAddress - The address of the account to retrieve information for.\n * @group Implementation\n */\nexport async function getInfo(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n}): Promise<AccountData> {\n return getInfoUtil(args);\n}\n\n/**\n * Retrieves the modules associated with a specified account address.\n *\n * @param args - The arguments for retrieving modules.\n * @param args.aptosConfig - The configuration for connecting to the Aptos blockchain.\n * @param args.accountAddress - The address of the account whose modules are to be retrieved.\n * @param args.options - Optional parameters for pagination and ledger version.\n * @param args.options.limit - The maximum number of modules to retrieve (default is 1000).\n * @param args.options.offset - The starting point for pagination. Note, this is obfuscated and is not an index.\n * @param args.options.ledgerVersion - The specific ledger version to query.\n * @group Implementation\n */\nexport async function getModules(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: { limit?: number } & LedgerVersionArg;\n}): Promise<MoveModuleBytecode[]> {\n const { aptosConfig, accountAddress, options } = args;\n return paginateWithObfuscatedCursor<{}, MoveModuleBytecode[]>({\n aptosConfig,\n originMethod: \"getModules\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/modules`,\n params: {\n ledger_version: options?.ledgerVersion,\n limit: options?.limit ?? 1000,\n },\n });\n}\n\n/**\n * Retrieves the modules associated with a specified account address.\n *\n * @param args - The arguments for retrieving modules.\n * @param args.aptosConfig - The configuration for connecting to the Aptos blockchain.\n * @param args.accountAddress - The address of the account whose modules are to be retrieved.\n * @param args.options - Optional parameters for pagination and ledger version.\n * @param args.options.cursor - The starting point for pagination. Note, this is obfuscated and is not an index.\n * @param args.options.limit - The maximum number of modules to retrieve (default is 100).\n * @param args.options.ledgerVersion - The specific ledger version to query.\n * @group Implementation\n */\nexport async function getModulesPage(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: CursorPaginationArgs & LedgerVersionArg;\n}): Promise<{ modules: MoveModuleBytecode[]; cursor: string | undefined }> {\n const { aptosConfig, accountAddress, options } = args;\n const { response, cursor } = await getPageWithObfuscatedCursor<{}, MoveModuleBytecode[]>({\n aptosConfig,\n originMethod: \"getModulesPage\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/modules`,\n params: {\n ledger_version: options?.ledgerVersion,\n cursor: options?.cursor,\n limit: options?.limit ?? 100,\n },\n });\n\n return { modules: response.data, cursor };\n}\n\n/**\n * Queries for a move module given an account address and module name.\n * This function can help you retrieve the module's ABI and other relevant information.\n *\n * @param args - The arguments for retrieving the module.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param args.accountAddress - The account address in hex-encoded 32 byte format.\n * @param args.moduleName - The name of the module to retrieve.\n * @param args.options - Optional parameters for the request.\n * @param args.options.ledgerVersion - Specifies the ledger version of transactions. By default, the latest version will be used.\n * @returns The move module.\n * @group Implementation\n */\nexport async function getModule(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n moduleName: string;\n options?: LedgerVersionArg;\n}): Promise<MoveModuleBytecode> {\n return getModuleUtil(args);\n}\n\n/**\n * Retrieves a list of transactions associated with a specific account address.\n * This function allows you to paginate through the transactions for better performance and usability.\n *\n * @param args - The arguments for retrieving transactions.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.accountAddress - The account address for which to retrieve transactions.\n * @param args.options - Optional pagination parameters.\n * @param args.options.offset - The starting point for pagination.\n * @param args.options.limit - The maximum number of transactions to retrieve.\n * @group Implementation\n */\nexport async function getTransactions(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs;\n}): Promise<CommittedTransactionResponse[]> {\n const { aptosConfig, accountAddress, options } = args;\n return paginateWithCursor<{}, CommittedTransactionResponse[]>({\n aptosConfig,\n originMethod: \"getTransactions\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/transactions`,\n params: { start: options?.offset, limit: options?.limit },\n });\n}\n\n/**\n * Retrieves a list of resources associated with a specific account address.\n *\n * @param args - The arguments for retrieving resources.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.accountAddress - The address of the account to fetch resources for.\n * @param args.options - Optional pagination and ledger version parameters.\n * @param args.options.limit - The maximum number of resources to retrieve (default is 999).\n * @param args.options.ledgerVersion - The specific ledger version to query.\n * @group Implementation\n */\nexport async function getResources(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: { limit?: number } & LedgerVersionArg;\n}): Promise<MoveResource[]> {\n const { aptosConfig, accountAddress, options } = args;\n return paginateWithObfuscatedCursor<{}, MoveResource[]>({\n aptosConfig,\n originMethod: \"getResources\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/resources`,\n params: {\n ledger_version: options?.ledgerVersion,\n limit: options?.limit ?? 999,\n },\n });\n}\n\n/**\n * Retrieves a page of resources associated with a specific account address.\n *\n * @param args - The arguments for retrieving resources.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.accountAddress - The address of the account to fetch resources for.\n * @param args.options - Optional pagination and ledger version parameters.\n * @param args.options.cursor - The starting point for pagination. Note, this is obfuscated and is not an index.\n * @param args.options.limit - The maximum number of resources to retrieve (default is 100).\n * @param args.options.ledgerVersion - The specific ledger version to query.\n * @group Implementation\n */\nexport async function getResourcesPage(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: CursorPaginationArgs & LedgerVersionArg;\n}): Promise<{ resources: MoveResource[]; cursor: string | undefined }> {\n const { aptosConfig, accountAddress, options } = args;\n const { response, cursor } = await getPageWithObfuscatedCursor<{}, MoveResource[]>({\n aptosConfig,\n originMethod: \"getResourcesPage\",\n path: `accounts/${AccountAddress.from(accountAddress).toString()}/resources`,\n params: {\n ledger_version: options?.ledgerVersion,\n cursor: options?.cursor,\n limit: options?.limit ?? 100,\n },\n });\n\n return { resources: response.data, cursor };\n}\n\n/**\n * Retrieves a specific resource of a given type for the specified account address.\n *\n * @param args - The arguments for retrieving the resource.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.accountAddress - The address of the account from which to retrieve the resource.\n * @param args.resourceType - The type of the resource to retrieve, specified as a MoveStructId.\n * @param args.options - Optional parameters for specifying the ledger version.\n * @group Implementation\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\n/**\n * Retrieves the original account address associated with a given authentication key, which is useful for handling key rotations.\n *\n * @param args - The arguments for the lookup.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param args.authenticationKey - The authentication key for which to look up the original address.\n * @param args.options - Optional parameters for specifying the ledger version.\n * @returns The original account address or the provided authentication key address if not found.\n * @throws Throws an error if the lookup fails for reasons other than the address not being found.\n * @group Implementation\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\n/**\n * Retrieves the count of tokens owned by a specific account address.\n *\n * @param args - The arguments for retrieving the account tokens count.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.accountAddress - The address of the account for which to count the tokens.\n * @returns The count of tokens owned by the specified account.\n * @group Implementation\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) doesn't 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\n/**\n * Retrieves the tokens owned by a specified account address.\n *\n * @param args - The arguments for retrieving the account's tokens.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param args.accountAddress - The address of the account whose tokens are being queried.\n * @param args.options - Optional parameters for filtering and pagination.\n * @param args.options.tokenStandard - The specific token standard to filter the results.\n * @param args.options.offset - The number of records to skip before starting to collect the result set.\n * @param args.options.limit - The maximum number of records to return.\n * @param args.options.orderBy - The criteria for ordering the results.\n * @returns A promise that resolves to the current token ownerships of the specified account.\n * @group Implementation\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\n/**\n * Retrieves the tokens owned by a specific account from a particular collection address.\n *\n * @param args - The parameters required to fetch the owned tokens.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.accountAddress - The address of the account whose tokens are being queried.\n * @param args.collectionAddress - The address of the collection from which tokens are being retrieved.\n * @param args.options - Optional parameters for filtering and pagination, including token standard, pagination arguments, and\n * order by options.\n * @group Implementation\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\n/**\n * Retrieves the collections owned by a specified account along with the tokens in those collections.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param args.accountAddress - The address of the account whose collections are being queried.\n * @param args.options - Optional parameters for filtering and pagination.\n * @param args.options.tokenStandard - An optional token standard to filter the collections.\n * @param args.options.offset - An optional offset for pagination.\n * @param args.options.limit - An optional limit for the number of results returned.\n * @param args.options.orderBy - An optional parameter to specify the order of the results.\n * @group Implementation\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 current_collection?: { token_standard: { _eq: string } };\n } = {\n owner_address: { _eq: address },\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\n/**\n * Retrieves the count of transactions associated with a specified account.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.accountAddress - The address of the account for which to retrieve the transaction count.\n * @returns The number of transactions associated with the specified account.\n * @group Implementation\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) doesn't 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\n/**\n * Retrieves the amount of a specific coin held by an account.\n *\n * @param args - The parameters for the request.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.accountAddress - The address of the account to query.\n * @param args.coinType - Optional; the type of coin to check the amount for.\n * @param args.faMetadataAddress - Optional; the address of the fungible asset metadata.\n * @returns The amount of the specified coin held by the account, or 0 if none is found.\n * @throws Error if neither coinType nor faMetadataAddress is provided.\n * @group Implementation\n */\nexport async function getAccountCoinAmount(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n coinType?: MoveStructId;\n faMetadataAddress?: AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, accountAddress, coinType, faMetadataAddress } = args;\n\n let coinAssetType: string | undefined = coinType;\n let faAddress: string;\n\n if (coinType !== undefined && faMetadataAddress !== undefined) {\n faAddress = AccountAddress.from(faMetadataAddress).toStringLong();\n } else if (coinType !== undefined && faMetadataAddress === undefined) {\n // TODO Move to a separate function as defined in the AIP for coin migration\n if (coinType === APTOS_COIN) {\n faAddress = AccountAddress.A.toStringLong();\n } else {\n faAddress = createObjectAddress(AccountAddress.A, coinType).toStringLong();\n }\n } else if (coinType === undefined && faMetadataAddress !== undefined) {\n const addr = AccountAddress.from(faMetadataAddress);\n faAddress = addr.toStringLong();\n if (addr === AccountAddress.A) {\n coinAssetType = APTOS_COIN;\n }\n // The paired CoinType should be populated outside of this function in another\n // async call. We cannot do this internally due to dependency cycles issue.\n } else {\n throw new Error(\"Either coinType, fungibleAssetAddress, or both must be provided\");\n }\n const address = AccountAddress.from(accountAddress).toStringLong();\n\n // Search by fungible asset address, unless it has a coin it migrated from\n let where: any = { asset_type: { _eq: faAddress } };\n if (coinAssetType !== undefined) {\n where = { asset_type: { _in: [coinAssetType, faAddress] } };\n }\n\n const data = await getAccountCoinsData({\n aptosConfig,\n accountAddress: address,\n options: {\n where,\n },\n });\n\n // commonjs (aka cjs) doesn't 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\n/**\n * Retrieves the current fungible asset balances for a specified account.\n *\n * @param args - The arguments for retrieving account coins data.\n * @param args.aptosConfig - The configuration for connecting to the Aptos network.\n * @param args.accountAddress - The address of the account for which to retrieve coin data.\n * @param args.options - Optional parameters for pagination and filtering the results.\n * @param args.options.offset - The number of items to skip before starting to collect the result set.\n * @param args.options.limit - The maximum number of items to return.\n * @param args.options.orderBy - The criteria for ordering the results.\n * @param args.options.where - Conditions to filter the results based on the current fungible asset balances.\n * @group Implementation\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\n/**\n * Retrieves the count of fungible asset coins held by a specified account.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.accountAddress - The address of the account for which to retrieve the coin count.\n * @throws Error if the count of account coins cannot be retrieved.\n * @group Implementation\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\n/**\n * Retrieves an account's balance for the given asset via the fullnode REST API.\n *\n * - `asset` may be a coin type (Move struct ID, e.g. `0x1::aptos_coin::AptosCoin`) or an FA metadata address.\n * - Calls: `GET /accounts/{accountAddress}/balance/{asset}` and returns the numeric balance.\n *\n * @param args - The parameters for the request.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.accountAddress - The account address to query.\n * @param args.asset - The asset identifier (coin type or FA metadata address).\n * @returns The balance as a number.\n * @group Implementation\n */\nexport async function getBalance(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n asset: MoveStructId | AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, accountAddress, asset } = args;\n\n const response = await getAptosFullNode<{}, number>({\n aptosConfig,\n originMethod: \"getBalance\",\n path: `accounts/${accountAddress}/balance/${asset}`,\n params: {\n accountAddress: accountAddress.toString(),\n asset: asset instanceof Uint8Array ? AccountAddress.from(asset).toString() : asset.toString(),\n },\n });\n\n return parseInt(response.data.toString(), 10);\n}\n\n/**\n * Retrieves the objects owned by a specified account.\n *\n * @param args - The parameters for the request.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param args.accountAddress - The address of the account whose owned objects are to be retrieved.\n * @param args.options - Optional parameters for pagination and ordering of the results.\n * @param args.options.offset - The number of items to skip before starting to collect the result set.\n * @param args.options.limit - The maximum number of items to return.\n * @param args.options.orderBy - The criteria to order the results by.\n * @returns A promise that resolves to the current objects owned by the specified account.\n * @group Implementation\n */\nexport async function getAccountOwnedObjects(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]>;\n}): Promise<GetObjectDataQueryResponse> {\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: GetObjectData,\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<GetObjectDataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountOwnedObjects\",\n });\n\n return data.current_objects;\n}\n\n/**\n * Derives an account from the provided private key and Aptos configuration.\n *\n * This function queries all owned accounts for the provided private key and returns the most\n * recently used account. If no account is found, it will throw an error unless `throwIfNoAccountFound` is set to false.\n *\n * If `throwIfNoAccountFound` is set to false, the function will return the default account for the private key via `Account.fromPrivateKey`.\n *\n * NOTE: There is a potential issue once the unified single signer scheme is adopted by the community.\n * Because one could create two accounts with the same private key with this new authenticator type,\n * we'll need to determine the order in which we look up the accounts: first unified scheme and then legacy scheme,\n * or first legacy scheme and then unified scheme.\n *\n * @param args - The arguments for deriving the account.\n * @param args.aptosConfig - The Aptos configuration used for account lookup.\n * @param args.privateKey - The private key used to derive the account.\n * @param args.options.throwIfNoAccountFound - If true, throw an error if no existing account is found on chain. Default is false.\n * @throws Error if the account cannot be derived from the private key.\n * @group Implementation\n * @deprecated Note that more inspection is needed by the user to determine which account exists on-chain\n */\nexport async function deriveAccountFromPrivateKey(args: {\n aptosConfig: AptosConfig;\n privateKey: PrivateKeyInput;\n options?: {\n throwIfNoAccountFound?: boolean;\n };\n}): Promise<Account> {\n const { aptosConfig, privateKey, options } = args;\n const throwIfNoAccountFound = options?.throwIfNoAccountFound ?? false;\n\n const accounts = await deriveOwnedAccountsFromPrivateKey({ aptosConfig, privateKey });\n if (accounts.length === 0) {\n if (throwIfNoAccountFound) {\n throw new Error(`No existing account found for private key.`);\n }\n // If no account is found, return the default account. This is a legacy account for Ed25519 private keys.\n return Account.fromPrivateKey({ privateKey });\n }\n return accounts[0];\n}\n\n/**\n * Checks if an account exists by verifying its information against the Aptos blockchain.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration for connecting to the Aptos blockchain.\n * @param args.authKey - The authentication key used to derive the account address.\n * @returns A promise that resolves to a boolean indicating whether the account exists.\n *\n * @throws Throws an Error if there is an issue while looking for account information.\n * @group Implementation\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 return doesAccountExistAtAddress({ aptosConfig, accountAddress });\n}\n\n/**\n * Checks if an account exists at a given address.\n *\n * @param args - The arguments for checking account existence.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param args.accountAddress - The address of the account to check.\n * @param args.options.withAuthKey - An optional authentication key which will also be checked against if provided.\n * @returns A promise that resolves to a boolean indicating whether the account exists.\n * @group Implementation\n */\nasync function doesAccountExistAtAddress(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddress;\n options?: { withAuthKey?: AuthenticationKey };\n}): Promise<boolean> {\n const { aptosConfig, accountAddress, options } = args;\n try {\n // Get the account resources and the balance of the account. We need to check both because\n // an account resource can exist with 0 balance and a balance can exist without an account resource (light accounts).\n const [resources, ownedObjects] = await Promise.all([\n getResources({\n aptosConfig,\n accountAddress,\n }),\n getAccountOwnedObjects({\n aptosConfig,\n accountAddress,\n options: {\n limit: 1,\n },\n }),\n ]);\n\n const accountResource: MoveResource<{ authentication_key: string }> | undefined = resources.find(\n (r) => r.type === \"0x1::account::Account\",\n ) as MoveResource<{ authentication_key: string }> | undefined;\n\n // If the account resource is not found and the balance is 0, then the account does not exist.\n if (!accountResource && ownedObjects.length === 0) {\n return false;\n }\n\n // If no auth key is provided as an argument, return true.\n if (!options?.withAuthKey) {\n return true;\n }\n\n // Get the auth key from the account resource if it exists. If the account resource does not exist,\n // then the auth key is the account address by default.\n let authKey;\n if (accountResource) {\n authKey = accountResource.data.authentication_key;\n } else {\n authKey = accountAddress.toStringLong();\n }\n\n if (authKey !== options.withAuthKey.toString()) {\n return false;\n }\n\n // Else the account exists and the auth key matches.\n return true;\n } catch (error: any) {\n throw new Error(`Error while checking if account exists at ${accountAddress.toString()}: ${error}`);\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 * Rotates the authentication key for a given account.\n *\n * @param args - The arguments for rotating the authentication key.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.fromAccount - The account from which the authentication key will be rotated.\n * @param args.toAccount - (Optional) The target account to rotate to. Required if not using toNewPrivateKey.\n * @param args.toNewPrivateKey - (Optional) The new private key to rotate to. Required if not using toAccount.\n *\n * @remarks\n * This function supports three modes of rotation:\n * 1. Using a target Account object (toAccount)\n * 2. Using a new private key (toNewPrivateKey)\n *\n * @returns A simple transaction object that can be submitted to the network.\n * @throws Error if the rotation fails or verification fails.\n *\n * @group Implementation\n */\nexport async function rotateAuthKey(\n args: {\n aptosConfig: AptosConfig;\n fromAccount: Account;\n options?: InputGenerateTransactionOptions;\n } & ({ toAccount: Ed25519Account | MultiEd25519Account } | { toNewPrivateKey: Ed25519PrivateKey }),\n): Promise<SimpleTransaction> {\n const { aptosConfig, fromAccount, options } = args;\n if (\"toNewPrivateKey\" in args) {\n return rotateAuthKeyWithChallenge({\n aptosConfig,\n fromAccount,\n toNewPrivateKey: args.toNewPrivateKey,\n options,\n });\n } else if (\"toAccount\" in args) {\n if (args.toAccount instanceof Ed25519Account) {\n return rotateAuthKeyWithChallenge({\n aptosConfig,\n fromAccount,\n toNewPrivateKey: args.toAccount.privateKey,\n options,\n });\n } else {\n return rotateAuthKeyWithChallenge({ aptosConfig, fromAccount, toAccount: args.toAccount, options });\n }\n } else {\n throw new Error(\"Invalid arguments\");\n }\n}\n\nasync function rotateAuthKeyWithChallenge(\n args: {\n aptosConfig: AptosConfig;\n fromAccount: Account;\n options?: InputGenerateTransactionOptions;\n } & ({ toNewPrivateKey: Ed25519PrivateKey } | { toAccount: MultiEd25519Account }),\n): Promise<SimpleTransaction> {\n const { aptosConfig, fromAccount, options } = args;\n const accountInfo = await getInfo({\n aptosConfig,\n accountAddress: fromAccount.accountAddress,\n });\n\n let newAccount: Account;\n if (\"toNewPrivateKey\" in args) {\n newAccount = Account.fromPrivateKey({ privateKey: args.toNewPrivateKey, legacy: true });\n } else {\n newAccount = args.toAccount;\n }\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 proofSignedByCurrentKey = fromAccount.sign(challengeHex);\n const proofSignedByNewKey = newAccount.sign(challengeHex);\n\n // Generate transaction\n return 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(proofSignedByCurrentKey.toUint8Array()),\n MoveVector.U8(proofSignedByNewKey.toUint8Array()),\n ],\n abi: rotateAuthKeyAbi,\n },\n options,\n });\n}\n\nconst rotateAuthKeyUnverifiedAbi: EntryFunctionABI = {\n typeParameters: [],\n parameters: [new TypeTagU8(), TypeTagVector.u8()],\n};\n\n/**\n * Rotates the authentication key for a given account without verifying the new key.\n *\n * @param args - The arguments for rotating the authentication key.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.fromAccount - The account from which the authentication key will be rotated.\n * @param args.toNewPublicKey - The new public key to rotate to.\n * @returns A simple transaction object that can be submitted to the network.\n * @throws Error if the rotation fails or verification fails.\n *\n * @group Implementation\n */\nexport async function rotateAuthKeyUnverified(args: {\n aptosConfig: AptosConfig;\n fromAccount: Account;\n toNewPublicKey: AccountPublicKey;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, fromAccount, toNewPublicKey, options } = args;\n\n return generateTransaction({\n aptosConfig,\n sender: fromAccount.accountAddress,\n data: {\n function: \"0x1::account::rotate_authentication_key_from_public_key\",\n functionArguments: [\n new U8(accountPublicKeyToSigningScheme(toNewPublicKey)), // to scheme\n MoveVector.U8(accountPublicKeyToBaseAccountPublicKey(toNewPublicKey).toUint8Array()),\n ],\n abi: rotateAuthKeyUnverifiedAbi,\n },\n options,\n });\n}\n\nexport type AccountInfo = {\n accountAddress: AccountAddress;\n publicKey: BaseAccountPublicKey;\n lastTransactionVersion: number;\n};\n\nexport async function getAccountsForPublicKey(args: {\n aptosConfig: AptosConfig;\n publicKey: BaseAccountPublicKey;\n options?: { includeUnverified?: boolean; noMultiKey?: boolean };\n}): Promise<AccountInfo[]> {\n const { aptosConfig, publicKey, options } = args;\n const noMultiKey = options?.noMultiKey ?? false;\n if (noMultiKey && publicKey instanceof AbstractMultiKey) {\n throw new Error(\"Multi-key accounts are not supported when noMultiKey is true.\");\n }\n const allPublicKeys: BaseAccountPublicKey[] = [publicKey];\n\n // For Ed25519, we add the both the legacy Ed25519PublicKey and the new AnyPublicKey form.\n if (publicKey instanceof AnyPublicKey && publicKey.publicKey instanceof Ed25519PublicKey) {\n allPublicKeys.push(publicKey.publicKey);\n } else if (publicKey instanceof Ed25519PublicKey) {\n allPublicKeys.push(new AnyPublicKey(publicKey));\n }\n\n // Run both operations in parallel\n const [defaultAccountData, multiPublicKeys] = await Promise.all([\n // Check the provided public key for the default account. In the case of Ed25519, this will check both the legacy Ed25519PublicKey\n // and the AnyPublicKey form and may an existing account for each.\n Promise.all(\n allPublicKeys.map(async (publicKey) => {\n const addressAndLastTxnVersion = await getDefaultAccountInfoForPublicKey({ aptosConfig, publicKey });\n if (addressAndLastTxnVersion) {\n return { ...addressAndLastTxnVersion, publicKey };\n }\n return undefined;\n }),\n ),\n // Get multi-keys for the provided public key if not already a multi-key.\n !(publicKey instanceof AbstractMultiKey) && !noMultiKey\n ? getMultiKeysForPublicKey({ aptosConfig, publicKey, options })\n : Promise.resolve([]),\n ]);\n\n const result: {\n accountAddress: AccountAddress;\n publicKey: BaseAccountPublicKey;\n lastTransactionVersion: number;\n }[] = [];\n\n // Add any default accounts that exist to the result.\n for (const data of defaultAccountData) {\n if (data) {\n result.push(data);\n }\n }\n\n // Add any multi-keys to allPublicKeys\n allPublicKeys.push(...multiPublicKeys);\n\n // Get a map of the auth key to the public key for all public keys.\n const authKeyToPublicKey = new Map(allPublicKeys.map((key) => [key.authKey().toString(), key]));\n\n // Get the account addresses for the auth keys.\n const authKeyAccountAddressPairs = await getAccountAddressesForAuthKeys({\n aptosConfig,\n authKeys: allPublicKeys.map((key) => key.authKey()),\n options,\n });\n\n for (const authKeyAccountAddressPair of authKeyAccountAddressPairs) {\n // Skip if the account address is already in the result.\n // This can happen in the rare edge case where the default account has been rotated but has been rotated back to the original auth key.\n if (result.find((r) => r.accountAddress === authKeyAccountAddressPair.accountAddress)) {\n continue;\n }\n // Get the public key for the auth key using the map we created earlier.\n const publicKey = authKeyToPublicKey.get(authKeyAccountAddressPair.authKey.toString());\n if (!publicKey) {\n throw new Error(\n `No publicKey found for authentication key ${authKeyAccountAddressPair.authKey}. This should never happen.`,\n );\n }\n result.push({\n accountAddress: authKeyAccountAddressPair.accountAddress,\n publicKey,\n lastTransactionVersion: authKeyAccountAddressPair.lastTransactionVersion,\n });\n }\n // Sort the result by the last transaction version in descending order (most recent first).\n return result.sort((a, b) => b.lastTransactionVersion - a.lastTransactionVersion);\n}\n\nexport async function deriveOwnedAccountsFromSigner(args: {\n aptosConfig: AptosConfig;\n signer: Account | PrivateKeyInput;\n options?: { includeUnverified?: boolean; noMultiKey?: boolean };\n}): Promise<Account[]> {\n const { aptosConfig, signer, options } = args;\n\n if (signer instanceof Ed25519PrivateKey || signer instanceof Secp256k1PrivateKey) {\n return deriveOwnedAccountsFromPrivateKey({ aptosConfig, privateKey: signer, options });\n }\n\n if (signer instanceof Ed25519Account || signer instanceof SingleKeyAccount) {\n return deriveOwnedAccountsFromPrivateKey({ aptosConfig, privateKey: signer.privateKey, options });\n }\n\n if (signer instanceof KeylessAccount || signer instanceof FederatedKeylessAccount) {\n return deriveOwnedAccountsFromKeylessSigner({ aptosConfig, keylessAccount: signer, options });\n }\n\n if (signer instanceof MultiKeyAccount) {\n if (signer.signers.length === 1) {\n return deriveOwnedAccountsFromSigner({ aptosConfig, signer: signer.signers[0], options });\n }\n }\n\n if (signer instanceof MultiEd25519Account) {\n if (signer.signers.length === 1) {\n return deriveOwnedAccountsFromPrivateKey({ aptosConfig, privateKey: signer.signers[0], options });\n }\n }\n\n throw new Error(\"Unknown signer type\");\n}\n\nasync function deriveOwnedAccountsFromKeylessSigner(args: {\n aptosConfig: AptosConfig;\n keylessAccount: KeylessAccount | FederatedKeylessAccount;\n options?: { includeUnverified?: boolean; noMultiKey?: boolean };\n}): Promise<Account[]> {\n const { aptosConfig, keylessAccount, options } = args;\n const addressesAndPublicKeys = await getAccountsForPublicKey({\n aptosConfig,\n publicKey: keylessAccount.getAnyPublicKey(),\n options,\n });\n\n const keylessAccountParams = {\n proof: keylessAccount.proofOrPromise,\n jwt: keylessAccount.jwt,\n ephemeralKeyPair: keylessAccount.ephemeralKeyPair,\n pepper: keylessAccount.pepper,\n verificationKeyHash: keylessAccount.verificationKeyHash,\n };\n\n const accounts: Account[] = [];\n for (const { accountAddress, publicKey } of addressesAndPublicKeys) {\n if (publicKey instanceof AbstractMultiKey) {\n if (publicKey.getSignaturesRequired() > 1) {\n continue;\n }\n if (publicKey instanceof MultiEd25519PublicKey) {\n throw new Error(\"Keyless authentication cannot be used for multi-ed25519 accounts. This should never happen.\");\n } else if (publicKey instanceof MultiKey) {\n accounts.push(new MultiKeyAccount({ multiKey: publicKey, signers: [keylessAccount], address: accountAddress }));\n }\n } else {\n if (keylessAccount instanceof FederatedKeylessAccount) {\n accounts.push(\n FederatedKeylessAccount.create({\n ...keylessAccountParams,\n address: accountAddress,\n jwkAddress: keylessAccount.publicKey.jwkAddress,\n }),\n );\n } else {\n accounts.push(\n KeylessAccount.create({\n ...keylessAccountParams,\n address: accountAddress,\n }),\n );\n }\n }\n }\n return accounts;\n}\n\nasync function deriveOwnedAccountsFromPrivateKey(args: {\n aptosConfig: AptosConfig;\n privateKey: Ed25519PrivateKey | Secp256k1PrivateKey;\n options?: { includeUnverified?: boolean; noMultiKey?: boolean };\n}): Promise<Account[]> {\n const { aptosConfig, privateKey, options } = args;\n const singleKeyAccount = Account.fromPrivateKey({ privateKey, legacy: false });\n const addressesAndPublicKeys = await getAccountsForPublicKey({\n aptosConfig,\n publicKey: new AnyPublicKey(privateKey.publicKey()),\n options,\n });\n\n const accounts: Account[] = [];\n\n // Iterate through the addressesAndPublicKeys and construct the accounts.\n for (const { accountAddress, publicKey } of addressesAndPublicKeys) {\n if (publicKey instanceof AbstractMultiKey) {\n // Skip multi-key accounts with more than 1 signature required as the user does not have full ownership with just 1 private key.\n if (publicKey.getSignaturesRequired() > 1) {\n continue;\n }\n // Construct the appropriate multi-key type.\n if (publicKey instanceof MultiEd25519PublicKey) {\n accounts.push(\n new MultiEd25519Account({ publicKey, signers: [privateKey as Ed25519PrivateKey], address: accountAddress }),\n );\n } else if (publicKey instanceof MultiKey) {\n accounts.push(\n new MultiKeyAccount({ multiKey: publicKey, signers: [singleKeyAccount], address: accountAddress }),\n );\n }\n } else {\n // Check if the public key is a legacy Ed25519PublicKey, if so, we need to use the legacy account constructor.\n const isLegacy = publicKey instanceof Ed25519PublicKey;\n accounts.push(Account.fromPrivateKey({ privateKey, address: accountAddress, legacy: isLegacy }));\n }\n }\n return accounts;\n}\n\n/**\n * Gets the multi-keys for a given public key.\n *\n * This function retrieves the multi-keys that contain the provided public key.\n * It performs the following steps:\n * 1. Constructs a where condition for the public key where the public key matches the provided public key.\n * 2. Queries the indexer for the multi-keys.\n * 3. Returns the multi-keys.\n *\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.publicKey - The public key to get the multi-keys for. This public key cannot itself be a multi-key.\n * @returns The multi-keys (MultiKey or MultiEd25519PublicKey) that contain the given public key.\n */\nasync function getMultiKeysForPublicKey(args: {\n aptosConfig: AptosConfig;\n publicKey: Ed25519PublicKey | AnyPublicKey;\n options?: { includeUnverified?: boolean };\n}): Promise<(MultiKey | MultiEd25519PublicKey)[]> {\n const { aptosConfig, publicKey, options } = args;\n if (publicKey instanceof AbstractMultiKey) {\n throw new Error(\"Public key is a multi-key.\");\n }\n const includeUnverified = options?.includeUnverified ?? false;\n const anyPublicKey = publicKey instanceof AnyPublicKey ? publicKey : new AnyPublicKey(publicKey);\n const baseKey = anyPublicKey.publicKey;\n const variant = anyPublicKeyVariantToString(anyPublicKey.variant);\n\n const whereCondition: any = {\n public_key: { _eq: baseKey.toString() },\n public_key_type: { _eq: variant },\n ...(includeUnverified ? {} : { is_public_key_used: { _eq: true } }),\n };\n\n const graphqlQuery = {\n query: GetAuthKeysForPublicKey,\n variables: {\n where_condition: whereCondition,\n },\n };\n\n const { public_key_auth_keys: data } = await queryIndexer<GetAuthKeysForPublicKeyQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getMultiKeysForPublicKey\",\n });\n\n const authKeys = data.map((entry) => {\n switch (entry.signature_type) {\n case \"multi_ed25519_signature\":\n return MultiEd25519PublicKey.deserializeWithoutLength(Deserializer.fromHex(entry.account_public_key!));\n case \"multi_key_signature\":\n return MultiKey.deserialize(Deserializer.fromHex(entry.account_public_key!));\n default:\n throw new Error(`Unknown multi-signature type: ${entry.signature_type}`);\n }\n });\n return authKeys;\n}\n\n/**\n * Gets the account addresses for the given authentication keys.\n *\n * This function retrieves the account addresses that are associated with the provided authentication keys.\n * It performs the following steps:\n * 1. Constructs a where condition for the authentication keys where auth key matches any of the provided auth keys.\n * 2. Queries the indexer for the account addresses and gets the results ordered by the last transaction version (most recent first).\n * 3. Returns the account addresses.\n *\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.authKeys - The authentication keys to get the account addresses for.\n * @param args.options.includeUnverified - Whether to include unverified accounts in the results. Unverified accounts\n * are accounts that can be authenticated with the signer, but there is no history of the signer using the account.\n * Default is false.\n * @returns The account addresses associated with the given authentication keys.\n */\nasync function getAccountAddressesForAuthKeys(args: {\n aptosConfig: AptosConfig;\n authKeys: AuthenticationKey[];\n options?: { includeUnverified?: boolean };\n}): Promise<{ authKey: AuthenticationKey; accountAddress: AccountAddress; lastTransactionVersion: number }[]> {\n const { aptosConfig, authKeys, options } = args;\n const includeUnverified = options?.includeUnverified ?? false;\n if (authKeys.length === 0) {\n throw new Error(\"No authentication keys provided\");\n }\n const whereCondition: any = {\n auth_key: { _in: authKeys.map((authKey) => authKey.toString()) },\n ...(includeUnverified ? {} : { is_auth_key_used: { _eq: true } }),\n };\n\n const graphqlQuery = {\n query: GetAccountAddressesForAuthKey,\n variables: {\n where_condition: whereCondition,\n order_by: [{ last_transaction_version: \"desc\" }],\n },\n };\n const { auth_key_account_addresses: data } = await queryIndexer<GetAccountAddressesForAuthKeyQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getAccountAddressesForAuthKeys\",\n });\n return data.map((entry) => ({\n authKey: new AuthenticationKey({ data: entry.auth_key }),\n accountAddress: new AccountAddress(Hex.hexInputToUint8Array(entry.account_address)),\n lastTransactionVersion: Number(entry.last_transaction_version),\n }));\n}\n\n/**\n * Returns the last transaction version that was signed by an account.\n *\n * If an account was created but has not signed any transactions, the last transaction version will be 0.\n *\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.accountAddress - The account address to get the latest transaction version for.\n * @returns The last transaction version that was signed by the account.\n */\nasync function getLatestTransactionVersionForAddress(args: {\n aptosConfig: AptosConfig;\n accountAddress: AccountAddressInput;\n}): Promise<number> {\n const { aptosConfig, accountAddress } = args;\n const transactions = await getTransactions({ aptosConfig, accountAddress, options: { limit: 1 } });\n if (transactions.length === 0) {\n return 0;\n }\n return Number(transactions[0].version);\n}\n\n/**\n * Gets the default account info for a given public key. 'Default account' means the account\n * is address is the same as the auth key derived from the public key and the account auth key has\n * not been rotated.\n *\n * @param args - The arguments for getting the default account info for a given public key.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.publicKey - The public key to use to derive the address.\n * @returns An object containing the account address and the last transaction version, or undefined if the account does not exist.\n */\nasync function getDefaultAccountInfoForPublicKey(args: {\n aptosConfig: AptosConfig;\n publicKey: AccountPublicKey;\n}): Promise<{ accountAddress: AccountAddress; lastTransactionVersion: number } | undefined> {\n const { aptosConfig, publicKey } = args;\n const derivedAddress = publicKey.authKey().derivedAddress();\n\n const [lastTransactionVersion, exists] = await Promise.all([\n getLatestTransactionVersionForAddress({\n aptosConfig,\n accountAddress: derivedAddress,\n }),\n doesAccountExistAtAddress({\n aptosConfig,\n accountAddress: derivedAddress,\n options: { withAuthKey: publicKey.authKey() },\n }),\n ]);\n if (exists) {\n return { accountAddress: derivedAddress, lastTransactionVersion };\n }\n return undefined;\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 {\n generateViewFunctionPayload,\n InputViewFunctionData,\n InputViewFunctionJsonData,\n ViewFunctionJsonPayload,\n} 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\nexport async function viewJson<T extends Array<MoveValue> = Array<MoveValue>>(args: {\n aptosConfig: AptosConfig;\n payload: InputViewFunctionJsonData;\n options?: LedgerVersionArg;\n}): Promise<T> {\n const { aptosConfig, payload, options } = args;\n const { data } = await postAptosFullNode<ViewFunctionJsonPayload, MoveValue[]>({\n aptosConfig,\n originMethod: \"viewJson\",\n path: \"view\",\n params: { ledger_version: options?.ledgerVersion },\n body: {\n function: payload.function,\n type_arguments: payload.typeArguments ?? [],\n arguments: payload.functionArguments ?? [],\n },\n });\n\n return data as T;\n}\n","import {\n SimpleTransaction,\n InputGenerateTransactionOptions,\n TypeTagAddress,\n TypeTagStruct,\n stringStructTag,\n} from \"../transactions\";\nimport { AccountAddressInput } from \"../core\";\nimport { generateTransaction } from \"./transactionSubmission\";\nimport { MoveFunctionId } from \"../types\";\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { getFunctionParts } from \"../utils/helpers\";\n\nexport async function addAuthenticationFunctionTransaction(args: {\n aptosConfig: AptosConfig;\n sender: AccountAddressInput;\n authenticationFunction: string;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, authenticationFunction, options } = args;\n const { moduleAddress, moduleName, functionName } = getFunctionParts(authenticationFunction as MoveFunctionId);\n return generateTransaction({\n aptosConfig,\n sender,\n data: {\n function: \"0x1::account_abstraction::add_authentication_function\",\n typeArguments: [],\n functionArguments: [moduleAddress, moduleName, functionName],\n abi: {\n typeParameters: [],\n parameters: [new TypeTagAddress(), new TypeTagStruct(stringStructTag()), new TypeTagStruct(stringStructTag())],\n },\n },\n options,\n });\n}\n\nexport async function removeAuthenticationFunctionTransaction(args: {\n aptosConfig: AptosConfig;\n sender: AccountAddressInput;\n authenticationFunction: string;\n options?: InputGenerateTransactionOptions;\n}) {\n const { aptosConfig, sender, authenticationFunction, options } = args;\n const { moduleAddress, moduleName, functionName } = getFunctionParts(authenticationFunction as MoveFunctionId);\n return generateTransaction({\n aptosConfig,\n sender,\n data: {\n function: \"0x1::account_abstraction::remove_authentication_function\",\n typeArguments: [],\n functionArguments: [moduleAddress, moduleName, functionName],\n abi: {\n typeParameters: [],\n parameters: [new TypeTagAddress(), new TypeTagStruct(stringStructTag()), new TypeTagStruct(stringStructTag())],\n },\n },\n options,\n });\n}\n\nexport async function removeDispatchableAuthenticatorTransaction(args: {\n aptosConfig: AptosConfig;\n sender: AccountAddressInput;\n options?: InputGenerateTransactionOptions;\n}) {\n const { aptosConfig, sender, options } = args;\n return generateTransaction({\n aptosConfig,\n sender,\n data: {\n function: \"0x1::account_abstraction::remove_authenticator\",\n typeArguments: [],\n functionArguments: [],\n abi: { typeParameters: [], parameters: [] },\n },\n options,\n });\n}\n","import { AccountAddress, AccountAddressInput } from \"../../core\";\nimport {\n addAuthenticationFunctionTransaction,\n removeAuthenticationFunctionTransaction,\n removeDispatchableAuthenticatorTransaction,\n} from \"../../internal/abstraction\";\nimport { view } from \"../../internal/view\";\nimport { InputGenerateTransactionOptions, TypeTagAddress } from \"../../transactions\";\nimport { MoveFunctionId } from \"../../types\";\nimport { getFunctionParts } from \"../../utils/helpers\";\nimport { AptosConfig } from \"../aptosConfig\";\n\nexport class AccountAbstraction {\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Adds a dispatchable authentication function to the account.\n *\n * @example\n * ```ts\n * const txn = await aptos.abstraction.addAuthenticationFunctionTransaction({\n * accountAddress: alice.accountAddress,\n * authenticationFunction: `${alice.accountAddress}::any_authenticator::authenticate`,\n * });\n *\n * const txn = await aptos.signAndSubmitTransaction({ signer: alice, transaction});\n * await aptos.waitForTransaction({ transactionHash: txn.hash });\n * ```\n *\n * @param args.accountAddress - The account to add the authentication function to.\n * @param args.authenticationFunction - The authentication function info to add.\n * @param args.options - The options for the transaction.\n * @returns A transaction to add the authentication function to the account.\n */\n public async addAuthenticationFunctionTransaction(args: {\n accountAddress: AccountAddressInput;\n authenticationFunction: string;\n options?: InputGenerateTransactionOptions;\n }) {\n const { accountAddress, authenticationFunction, options } = args;\n return addAuthenticationFunctionTransaction({\n aptosConfig: this.config,\n authenticationFunction,\n sender: accountAddress,\n options,\n });\n }\n\n /**\n * Removes a dispatchable authentication function from the account.\n *\n * @example\n * ```ts\n * const txn = await aptos.abstraction.removeAuthenticationFunctionTransaction({\n * accountAddress: alice.accountAddress,\n * authenticationFunction: `${alice.accountAddress}::any_authenticator::authenticate`,\n * });\n *\n * const txn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });\n * await aptos.waitForTransaction({ transactionHash: txn.hash });\n * ```\n *\n * @param args.accountAddress - The account to remove the authentication function from.\n * @param args.authenticationFunction - The authentication function info to remove.\n * @param args.options - The options for the transaction.\n * @returns A transaction to remove the authentication function from the account.\n */\n public async removeAuthenticationFunctionTransaction(args: {\n accountAddress: AccountAddressInput;\n authenticationFunction: string;\n options?: InputGenerateTransactionOptions;\n }) {\n const { accountAddress, authenticationFunction, options } = args;\n return removeAuthenticationFunctionTransaction({\n aptosConfig: this.config,\n sender: accountAddress,\n authenticationFunction,\n options,\n });\n }\n\n /**\n * Removes a dispatchable authenticator from the account.\n *\n * @example\n * ```ts\n * const txn = await aptos.abstraction.removeDispatchableAuthenticatorTransaction({\n * accountAddress: alice.accountAddress,\n * });\n *\n * const txn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });\n * await aptos.waitForTransaction({ transactionHash: txn.hash });\n * ```\n *\n * @param args.accountAddress - The account to remove the authenticator from.\n * @param args.options - The options for the transaction.\n * @returns A transaction to remove the authenticator from the account.\n */\n public async removeDispatchableAuthenticatorTransaction(args: {\n accountAddress: AccountAddressInput;\n options?: InputGenerateTransactionOptions;\n }) {\n const { accountAddress, options } = args;\n return removeDispatchableAuthenticatorTransaction({ aptosConfig: this.config, sender: accountAddress, options });\n }\n\n /**\n * Gets the dispatchable authentication function for the account.\n *\n * @example\n * ```ts\n * const functionInfos = await aptos.abstraction.getAuthenticationFunction({\n * accountAddress: alice.accountAddress,\n * });\n *\n * if (functionInfos) {\n * console.log(`Account ${alice.accountAddress.toString()} is using account abstraction!`);\n * } else {\n * console.log(`Account ${alice.accountAddress.toString()} is not using account abstraction.`);\n * }\n * ```\n *\n * @param args.accountAddress - The account to get the dispatchable authentication function for.\n * @returns The dispatchable authentication function for the account.\n */\n public async getAuthenticationFunction(args: { accountAddress: AccountAddressInput }) {\n const { accountAddress } = args;\n const [{ vec: functionInfoOption }] = await view<\n [{ vec: { function_name: string; module_name: string; module_address: string }[][] }]\n >({\n aptosConfig: this.config,\n payload: {\n function: \"0x1::account_abstraction::dispatchable_authenticator\",\n functionArguments: [AccountAddress.from(accountAddress)],\n abi: { typeParameters: [], parameters: [new TypeTagAddress()], returnTypes: [] },\n },\n });\n\n if (functionInfoOption.length === 0) return undefined;\n\n return functionInfoOption[0].map((functionInfo) => ({\n moduleAddress: AccountAddress.fromString(functionInfo.module_address),\n moduleName: functionInfo.module_name,\n functionName: functionInfo.function_name,\n }));\n }\n\n /**\n * Will return true if the account is abstracted, otherwise false.\n *\n * @example\n * ```ts\n * const isAccountAbstractionEnabled = await aptos.abstraction.isAccountAbstractionEnabled({\n * accountAddress: alice.accountAddress,\n * authenticationFunction: `${alice.accountAddress}::any_authenticator::authenticate`,\n * });\n * if (isAccountAbstractionEnabled) {\n * console.log(`Account ${alice.accountAddress.toString()} is using account abstraction!`);\n * } else {\n * console.log(`Account ${alice.accountAddress.toString()} is not using account abstraction.`);\n * }\n * ```\n *\n * @param args.accountAddress - The account to check.\n * @returns Whether the account is abstracted.\n */\n public isAccountAbstractionEnabled = async (args: {\n accountAddress: AccountAddressInput;\n authenticationFunction: string;\n }) => {\n const functionInfos = await this.getAuthenticationFunction(args);\n const { moduleAddress, moduleName, functionName } = getFunctionParts(args.authenticationFunction as MoveFunctionId);\n return (\n functionInfos?.some(\n (functionInfo) =>\n AccountAddress.fromString(moduleAddress).equals(functionInfo.moduleAddress) &&\n moduleName === functionInfo.moduleName &&\n functionName === functionInfo.functionName,\n ) ?? false\n );\n };\n\n /**\n * Creates a transaction to enable account abstraction with the given authentication function.\n *\n * @example\n * ```ts\n * const txn = await aptos.abstraction.enableAccountAbstractionTransaction({\n * accountAddress: alice.accountAddress,\n * authenticationFunction: `{alice.accountAddress}::any_authenticator::authenticate`,\n * });\n *\n * const txn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });\n * await aptos.waitForTransaction({ transactionHash: txn.hash });\n * ```\n *\n * @param args.accountAddress - The account to enable account abstraction for.\n * @param args.authenticationFunction - The authentication function info to use.\n * @param args.options - The options for the transaction.\n * @returns A transaction to enable account abstraction for the account.\n */\n public enableAccountAbstractionTransaction = this.addAuthenticationFunctionTransaction;\n\n /**\n * Creates a transaction to disable account abstraction. If an authentication function is provided, it will specify to\n * remove the authentication function.\n *\n * @example\n * ```ts\n * const txn = await aptos.abstraction.disableAccountAbstractionTransaction({\n * accountAddress: alice.accountAddress,\n * authenticationFunction: `${alice.accountAddress}::any_authenticator::authenticate`,\n * });\n *\n * const txn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });\n * await aptos.waitForTransaction({ transactionHash: txn.hash });\n * ```\n *\n * @param args.accountAddress - The account to disable account abstraction for.\n * @param args.authenticationFunction - The authentication function info to remove.\n * @param args.options - The options for the transaction.\n * @returns A transaction to disable account abstraction for the account.\n */\n public disableAccountAbstractionTransaction = async (args: {\n accountAddress: AccountAddressInput;\n authenticationFunction?: string;\n options?: InputGenerateTransactionOptions;\n }) => {\n const { accountAddress, authenticationFunction, options } = args;\n if (authenticationFunction) {\n return this.removeAuthenticationFunctionTransaction({\n accountAddress,\n authenticationFunction,\n options,\n });\n }\n return this.removeDispatchableAuthenticatorTransaction({ accountAddress, options });\n };\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Account as AccountModule } from \"../account\";\nimport {\n AccountAddress,\n AccountAddressInput,\n createObjectAddress,\n BaseAccountPublicKey,\n PrivateKeyInput,\n} from \"../core\";\nimport {\n AccountData,\n AnyNumber,\n CursorPaginationArgs,\n GetAccountCoinsDataResponse,\n GetAccountCollectionsWithOwnedTokenResponse,\n GetAccountOwnedTokensFromCollectionResponse,\n GetAccountOwnedTokensQueryResponse,\n GetObjectDataQueryResponse,\n LedgerVersionArg,\n MoveModuleBytecode,\n MoveResource,\n MoveStructId,\n MoveValue,\n OrderByArg,\n PaginationArgs,\n TokenStandardArg,\n TransactionResponse,\n WhereArg,\n} from \"../types\";\nimport {\n deriveAccountFromPrivateKey,\n getAccountCoinsCount,\n getAccountCoinsData,\n getAccountCollectionsWithOwnedTokens,\n getAccountOwnedObjects,\n getAccountOwnedTokens,\n getAccountOwnedTokensFromCollectionAddress,\n getAccountsForPublicKey,\n getAccountTokensCount,\n getAccountTransactionsCount,\n getBalance,\n getInfo,\n getModule,\n getModules,\n getModulesPage,\n getResource,\n getResources,\n getResourcesPage,\n getTransactions,\n lookupOriginalAccountAddress,\n deriveOwnedAccountsFromSigner,\n AccountInfo,\n} from \"../internal/account\";\nimport { APTOS_COIN, APTOS_FA, ProcessorType } from \"../utils/const\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { waitForIndexerOnVersion } from \"./utils\";\nimport { CurrentFungibleAssetBalancesBoolExp } from \"../types/generated/types\";\nimport { view } from \"../internal/view\";\nimport { isEncodedStruct, parseEncodedStruct } from \"../utils\";\nimport { memoizeAsync } from \"../utils/memoize\";\nimport { AccountAbstraction } from \"./account/abstraction\";\n\n/**\n * A class to query all `Account` related queries on Aptos.\n * @group Account\n */\nexport class Account {\n abstraction: AccountAbstraction;\n\n /**\n * Creates an instance of the Aptos client with the provided configuration.\n *\n * @param config - The configuration settings for the Aptos client.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Initialize the Aptos client with testnet configuration\n * const config = new AptosConfig({ network: Network.TESTNET }); // specify your own network if needed\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n constructor(readonly config: AptosConfig) {\n this.abstraction = new AccountAbstraction(config);\n }\n\n /**\n * Queries the current state for an Aptos account given its account address.\n *\n * @param args - The arguments for retrieving account information.\n * @param args.accountAddress - The Aptos account address to query.\n * @returns The account data.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve account information for a specific address\n * const accountInfo = await aptos.getAccountInfo({ accountAddress: \"0x1\" }); // replace with a real account address\n * console.log(accountInfo);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * This function may call the API multiple times to auto paginate through results.\n *\n * @param args.accountAddress - The Aptos account address to query modules for.\n * @param args.options.limit - The maximum number of results to return.\n * @param args.options.ledgerVersion - The ledger version to query; if not provided, it retrieves the latest version.\n *\n * @returns - The account modules associated with the specified address.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching account modules for a specific account\n * const accountModules = await aptos.getAccountModules({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * limit: 10, // limiting to 10 modules\n * },\n * });\n *\n * console.log(accountModules);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n async getAccountModules(args: {\n accountAddress: AccountAddressInput;\n options?: { limit?: number } & LedgerVersionArg;\n }): Promise<MoveModuleBytecode[]> {\n return getModules({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries for a page of modules in an account given an account address.\n *\n * @param args.accountAddress - The Aptos account address to query modules for.\n * @param args.options.cursor - The cursor to start returning results from. Note, this is obfuscated and is not an index.\n * @param args.options.limit - The maximum number of results to return.\n * @param args.options.ledgerVersion - The ledger version to query; if not provided, it retrieves the latest version.\n *\n * @returns - The account modules associated with the specified address. Along with a cursor for future pagination. If the cursor is undefined, it means there are no more modules to fetch.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching account modules for a specific account\n * const {modules, cursor} = await aptos.getAccountModulesPage({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * cursor: undefined, // starting from the first module\n * limit: 10, // limiting to 10 modules\n * },\n * });\n *\n * console.log(modules);\n * console.log(`More to fetch: ${cursor !== undefined}`);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n async getAccountModulesPage(args: {\n accountAddress: AccountAddressInput;\n options?: CursorPaginationArgs & LedgerVersionArg;\n }): Promise<{ modules: MoveModuleBytecode[]; cursor: string | undefined }> {\n return getModulesPage({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries for a specific account module given an account address and module name.\n *\n * @param args.accountAddress - The 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 The account module associated with the specified account address and module name.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the account module for a specific account address and module name\n * const module = await aptos.getAccountModule({\n * accountAddress: \"0x1\", // replace with a real account address\n * moduleName: \"MyModule\" // specify the module name\n * });\n *\n * console.log(module);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * This function may call the API multiple times to auto paginate and retrieve all account transactions.\n *\n * @param args.accountAddress - The Aptos account address to query transactions for.\n * @param args.options - Optional pagination arguments.\n * @param args.options.offset - The number of transactions to start returning results from.\n * @param args.options.limit - The maximum number of results to return.\n *\n * @returns The account transactions.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetch transactions for a specific account\n * const transactions = await aptos.getAccountTransactions({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * offset: 0, // starting from the first transaction\n * limit: 10, // limiting to 10 transactions\n * },\n * });\n *\n * console.log(transactions);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * This function may call the API multiple times to auto paginate through results.\n *\n * @param args.accountAddress - The Aptos account address to query resources for.\n * @param args.options.limit - The maximum 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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching account resources for a specific account address\n * const resources = await aptos.getAccountResources({ accountAddress: \"0x1\" }); // replace with a real account address\n * console.log(resources);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 page of account resources given an account address.\n *\n * @param args.accountAddress - The Aptos account address to query resources for.\n * @param args.options.cursor - The cursor to start returning results from. Note, this is obfuscated and is not an index.\n * @param args.options.limit - The maximum 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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching account resources for a specific account address\n * const resources = await aptos.getAccountResourcesPage({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * cursor: undefined, // starting from the first resource\n * limit: 10, // limiting to 10 resources\n * },\n * });\n * console.log(resources);\n * console.log(`More to fetch: ${resources.cursor !== undefined}`);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n async getAccountResourcesPage(args: {\n accountAddress: AccountAddressInput;\n options?: CursorPaginationArgs & LedgerVersionArg;\n }): Promise<{ resources: MoveResource[]; cursor: string | undefined }> {\n return getResourcesPage({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries a specific account resource given an account address and resource type.\n *\n * @template T - The typed output of the resource.\n * @param args.accountAddress - The Aptos account address to query.\n * @param args.resourceType - The string representation of an on-chain Move struct type, e.g., \"0x1::aptos_coin::AptosCoin\".\n * @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.\n * @returns The account resource of the specified type.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the account resource for a specific account address and resource type\n * const resource = await aptos.getAccountResource({\n * accountAddress: \"0x1\", // replace with a real account address\n * resourceType: \"0x1::aptos_coin::AptosCoin\"\n * });\n *\n * console.log(resource);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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, handling both rotated and non-rotated keys.\n *\n * @param args.authenticationKey - The authentication key for which to look up the account address.\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 account address associated with the authentication key.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Look up the original account address for a given authentication key\n * const accountAddress = await aptos.lookupOriginalAccountAddress({\n * authenticationKey: \"0x1\", // replace with a real authentication key\n * });\n *\n * console.log(\"Original Account Address:\", accountAddress);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 a specified account.\n *\n * @param args - The parameters for the query.\n * @param args.accountAddress - The account address to query the token count for.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n * @returns The current count of tokens owned by the account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the count of tokens owned by the account\n * const tokensCount = await aptos.getAccountTokensCount({ accountAddress: \"0x1\" }); // replace with a real account address\n * console.log(`Tokens Count: ${tokensCount}`);\n * }\n * runExample().catch(console.error);\n * ```\n * @group 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 tokens currently owned by a specified account, including NFTs and fungible tokens.\n * If desired, you can filter the results by a specific token standard.\n *\n * @param args.accountAddress The account address for which to retrieve owned tokens.\n * @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.\n * @param args.options.tokenStandard Optional filter for the NFT standard to query for.\n * @param args.options.offset Optional number to start returning results from.\n * @param args.options.limit Optional number of results to return.\n * @param args.options.orderBy Optional order to sort the tokens by.\n * @returns An array of tokens with their respective data.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the tokens owned by a specific account\n * const accountOwnedTokens = await aptos.getAccountOwnedTokens({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * limit: 10, // specify how many tokens to return\n * orderBy: \"created_at\", // specify the order of the results\n * },\n * });\n *\n * console.log(accountOwnedTokens);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * 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 parameter.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get tokens owned by a specific account in a specific collection\n * const accountOwnedTokens = await aptos.getAccountOwnedTokensFromCollectionAddress({\n * accountAddress: \"0x1\", // replace with a real account address\n * collectionAddress: \"0x2\", // replace with a real collection address\n * });\n *\n * console.log(accountOwnedTokens);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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, including NFTs, fungible tokens, and soulbound tokens.\n * If you want to filter by a specific token standard, you can pass an optional tokenStandard parameter.\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 of the 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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get account collections with owned tokens for a specific account\n * const accountCollectionsWithOwnedTokens = await aptos.getAccountCollectionsWithOwnedTokens({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * tokenStandard: \"NFT\", // specify the token standard if needed\n * limit: 10, // specify the number of results to return\n * },\n * });\n *\n * console.log(accountCollectionsWithOwnedTokens);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * @param args - The parameters for the query.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the count of transactions for a specific account\n * const accountTransactionsCount = await aptos.getAccountTransactionsCount({\n * accountAddress: \"0x1\", // replace with a real account address\n * minimumLedgerVersion: 1, // specify your own minimum ledger version if needed\n * });\n *\n * console.log(accountTransactionsCount);\n * }\n * runExample().catch(console.error);\n * ```\n * @group 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 * Retrieves the coins data for a specified account.\n *\n * @param args.accountAddress - The account address for which to retrieve the coin's data.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n * @param args.options.offset - Optional. The number of coins 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 specific criteria.\n * @returns An array containing the coins data for the specified account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching coins data for a specific account\n * const accountCoinsData = await aptos.getAccountCoinsData({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * limit: 10, // specify the number of results to return\n * orderBy: { asset_type: \"asc\" }, // specify the order of results\n * },\n * });\n *\n * console.log(accountCoinsData);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * Retrieves the current count of an account's coins aggregated across all types.\n *\n * @param args The parameters for the account coins count query.\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 The current count of the aggregated coins for the specified account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Getting the account coins count for a specific account\n * const accountCoinsCount = await aptos.getAccountCoinsCount({ accountAddress: \"0x1\" }); // replace with a real account address\n * console.log(\"Account Coins Count:\", accountCoinsCount);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\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 * Retrieves the current amount of APT for a specified account. If the account does not exist, it will return 0.\n *\n * @param args The arguments for the account query.\n * @param args.accountAddress The account address for which to retrieve the APT amount.\n * @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.\n * @returns The current amount of APT for the specified account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the APT amount for a specific account\n * const accountAPTAmount = await aptos.getAccountAPTAmount({ accountAddress: \"0x1\" }); // replace with a real account address\n * console.log(\"Account APT Amount:\", accountAPTAmount);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n async getAccountAPTAmount(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n return this.getAccountCoinAmount({ coinType: APTOS_COIN, faMetadataAddress: APTOS_FA, ...args });\n }\n\n /**\n * Queries the current amount of a specified coin held by an account.\n *\n * @deprecated Use `getBalance({ accountAddress, asset })` instead.\n * This method is slated for removal in a future release.\n *\n * @param args The parameters for querying the account's coin amount.\n * @param args.accountAddress The account address to query for the coin amount.\n * @param args.coinType The coin type to query. Note: If not provided, it may be automatically populated if `faMetadataAddress`\n * is specified.\n * @param args.faMetadataAddress The fungible asset metadata address to query. Note: If not provided, it may be automatically\n * populated if `coinType` is specified.\n * @returns The current amount of the specified coin held by the account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Prefer the new API\n * const amount = await aptos.getBalance({ accountAddress: \"0x1\", asset: \"0x1::aptos_coin::AptosCoin\" });\n * console.log(`Balance: ${amount}`);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n async getAccountCoinAmount(args: {\n accountAddress: AccountAddressInput;\n coinType?: MoveStructId;\n faMetadataAddress?: AccountAddressInput;\n }): Promise<number> {\n const { accountAddress, coinType, faMetadataAddress } = args;\n\n // Attempt to populate the CoinType field if the FA address is provided.\n // We cannot do this internally due to dependency cycles issue.\n let coinAssetType: MoveStructId | undefined = coinType;\n if (coinType === undefined && faMetadataAddress !== undefined) {\n coinAssetType = await memoizeAsync(\n async () => {\n try {\n const pairedCoinTypeStruct = (\n await view<[{ vec: [MoveStructId] }]>({\n aptosConfig: this.config,\n payload: { function: \"0x1::coin::paired_coin\", functionArguments: [faMetadataAddress] },\n })\n )[0];\n\n // Check if the Option has a value, and if so, parse the struct\n if (pairedCoinTypeStruct.vec.length > 0 && isEncodedStruct(pairedCoinTypeStruct.vec[0])) {\n return parseEncodedStruct(pairedCoinTypeStruct.vec[0]);\n }\n } catch (error) {\n /* No paired coin type found */\n }\n return undefined;\n },\n `coin-mapping-${faMetadataAddress.toString()}`,\n 1000 * 60 * 5, // 5 minutes\n )();\n }\n\n let faAddress: string;\n\n if (coinType !== undefined && faMetadataAddress !== undefined) {\n faAddress = AccountAddress.from(faMetadataAddress).toStringLong();\n } else if (coinType !== undefined && faMetadataAddress === undefined) {\n // TODO Move to a separate function as defined in the AIP for coin migration\n if (coinType === APTOS_COIN) {\n faAddress = AccountAddress.A.toStringLong();\n } else {\n faAddress = createObjectAddress(AccountAddress.A, coinType).toStringLong();\n }\n } else if (coinType === undefined && faMetadataAddress !== undefined) {\n const addr = AccountAddress.from(faMetadataAddress);\n faAddress = addr.toStringLong();\n if (addr === AccountAddress.A) {\n coinAssetType = APTOS_COIN;\n }\n // The paired CoinType should be populated outside of this function in another\n // async call. We cannot do this internally due to dependency cycles issue.\n } else {\n throw new Error(\"Either coinType, faMetadataAddress, or both must be provided\");\n }\n\n // When there is a coin mapping, use that first, otherwise use the fungible asset address\n // TODO: This function's signature at the top, returns number, but it could be greater than can be represented\n if (coinAssetType !== undefined) {\n const [balanceStr] = await view<[string]>({\n aptosConfig: this.config,\n payload: {\n function: \"0x1::coin::balance\",\n typeArguments: [coinAssetType],\n functionArguments: [accountAddress],\n },\n });\n return parseInt(balanceStr, 10);\n }\n const [balanceStr] = await view<[string]>({\n aptosConfig: this.config,\n payload: {\n function: \"0x1::primary_fungible_store::balance\",\n typeArguments: [\"0x1::object::ObjectCore\"],\n functionArguments: [accountAddress, faAddress],\n },\n });\n return parseInt(balanceStr, 10);\n }\n\n /**\n * Retrieves the balance for an account and asset.\n *\n * @param args The parameters for the balance query.\n * @param args.accountAddress The account address to query.\n * @param args.asset The asset to query: Move struct ID (e.g., `0x1::aptos_coin::AptosCoin`) or FA metadata address.\n * @returns The balance as a number.\n *\n * @example\n * ```ts\n * const aptos = new Aptos(new AptosConfig());\n * // APT coin by type\n * const apt = await aptos.getBalance({ accountAddress: \"0x1\", asset: \"0x1::aptos_coin::AptosCoin\" });\n * // Some FA by metadata address\n * const fa = await aptos.getBalance({ accountAddress: \"0x1\", asset: \"0xa\" });\n * ```\n * @group Account\n */\n async getBalance(args: {\n accountAddress: AccountAddressInput;\n asset: MoveStructId | AccountAddressInput;\n }): Promise<number> {\n return getBalance({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries an account's owned objects.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the objects owned by the specified account\n * const accountOwnedObjects = await aptos.getAccountOwnedObjects({\n * accountAddress: \"0x1\", // replace with a real account address\n * minimumLedgerVersion: 1, // optional, specify if needed\n * options: {\n * offset: 0, // optional, specify if needed\n * limit: 10, // optional, specify if needed\n * orderBy: \"created_at\", // optional, specify if needed\n * },\n * });\n *\n * console.log(accountOwnedObjects);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n */\n async getAccountOwnedObjects(args: {\n accountAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]>;\n }): Promise<GetObjectDataQueryResponse> {\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. This function resolves the provided private key type and derives the public\n * key from it.\n *\n * If the privateKey is a Secp256k1 type, it derives the account using the derived public key and auth key using the SingleKey\n * scheme locally.\n * If the privateKey is an ED25519 type, it looks up the authentication key on chain to determine whether it is a Legacy ED25519\n * key or a Unified ED25519 key, and then derives the account based on that.\n *\n * @param args - The arguments for deriving the account.\n * @param args.privateKey - An account private key.\n * @returns The derived Account type.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Ed25519PrivateKey } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Deriving an account from a private key\n * const account = await aptos.deriveAccountFromPrivateKey({\n * privateKey: new Ed25519PrivateKey(\"0x123\") // replace with a real private key\n * });\n *\n * console.log(account);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Account\n * @deprecated Note that more inspection is needed by the user to determine which account exists on-chain\n */\n async deriveAccountFromPrivateKey(args: {\n privateKey: PrivateKeyInput;\n minimumLedgerVersion?: AnyNumber;\n options?: {\n throwIfNoAccountFound?: boolean;\n };\n }): Promise<AccountModule> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.ACCOUNT_RESTORATION_PROCESSOR,\n });\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.OBJECT_PROCESSOR,\n });\n return deriveAccountFromPrivateKey({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Derives all accounts owned by a signer. This function takes a signer (either an Account or PrivateKey)\n * and returns all accounts that can be derived from it, ordered by the most recently used account first.\n *\n * Note, this function will not return accounts that require more than one signer to be used.\n *\n * @param args - The arguments for deriving owned accounts\n * @param args.signer - The signer to derive accounts from (Account or PrivateKey)\n * @param args.minimumLedgerVersion - The minimum ledger version to wait for before querying\n * @param args.options.includeUnverified - Whether to include unverified accounts in the results. Unverified accounts\n * are accounts that can be authenticated with the signer, but there is no history of the signer using the account.\n * Default is false.\n * @param args.options.noMultiKey - If true, do not include multi-key accounts in the results. Default is false.\n * @returns Promise resolving to an array of derived Account objects\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Ed25519Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function getOwnedAccounts() {\n * const signer = Ed25519Account.generate();\n * const accounts = await aptos.deriveOwnedAccountsFromSigner({\n * signer\n * });\n * const account = accounts[0];\n * console.log(account);\n * }\n * ```\n * @group Account\n */\n async deriveOwnedAccountsFromSigner(args: {\n signer: AccountModule | PrivateKeyInput;\n minimumLedgerVersion?: AnyNumber;\n options?: { includeUnverified?: boolean; noMultiKey?: boolean };\n }): Promise<AccountModule[]> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.ACCOUNT_RESTORATION_PROCESSOR,\n });\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.OBJECT_PROCESSOR,\n });\n return deriveOwnedAccountsFromSigner({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Gets all account info (address, account public key, last transaction version) that have are associated with a public key and **related public keys**\n *\n * For a given public key, it will query all multikeys that the public key is part of. Then for the provided public key and\n * any multikeys found in the previous step, it will query for any accounts that have an auth key that matches any of the\n * public keys.\n *\n * Note: If an Ed25519PublicKey or an AnyPublicKey that wraps Ed25519PublicKey is passed in, it will query for both legacy and single singer cases.\n *\n * @param args - The arguments for getting accounts for a public key\n * @param args.publicKey - The public key to look up accounts for\n * @param args.minimumLedgerVersion - The minimum ledger version to wait for before querying\n * @param args.options.includeUnverified - Whether to include unverified accounts in the results. Unverified accounts\n * are accounts that can be authenticated with the signer, but there is no history of the signer using the account. Default\n * is false.\n * @param args.options.noMultiKey - Whether to exclude multi-key accounts in the results. Default is false.\n * @returns Promise resolving to an array of account addresses and their associated public keys\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Ed25519PrivateKey } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function getAccounts() {\n * const privateKey = Ed25519PrivateKey.generate();\n * const publicKey = privateKey.publicKey();\n * const accounts = await aptos.getAccountsForPublicKey({\n * publicKey\n * });\n * console.log(accounts);\n * }\n * ```\n * @group Account\n */\n async getAccountsForPublicKey(args: {\n publicKey: BaseAccountPublicKey;\n minimumLedgerVersion?: AnyNumber;\n options?: { includeUnverified?: boolean; noMultiKey?: boolean };\n }): Promise<AccountInfo[]> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.ACCOUNT_RESTORATION_PROCESSOR,\n });\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.OBJECT_PROCESSOR,\n });\n return getAccountsForPublicKey({\n aptosConfig: this.config,\n ...args,\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\n/**\n * Generates a transaction to transfer coins from one account to another.\n * This function allows you to specify the sender, recipient, amount, and coin type for the transaction.\n *\n * @param args - The parameters for the transaction.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.sender - The address of the account sending the coins.\n * @param args.recipient - The address of the account receiving the coins.\n * @param args.amount - The amount of coins to transfer.\n * @param args.coinType - (Optional) The type of coin to transfer, defaults to Aptos Coin if not specified.\n * @param args.options - (Optional) Options for generating the transaction.\n * @group Implementation\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 * @group Coin\n */\nexport class Coin {\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a new Aptos client with testnet configuration\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Coin\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Generate a transfer coin transaction that can be simulated, signed, and submitted.\n * This function helps you create a transaction to transfer a specified amount of coins\n * from one account to another within the Aptos network.\n *\n * @param args The arguments for the transfer transaction.\n * @param args.sender The sender account address.\n * @param args.recipient The recipient account address.\n * @param args.amount The amount of coins to transfer.\n * @param args.coinType Optional. The coin struct type to transfer. Defaults to 0x1::aptos_coin::AptosCoin.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns SimpleTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Generate a transfer coin transaction\n * const transaction = await aptos.transferCoinTransaction({\n * sender: \"0x1\", // replace with a real sender account address\n * recipient: \"0x2\", // replace with a real recipient account address\n * amount: 10,\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Coin\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 * @group Implementation\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { Bool, MoveString, MoveVector, U64 } from \"../bcs\";\nimport { AccountAddress, AccountAddressInput } from \"../core\";\nimport { Account } from \"../account\";\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 WhereArg,\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 {\n CurrentCollectionsV2BoolExp,\n CurrentTokenOwnershipsV2BoolExp,\n TokenActivitiesV2BoolExp,\n} 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\n/**\n * The keys of the PropertyTypeMap, representing different property types.\n * @group Implementation\n */\nexport type PropertyType = keyof typeof PropertyTypeMap;\n\n/**\n * Accepted property value types for user input, including boolean, number, bigint, string, AccountAddress, and Uint8Array.\n * To pass in an Array, use Uint8Array type\n * for example `new MoveVector([new MoveString(\"hello\"), new MoveString(\"world\")]).bcsToBytes()`\n * @group Implementation\n */\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\n/**\n * Retrieves data for a specific digital asset using its address.\n *\n * @param args - The arguments for fetching digital asset data.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.digitalAssetAddress - The address of the digital asset to retrieve data for.\n * @returns The data of the specified digital asset.\n * @group Implementation\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\n/**\n * Retrieves the current ownership details of a specified digital asset.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.digitalAssetAddress - The address of the digital asset to query ownership for.\n * @returns The current ownership details of the specified digital asset.\n * @group Implementation\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\n/**\n * Retrieves the digital assets owned by a specified account address.\n *\n * @param args - The arguments for retrieving owned digital assets.\n * @param args.aptosConfig - The configuration for connecting to the Aptos network.\n * @param args.ownerAddress - The address of the account whose owned digital assets are being queried.\n * @param args.options - Optional pagination and ordering parameters for the query.\n * @param args.options.offset - The number of records to skip for pagination.\n * @param args.options.limit - The maximum number of records to return.\n * @param args.options.orderBy - The criteria for ordering the results.\n *\n * @returns An array of digital assets currently owned by the specified account.\n * @group Implementation\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\n/**\n * Retrieves the activity associated with a specific digital asset.\n * This function allows you to track the token activities for a given digital asset address.\n *\n * @param args - The arguments for retrieving digital asset activity.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.digitalAssetAddress - The address of the digital asset to query.\n * @param args.options - Optional parameters for pagination and ordering.\n * @param args.options.offset - The number of records to skip before starting to collect the result set.\n * @param args.options.limit - The maximum number of records to return.\n * @param args.options.orderBy - The criteria to order the results by.\n * @returns A promise that resolves to an array of token activities for the specified digital asset.\n * @group Implementation\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\n/**\n * Options for creating a collection, allowing customization of various attributes such as supply limits, mutability of metadata,\n * and royalty settings.\n *\n * @param maxSupply - Maximum number of tokens that can be minted in the collection.\n * @param mutableDescription - Indicates if the collection description can be changed after creation.\n * @param mutableRoyalty - Indicates if the royalty settings can be modified after creation.\n * @param mutableURI - Indicates if the collection URI can be updated.\n * @param mutableTokenDescription - Indicates if individual token descriptions can be modified.\n * @param mutableTokenName - Indicates if individual token names can be changed.\n * @param mutableTokenProperties - Indicates if individual token properties can be altered.\n * @param mutableTokenURI - Indicates if individual token URIs can be updated.\n * @param tokensBurnableByCreator - Indicates if the creator can burn tokens from the collection.\n * @param tokensFreezableByCreator - Indicates if the creator can freeze tokens in the collection.\n * @param royaltyNumerator - The numerator for calculating royalties.\n * @param royaltyDenominator - The denominator for calculating royalties.\n * @group Implementation\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\n/**\n * Creates a new collection transaction on the Aptos blockchain.\n * This function allows you to define the properties of the collection, including its name, description, and URI.\n *\n * @param args - The parameters for creating the collection transaction.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.creator - The account that will create the collection.\n * @param args.description - A description of the collection.\n * @param args.name - The name of the collection.\n * @param args.uri - The URI associated with the collection.\n * @param args.options - Optional parameters for generating the transaction.\n * @param args.maxSupply - The maximum supply of tokens in the collection (optional).\n * @param args.mutableDescription - Indicates if the collection description can be changed (optional, defaults to true).\n * @param args.mutableRoyalty - Indicates if the royalty settings can be changed (optional, defaults to true).\n * @param args.mutableURI - Indicates if the URI can be changed (optional, defaults to true).\n * @param args.mutableTokenDescription - Indicates if the token description can be changed (optional, defaults to true).\n * @param args.mutableTokenName - Indicates if the token name can be changed (optional, defaults to true).\n * @param args.mutableTokenProperties - Indicates if the token properties can be changed (optional, defaults to true).\n * @param args.mutableTokenURI - Indicates if the token URI can be changed (optional, defaults to true).\n * @param args.tokensBurnableByCreator - Indicates if tokens can be burned by the creator (optional, defaults to true).\n * @param args.tokensFreezableByCreator - Indicates if tokens can be frozen by the creator (optional, defaults to true).\n * @param args.royaltyNumerator - The numerator for calculating royalties (optional, defaults to 0).\n * @param args.royaltyDenominator - The denominator for calculating royalties (optional, defaults to 1).\n * @group Implementation\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\n/**\n * Retrieves data for the current collections based on specified options.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.options - Optional parameters for filtering and pagination.\n * @param args.options.tokenStandard - The token standard to filter the collections (default is \"v2\").\n * @param args.options.offset - The offset for pagination.\n * @param args.options.limit - The limit for pagination.\n * @param args.options.where - The conditions to filter the collections.\n * @returns The data of the current collections.\n * @group Implementation\n */\nexport async function getCollectionData(args: {\n aptosConfig: AptosConfig;\n options?: TokenStandardArg & PaginationArgs & WhereArg<CurrentCollectionsV2BoolExp>;\n}): Promise<GetCollectionDataResponse> {\n const { aptosConfig, options } = args;\n\n const whereCondition: any = options?.where;\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 offset: options?.offset,\n limit: options?.limit,\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\n/**\n * Retrieves collection data based on the creator's address and the collection name.\n *\n * @param args - The arguments for retrieving the collection data.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.creatorAddress - The address of the creator whose collection data is being retrieved.\n * @param args.collectionName - The name of the collection to fetch data for.\n * @param args.options - Optional parameters for filtering the results, including token standard and pagination options.\n * @param args.options.tokenStandard - The token standard to filter the results by (optional).\n * @param args.options.pagination - Pagination options for the results (optional).\n * @group Implementation\n */\nexport async function getCollectionDataByCreatorAddressAndCollectionName(args: {\n aptosConfig: AptosConfig;\n creatorAddress: AccountAddressInput;\n collectionName: string;\n options?: TokenStandardArg & PaginationArgs;\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 if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard ?? \"v2\" };\n }\n\n return getCollectionData({ aptosConfig, options: { ...options, where: whereCondition } });\n}\n\n/**\n * Retrieves collection data associated with a specific creator's address.\n * This function allows you to filter the collections based on the creator's address and optional token standards.\n *\n * @param args - The arguments for retrieving collection data.\n * @param args.aptosConfig - The configuration for the Aptos network.\n * @param args.creatorAddress - The address of the creator whose collection data is being retrieved.\n * @param args.options - Optional parameters for filtering the results.\n * @param args.options.tokenStandard - The token standard to filter the collections by.\n * @param args.options.pagination - Pagination options for the results.\n * @group Implementation\n */\nexport async function getCollectionDataByCreatorAddress(args: {\n aptosConfig: AptosConfig;\n creatorAddress: AccountAddressInput;\n options?: TokenStandardArg & PaginationArgs;\n}): Promise<GetCollectionDataResponse> {\n const { aptosConfig, creatorAddress, options } = args;\n const address = AccountAddress.from(creatorAddress);\n\n const whereCondition: any = {\n creator_address: { _eq: address.toStringLong() },\n };\n if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard ?? \"v2\" };\n }\n\n return getCollectionData({ aptosConfig, options: { ...options, where: whereCondition } });\n}\n\n/**\n * Retrieves data for a specific collection using its unique identifier.\n * This function allows you to filter the collection data based on the token standard and pagination options.\n *\n * @param args - The arguments for retrieving collection data.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.collectionId - The unique identifier for the collection.\n * @param args.options - Optional parameters for filtering by token standard and pagination.\n * @param args.options.tokenStandard - The standard of the token to filter the collection data.\n * @param args.options.page - The page number for pagination.\n * @param args.options.limit - The number of items per page for pagination.\n * @group Implementation\n */\nexport async function getCollectionDataByCollectionId(args: {\n aptosConfig: AptosConfig;\n collectionId: AccountAddressInput;\n options?: TokenStandardArg & PaginationArgs;\n}): Promise<GetCollectionDataResponse> {\n const { aptosConfig, collectionId, options } = args;\n const address = AccountAddress.from(collectionId);\n\n const whereCondition: any = {\n collection_id: { _eq: address.toStringLong() },\n };\n\n if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard ?? \"v2\" };\n }\n\n return getCollectionData({ aptosConfig, options: { ...options, where: whereCondition } });\n}\n\n/**\n * Retrieves the collection ID based on the creator's address and the collection name.\n * This function helps in identifying a specific collection within the Aptos ecosystem.\n *\n * @param args - The parameters for retrieving the collection ID.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.creatorAddress - The address of the creator of the collection.\n * @param args.collectionName - The name of the collection to look up.\n * @param args.options - Optional parameters for additional filtering.\n * @param args.options.tokenStandard - The token standard to filter the collection (default is \"v2\").\n * @returns The ID of the specified collection.\n * @group Implementation\n */\nexport async function getCollectionId(args: {\n aptosConfig: AptosConfig;\n creatorAddress: AccountAddressInput;\n collectionName: string;\n options?: TokenStandardArg;\n}): Promise<string> {\n const { creatorAddress, collectionName, options, aptosConfig } = 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 if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard ?? \"v2\" };\n }\n\n return (await getCollectionData({ aptosConfig, options: { where: whereCondition } })).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\n/**\n * Creates a transaction to mint a digital asset on the Aptos blockchain.\n * This function allows you to specify various attributes of the asset, including its collection, description, name, and URI.\n *\n * @param args - The arguments for minting the digital asset.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.creator - The account that will create the digital asset.\n * @param args.collection - The name of the collection to which the asset belongs.\n * @param args.description - A brief description of the digital asset.\n * @param args.name - The name of the digital asset.\n * @param args.uri - The URI pointing to the asset's metadata.\n * @param [args.propertyKeys] - Optional array of property keys associated with the asset.\n * @param [args.propertyTypes] - Optional array of property types corresponding to the asset's properties.\n * @param [args.propertyValues] - Optional array of property values for the asset's properties.\n * @param [args.options] - Optional transaction generation options.\n * @group Implementation\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\n /**\n * Retrieves the raw values of specified properties from an array of property values based on their types.\n *\n * @param propertyValues - An array of property values from which to extract the raw data.\n * @param propertyTypes - An array of strings representing the types of properties to retrieve.\n * @returns An array of Uint8Array containing the raw values for the specified property types.\n * @group Implementation\n */\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\n/**\n * Initiates a transaction to transfer a digital asset from one account to another.\n * This function helps in executing the transfer of digital assets securely and efficiently.\n *\n * @param args - The arguments required to perform the transfer.\n * @param args.aptosConfig - Configuration settings for the Aptos client.\n * @param args.sender - The account initiating the transfer.\n * @param args.digitalAssetAddress - The address of the digital asset being transferred.\n * @param args.recipient - The address of the account receiving the digital asset.\n * @param args.digitalAssetType - (Optional) The type of the digital asset being transferred.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Creates a transaction to mint a soul-bound token.\n * This function allows you to specify the token's attributes and recipient, facilitating the creation of unique digital assets.\n *\n * @param args - The parameters required to mint the soul-bound token.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.account - The account initiating the minting transaction.\n * @param args.collection - The name of the collection to which the token belongs.\n * @param args.description - A description of the token being minted.\n * @param args.name - The name of the token.\n * @param args.uri - The URI pointing to the token's metadata.\n * @param args.recipient - The address of the account that will receive the minted token.\n * @param [args.propertyKeys] - Optional array of property keys associated with the token.\n * @param [args.propertyTypes] - Optional array of property types corresponding to the property keys.\n * @param [args.propertyValues] - Optional array of property values that match the property keys and types.\n * @param [args.options] - Optional transaction generation options.\n * @throws Error if the counts of property keys, property types, and property values do not match.\n * @group Implementation\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\n/**\n * Creates a transaction to burn a specified digital asset.\n * This function allows users to permanently remove a digital asset from their account.\n *\n * @param args - The arguments for the transaction.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.creator - The account that is initiating the burn transaction.\n * @param args.digitalAssetAddress - The address of the digital asset to be burned.\n * @param args.digitalAssetType - Optional; the type of the digital asset being burned.\n * @param args.options - Optional; additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Creates a transaction to freeze the transfer of a digital asset.\n * This function helps you prevent the transfer of a specified digital asset by generating the appropriate transaction.\n *\n * @param args - The parameters for the transaction.\n * @param args.aptosConfig - The configuration settings for the Aptos client.\n * @param args.creator - The account that is creating the transaction.\n * @param args.digitalAssetAddress - The address of the digital asset to be frozen.\n * @param args.digitalAssetType - (Optional) The type of the digital asset as a Move struct ID.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Unfreezes a digital asset transfer transaction, allowing the transfer of the specified digital asset.\n *\n * @param args - The arguments for unfreezing the digital asset transfer transaction.\n * @param args.aptosConfig - The Aptos configuration settings.\n * @param args.creator - The account that is initiating the unfreeze transaction.\n * @param args.digitalAssetAddress - The address of the digital asset to be unfrozen.\n * @param args.digitalAssetType - (Optional) The type of the digital asset being unfrozen.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Sets the description for a digital asset, allowing users to provide additional context or information about the asset.\n *\n * @param args - The arguments for setting the digital asset description.\n * @param args.aptosConfig - The Aptos configuration to use for the transaction.\n * @param args.creator - The account that is creating the transaction.\n * @param args.description - The new description for the digital asset.\n * @param args.digitalAssetAddress - The address of the digital asset whose description is being set.\n * @param args.digitalAssetType - (Optional) The type of the digital asset.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Sets the name of a digital asset on the Aptos blockchain.\n * This function allows you to update the name of a specified digital asset, enabling better identification and categorization.\n *\n * @param args - The parameters for setting the digital asset name.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.creator - The account that is creating the transaction.\n * @param args.name - The new name to assign to the digital asset.\n * @param args.digitalAssetAddress - The address of the digital asset to update.\n * @param args.digitalAssetType - (Optional) The type of the digital asset, represented as a Move struct ID.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Sets the URI for a digital asset, allowing you to update the metadata associated with it.\n *\n * @param args - The arguments for setting the digital asset URI.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.creator - The account that is creating the transaction.\n * @param args.uri - The new URI to be set for the digital asset.\n * @param args.digitalAssetAddress - The address of the digital asset whose URI is being set.\n * @param args.digitalAssetType - The optional type of the digital asset; defaults to a predefined type if not provided.\n * @param args.options - Optional settings for generating the transaction.\n * @group Implementation\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\n/**\n * Creates a transaction to add a property to a digital asset.\n * This function helps in enhancing the metadata associated with a digital asset by allowing the addition of custom properties.\n *\n * @param args - The arguments for the transaction.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.creator - The account that is creating the transaction.\n * @param args.propertyKey - The key for the property being added.\n * @param args.propertyType - The type of the property being added.\n * @param args.propertyValue - The value of the property being added.\n * @param args.digitalAssetAddress - The address of the digital asset to which the property is being added.\n * @param args.digitalAssetType - The optional type of the digital asset.\n * @param args.options - Optional transaction generation options.\n * @group Implementation\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\n/**\n * Removes a property from a digital asset on the Aptos blockchain.\n * This function helps in managing the attributes of digital assets by allowing the removal of specific properties.\n *\n * @param args - The arguments for the transaction.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.creator - The account that is creating the transaction.\n * @param args.propertyKey - The key of the property to be removed.\n * @param args.digitalAssetAddress - The address of the digital asset from which the property will be removed.\n * @param args.digitalAssetType - The type of the digital asset (optional).\n * @param args.options - Additional options for generating the transaction (optional).\n * @group Implementation\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\n/**\n * Updates a property of a digital asset by generating a transaction for the Aptos blockchain.\n * This function allows you to modify attributes of a digital asset, facilitating dynamic changes to its properties.\n *\n * @param args - The arguments for updating the digital asset property.\n * @param args.aptosConfig - The configuration settings for the Aptos blockchain.\n * @param args.creator - The account that is creating the transaction.\n * @param args.propertyKey - The key of the property to be updated.\n * @param args.propertyType - The type of the property being updated.\n * @param args.propertyValue - The new value for the property.\n * @param args.digitalAssetAddress - The address of the digital asset to update.\n * @param args.digitalAssetType - (Optional) The type of the digital asset.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n /**\n * Retrieves the raw byte representation of a single property value based on its type.\n *\n * @param propertyValue - The value of the property to convert.\n * @param propertyType - The type of the property, which determines how the value is processed.\n * @returns The raw byte representation of the property value.\n * @group Implementation\n */\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\n/**\n * Creates a transaction to add a typed property to a digital asset.\n * This function helps in customizing digital assets by associating them with specific properties.\n *\n * @param args - The arguments required to create the transaction.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.creator - The account that is creating the transaction.\n * @param args.propertyKey - The key for the property being added.\n * @param args.propertyType - The type of the property being added.\n * @param args.propertyValue - The value of the property being added.\n * @param args.digitalAssetAddress - The address of the digital asset to which the property is being added.\n * @param args.digitalAssetType - (Optional) The type of the digital asset.\n * @param args.options - (Optional) Additional options for generating the transaction.\n * @group Implementation\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\n/**\n * Updates the typed property of a digital asset by generating a transaction for the Aptos blockchain.\n *\n * @param args - The arguments for updating the digital asset typed property.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.creator - The account that is creating the transaction.\n * @param args.propertyKey - The key of the property to be updated.\n * @param args.propertyType - The type of the property being updated.\n * @param args.propertyValue - The new value for the property.\n * @param args.digitalAssetAddress - The address of the digital asset to be updated.\n * @param args.digitalAssetType - Optional. The type of the digital asset, if not provided, defaults to the standard type.\n * @param args.options - Optional. Additional options for generating the transaction.\n * @group Implementation\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 { AccountAddress, AccountAddressInput } from \"../core\";\nimport { Account } from \"../account\";\nimport { InputGenerateTransactionOptions } from \"../transactions/types\";\nimport {\n addDigitalAssetPropertyTransaction,\n addDigitalAssetTypedPropertyTransaction,\n burnDigitalAssetTransaction,\n CreateCollectionOptions,\n createCollectionTransaction,\n freezeDigitalAssetTransferTransaction,\n getCollectionData,\n getCollectionDataByCollectionId,\n getCollectionDataByCreatorAddress,\n getCollectionDataByCreatorAddressAndCollectionName,\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 * @group DigitalAsset\n */\nexport class DigitalAsset {\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your desired network\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries data of a specific collection by the collection creator address and the collection name.\n * This function is deprecated; use `getCollectionDataByCreatorAddressAndCollectionName` instead.\n *\n * If a creator account has two collections with the same name in v1 and v2, you can pass an optional `tokenStandard` parameter\n * to query a specific standard.\n *\n * @param args - The arguments for querying the collection data.\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 - Optional parameters for the query.\n * @param args.options.tokenStandard - The token standard to query.\n * @returns GetCollectionDataResponse - The response type containing the collection data.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Querying collection data by creator address and collection name\n * const collection = await aptos.getCollectionData({\n * creatorAddress: \"0x1\", // replace with a real creator address\n * collectionName: \"myCollection\", // specify your collection name\n * });\n *\n * console.log(collection);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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\n const { 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 if (options?.tokenStandard) {\n whereCondition.token_standard = { _eq: options?.tokenStandard ?? \"v2\" };\n }\n\n return getCollectionData({ aptosConfig: this.config, options: { where: whereCondition } });\n }\n\n /**\n * Queries data of a specific collection by the collection creator address and the collection name.\n * If a creator account has multiple collections with the same name across different versions,\n * specify the `tokenStandard` parameter to query a specific standard.\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 - Optional token standard to query.\n * @returns GetCollectionDataResponse - The response type containing collection data.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching collection data by creator address and collection name\n * const collection = await aptos.getCollectionDataByCreatorAddressAndCollectionName({\n * creatorAddress: \"0x1\", // replace with a real creator address\n * collectionName: \"myCollection\",\n * minimumLedgerVersion: 1, // optional, specify if needed\n * options: { tokenStandard: \"v2\" } // optional, specify if needed\n * });\n *\n * console.log(collection);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\n */\n async getCollectionDataByCreatorAddressAndCollectionName(args: {\n creatorAddress: AccountAddressInput;\n collectionName: string;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg & PaginationArgs;\n }): Promise<GetCollectionDataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n\n return getCollectionDataByCreatorAddressAndCollectionName({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Retrieves data for a specific collection created by a given creator address.\n * This function allows you to query collection data while optionally specifying a minimum ledger version and pagination options.\n *\n * @param args.creatorAddress - The address of the collection's creator.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n * @param args.options.tokenStandard - Optional token standard to query.\n * @param args.options.pagination - Optional pagination arguments.\n * @returns GetCollectionDataResponse - The response type containing collection data.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve collection data by creator address\n * const collectionData = await aptos.getCollectionDataByCreatorAddress({\n * creatorAddress: \"0x1\", // replace with a real creator address\n * minimumLedgerVersion: 1, // specify the minimum ledger version if needed\n * options: {\n * tokenStandard: \"v2\", // specify the token standard if needed\n * pagination: { limit: 10, offset: 0 } // specify pagination options if needed\n * }\n * });\n *\n * console.log(collectionData);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\n */\n async getCollectionDataByCreatorAddress(args: {\n creatorAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg & PaginationArgs;\n }): Promise<GetCollectionDataResponse> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.TOKEN_V2_PROCESSOR,\n });\n\n return getCollectionDataByCreatorAddress({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries data of a specific collection by the collection ID.\n *\n * @param args.collectionId - The ID of the collection, which is the same as the address of the collection object.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n * @param args.options - Optional parameters for token standard and pagination.\n * @returns GetCollectionDataResponse - The response type containing the collection data.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching collection data by collection ID\n * const collection = await aptos.getCollectionDataByCollectionId({\n * collectionId: \"0x123\", // replace with a real collection ID\n * });\n *\n * console.log(collection);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\n */\n async getCollectionDataByCollectionId(args: {\n collectionId: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: TokenStandardArg & PaginationArgs;\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 the ID of a specified collection.\n * This ID corresponds to the collection's object address in V2, while V1 does not utilize objects and lacks an address.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching the collection ID for a specific creator and collection name\n * const collectionId = await aptos.getCollectionId({\n * creatorAddress: \"0x1\", // replace with a real creator address\n * collectionName: \"myCollection\"\n * });\n *\n * console.log(\"Collection ID:\", collectionId);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 * Retrieves digital asset data using the address of a digital asset.\n *\n * @param args - The parameters for the request.\n * @param args.digitalAssetAddress - 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 for the digital asset.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching digital asset data for a specific address\n * const digitalAsset = await aptos.getDigitalAssetData({\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(digitalAsset);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 * Retrieves the current ownership data of a specified digital asset using its address.\n *\n * @param args The parameters for the request.\n * @param args.digitalAssetAddress 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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Getting the current ownership of a digital asset\n * const digitalAssetOwner = await aptos.getCurrentDigitalAssetOwnership({\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(digitalAssetOwner);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 * Retrieves the digital assets owned by a specified address.\n *\n * @param args.ownerAddress The address of the owner.\n * @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.\n * @param args.options Optional pagination and ordering parameters for the response.\n *\n * @returns GetOwnedTokensResponse containing ownership data of the digital assets belonging to the ownerAddress.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching the digital assets owned by the specified address\n * const digitalAssets = await aptos.getOwnedDigitalAssets({\n * ownerAddress: \"0x1\", // replace with a real account address\n * });\n *\n * console.log(digitalAssets);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 * Retrieves the activity data for a specified digital asset using its address.\n *\n * @param args - The parameters for the request.\n * @param args.digitalAssetAddress - The address of the digital asset.\n * @param args.minimumLedgerVersion - Optional minimum ledger version to sync up to before querying.\n * @param args.options - Optional pagination and ordering parameters.\n *\n * @returns A promise that resolves to the activity data related to the digital asset.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the activity data for a digital asset\n * const digitalAssetActivity = await aptos.getDigitalAssetActivity({\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(digitalAssetActivity);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 * @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 * @param args.options - Optional parameters for generating the transaction.\n *\n * The parameters below are optional:\n * @param args.maxSupply - Controls the max supply of the digital assets. Defaults to MAX_U64_BIG_INT.\n * @param args.mutableDescription - Controls mutability of the collection's description. Defaults to true.\n * @param args.mutableRoyalty - Controls mutability of the collection's royalty. Defaults to true.\n * @param args.mutableUri - Controls mutability of the collection's URI. Defaults to true.\n * @param args.mutableTokenDescription - Controls mutability of the digital asset's description. Defaults to true.\n * @param args.mutableTokenName - Controls mutability of the digital asset's name. Defaults to true.\n * @param args.mutableTokenProperties - Controls mutability of digital asset's properties. Defaults to true.\n * @param args.mutableTokenUri - Controls mutability of the digital asset's URI. Defaults to true.\n * @param args.tokensBurnableByCreator - Controls whether digital assets can be burnable by the creator. Defaults to true.\n * @param args.tokensFreezableByCreator - Controls whether digital assets can be frozen by the creator. Defaults to true.\n * @param args.royaltyNumerator - The numerator of the royalty to be paid to the creator when a digital asset is transferred.\n * Defaults to 0.\n * @param args.royaltyDenominator - The denominator of the royalty to be paid to the creator when a digital asset is\n * transferred. Defaults to 1.\n *\n * @returns A SimpleTransaction that when submitted will create the collection.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Creating a new collection transaction\n * const transaction = await aptos.createCollectionTransaction({\n * creator: Account.generate(), // Replace with a real account\n * description: \"A unique collection of digital assets.\",\n * name: \"My Digital Collection\",\n * uri: \"https://mycollection.com\",\n * });\n *\n * console.log(\"Transaction created:\", transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 creator's account within an existing collection.\n * This function helps you generate a transaction that can be simulated or submitted to the blockchain for minting a digital asset.\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 * @param args.propertyKeys - Optional array of property keys for the digital asset.\n * @param args.propertyTypes - Optional array of property types for the digital asset.\n * @param args.propertyValues - Optional array of property values for the digital asset.\n * @param args.options - Optional transaction generation options.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Creating a transaction to mint a digital asset\n * const transaction = await aptos.mintDigitalAssetTransaction({\n * creator: Account.generate(), // replace with a real account\n * collection: \"MyCollection\",\n * description: \"This is a digital asset.\",\n * name: \"MyDigitalAsset\",\n * uri: \"https://example.com/my-digital-asset\",\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 ownership of a non-fungible digital asset.\n * This function allows you to transfer a digital asset only if it is not frozen, meaning the ownership transfer is not disabled.\n *\n * @param args The arguments for transferring the digital asset.\n * @param args.sender The sender account of the current digital asset owner.\n * @param args.digitalAssetAddress The address of the digital asset being transferred.\n * @param args.recipient The account address of the recipient.\n * @param args.digitalAssetType Optional. The type of the digital asset, defaults to \"0x4::token::Token\".\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Transfer a digital asset\n * const transaction = await aptos.transferDigitalAssetTransaction({\n * sender: Account.generate(), // replace with a real sender account\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * recipient: \"0x456\", // replace with a real recipient account address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 * This function allows you to create a unique digital asset that is bound to a specific account.\n *\n * @param args - The arguments for minting the soul bound transaction.\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 * @param args.options - Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Mint a soul bound digital asset\n * const transaction = await aptos.mintSoulBoundTransaction({\n * account: Account.generate(), // Replace with a real account\n * collection: \"collectionName\",\n * description: \"collectionDescription\",\n * name: \"digitalAssetName\",\n * uri: \"digital-asset-uri.com\",\n * recipient: \"0x123\" // Replace with a real recipient account address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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, allowing for the removal of a specified digital asset from the blockchain.\n *\n * @param args The arguments for burning the digital asset.\n * @param args.creator The creator account that is burning the digital asset.\n * @param args.digitalAssetAddress The address of the digital asset to be burned.\n * @param args.digitalAssetType Optional. The type of the digital asset being burned.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const creator = Account.generate(); // Replace with a real creator account\n * const transaction = await aptos.burnDigitalAssetTransaction({\n * creator: creator,\n * digitalAssetAddress: \"0x123\", // Replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 the ability to transfer a specified digital asset.\n * This function allows the creator to restrict the transfer capability of a digital asset.\n *\n * @param args The arguments for freezing the digital asset transfer.\n * @param args.creator The creator account initiating the freeze.\n * @param args.digitalAssetAddress The address of the digital asset to be frozen.\n * @param args.digitalAssetType Optional. The type of the digital asset being frozen.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Freeze the digital asset transfer\n * const transaction = await aptos.freezeDigitalAssetTransaferTransaction({\n * creator: Account.generate(), // Replace with a real account if needed\n * digitalAssetAddress: \"0x123\", // Replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 the ability to transfer a digital asset.\n * This function allows the specified creator account to unfreeze the transfer of a digital asset identified by its address.\n *\n * @param args The parameters for unfreezing the digital asset transfer.\n * @param args.creator The creator account that is unfreezing the digital asset transfer.\n * @param args.digitalAssetAddress The address of the digital asset to unfreeze.\n * @param args.digitalAssetType Optional. The type of the digital asset being unfrozen.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Unfreeze the ability to transfer a digital asset\n * const transaction = await aptos.unfreezeDigitalAssetTransaferTransaction({\n * creator: Account.generate(), // replace with a real creator account\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\n */\n // TODO: Rename Transafer to Transfer\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 to provide additional context or information about the asset.\n *\n * @param args The parameters for setting the digital asset description.\n * @param args.creator The creator account responsible for the digital asset.\n * @param args.description The digital asset description to be set.\n * @param args.digitalAssetAddress The address of the digital asset.\n * @param args.digitalAssetType Optional. The type of the digital asset.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Set the digital asset description\n * const transaction = await aptos.setDigitalAssetDescriptionTransaction({\n * creator: Account.generate(), // replace with a real account\n * description: \"This is a digital asset description.\",\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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, allowing you to define a name for a specific digital asset on the blockchain.\n *\n * @param args The parameters for setting the digital asset name.\n * @param args.creator The creator account responsible for the transaction.\n * @param args.name The desired name for the digital asset.\n * @param args.digitalAssetAddress The address of the digital asset.\n * @param args.digitalAssetType Optional. The type of the digital asset, represented as a Move struct ID.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the blockchain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const creator = Account.generate(); // Generate a new account for the creator\n * const digitalAssetAddress = \"0x123\"; // replace with a real digital asset address\n *\n * // Set the digital asset name\n * const transaction = await aptos.setDigitalAssetNameTransaction({\n * creator: creator,\n * name: \"digitalAssetName\",\n * digitalAssetAddress: digitalAssetAddress,\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 URI for a digital asset, allowing you to associate a unique identifier with the asset.\n *\n * @param args The parameters for the transaction.\n * @param args.creator The creator account initiating the transaction.\n * @param args.uri The digital asset URI to be set.\n * @param args.digitalAssetAddress The address of the digital asset.\n * @param args.digitalAssetType Optional. The type of the digital asset.\n * @param args.options Optional. Additional options for generating the transaction.\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Set the URI for a digital asset\n * const transaction = await aptos.setDigitalAssetURITransaction({\n * creator: Account.generate(), // Replace with a real creator account\n * uri: \"digital-asset-uri.com\",\n * digitalAssetAddress: \"0x123\", // Replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 to the blockchain.\n * This function allows you to specify a new property for a digital asset, including its key, type, and value.\n *\n * @param args - The arguments for adding a digital asset property.\n * @param args.creator - The account that mints the digital asset.\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 * @param args.digitalAssetAddress - The digital asset address.\n * @param args.digitalAssetType - (Optional) The type of the digital asset.\n * @param args.options - (Optional) Options for generating the transaction.\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Add a digital asset property\n * const transaction = await aptos.addDigitalAssetPropertyTransaction({\n * creator: Account.generate(), // Replace with a real account\n * propertyKey: \"newKey\",\n * propertyType: \"BOOLEAN\",\n * propertyValue: true,\n * digitalAssetAddress: \"0x123\", // Replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 from the blockchain.\n * This function allows you to delete an existing property associated with a digital asset.\n *\n * @param args The parameters required to remove the digital asset property.\n * @param args.creator The account that mints the digital asset.\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 * @param args.digitalAssetAddress The digital asset address.\n * @param args.digitalAssetType Optional. The type of the digital asset.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Remove a digital asset property\n * const transaction = await aptos.removeDigitalAssetPropertyTransaction({\n * creator: Account.generate(), // replace with a real account\n * propertyKey: \"newKey\",\n * propertyType: \"BOOLEAN\",\n * propertyValue: true,\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 on-chain.\n *\n * @param args The parameters for updating the digital asset property.\n * @param args.creator The account that mints the digital asset.\n * @param args.digitalAssetAddress The address of the digital asset.\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 * @param args.digitalAssetType Optional. The type of the digital asset.\n * @param args.options Optional. Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Update a digital asset property\n * const transaction = await aptos.updateDigitalAssetPropertyTransaction({\n * creator: Account.generate(), // replace with a real account\n * propertyKey: \"newKey\",\n * propertyType: \"BOOLEAN\",\n * propertyValue: false,\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 to the blockchain.\n * This function allows you to define and store a specific property for a digital asset, enabling better categorization and\n * management of digital assets.\n *\n * @param args - The parameters for adding the typed property.\n * @param args.creator - The account that mints the digital asset.\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 * @param args.digitalAssetAddress - The digital asset address.\n * @param args.digitalAssetType - The optional type of the digital asset.\n * @param args.options - Optional transaction generation options.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Adding a typed digital asset property\n * const transaction = await aptos.addDigitalAssetTypedPropertyTransaction({\n * creator: Account.generate(), // replace with a real account\n * propertyKey: \"typedKey\",\n * propertyType: \"STRING\",\n * propertyValue: \"hello\",\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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 on-chain.\n * This function allows you to modify the properties of a digital asset, enabling dynamic updates to its attributes.\n *\n * @param args - The arguments for updating the digital asset property.\n * @param args.creator - The account that mints the digital asset.\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 * @param args.digitalAssetAddress - The digital asset address.\n * @param args.digitalAssetType - (Optional) The type of the digital asset.\n * @param args.options - (Optional) Additional options for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Update a typed digital asset property\n * const transaction = await aptos.updateDigitalAssetTypedPropertyTransaction({\n * creator: Account.generate(), // replace with a real account\n * propertyKey: \"typedKey\",\n * propertyType: \"U8\",\n * propertyValue: 2,\n * digitalAssetAddress: \"0x123\", // replace with a real digital asset address\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group DigitalAsset\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/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 * @group Implementation\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\n/**\n * Funds an account with a specified amount of tokens from the Aptos faucet.\n * This function is useful for quickly providing a new or existing account with tokens to facilitate transactions.\n *\n * Note that only devnet has a publicly accessible faucet. For testnet, you must use\n * the minting page at https://aptos.dev/network/faucet.\n *\n * @param args - The arguments for funding the account.\n * @param args.aptosConfig - The configuration settings for connecting to the Aptos network.\n * @param args.accountAddress - The address of the account to be funded.\n * @param args.amount - The amount of tokens to fund the account with.\n * @param args.options - Optional parameters for the transaction.\n * @param args.options.timeoutSecs - The maximum time to wait for the transaction to complete, in seconds.\n * @param args.options.checkSuccess - A flag indicating whether to check if the transaction was successful.\n *\n * @throws Error if the transaction does not return a user transaction type.\n * @group Implementation\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\";\nimport { ProcessorType } from \"../utils\";\n\n/**\n * A class to query all `Faucet` related queries on Aptos.\n * @group Faucet\n */\nexport class Faucet {\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n *\n * Note that only devnet has a publicly accessible faucet. For testnet, you must use\n * the minting page at https://aptos.dev/network/faucet.\n *\n * @param config - The configuration settings for the Aptos client.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({ network: Network.DEVNET }); // specify your own network if needed\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Faucet\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * This function creates an account if it does not exist and mints the specified amount of coins into that account.\n *\n * Note that only devnet has a publicly accessible faucet. For testnet, you must use\n * the minting page at https://aptos.dev/network/faucet.\n *\n * @param args - The arguments for funding the account.\n * @param args.accountAddress - The address of the account to fund.\n * @param args.amount - The amount of tokens to fund the account with.\n * @param args.options - Configuration options for waiting for the transaction.\n * @returns Transaction hash of the transaction that funded the account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.DEVNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fund an account with a specified amount of tokens\n * const transaction = await aptos.fundAccount({\n * accountAddress: \"0x1\", // replace with your account address\n * amount: 100,\n * });\n *\n * console.log(\"Transaction hash:\", transaction.hash);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Faucet\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 the user explicitly says to NOT wait by setting waitForIndexer to false, then we skip this.\n // But, by default we want to wait for the indexer.\n if (args.options?.waitForIndexer === undefined || args.options?.waitForIndexer) {\n await waitForIndexer({\n aptosConfig: this.config,\n minimumLedgerVersion: BigInt(fundTxn.version),\n processorType: ProcessorType.FUNGIBLE_ASSET_PROCESSOR,\n });\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 * @group Implementation\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 { AccountAddressInput } from \"../core\";\nimport { Account } from \"../account\";\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\n/**\n * Retrieves metadata for fungible assets based on specified criteria.\n * This function allows you to filter and paginate through fungible asset metadata.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration for Aptos.\n * @param [args.options] - Optional parameters for pagination and filtering.\n * @param [args.options.limit] - The maximum number of results to return.\n * @param [args.options.offset] - The number of results to skip before starting to collect the result set.\n * @param [args.options.where] - Conditions to filter the results.\n * @group Implementation\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\n/**\n * Retrieves the activities associated with fungible assets.\n * This function allows you to filter and paginate through the activities based on specified conditions.\n *\n * @param args - The arguments for retrieving fungible asset activities.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param [args.options] - Optional parameters for pagination and filtering.\n * @param [args.options.limit] - The maximum number of activities to retrieve.\n * @param [args.options.offset] - The number of activities to skip before starting to collect the result set.\n * @param [args.options.where] - Conditions to filter the activities.\n * @returns A promise that resolves to an array of fungible asset activities.\n * @group Implementation\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\n/**\n * Retrieves the current balances of fungible assets for a specified configuration.\n *\n * @param args - The arguments for retrieving fungible asset balances.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.options - Optional parameters for pagination and filtering.\n * @param args.options.limit - The maximum number of results to return.\n * @param args.options.offset - The number of results to skip before starting to collect the results.\n * @param args.options.where - Conditions to filter the results based on specific criteria.\n * @returns The current balances of fungible assets.\n * @group Implementation\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\n/**\n * Transfers a specified amount of a fungible asset from the sender to the recipient.\n * This function helps facilitate the transfer of digital assets between accounts on the Aptos blockchain.\n *\n * @param args - The parameters for the transfer operation.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.sender - The account initiating the transfer.\n * @param args.fungibleAssetMetadataAddress - The address of the fungible asset's metadata.\n * @param args.recipient - The address of the account receiving the asset.\n * @param args.amount - The amount of the fungible asset to transfer.\n * @param args.options - Optional settings for generating the transaction.\n * @group Implementation\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\n/**\n * Transfers a specified amount of a fungible asset from any (primary or secondary) fungible store to any (primary or secondary) fungible store.\n * This function helps facilitate the transfer of digital assets between fungible stores on the Aptos blockchain.\n *\n * @param args - The parameters for the transfer operation.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.sender - The account initiating the transfer.\n * @param args.fromStore - The address of the fungible store initiating the transfer.\n * @param args.toStore - The address of the fungible store receiving the asset.\n * @param args.amount - The amount of the fungible asset to transfer. Must be a positive number.\n * @param args.options - Optional settings for generating the transaction.\n * @returns A SimpleTransaction that can be submitted to the blockchain.\n * @throws Error if the transaction generation fails or if the input parameters are invalid.\n * @group Implementation\n */\nexport async function transferFungibleAssetBetweenStores(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n fromStore: AccountAddressInput;\n toStore: AccountAddressInput;\n amount: AnyNumber;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, fromStore, toStore, amount, options } = args;\n return generateTransaction({\n aptosConfig,\n sender: sender.accountAddress,\n data: {\n function: \"0x1::dispatchable_fungible_asset::transfer\",\n typeArguments: [\"0x1::fungible_asset::FungibleStore\"],\n functionArguments: [fromStore, toStore, 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 transferFungibleAssetBetweenStores,\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 } from \"../account\";\nimport { AccountAddress, AccountAddressInput } from \"../core\";\nimport { InputGenerateTransactionOptions } from \"../transactions\";\nimport { SimpleTransaction } from \"../transactions/instances/simpleTransaction\";\n\n/**\n * A class for querying and managing fungible asset-related operations on the Aptos blockchain.\n * @group FungibleAsset\n */\nexport class FungibleAsset {\n /**\n * Initializes a new instance of the Aptos class with the provided configuration.\n * This allows you to interact with the Aptos blockchain using the specified network settings.\n *\n * @param config - The configuration settings for connecting to the Aptos network.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your own network if needed\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries all fungible asset metadata.\n *\n * @param args Optional parameters for the query.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching fungible asset metadata\n * const fungibleAssets = await aptos.getFungibleAssetMetadata();\n * console.log(fungibleAssets);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\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 the fungible asset metadata for a specific asset type.\n * This function helps retrieve detailed information about a fungible asset based on its type.\n *\n * @param args - The parameters for the query.\n * @param args.assetType - The asset type of the fungible asset, e.g., \"0x1::aptos_coin::AptosCoin\" for Aptos Coin.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n *\n * @returns A fungible asset metadata item.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve fungible asset metadata by asset type\n * const fungibleAsset = await aptos.getFungibleAssetMetadataByAssetType({\n * assetType: \"0x1::aptos_coin::AptosCoin\" // replace with your asset type\n * });\n *\n * console.log(fungibleAsset);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\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 * Retrieves fungible asset metadata based on the creator address.\n *\n * This function allows you to query metadata for a specific fungible asset created by a given address.\n *\n * @param args - The parameters for the query.\n * @param args.creatorAddress - The creator address of the fungible asset.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n *\n * @returns A fungible asset metadata item.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve fungible asset metadata by creator address\n * const fungibleAsset = await aptos.getFungibleAssetMetadataByCreatorAddress({\n * creatorAddress: \"0x123\", // replace with a real creator address\n * });\n *\n * console.log(fungibleAsset);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\n */\n async getFungibleAssetMetadataByCreatorAddress(args: {\n creatorAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n }): Promise<GetFungibleAssetMetadataResponse> {\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 creator_address: { _eq: AccountAddress.from(args.creatorAddress).toStringLong() },\n },\n },\n });\n\n return data;\n }\n\n /**\n * Queries all fungible asset activities and returns a list of their metadata.\n *\n * @param args Optional parameters for the query.\n * @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying.\n * @param args.options Optional configuration for pagination and filtering.\n * @returns A list of fungible asset metadata.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching fungible asset activities\n * const fungibleAssetActivities = await aptos.getFungibleAssetActivities();\n * console.log(fungibleAssetActivities);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\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 * @param args Optional parameters for the query.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching current fungible asset balances\n * const fungibleAssetBalances = await aptos.getCurrentFungibleAssetBalances();\n *\n * console.log(fungibleAssetBalances);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\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 a specified amount of fungible asset from the sender's primary store to the recipient's primary store.\n * This method allows you to transfer any fungible asset, including fungible tokens.\n *\n * @param args - The arguments for the transfer operation.\n * @param args.sender - The sender account.\n * @param args.fungibleAssetMetadataAddress - The fungible asset account address. For example, if you're transferring USDT,\n * this would be the USDT address.\n * @param args.recipient - The recipient account address.\n * @param args.amount - The number of assets to transfer.\n * @param args.options - Optional parameters for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Transfer fungible asset from sender to recipient\n * const transaction = await aptos.transferFungibleAsset({\n * sender: Account.generate(), // replace with a real sender account\n * fungibleAssetMetadataAddress: \"0x123\", // replace with a real fungible asset address\n * recipient: \"0x456\", // replace with a real recipient account\n * amount: 5\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group FungibleAsset\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 /**\n * Transfer a specified amount of fungible asset from the sender's any (primary or secondary) fungible store to any (primary or secondary) fungible store.\n * This method allows you to transfer any fungible asset, including fungible tokens.\n *\n * @param args - The arguments for the transfer operation.\n * @param args.sender - The sender account initiating the transfer.\n * @param args.fromStore - The fungible store address initiating the transfer.\n * @param args.toStore - The fungible store address receiving the asset.\n * @param args.amount - The number of assets to transfer. Must be a positive number.\n * @param args.options - Optional parameters for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @throws Error if:\n * - The sender account is invalid\n * - The store addresses are invalid\n * - The amount is negative or zero\n * - The transaction fails to generate\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function transferAssets() {\n * // Transfer 100 units of the asset from senderStore to recipientStore\n * const transaction = await aptos.transferFungibleAssetBetweenStores({\n * sender: Account.generate(), // replace with a real sender account\n * fromStore: \"0x123\", // replace with a real fungible store address\n * toStore: \"0x456\", // replace with a real fungible store address\n * amount: 100\n * });\n *\n * console.log(transaction);\n * }\n *\n * transferAssets().catch(console.error);\n * ```\n * @group FungibleAsset\n */\n async transferFungibleAssetBetweenStores(args: {\n sender: Account;\n fromStore: AccountAddressInput;\n toStore: AccountAddressInput;\n amount: AnyNumber;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return transferFungibleAssetBetweenStores({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AptosConfig } from \"./aptosConfig\";\nimport {\n getChainTopUserTransactions,\n getIndexerLastSuccessVersion,\n getLedgerInfo,\n getProcessorStatus,\n queryIndexer,\n} from \"../internal/general\";\nimport { getBlockByHeight, getBlockByVersion } from \"../internal/transaction\";\nimport { view, viewJson } from \"../internal/view\";\nimport {\n AnyNumber,\n Block,\n GetChainTopUserTransactionsResponse,\n GetProcessorStatusResponse,\n GraphqlQuery,\n LedgerInfo,\n LedgerVersionArg,\n MoveValue,\n} from \"../types\";\nimport { ProcessorType } from \"../utils/const\";\nimport { InputViewFunctionData, InputViewFunctionJsonData } from \"../transactions\";\n\n/**\n * A class to query various Aptos-related information and perform operations on the Aptos blockchain.\n * @group General\n */\nexport class General {\n readonly config: AptosConfig;\n\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n * This allows users to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., TESTNET, MAINNET).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({\n * network: Network.TESTNET, // specify the network\n * nodeUrl: \"https://testnet.aptos.dev\" // specify the node URL\n * });\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\n */\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Queries for the Aptos ledger information.\n *\n * @returns The Aptos Ledger Info, which includes details such as chain ID, epoch, and ledger version.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching the ledger information\n * const ledgerInfo = await aptos.getLedgerInfo();\n *\n * console.log(ledgerInfo);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\n */\n async getLedgerInfo(): Promise<LedgerInfo> {\n return getLedgerInfo({ aptosConfig: this.config });\n }\n\n /**\n * Retrieves the chain ID of the Aptos blockchain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching the chain ID\n * const chainId = await aptos.getChainId();\n * console.log(\"Chain ID:\", chainId);\n * }\n * runExample().catch(console.error);\n *\n * @returns The chain ID of the Aptos blockchain.\n * ```\n * @group General\n */\n async getChainId(): Promise<number> {\n const result = await this.getLedgerInfo();\n return result.chain_id;\n }\n\n /**\n * Retrieves block information by the specified ledger version.\n *\n * @param args - The arguments for retrieving the block.\n * @param args.ledgerVersion - The ledger version to lookup block information for.\n * @param args.options - Optional parameters for the request.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve block information for a specific ledger version\n * const block = await aptos.getBlockByVersion({ ledgerVersion: 5 });\n * console.log(block);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\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 * Retrieve a block by its height, allowing for the inclusion of transactions if specified.\n *\n * @param args - The parameters for the block retrieval.\n * @param args.blockHeight - The block height to look up, starting at 0.\n * @param args.options - Optional settings for the retrieval.\n * @param args.options.withTransactions - If set to true, includes all transactions in the block.\n *\n * @returns The block with optional transactions included.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve the block at height 5, including transactions\n * const block = await aptos.getBlockByHeight({ blockHeight: 5, options: { withTransactions: true } });\n * console.log(block);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\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 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 * @group General\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 for a Move view function with JSON, this provides compatability with the old `aptos` package\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.toString()],\n * }\n * })\n *\n * @returns an array of Move values\n * @group General\n */\n async viewJson<T extends Array<MoveValue>>(args: {\n payload: InputViewFunctionJsonData;\n options?: LedgerVersionArg;\n }): Promise<T> {\n return viewJson<T>({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Queries the top user transactions based on the specified limit.\n *\n * @param args - The arguments for querying top user transactions.\n * @param args.limit - The number of transactions to return.\n * @returns GetChainTopUserTransactionsResponse\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetch the top user transactions with a limit of 5\n * const topUserTransactions = await aptos.getChainTopUserTransactions({ limit: 5 });\n *\n * console.log(topUserTransactions);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\n */\n async getChainTopUserTransactions(args: { limit: number }): Promise<GetChainTopUserTransactionsResponse> {\n return getChainTopUserTransactions({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Retrieves data from the Aptos Indexer using a GraphQL query.\n * This function allows you to execute complex queries to fetch specific data from the Aptos blockchain.\n *\n * @param args.query.query - A GraphQL query string.\n * @param args.query.variables - The variables for the query (optional).\n *\n * @return The provided T type.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Querying the Aptos Indexer for ledger information\n * const topUserTransactions = await aptos.queryIndexer({\n * query: { query: `query MyQuery {\n * ledger_infos {\n * chain_id\n * }\n * }`}\n * });\n *\n * console.log(topUserTransactions);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\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, providing insight into the ledger version the indexer is updated to, which\n * may lag behind the full nodes.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the last successful indexer version\n * const version = await aptos.getIndexerLastSuccessVersion();\n * console.log(`Last successful indexer version: ${version}`);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\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 * @param processorType The processor type to query.\n * @returns The status of the specified processor type.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the processor status for the account transactions processor\n * const status = await aptos.getProcessorStatus(\"account_transactions_processor\");\n * console.log(status);\n * }\n * runExample().catch(console.error);\n * ```\n * @group General\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\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 * @group Implementation\n */\n\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { Account } from \"../account\";\nimport { 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 * Validate if a given fragment is a valid ANS segment.\n * This function checks the length and character constraints of the fragment to ensure it meets the ANS standards.\n *\n * @param fragment - A fragment of a name, either the domain or subdomain.\n * @returns A boolean indicating if the fragment is a valid fragment.\n * @group Implementation\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, which can include or exclude the .apt suffix.\n * @group Implementation\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\n/**\n * Policy for determining how subdomains expire in relation to their parent domain.\n * @group Implementation\n */\nexport enum SubdomainExpirationPolicy {\n Independent = 0,\n FollowsDomain = 1,\n}\n\n/**\n * Determine if a given ANS name is considered active based on its expiration dates.\n * Domains are active if their expiration date is in the future, while subdomains may\n * follow their parent's expiration policy (1) or expire independently (0).\n * If the subdomain is expiring independently, it can expire before their parent, but not after.\n *\n * @param name - An ANS name returned from one of the functions of the SDK.\n * @returns A boolean indicating whether the contract considers the name active or not.\n * @group Implementation\n */\nexport function isActiveANSName(name: GetANSNameResponse[0]): boolean {\n if (!name) return false;\n\n const isTLDExpired = new Date(name.domain_expiration_timestamp).getTime() < Date.now();\n const isExpired = new Date(name.expiration_timestamp).getTime() < Date.now();\n\n // If we are a subdomain, if our parent is expired we are always expired\n if (name.subdomain && isTLDExpired) return false;\n\n // If we are a subdomain and our expiration policy is to follow the domain, we\n // are active (since we know our parent is not expired by this point)\n if (name.subdomain && name.subdomain_expiration_policy === SubdomainExpirationPolicy.FollowsDomain) return true;\n\n // At this point, we are either a TLD or a subdomain with an independent\n // expiration policy, we are active as long as we the expiration timestamp\n return !isExpired;\n}\n\nexport const LOCAL_ANS_ACCOUNT_PK =\n process.env.ANS_TEST_ACCOUNT_PRIVATE_KEY ??\n \"ed25519-priv-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\n/**\n * Retrieves the address of the ANS contract based on the specified Aptos network configuration.\n *\n * @param aptosConfig - The configuration object for the Aptos network.\n * @param aptosConfig.network - The network for which to retrieve the ANS contract address.\n *\n * @throws Throws an error if the ANS contract is not deployed to the specified network.\n * @group Implementation\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\n/**\n * Retrieve the owner address of a specified domain or subdomain.\n *\n * @param args - The arguments for retrieving the owner address.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.name - The name of the domain or subdomain to query.\n * @returns The account address of the owner, or undefined if not found.\n * @group Implementation\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\n/**\n * Parameters for registering a name in the Aptos network.\n *\n * @param aptosConfig - Configuration settings for the Aptos network.\n * @param sender - The account initiating the name registration.\n * @param name - The name to be registered.\n * @param expiration - The expiration policy for the name registration.\n * @param transferable - Whether the name can be transferred to another owner.\n * @param toAddress - The address that will be set as the owner_address of the name.\n * @param targetAddress - The address that this name will resolve to.\n * @group Implementation\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\n/**\n * Registers a domain or subdomain with the specified parameters. This function ensures that the provided names and expiration\n * policies are valid before proceeding with the registration process.\n *\n * @param args - The parameters required for registering a name.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.expiration - The expiration details for the registration.\n * @param args.name - The name to be registered, which can be a domain or subdomain.\n * @param args.sender - The account details of the sender initiating the registration.\n * @param args.targetAddress - The target address for the registration, which is the address the name will resolve to.\n * @param args.toAddress - The address that will be set as the owner_address in records, defaults to sender if not provided.\n * @param args.options - Additional options for the registration process.\n * @param args.transferable - Indicates whether the registered name is transferable to another account.\n *\n * @throws Error if the provided expiration policy is invalid for subdomains.\n * @throws Error if the domain does not exist.\n * @throws Error if the subdomain expiration time exceeds the domain expiration time.\n *\n * @returns A transaction object representing the registration process.\n * @group Implementation\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\n/**\n * Retrieves the expiration time of a specified domain or subdomain in epoch milliseconds.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.name - The name of the domain or subdomain to check.\n * @returns The expiration time in epoch milliseconds, or undefined if an error occurs.\n * @group Implementation\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\n/**\n * Retrieves the primary name associated with a given account address.\n * This function helps in obtaining the complete domain name by combining the subdomain and domain names.\n *\n * @param args - The arguments for retrieving the primary name.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.address - The account address for which to retrieve the primary name.\n * @returns The primary name as a string, or undefined if no domain name exists.\n * @group Implementation\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\n/**\n * Sets the primary name for the specified account, allowing for the association of a domain or subdomain with the account.\n * If no name is provided, it clears the existing primary name.\n *\n * @param args - The arguments for setting the primary name.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.sender - The account that is sending the transaction.\n * @param args.name - The name to set as the primary name. If omitted, the function will clear the primary name.\n * @param args.options - Optional transaction generation options.\n * @returns A transaction object representing the operation.\n * @group Implementation\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\n/**\n * Retrieves the target address associated with a given domain name and subdomain name.\n * The target address is different from the owner address - it's the address this name\n * resolves to, which may be different from who owns the name.\n *\n * @param args - The arguments for retrieving the target address.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.name - The name of the domain, which may include a subdomain.\n * @returns The target address as an AccountAddress, or undefined if not found.\n * @group Implementation\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\n/**\n * Sets the target address for a specified domain and subdomain in the Aptos network.\n * This function helps to associate a given address with a domain name, allowing for easier access and management of resources.\n *\n * @param args - The arguments for setting the target address.\n * @param args.aptosConfig - The configuration settings for the Aptos network.\n * @param args.sender - The account that is sending the transaction.\n * @param args.name - The name of the domain or subdomain to be set.\n * @param args.address - The address to be associated with the domain or subdomain.\n * @param args.options - Optional parameters for generating the transaction.\n *\n * @returns A transaction object representing the set target address operation.\n * @group Implementation\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\n/**\n * Retrieves the active Aptos name associated with the specified domain and subdomain.\n *\n * @param args - The parameters for the function.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.name - The name to look up, which includes the domain and optional subdomain.\n * @returns The active Aptos name if it exists; otherwise, returns undefined.\n * @group Implementation\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 };\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 isActiveANSName(res) ? res : undefined;\n}\n\n/**\n * Options for querying names, including pagination, ordering, and filtering criteria.\n *\n * @param options - Pagination and filtering options for the query.\n * @group Implementation\n */\ninterface QueryNamesOptions {\n options?: PaginationArgs & OrderByArg<GetANSNameResponse[0]> & WhereArg<CurrentAptosNamesBoolExp>;\n}\n\n/**\n * Arguments for retrieving account names based on the specified account address.\n *\n * @param accountAddress - The address of the account for which names are to be retrieved.\n * @group Implementation\n */\nexport interface GetAccountNamesArgs extends QueryNamesOptions {\n accountAddress: AccountAddressInput;\n}\n\n/**\n * Retrieves all the current Aptos names owned by an account. This uses the\n * owner_address field, not the registered_address field.\n *\n * @param args - The arguments for retrieving account names.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.options - Optional parameters for querying account names.\n * @param args.options.limit - The maximum number of names to retrieve.\n * @param args.options.offset - The number of names to skip before starting to collect the result set.\n * @param args.options.orderBy - The field by which to order the results.\n * @param args.options.where - Additional conditions to filter the results.\n * @param args.accountAddress - The address of the account for which to retrieve names.\n *\n * @returns An array of sanitized Aptos names associated with the specified account address.\n * @group Implementation\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\n/**\n * Arguments for retrieving the domains associated with a specific account.\n *\n * @param accountAddress - The address of the account for which to fetch domains.\n * @group Implementation\n */\nexport interface GetAccountDomainsArgs extends QueryNamesOptions {\n accountAddress: AccountAddressInput;\n}\n\n/**\n * Retrieves the list of top-level domains owned by a specified account,\n * using the owner_address field.\n *\n * @param args - The arguments for retrieving account domains.\n * @param args.aptosConfig - The Aptos configuration object.\n * @param args.options - Optional parameters for the query.\n * @param args.options.limit - The maximum number of results to return.\n * @param args.options.offset - The number of results to skip before starting to collect the result set.\n * @param args.options.orderBy - The field by which to order the results.\n * @param args.options.where - Additional conditions to filter the results.\n * @param args.options.where.owner_address - The address of the account whose domains are being queried.\n * @param args.options.where.expiration_timestamp - The minimum expiration timestamp for the domains.\n * @param args.options.where.subdomain - The specific subdomain to filter by.\n *\n * @returns An array of sanitized domain names owned by the specified account.\n * @group Implementation\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\n/**\n * Arguments for retrieving subdomains associated with a specific account.\n *\n * @param accountAddress - The address of the account for which to fetch subdomains.\n * @group Implementation\n */\nexport interface GetAccountSubdomainsArgs extends QueryNamesOptions {\n accountAddress: AccountAddressInput;\n}\n\n/**\n * Retrieves a list of subdomains owned by a specified account address, determined\n * by the owner_address field.\n *\n * @param args - The arguments for retrieving account subdomains.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.options - Optional parameters for the query.\n * @param args.options.limit - The maximum number of results to return.\n * @param args.options.offset - The number of results to skip before starting to collect the result set.\n * @param args.options.orderBy - The field by which to order the results.\n * @param args.options.where - Additional conditions to filter the results.\n * @param args.options.where.owner_address - The address of the account to filter by.\n * @param args.options.where.expiration_timestamp - The expiration timestamp to filter by.\n * @param args.options.where.subdomain - The subdomain condition to filter by.\n * @param args.accountAddress - The address of the account whose subdomains are being queried.\n * @group Implementation\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\n/**\n * Arguments for retrieving subdomains associated with a specific domain.\n *\n * @param domain - The domain for which to fetch subdomains.\n * @group Implementation\n */\nexport interface GetDomainSubdomainsArgs extends QueryNamesOptions {\n domain: string;\n}\n\n/**\n * Retrieve the active subdomains associated with a specified domain,\n * regardless of who is in possession of the domain.\n *\n * This function queries by domain name only, not by owner, so it will return\n * all subdomains of a domain even if they're owned by different accounts.\n *\n * @param args - The arguments for retrieving subdomains.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.options - Optional parameters for the query.\n * @param args.options.limit - The maximum number of results to return.\n * @param args.options.offset - The number of results to skip before starting to collect the results.\n * @param args.options.orderBy - The field by which to order the results.\n * @param args.options.where - Additional conditions to filter the results.\n * @param args.domain - The domain for which to retrieve subdomains.\n *\n * @returns An array of active subdomain names.\n * @group Implementation\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 },\n },\n },\n });\n\n return data.current_aptos_names.map(sanitizeANSName).filter(isActiveANSName);\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 - The arguments for the function.\n * @param args.aptosConfig - An AptosConfig object containing the configuration settings.\n * @returns The expiration date in ISO 8601 format.\n * @group Implementation\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\n/**\n * Renews a domain for a specified duration. This function allows you to extend the registration of a domain for one year.\n *\n * @param args - The parameters required to renew the domain.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.sender - The account that is sending the renewal transaction.\n * @param args.name - The name of the domain to renew.\n * @param args.years - The number of years to renew the domain for. Currently, only 1 year renewals are supported. (optional, default is 1)\n * @param args.options - Additional options for generating the transaction. (optional)\n * @throws Error if the name contains a subdomain or if the years parameter is not equal to 1.\n * @group Implementation\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 *\n * @param name - The ANS name response to sanitize.\n * @param name.expiration_timestamp - The expiration timestamp in ISO string format.\n * @group Implementation\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 } from \"../account\";\nimport { 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 * @group ANS\n */\nexport class ANS {\n /**\n * Initializes a new instance of the Aptos class with the provided configuration.\n * This allows you to interact with the Aptos blockchain using the specified network settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., mainnet, testnet).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n * @param config.faucetUrl - The URL of the faucet to use for funding accounts.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for connecting to the Aptos testnet\n * const config = new AptosConfig({ network: Network.TESTNET });\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Retrieve the owner address of a specified domain name or subdomain name from the contract.\n *\n * @param args - The arguments for retrieving the owner address.\n * @param args.name - A string representing the name of the domain or subdomain to retrieve the owner address for.\n *\n * @returns AccountAddress if the name is owned, undefined otherwise.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve the owner address of \"test.aptos\"\n * const owner = await aptos.getOwnerAddress({ name: \"test.aptos\" });\n * console.log(owner); // Logs the owner address or undefined if not owned\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 * @param args - The arguments for retrieving the expiration.\n * @param args.name - A string of the name to retrieve.\n *\n * @returns number as a unix timestamp in milliseconds.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the expiration time for the domain \"test.aptos\"\n * const exp = await aptos.getExpiration({ name: \"test.aptos\" });\n *\n * // Log the expiration date\n * console.log(new Date(exp)); // Outputs the expiration date\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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, which indicates the address the name points to for use on-chain.\n * Note that the target address can point to addresses that do not own the name.\n *\n * @param args - The arguments for retrieving the target address.\n * @param args.name - A string representing the name, which can be a primary name, a subdomain, or a combination (e.g.,\n * \"primary\", \"primary.apt\", \"secondary.primary\", \"secondary.primary.apt\").\n *\n * @returns AccountAddress if the name has a target, undefined otherwise.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve the target address for the specified domain name\n * const targetAddr = await aptos.getTargetAddress({ name: \"test.aptos\" });\n *\n * console.log(targetAddr); // Logs the target address, e.g., 0x123...\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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, pointing it to a specified address for use on-chain.\n * The target address can be different from the owner of the name.\n *\n * @param args - The arguments for setting the target address.\n * @param args.sender - The account initiating the transaction.\n * @param args.name - A string representing the domain or subdomain name (e.g., \"test.aptos\").\n * @param args.address - The AccountAddressInput of the address to set the domain or subdomain to.\n * @param args.options - Optional settings for generating the transaction.\n *\n * @returns SimpleTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Setting the target address for a domain name\n * const sender = Account.generate(); // replace with a real account\n * const address = \"0x1\"; // replace with a real account address\n *\n * await aptos.setTargetAddress({\n * sender: sender,\n * name: \"test.aptos\",\n * address: address,\n * });\n *\n * const targetAddress = await aptos.getTargetAddress({ name: \"test.aptos\" });\n * console.log(targetAddress); // Should log the address set for \"test.aptos\"\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 multiple names, but only one primary name, which may not exist.\n *\n * @param args - The arguments for retrieving the primary name.\n * @param args.address - An AccountAddressInput (address) of the account.\n *\n * @returns A string if the account has a primary name, undefined otherwise.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve the primary name for the specified account address\n * const name = await aptos.getPrimaryName({ address: \"0x1\" }); // replace with a real account address\n * console.log(name);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 account, allowing them to designate a single primary name among potentially multiple\n * names. An account may not have a primary name.\n *\n * @param args - The arguments for setting the primary name.\n * @param args.sender - The sender account.\n * @param args.name - A string representing the name to set as primary (e.g., \"test.aptos\").\n * @param args.options - Optional transaction options.\n *\n * @returns SimpleTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Set the primary name for the sender account\n * const sender = Account.generate(); // replace with a real account\n * await aptos.setPrimaryName({ sender, name: \"test.aptos\" });\n *\n * const primaryName = await aptos.getPrimaryName({ address: sender.accountAddress });\n * console.log(\"Primary Name:\", primaryName); // Should log: \"Primary Name: test.aptos\"\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 * This function allows you to register a domain or subdomain name with specific expiration policies and options.\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. Examples include:\n * \"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 the date when the subdomain will expire. Only\n * applicable when the policy is 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, the sender's address will\n * be used.\n * @param args.toAddress optional - The address to send the domain name to. If not provided, the transaction will be sent to the\n * router.\n *\n * @returns SimpleTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Registering a subdomain name assuming def.apt is already registered and belongs to the sender alice.\n * const txn = await aptos.registerName({\n * sender: \"0x1\", // replace with a real sender account\n * name: \"test.aptos.apt\",\n * expiration: {\n * policy: \"subdomain:independent\",\n * expirationDate: Date.now() + 30 * 24 * 60 * 60 * 1000, // expires in 30 days\n * },\n * });\n *\n * console.log(\"Transaction:\", txn);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 for one year.\n * If a domain name was minted with V1 of the contract, it will automatically be upgraded to V2 via this transaction.\n *\n * @param args - The arguments for renewing the domain.\n * @param args.sender - The sender account, which must be the domain owner.\n * @param args.name - A string representing the domain to renew. Subdomains cannot be renewed.\n * @param args.years - The number of years to renew the name. Currently, only one year is permitted.\n * @param args.options - Optional transaction options.\n *\n * @returns SimpleTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Renew the domain \"test\" for one year\n * const transaction = await aptos.renewDomain({\n * sender: Account.generate(), // replace with a real account\n * name: \"test\"\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 based on the provided name argument.\n *\n * @param args - The arguments for retrieving the name.\n * @param args.name - A string of the name to retrieve, e.g. \"test.aptos.apt\" or \"test.apt\" or \"test\".\n * Can be inclusive or exclusive of the .apt suffix and can be a subdomain.\n *\n * @returns A promise of an ANSName or undefined if the name is not active.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching a name from the indexer\n * const name = await aptos.getName({ name: \"test.aptos\" }); // replace with a real name\n * console.log(name);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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, including both top-level domains and subdomains.\n *\n * @param args - The arguments for fetching account names.\n * @param args.accountAddress - An AccountAddressInput of the address to retrieve names for.\n * @param args.options - Optional parameters for fetching names.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetch account names for a specific address\n * const accountNames = await aptos.getAccountNames({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * limit: 10, // specify how many names to fetch\n * orderBy: \"name\", // specify the order by which to sort the names\n * },\n * });\n *\n * console.log(accountNames);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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 a specified account.\n *\n * @param args - The arguments for retrieving account domains.\n * @param args.accountAddress - An 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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching all top-level domain names for a specific account\n * const domains = await aptos.getAccountDomains({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * limit: 10, // specify the number of names to fetch\n * offset: 0, // specify the offset for pagination\n * orderBy: \"created_at\", // specify the order by which to sort the names\n * where: {\n * // additional filters can be specified here\n * },\n * },\n * });\n *\n * console.log(domains);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\n */\n async getAccountDomains(args: GetAccountDomainsArgs): Promise<GetANSNameResponse> {\n return getAccountDomains({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches all subdomain names for a specified account.\n *\n * @param args - The arguments for retrieving subdomains.\n * @param args.accountAddress - The address to retrieve subdomain names for.\n * @param args.options - Optional parameters for fetching subdomains.\n * @param args.options.offset - The offset to start from when fetching names.\n * @param args.options.limit - The number of 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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching subdomain names for a specific account\n * const subdomains = await aptos.getAccountSubdomains({\n * accountAddress: \"0x1\", // replace with a real account address\n * options: {\n * limit: 10, // specify the number of subdomains to fetch\n * offset: 0, // specify the offset for pagination\n * orderBy: \"name\", // specify the order by which to sort the names\n * },\n * });\n *\n * console.log(subdomains);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\n */\n async getAccountSubdomains(args: GetAccountSubdomainsArgs): Promise<GetANSNameResponse> {\n return getAccountSubdomains({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches all subdomain names for a given domain, excluding the domain itself.\n *\n * @param args - The arguments for fetching subdomains.\n * @param args.domain - A string of the domain name, e.g., \"test.apt\" or \"test\" (without the suffix of .apt).\n * @param args.options - Optional parameters for fetching subdomains.\n * @param args.options.offset - Optional, the offset to start from when fetching names.\n * @param args.options.limit - Optional, the number of 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 that resolves to an array of ANSName.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching subdomains for a specific domain\n * const subdomains = await aptos.getDomainSubdomains({\n * domain: \"test\", // replace with your domain\n * options: {\n * limit: 10, // specify the number of subdomains to fetch\n * offset: 0, // specify the starting point for fetching\n * orderBy: \"name\", // specify the order by which to sort the results\n * },\n * });\n *\n * console.log(subdomains);\n * }\n * runExample().catch(console.error);\n * ```\n * @group ANS\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\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 * staking namespace and without having a dependency cycle error.\n * @group Implementation\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\n/**\n * Retrieves the number of active delegators for a specified pool address.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.poolAddress - The address of the pool for which to retrieve the number of delegators.\n * @returns The number of active delegators for the specified pool address.\n * @group Implementation\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) doesn't 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\n/**\n * Retrieves the number of active delegators for all pools.\n *\n * @param args - The arguments for the function.\n * @param args.aptosConfig - The configuration for the Aptos client.\n * @param [args.options] - Optional parameters for ordering the results.\n * @param args.options.orderBy - Specifies the order in which to return the results.\n * @returns The number of active delegators per pool.\n * @group Implementation\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\n/**\n * Retrieves the delegated staking activities for a specified delegator and pool.\n *\n * @param args - The parameters for the query.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.delegatorAddress - The address of the delegator whose activities are being queried.\n * @param args.poolAddress - The address of the pool associated with the delegated staking activities.\n * @returns The delegated staking activities for the specified delegator and pool.\n * @group Implementation\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\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 * @group Staking\n */\nexport class Staking {\n /**\n * Creates an instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., TESTNET, MAINNET).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your network\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Staking\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Queries the current number of delegators in a specified pool. Throws an error if the pool is not found.\n *\n * @param args - The parameters for the query.\n * @param args.poolAddress - The address of the pool to query.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get the number of delegators for a specific pool\n * const delegators = await aptos.getNumberOfDelegators({ poolAddress: \"0x1\" }); // replace with a real pool address\n * console.log(`Number of delegators: ${delegators}`);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Staking\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 * Retrieves the current number of delegators across all pools.\n *\n * @param args Optional parameters for the query.\n * @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.\n * @param args.options Optional ordering options for the response.\n * @returns GetNumberOfDelegatorsForAllPoolsResponse response type containing the number of delegators per pool.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Retrieve the number of delegators for all pools\n * const delegators = await aptos.getNumberOfDelegatorsForAllPools();\n * console.log(delegators);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Staking\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 for a specific delegator and pool.\n *\n * @param args - The arguments for querying delegated staking activities.\n * @param args.delegatorAddress - The address of the delegator.\n * @param args.poolAddress - The address of the staking pool.\n * @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.\n * @returns The response containing delegated staking activities.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Get delegated staking activities for a specific delegator and pool\n * const activities = await aptos.getDelegatedStakingActivities({\n * delegatorAddress: \"0x1\", // replace with a real delegator address\n * poolAddress: \"0x2\", // replace with a real pool address\n * minimumLedgerVersion: 1, // specify your own if needed\n * });\n *\n * console.log(activities);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Staking\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 { AccountAddressInput } from \"../../core\";\nimport { generateTransaction } from \"../../internal/transactionSubmission\";\nimport {\n InputGenerateTransactionPayloadData,\n InputGenerateTransactionOptions,\n InputGenerateOrderlessTransactionOptions,\n} 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 * @group Implementation\n */\nexport class Build {\n readonly config: AptosConfig;\n\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., TESTNET, MAINNET).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n * @param config.account - The account details for authentication.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({\n * network: Network.TESTNET, // specify the network\n * nodeUrl: \"https://testnet.aptos.dev\", // specify the node URL\n * });\n *\n * // Initialize the Aptos client\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Build a simple transaction.\n *\n * This function allows you to create a transaction with specified sender and data.\n *\n * @param args.sender - The sender account address.\n * @param args.data - The transaction data.\n * @param args.options - Optional transaction configurations.\n * @param args.withFeePayer - Whether there is a fee payer for the transaction.\n *\n * @returns SimpleTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Build a simple transaction\n * const transaction = await aptos.transaction.simple({\n * sender: \"0x1\", // replace with a real sender account address\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [\"0x2\", 100], // replace with a real destination account address\n * },\n * options: {\n * gasUnitPrice: 100, // specify your own gas unit price if needed\n * maxGasAmount: 1000, // specify your own max gas amount if needed\n * },\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\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 that allows multiple signers to authorize a transaction.\n *\n * @param args - The parameters for creating the multi-agent transaction.\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 transaction configurations.\n * @param args.withFeePayer - Whether there is a fee payer for the transaction.\n *\n * @returns MultiAgentTransaction\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Build a multi-agent transaction\n * const transaction = await aptos.multiAgent({\n * sender: \"0x1\", // replace with a real sender account address\n * data: {\n * // Transaction data structure\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [\"0x2\", 100], // replace with a real destination account address and amount\n * },\n * secondarySignerAddresses: [\"0x3\", \"0x4\"], // replace with real secondary signer addresses\n * options: {\n * // Optional transaction configurations\n * maxGasAmount: \"1000\",\n * gasUnitPrice: \"1\",\n * },\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\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","// 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 * @group Implementation\n */\nexport class Simulate {\n readonly config: AptosConfig;\n\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., TESTNET, MAINNET).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your desired network\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Simulates a transaction based on the provided parameters and returns the result.\n * This function helps you understand the outcome of a transaction before executing it on the blockchain.\n *\n * @param args - The parameters for simulating the transaction.\n * @param args.signerPublicKey - The public key of the signer for the transaction (optional).\n * @param args.transaction - The raw transaction data to simulate.\n * @param args.feePayerPublicKey - The public key of the fee payer (optional).\n * @param args.options - Additional options for simulating the transaction (optional).\n *\n * @example\n * ```typescript\n * import {\n * Account,\n * Aptos,\n * AptosConfig,\n * Network,\n * } from \"@aptos-labs/ts-sdk\";\n *\n * async function example() {\n * let sender = Account.generate();\n * let receiver = Account.generate();\n *\n * // 0. Set up the client and test accounts\n * const config = new AptosConfig({ network: Network.DEVNET });\n * const aptos = new Aptos(config);\n *\n * await aptos.fundAccount({\n * accountAddress: sender.accountAddress,\n * amount: 100_000_000,\n * });\n *\n * // 1. Build the transaction to preview the impact of it\n * const transaction = await aptos.transaction.build.simple({\n * sender: sender.accountAddress,\n * data: {\n * // All transactions on Aptos are implemented via smart contracts.\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [receiver.accountAddress, 100],\n * },\n * });\n *\n * // 2. Simulate to see what would happen if we execute this transaction\n * const [userTransactionResponse] = await aptos.transaction.simulate.simple({\n * signerPublicKey: sender.publicKey,\n * transaction,\n * });\n * console.log(userTransactionResponse);\n *\n * // If the fee looks ok, continue to signing!\n * // ...\n * }\n *\n * example();\n * ```\n * @group Implementation\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 * Simulates a multi-agent transaction by generating a signed transaction and posting it to the Aptos full node.\n * This function helps in understanding the outcome of a transaction involving multiple signers before it is executed.\n *\n * @param args - The parameters for simulating the transaction.\n * @param args.signerPublicKey - The public key of the primary signer (optional).\n * @param args.transaction - The raw transaction to be simulated.\n * @param args.secondarySignersPublicKeys - An array of public keys for secondary signers (optional).\n * Each element of the array can be optional, allowing the corresponding key check to be skipped.\n * @param args.feePayerPublicKey - The public key of the fee payer (optional).\n * @param args.options - Options for simulating the transaction (optional).\n *\n * @example\n * ```typescript\n * import {\n * Account,\n * Aptos,\n * AptosConfig,\n * Network,\n * } from \"@aptos-labs/ts-sdk\";\n *\n * async function example() {\n * let sender1 = Account.generate();\n * let sender2 = Account.generate();\n * let receiver = Account.generate();\n *\n * // 0. Set up the client and test accounts\n * const config = new AptosConfig({ network: Network.DEVNET });\n * const aptos = new Aptos(config);\n *\n * await aptos.fundAccount({\n * accountAddress: sender.accountAddress,\n * amount: 100_000_000,\n * });\n *\n * // 1. Build\n * console.log(\"\\n=== 1. Building the transaction ===\\n\");\n * const transaction = await aptos.transaction.build.multiAgent({\n * sender: sender1.accountAddress,\n * secondarySignerAddresses: [sender2.accountAddress],\n * data: {\n * // REPLACE WITH YOUR MULTI-AGENT FUNCTION HERE\n * function:\n * \"<REPLACE WITH YOUR MULTI AGENT MOVE ENTRY FUNCTION> (Syntax {address}::{module}::{function})\",\n * functionArguments: [],\n * },\n * });\n * console.log(\"Transaction:\", transaction);\n *\n * // 2. Simulate (Optional)\n * console.log(\"\\n === 2. Simulating Response (Optional) === \\n\");\n * const [userTransactionResponse] = await aptos.transaction.simulate.multiAgent(\n * {\n * signerPublicKey: sender1.publicKey,\n * secondarySignersPublicKeys: [sender2.publicKey],\n * transaction,\n * },\n * );\n * console.log(userTransactionResponse);\n *\n * // If the fee looks ok, continue to signing!\n * // ...\n * }\n *\n * example();\n * ```\n * @group Implementation\n */\n @ValidateFeePayerDataOnSimulation\n async multiAgent(args: {\n signerPublicKey?: PublicKey;\n transaction: AnyRawTransaction;\n secondarySignersPublicKeys?: Array<PublicKey | undefined>;\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, InputTransactionPluginData } 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 * @group Implementation\n */\nexport class Submit {\n readonly config: AptosConfig;\n\n /**\n * Initializes a new instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., TESTNET, MAINNET).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n * @param config.faucetUrl - The URL of the faucet for obtaining test tokens.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({\n * network: Network.TESTNET, // Use the TESTNET for testing\n * nodeUrl: \"https://testnet.aptos.dev\", // Specify the node URL\n * faucetUrl: \"https://faucet.testnet.aptos.dev\" // Specify the faucet URL\n * });\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n constructor(config: AptosConfig) {\n this.config = config;\n }\n\n /**\n * Submits a transaction to the Aptos blockchain using the provided transaction details and authenticators.\n * This function allows you to execute transactions securely by specifying the sender and optional fee payer authenticators.\n *\n * @param args - The arguments for submitting the transaction.\n * @param args.transaction - The raw transaction data to be submitted.\n * @param args.senderAuthenticator - The authenticator for the sender's account.\n * @param [args.feePayerAuthenticator] - The optional authenticator for the fee payer's account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const sender = Account.generate(); // Generate a new sender account\n * const transaction = await aptos.transaction.build.simple({\n * sender: sender.accountAddress,\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [Account.generate().accountAddress, 100], // Replace with a real destination account\n * },\n * });\n *\n * // Submit the transaction\n * const response = await aptos.simple({\n * transaction,\n * senderAuthenticator: sender.getAuthenticator(), // Use the sender's authenticator\n * });\n *\n * console.log(\"Transaction submitted:\", response);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n async simple(\n args: {\n transaction: AnyRawTransaction;\n senderAuthenticator: AccountAuthenticator;\n feePayerAuthenticator?: AccountAuthenticator;\n } & InputTransactionPluginData,\n ): Promise<PendingTransactionResponse> {\n validateFeePayerDataOnSubmission(this.config, args);\n return submitTransaction({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Submits a multi-agent transaction to the Aptos network, allowing multiple signers to authorize the transaction.\n * This function is useful for scenarios where a transaction requires approval from multiple accounts.\n *\n * @param args - The parameters for the multi-agent transaction.\n * @param args.transaction - The raw transaction to be submitted.\n * @param args.senderAuthenticator - The authenticator for the sender account.\n * @param args.additionalSignersAuthenticators - An array of authenticators for additional signers.\n * @param [args.feePayerAuthenticator] - An optional authenticator for the fee payer account.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const sender = Account.generate(); // Generate a new sender account\n * const additionalSigner1 = Account.generate(); // Generate an additional signer account\n * const additionalSigner2 = Account.generate(); // Generate another additional signer account\n *\n * const transaction = await aptos.transaction.build.simple({\n * sender: sender.accountAddress,\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [additionalSigner1.accountAddress, 100],\n * },\n * });\n *\n * const response = await aptos.multiAgent({\n * transaction,\n * senderAuthenticator: sender.getAuthenticator(), // Use the sender's authenticator\n * additionalSignersAuthenticators: [\n * additionalSigner1.getAuthenticator(), // Use the first additional signer's authenticator\n * additionalSigner2.getAuthenticator(), // Use the second additional signer's authenticator\n * ],\n * });\n *\n * console.log(response); // Log the response from the transaction submission\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n async multiAgent(\n args: {\n transaction: AnyRawTransaction;\n senderAuthenticator: AccountAuthenticator;\n additionalSignersAuthenticators: Array<AccountAuthenticator>;\n feePayerAuthenticator?: AccountAuthenticator;\n } & InputTransactionPluginData,\n ): Promise<PendingTransactionResponse> {\n validateFeePayerDataOnSubmission(this.config, args);\n return submitTransaction({ aptosConfig: this.config, ...args });\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 \"../../account\";\n\nexport class TransactionManagement extends EventEmitter<TransactionWorkerEvents> {\n account!: Account;\n\n transactionWorker!: TransactionWorker;\n\n readonly config: AptosConfig;\n\n /**\n * Initializes a new instance of the Aptos client with the provided configuration settings.\n * This allows you to interact with the Aptos blockchain using the specified network and options.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., TESTNET, MAINNET).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n * @param config.account - Optional account settings for authentication.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({\n * network: Network.TESTNET, // specify the network to use\n * nodeUrl: \"https://testnet.aptos.dev\" // replace with your node URL\n * });\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized successfully.\");\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n constructor(config: AptosConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Initializes the transaction worker using the provided sender account and begins listening for events.\n * This function is essential for setting up the transaction processing environment.\n *\n * @param args - The arguments for starting the transaction worker.\n * @param args.sender - The sender account to sign and submit the transaction.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const sender = Account.generate(); // Generate a new account for sending transactions\n *\n * // Start the transaction worker with the sender account\n * aptos.start({ sender });\n *\n * console.log(\"Transaction worker started with sender:\", sender.accountAddress);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\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 * Pushes transaction data to the transaction worker for processing.\n *\n * @param args.data An array of transaction payloads to be processed.\n * @param args.options Optional. Transaction generation configurations (excluding accountSequenceNumber).\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Prepare transaction payloads\n * const payloads = [\n * {}, // Build your first transaction payload\n * {}, // Build your second transaction payload\n * ];\n *\n * // Push transaction data to the worker\n * aptos.push({\n * data: payloads,\n * {}, // Specify options as needed\n * });\n *\n * console.log(\"Transaction data pushed successfully.\");\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\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 * Starts listening to transaction worker events, allowing the application to respond to transaction status changes.\n * This function enables the application to handle events such as transaction sent, execution success, or failure.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Register to listen for transaction events\n * aptos.registerToEvents();\n *\n * // You can send a transaction here to see the events in action\n * const sender = Account.generate(); // replace with a real account\n * const destination = Account.generate(); // replace with a real account\n *\n * const transaction = await aptos.transaction.build.simple({\n * sender: sender.accountAddress,\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [destination.accountAddress, 100],\n * },\n * });\n *\n * await aptos.transaction.send(transaction);\n *\n * console.log(\"Transaction sent and events registered.\");\n * }\n * runExample().catch(console.error);\n * ```\n * @group Implementation\n */\n private registerToEvents() {\n // TODO - Should we ask events to listen to this as an input?\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 * don't 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 * @group Implementation\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","/**\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 * @group Implementation\n * @category Transactions\n */\n\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport { Account } from \"../../account\";\nimport { getInfo } from \"../../internal/account\";\nimport { nowInSeconds, sleep } from \"../../utils/helpers\";\n\n/**\n * Represents an account's sequence number management for transaction handling on the Aptos blockchain.\n * This class provides methods to retrieve the next available sequence number, synchronize with the on-chain sequence number,\n * and manage local sequence numbers while ensuring thread safety.\n *\n * @param aptosConfig - The configuration settings for Aptos.\n * @param account - The account associated with the sequence number.\n * @param maxWaitTime - The maximum time to wait for a transaction to commit.\n * @param maximumInFlight - The maximum number of transactions that can be in flight at once.\n * @param sleepTime - The time to wait before retrying to get the sequence number.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountSequenceNumber {\n readonly aptosConfig: AptosConfig;\n\n readonly account: Account;\n\n // sequence number on chain\n // TODO: Change to Uncommitted\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 an 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 * @group Implementation\n * @category Transactions\n */\n lock = false;\n\n maxWaitTime: number;\n\n maximumInFlight: number;\n\n sleepTime: number;\n\n /**\n * Creates an instance of the class with the specified configuration and account details.\n * This constructor initializes the necessary parameters for managing Aptos transactions.\n *\n * @param aptosConfig - The configuration settings for Aptos.\n * @param account - The account associated with the Aptos transactions.\n * @param maxWaitTime - The maximum time to wait for a transaction to be processed, in milliseconds.\n * @param maximumInFlight - The maximum number of transactions that can be in flight at the same time.\n * @param sleepTime - The time to sleep between transaction checks, in milliseconds.\n * @group Implementation\n * @category Transactions\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 * This function ensures that the sequence number is updated and synchronized, handling potential delays in transaction commits.\n *\n * @returns {BigInt} The next available sequence number.\n * @group Implementation\n * @category Transactions\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 = nowInSeconds();\n while (this.currentNumber! - this.lastUncommintedNumber! >= this.maximumInFlight) {\n await sleep(this.sleepTime);\n if (nowInSeconds() - startTime > this.maxWaitTime) {\n /* eslint-disable no-console */\n console.warn(\n `Waited over 30 seconds for a transaction to commit, re-syncing ${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 * @returns {Promise<void>} A promise that resolves when the account has been initialized.\n *\n * @throws {Error} Throws an error if the account information cannot be retrieved.\n * @group Implementation\n * @category Transactions\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's sequence number with the one on-chain.\n *\n * @returns The on-chain sequence number for this account.\n * @group Implementation\n * @category Transactions\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 the local sequence number with the sequence number on-chain for the specified account.\n * This function polls the network until all submitted transactions have either been committed or until the maximum wait time has elapsed.\n *\n * @throws {Error} Throws an error if there is an issue synchronizing the account sequence number with the one on-chain.\n * @group Implementation\n * @category Transactions\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 = nowInSeconds();\n while (this.lastUncommintedNumber !== this.currentNumber) {\n if (nowInSeconds() - startTime > this.maxWaitTime) {\n /* eslint-disable no-console */\n console.warn(\n `Waited over 30 seconds for a transaction to commit, re-syncing ${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","/* eslint-disable no-await-in-loop */\n\nimport EventEmitter from \"eventemitter3\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport { Account } from \"../../account\";\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\n/**\n * @group Implementation\n * @category Transactions\n */\nexport const promiseFulfilledStatus = \"fulfilled\";\n\n/**\n * Events emitted by the transaction worker during its operation, allowing the dapp to respond to various transaction states.\n * @group Implementation\n * @category Transactions\n */\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/**\n * Defines the events emitted by the transaction worker during various stages of transaction processing. *\n * @group Implementation\n * @category Transactions\n */\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/**\n * The payload for when the worker has finished its job.\n * @group Implementation\n * @category Transactions\n */\nexport type ExecutionFinishEventData = {\n message: string;\n};\n\n/**\n * The payload for a success event.\n * @group Implementation\n * @category Transactions\n */\nexport type SuccessEventData = {\n message: string;\n transactionHash: string;\n};\n\n/**\n * The payload for a failure event.\n * @group Implementation\n * @category Transactions\n */\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 * @group Implementation\n * @category Transactions\n */\nexport class TransactionWorker extends EventEmitter<TransactionWorkerEvents> {\n readonly aptosConfig: AptosConfig;\n\n readonly account: Account;\n\n // current account sequence number\n // TODO: Rename Sequnce -> Sequence\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 * @group Implementation\n * @category Transactions\n */\n transactionsQueue = new AsyncQueue<\n [InputGenerateTransactionPayloadData, InputGenerateTransactionOptions | undefined]\n >();\n\n /**\n * signed transactions waiting to be submitted\n * @group Implementation\n * @category Transactions\n */\n outstandingTransactions = new AsyncQueue<[Promise<PendingTransactionResponse>, bigint]>();\n\n /**\n * transactions that have been submitted to chain\n * @group Implementation\n * @category Transactions\n */\n sentTransactions: Array<[string, bigint, any]> = [];\n\n /**\n * transactions that have been committed to chain\n * @group Implementation\n * @category Transactions\n */\n executedTransactions: Array<[string, bigint, any]> = [];\n\n /**\n * Initializes a new instance of the class, providing a framework for receiving payloads to be processed.\n *\n * @param aptosConfig - A configuration object for Aptos.\n * @param account - The account that will be used for sending transactions.\n * @param maxWaitTime - The maximum wait time to wait before re-syncing the sequence number to the current on-chain state,\n * default is 30 seconds.\n * @param maximumInFlight - The maximum number of transactions that can be submitted per account, default is 100.\n * @param sleepTime - The time to wait in seconds before re-evaluating if the maximum number of transactions are in flight,\n * default is 10 seconds.\n * @group Implementation\n * @category Transactions\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 * Submits the next transaction for the account by generating it with the current sequence number\n * and adding it to the outstanding transaction queue for processing.\n * This function continues to submit transactions until there are no more to process.\n *\n * @throws {Error} Throws an error if the transaction submission fails.\n * @group Implementation\n * @category Transactions\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 transactions to the chain.\n * This function processes each transaction, checking their status and emitting events based on whether they were successfully\n * sent or failed.\n *\n * @throws {Error} Throws an error if the process execution fails.\n * @event TransactionWorkerEventsEnum.TransactionSent - Emitted when a transaction has been successfully committed to the chain.\n * @event TransactionWorkerEventsEnum.TransactionSendFailed - Emitted when a transaction fails to commit, along with the error\n * reason.\n * @event TransactionWorkerEventsEnum.ExecutionFinish - Emitted when the execution of transactions is complete.\n * @group Implementation\n * @category Transactions\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 a transaction has been sent to the chain, this function checks for its execution status.\n * @param sentTransaction - The transaction that was sent to the chain and is now waiting to be executed.\n * @param sequenceNumber - The account's sequence number that was sent with the transaction.\n * @group Implementation\n * @category Transactions\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 * Pushes a transaction to the transactions queue for processing.\n *\n * @param transactionData - The transaction payload containing necessary details.\n * @param transactionData.abi - For all entry function payloads, the ABI to skip remote ABI lookups.\n * @param options - Optional parameters for transaction configuration.\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 * @group Implementation\n * @category Transactions\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 the chain.\n *\n * @param account - An Aptos account used as the sender of the transaction.\n * @param sequenceNumber - A sequence number the transaction will be generated with.\n * @returns A signed transaction object or undefined if the transaction queue is empty.\n * @group Implementation\n * @category Transactions\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, replayProtectionNonce: undefined },\n });\n }\n\n /**\n * Starts transaction submission and processing by executing tasks from the queue until it is cancelled.\n *\n * @throws {Error} Throws an error if unable to start transaction batching.\n * @group Implementation\n * @category Transactions\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 * @throws {Error} Throws an error if the worker has already started.\n * @group Implementation\n * @category Transactions\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 transaction management process.\n *\n * @throws {Error} Throws an error if the worker has already stopped.\n * @group Implementation\n * @category Transactions\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","// 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 FeePayerOrFeePayerAuthenticatorOrNeither,\n getSigningMessage,\n publicPackageTransaction,\n signAndSubmitAsFeePayer,\n signAndSubmitTransaction,\n signAsFeePayer,\n signTransaction,\n} from \"../internal/transactionSubmission\";\nimport {\n AccountAuthenticator,\n AnyRawTransaction,\n InputGenerateTransactionOptions,\n InputGenerateTransactionPayloadData,\n InputTransactionPluginData,\n} from \"../transactions\";\nimport { AccountAddressInput, AccountPublicKey, AuthenticationKey, Ed25519PrivateKey } from \"../core\";\nimport { Account, Ed25519Account, MultiEd25519Account } from \"../account\";\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\";\nimport { rotateAuthKey, rotateAuthKeyUnverified } from \"../internal/account\";\n\n/**\n * Represents a transaction in the Aptos blockchain,\n * providing methods to build, simulate, submit, and manage transactions.\n * This class encapsulates functionalities for querying transaction details,\n * estimating gas prices, signing transactions, and handling transaction states.\n *\n * This class is used as part of the Aptos object, so should be called like so:\n * @example\n * ```typescript\n * import { Account, Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const APTOS_COIN = \"0x1::aptos_coin::AptosCoin\";\n * const COIN_STORE = `0x1::coin::CoinStore<${APTOS_COIN}>`;\n * const ALICE_INITIAL_BALANCE = 100_000_000;\n * const TRANSFER_AMOUNT = 100;\n *\n * async function example() {\n * console.log(\n * \"This example will create two accounts (Alice and Bob), fund them, and transfer between them.\",\n * );\n *\n * // Set up the client\n * const config = new AptosConfig({ network: Network.DEVNET });\n * const aptos = new Aptos(config);\n *\n * // Generate two account credentials\n * // Each account has a private key, a public key, and an address\n * const alice = Account.generate();\n * const bob = Account.generate();\n *\n * console.log(\"=== Addresses ===\\n\");\n * console.log(`Alice's address is: ${alice.accountAddress}`);\n * console.log(`Bob's address is: ${bob.accountAddress}`);\n *\n * // Fund the accounts using a faucet\n * console.log(\"\\n=== Funding accounts ===\\n\");\n *\n * await aptos.fundAccount({\n * accountAddress: alice.accountAddress,\n * amount: ALICE_INITIAL_BALANCE,\n * });\n *\n * // Send a transaction from Alice's account to Bob's account\n * const txn = await aptos.transaction.build.simple({\n * sender: alice.accountAddress,\n * data: {\n * // All transactions on Aptos are implemented via smart contracts.\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [bob.accountAddress, 100],\n * },\n * });\n *\n * console.log(\"\\n=== Transfer transaction ===\\n\");\n * // Both signs and submits\n * const committedTxn = await aptos.signAndSubmitTransaction({\n * signer: alice,\n * transaction: txn,\n * });\n * // Waits for Aptos to verify and execute the transaction\n * const executedTransaction = await aptos.waitForTransaction({\n * transactionHash: committedTxn.hash,\n * });\n * console.log(\"Transaction hash:\", executedTransaction.hash);\n *\n * console.log(\"\\n=== Balances after transfer ===\\n\");\n * const newAliceAccountBalance = await aptos.getAccountResource({\n * accountAddress: alice.accountAddress,\n * resourceType: COIN_STORE,\n * });\n * const newAliceBalance = Number(newAliceAccountBalance.coin.value);\n * console.log(`Alice's balance is: ${newAliceBalance}`);\n *\n * const newBobAccountBalance = await aptos.getAccountResource({\n * accountAddress: bob.accountAddress,\n * resourceType: COIN_STORE,\n * });\n * const newBobBalance = Number(newBobAccountBalance.coin.value);\n * console.log(`Bob's balance is: ${newBobBalance}`);\n * }\n *\n * example();\n * ```\n * @group Transaction\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 /**\n * Creates an instance of the Aptos client with the specified configuration.\n * This allows you to interact with the Aptos blockchain using the provided settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., Testnet, Mainnet).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a new Aptos client instance\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify the network\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client created successfully:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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, excluding pending transactions.\n * Use this function to retrieve historical transactions from the blockchain.\n *\n * @param args Optional parameters for pagination.\n * @param args.options Optional pagination options.\n * @param args.options.offset The number of the transaction to start with.\n * @param args.options.limit The number of results to return.\n *\n * @returns An array of on-chain transactions.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetch transactions with pagination\n * const transactions = await aptos.getTransactions({\n * options: {\n * offset: 0, // Start from the first transaction\n * limit: 10, // Limit to 10 results\n * },\n * });\n *\n * console.log(transactions);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 * @param args - The arguments for querying the transaction.\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 * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching a transaction by its version\n * const transaction = await aptos.getTransactionByVersion({ ledgerVersion: 1 }); // replace 1 with a real version\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 transactions by their transaction hash, returning both pending and committed transactions.\n *\n * @param args - The arguments for querying the transaction.\n * @param args.transactionHash - The transaction hash should be a hex-encoded bytes string with a 0x prefix.\n * @returns The transaction from the mempool (pending) or the on-chain (committed) transaction.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetch a transaction by its hash\n * const transaction = await aptos.getTransactionByHash({ transactionHash: \"0x123\" }); // replace with a real transaction hash\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group 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 the specified transaction is currently in a pending state.\n * This function helps you determine the status of a transaction using its hash.\n *\n * @param args - The arguments for the function.\n * @param args.transactionHash - A hash of the transaction in hexadecimal format.\n * @returns `true` if the transaction is in a pending state and `false` otherwise.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Check if the transaction is pending using its hash\n * const isPendingTransaction = await aptos.isPendingTransaction({ transactionHash: \"0x123\" }); // replace with a real transaction hash\n * console.log(\"Is the transaction pending?\", isPendingTransaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 and provides the transaction response.\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 * @param args.transactionHash - The hash of a transaction previously submitted to the blockchain.\n * @param args.options - Optional parameters for waiting behavior.\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.\n * @returns The transaction on-chain response.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Wait for a transaction to complete using its hash\n * const transactionHash = \"0x123\"; // replace with a real transaction hash\n * const transactionResponse = await aptos.waitForTransaction({\n * transactionHash,\n * options: {\n * timeoutSecs: 30, // specify your own timeout if needed\n * checkSuccess: true,\n * },\n * });\n *\n * console.log(transactionResponse);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 * Estimates the gas unit price required to process a transaction on the Aptos blockchain in a timely manner.\n * This helps users to understand the cost associated with their transactions.\n * {@link https://api.mainnet.aptoslabs.com/v1/spec#/operations/estimate_gas_price}\n *\n * @returns An object containing the estimated gas price.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your network\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Getting the gas price estimation\n * const gasPriceEstimation = await aptos.getGasPriceEstimation();\n *\n * console.log(\"Estimated Gas Price:\", gasPriceEstimation);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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, allowing a user to sign it using their preferred method before submission to the network.\n *\n * @param args - The arguments for obtaining the signing message.\n * @param args.transaction - A raw transaction for signing elsewhere.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const transaction = await aptos.transaction.build.simple({\n * sender: \"0x1\", // replace with a real sender address\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [\"0x2\", 100], // replace with a real destination address\n * },\n * });\n *\n * const message = await aptos.getSigningMessage({ transaction });\n * console.log(message);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 the blockchain.\n * This function helps you create a transaction that can be simulated or submitted to the chain for publishing a package.\n *\n * To get the `metadataBytes` and `byteCode`, can compile using Aptos CLI with command\n * `aptos move compile --save-metadata ...`,\n *\n * {@link https://aptos.dev/tutorials/your-first-dapp/#step-4-publish-a-move-module}\n *\n * @param args The arguments for publishing the package.\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 * @param args.options Optional settings for generating the transaction.\n *\n * @returns A SimpleTransaction that can be simulated or submitted to the chain.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Replace with a real account address\n * const account = \"0x1\";\n * const metadataBytes = \"0x...\"; // replace with real metadata bytes\n * const byteCode = \"0x...\"; // replace with real module bytecode\n *\n * const transaction = await aptos.publishPackageTransaction({\n * account,\n * metadataBytes,\n * moduleBytecode: [byteCode],\n * });\n *\n * console.log(transaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 * Rotates the authentication key for a given account. Once an account is rotated, only the new private key\n * or keyless signing scheme can be used to sign transactions for the account.\n *\n * @param args - The arguments for rotating the authentication key.\n * @param args.fromAccount - The account from which the authentication key will be rotated.\n * @param args.toAccount - (Optional) The target account to rotate to. Required if not using toNewPrivateKey.\n * @param args.toNewPrivateKey - (Optional) The new private key to rotate to. Required if not using toAccount.\n *\n * @remarks\n * This function supports three modes of rotation:\n * 1. Using a target Account object (toAccount)\n * 2. Using a new private key (toNewPrivateKey)\n *\n * For Ed25519 accounts, the function will use a challenge-based rotation that requires signatures from both the old and new keys.\n * For multi-key accounts like MultiEd25519Account, the function will use a challenge-based rotation that requires signatures from both keys.\n * For other account types, the function will use an unverified rotation that only requires the new public key.\n *\n * @returns SimpleTransaction that can be submitted to rotate the auth key\n *\n * @example\n * ```typescript\n * // Create and submit transaction to rotate the auth key\n * const transaction = await aptos.rotateAuthKey({\n * fromAccount,\n * toAccount: toAccount,\n * });\n *\n * // Sign and submit the transaction\n * const pendingTransaction = await aptos.signAndSubmitTransaction({\n * signer: fromAccount,\n * transaction,\n * });\n * ```\n * @group Transaction\n */\n async rotateAuthKey(\n args: {\n fromAccount: Account;\n options?: InputGenerateTransactionOptions;\n } & ({ toAccount: Ed25519Account | MultiEd25519Account } | { toNewPrivateKey: Ed25519PrivateKey }),\n ): Promise<SimpleTransaction> {\n return rotateAuthKey({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Rotates the authentication key for a given account without verifying the new key.\n *\n * Accounts with their auth key rotated via this function will be derivable via the `getAccountsForPublicKey` and\n * `deriveOwnedAccountsFromSigner` functions however the public key will be unverified (no proof of ownership). Thus\n * includeUnverified must be set to true to derive the account until the public key is verified via signing a transaction.\n *\n * @param args - The arguments for rotating the authentication key.\n * @param args.fromAccount - The account from which the authentication key will be rotated.\n * @param args.toNewPublicKey - The new public key to rotate to.\n *\n * @returns A simple transaction object that can be submitted to the network.\n *\n * @example\n * ```typescript\n * // Create and submit transaction to rotate the auth key\n * const transaction = await aptos.rotateAuthKeyUnverified({\n * fromAccount,\n * toNewPublicKey,\n * });\n *\n * // Sign and submit the transaction\n * const pendingTransaction = await aptos.signAndSubmitTransaction({\n * signer: fromAccount,\n * transaction,\n * });\n * ```\n * @group Transaction\n */\n async rotateAuthKeyUnverified(args: {\n fromAccount: Account;\n options?: InputGenerateTransactionOptions;\n toNewPublicKey: AccountPublicKey;\n }): Promise<SimpleTransaction> {\n return rotateAuthKeyUnverified({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Sign a transaction that can later be submitted to the chain.\n * This function is essential for ensuring the authenticity of the transaction by using the provided account's signing capabilities.\n *\n * @param args - The arguments for signing the transaction.\n * @param args.signer - The account that will sign the transaction.\n * @param args.transaction - A raw transaction to sign.\n *\n * @returns AccountAuthenticator - The authenticator for the signed transaction.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const sender = Account.generate(); // Generate a new account for signing\n * const transaction = await aptos.transaction.build.simple({\n * sender: sender.accountAddress,\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [ \"0x1\", 100 ], // replace with a real account address and amount\n * },\n * });\n *\n * const signedTransaction = await aptos.transaction.sign({\n * signer: sender,\n * transaction,\n * }); // Sign the transaction\n *\n * console.log(\"Signed Transaction:\", signedTransaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 the chain.\n * This function ensures that the transaction is marked with the fee payer's address, allowing it to be processed correctly.\n *\n * @param args - The arguments for signing the transaction.\n * @param args.signer - The fee payer signer account.\n * @param args.transaction - A raw transaction to sign on. This transaction must include a `feePayerAddress` property.\n *\n * @returns AccountAuthenticator - The authenticator for the signed transaction.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const sender = Account.generate(); // Generate a new account for the fee payer\n * const transaction = await aptos.transaction.build.simple({\n * // All transactions on Aptos are implemented via smart contracts.\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [sender.accountAddress, 100],\n * feePayerAddress: sender.accountAddress, // Set the fee payer address\n * });\n *\n * const signedTransaction = await aptos.transaction.signAsFeePayer({\n * signer: sender,\n * transaction,\n * });\n *\n * console.log(\"Signed transaction as fee payer:\", signedTransaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\n */\n // eslint-disable-next-line class-methods-use-this\n signAsFeePayer(args: { signer: Account; transaction: AnyRawTransaction }): AccountAuthenticator {\n return signAsFeePayer({\n ...args,\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 by submitting multiple transaction payloads.\n * This function is useful for efficiently processing and submitting transactions that do not depend on each other, such as\n * batch funding or batch token minting.\n *\n * @param args - The arguments for batching transactions.\n * @param args.sender - The sender account to sign and submit the transactions.\n * @param args.data - An array of transaction payloads to be processed.\n * @param args.options - Optional. Transaction generation configurations (excluding accountSequenceNumber).\n *\n * @throws Error if any worker failure occurs during submission.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, Account } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n * const sender = Account.generate(); // Generate a new account for sending transactions\n *\n * async function runExample() {\n * const transactions = [\n * { }, // Build your first transaction payload\n * { }, // Build your second transaction payload\n * ];\n *\n * // Batch transactions for the single account\n * await aptos.batchTransactionsForSingleAccount({\n * sender,\n * data: transactions,\n * });\n *\n * console.log(\"Batch transactions submitted successfully.\");\n * }\n * runExample().catch(console.error);\n * ```\n * @group Transaction\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 the blockchain.\n * This function allows you to execute a transaction after signing it with the specified account.\n *\n * @param args The arguments for signing and submitting the transaction.\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 * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const sender = Account.generate(); // Generate a new account for sending the transaction\n * const transaction = await aptos.transaction.build.simple({\n * sender: sender.accountAddress,\n * data: {\n * function: \"0x1::aptos_account::transfer\",\n * functionArguments: [ \"0x1\", 100 ], // replace with a real account address\n * },\n * });\n *\n * // Sign and submit the transaction\n * const pendingTransaction = await aptos.signAndSubmitTransaction({\n * signer: sender,\n * transaction,\n * });\n *\n * console.log(pendingTransaction);\n * }\n * runExample().catch(console.error);\n * ```\n * @return PendingTransactionResponse\n * @group Transaction\n */\n async signAndSubmitTransaction(\n args: FeePayerOrFeePayerAuthenticatorOrNeither & {\n signer: Account;\n transaction: AnyRawTransaction;\n } & InputTransactionPluginData,\n ): Promise<PendingTransactionResponse> {\n return signAndSubmitTransaction({\n aptosConfig: this.config,\n ...args,\n });\n }\n\n /**\n * Sign and submit a single signer transaction as the fee payer to chain given an authenticator by the sender of the transaction.\n *\n * @param args.feePayer The fee payer account to sign the transaction\n * @param args.senderAuthenticator The AccountAuthenticator signed by the sender of 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({sender: alice.accountAddress, feePayer: true ...})\n * const senderAuthenticator = alice.signTransactionWithAuthenticator(transaction)\n * const pendingTransaction = await aptos.signAndSubmitAsFeePayer({\n * senderAuthenticator,\n * feePayer: bob,\n * transaction,\n * })\n *\n * @return PendingTransactionResponse\n * @group Transaction\n */\n async signAndSubmitAsFeePayer(\n args: {\n feePayer: Account;\n senderAuthenticator: AccountAuthenticator;\n transaction: AnyRawTransaction;\n } & InputTransactionPluginData,\n ): Promise<PendingTransactionResponse> {\n return signAndSubmitAsFeePayer({\n aptosConfig: this.config,\n ...args,\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/keyless}. By moving the methods out into a separate file,\n * other namespaces and processes can access these methods without depending on the entire\n * keyless namespace and without having a dependency cycle error.\n * @group Implementation\n */\nimport { jwtDecode, JwtPayload } from \"jwt-decode\";\nimport { AptosConfig } from \"../api/aptosConfig\";\nimport { postAptosPepperService, postAptosProvingService } from \"../client\";\nimport {\n AccountAddressInput,\n EphemeralSignature,\n Groth16Zkp,\n Hex,\n KeylessPublicKey,\n MoveJWK,\n ZeroKnowledgeSig,\n ZkProof,\n getKeylessConfig,\n} from \"../core\";\nimport { HexInput, ZkpVariant } from \"../types\";\nimport { Account, EphemeralKeyPair, KeylessAccount, ProofFetchCallback } from \"../account\";\nimport { PepperFetchRequest, PepperFetchResponse, ProverRequest, ProverResponse } from \"../types/keyless\";\nimport { lookupOriginalAccountAddress } from \"./account\";\nimport { FederatedKeylessPublicKey } from \"../core/crypto/federatedKeyless\";\nimport { FederatedKeylessAccount } from \"../account/FederatedKeylessAccount\";\nimport { MoveVector } from \"../bcs\";\nimport { generateTransaction } from \"./transactionSubmission\";\nimport { InputGenerateTransactionOptions, SimpleTransaction } from \"../transactions\";\nimport { KeylessError, KeylessErrorType } from \"../errors\";\nimport { FIREBASE_AUTH_ISS_PATTERN } from \"../utils/const\";\n\n/**\n * Retrieves a pepper value based on the provided configuration and authentication details.\n *\n * @param args - The arguments required to fetch the pepper.\n * @param args.aptosConfig - The configuration object for Aptos.\n * @param args.jwt - The JSON Web Token used for authentication.\n * @param args.ephemeralKeyPair - The ephemeral key pair used for the operation.\n * @param args.uidKey - An optional unique identifier key (defaults to \"sub\").\n * @param args.derivationPath - An optional derivation path for the key.\n * @returns A Uint8Array containing the fetched pepper value.\n * @group Implementation\n */\nexport async function getPepper(args: {\n aptosConfig: AptosConfig;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n uidKey?: string;\n derivationPath?: string;\n}): Promise<Uint8Array> {\n const { aptosConfig, jwt, ephemeralKeyPair, uidKey = \"sub\", derivationPath } = args;\n\n const body = {\n jwt_b64: jwt,\n epk: ephemeralKeyPair.getPublicKey().bcsToHex().toStringWithoutPrefix(),\n exp_date_secs: ephemeralKeyPair.expiryDateSecs,\n epk_blinder: Hex.fromHexInput(ephemeralKeyPair.blinder).toStringWithoutPrefix(),\n uid_key: uidKey,\n derivation_path: derivationPath,\n };\n const { data } = await postAptosPepperService<PepperFetchRequest, PepperFetchResponse>({\n aptosConfig,\n path: \"fetch\",\n body,\n originMethod: \"getPepper\",\n overrides: { WITH_CREDENTIALS: false },\n });\n return Hex.fromHexInput(data.pepper).toUint8Array();\n}\n\n/**\n * Generates a zero-knowledge proof based on the provided parameters.\n * This function is essential for creating a signed proof that can be used in various cryptographic operations.\n *\n * @param args - The parameters required to generate the proof.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.jwt - The JSON Web Token used for authentication.\n * @param args.ephemeralKeyPair - The ephemeral key pair used for generating the proof.\n * @param args.pepper - An optional hex input used to enhance security (default is generated if not provided).\n * @param args.uidKey - An optional string that specifies the unique identifier key (defaults to \"sub\").\n * @throws Error if the pepper length is not valid or if the ephemeral key pair's lifespan exceeds the maximum allowed.\n * @group Implementation\n */\nexport async function getProof(args: {\n aptosConfig: AptosConfig;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n pepper?: HexInput;\n uidKey?: string;\n maxExpHorizonSecs?: number;\n}): Promise<ZeroKnowledgeSig> {\n const {\n aptosConfig,\n jwt,\n ephemeralKeyPair,\n pepper = await getPepper(args),\n uidKey = \"sub\",\n maxExpHorizonSecs = (await getKeylessConfig({ aptosConfig })).maxExpHorizonSecs,\n } = args;\n if (Hex.fromHexInput(pepper).toUint8Array().length !== KeylessAccount.PEPPER_LENGTH) {\n throw new Error(`Pepper needs to be ${KeylessAccount.PEPPER_LENGTH} bytes`);\n }\n const decodedJwt = jwtDecode<JwtPayload>(jwt);\n if (typeof decodedJwt.iat !== \"number\") {\n throw new Error(\"iat was not found\");\n }\n if (maxExpHorizonSecs < ephemeralKeyPair.expiryDateSecs - decodedJwt.iat) {\n throw Error(`The EphemeralKeyPair is too long lived. It's lifespan must be less than ${maxExpHorizonSecs}`);\n }\n const json = {\n jwt_b64: jwt,\n epk: ephemeralKeyPair.getPublicKey().bcsToHex().toStringWithoutPrefix(),\n epk_blinder: Hex.fromHexInput(ephemeralKeyPair.blinder).toStringWithoutPrefix(),\n exp_date_secs: ephemeralKeyPair.expiryDateSecs,\n exp_horizon_secs: maxExpHorizonSecs,\n pepper: Hex.fromHexInput(pepper).toStringWithoutPrefix(),\n uid_key: uidKey,\n };\n\n const { data } = await postAptosProvingService<ProverRequest, ProverResponse>({\n aptosConfig,\n path: \"prove\",\n body: json,\n originMethod: \"getProof\",\n overrides: { WITH_CREDENTIALS: false },\n });\n\n const proofPoints = data.proof;\n const groth16Zkp = new Groth16Zkp({\n a: proofPoints.a,\n b: proofPoints.b,\n c: proofPoints.c,\n });\n\n const signedProof = new ZeroKnowledgeSig({\n proof: new ZkProof(groth16Zkp, ZkpVariant.Groth16),\n trainingWheelsSignature: EphemeralSignature.fromHex(data.training_wheels_signature),\n expHorizonSecs: maxExpHorizonSecs,\n });\n return signedProof;\n}\n\n/**\n * Derives a keyless account by fetching the necessary proof and looking up the original account address.\n * This function helps in creating a keyless account that can be used without managing private keys directly.\n *\n * @param args - The arguments required to derive the keyless account.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param args.jwt - The JSON Web Token used for authentication.\n * @param args.ephemeralKeyPair - The ephemeral key pair used for cryptographic operations.\n * @param args.uidKey - An optional unique identifier key for the user.\n * @param args.pepper - An optional hexadecimal input used for additional security.\n * @param args.proofFetchCallback - An optional callback function to handle the proof fetch outcome.\n * @returns A keyless account object.\n * @group Implementation\n */\nexport async function deriveKeylessAccount(args: {\n aptosConfig: AptosConfig;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n}): Promise<KeylessAccount>;\n\nexport async function deriveKeylessAccount(args: {\n aptosConfig: AptosConfig;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n jwkAddress: AccountAddressInput;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n}): Promise<FederatedKeylessAccount>;\n\nexport async function deriveKeylessAccount(args: {\n aptosConfig: AptosConfig;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n jwkAddress?: AccountAddressInput;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n}): Promise<KeylessAccount | FederatedKeylessAccount>;\n\nexport async function deriveKeylessAccount(args: {\n aptosConfig: AptosConfig;\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n jwkAddress?: AccountAddressInput;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n}): Promise<KeylessAccount | FederatedKeylessAccount> {\n const { aptosConfig, jwt, jwkAddress, uidKey, proofFetchCallback, pepper = await getPepper(args) } = args;\n const { verificationKey, maxExpHorizonSecs } = await getKeylessConfig({ aptosConfig });\n\n const proofPromise = getProof({ ...args, pepper, maxExpHorizonSecs });\n // If a callback is provided, pass in the proof as a promise to KeylessAccount.create. This will make the proof be fetched in the\n // background and the callback will handle the outcome of the fetch. This allows the developer to not have to block on the proof fetch\n // allowing for faster rendering of UX.\n //\n // If no callback is provided, the just await the proof fetch and continue synchronously.\n const proof = proofFetchCallback ? proofPromise : await proofPromise;\n\n // Look up the original address to handle key rotations and then instantiate the account.\n if (jwkAddress !== undefined) {\n const publicKey = FederatedKeylessPublicKey.fromJwtAndPepper({ jwt, pepper, jwkAddress, uidKey });\n const address = await lookupOriginalAccountAddress({\n aptosConfig,\n authenticationKey: publicKey.authKey().derivedAddress(),\n });\n\n return FederatedKeylessAccount.create({\n ...args,\n address,\n proof,\n pepper,\n proofFetchCallback,\n jwkAddress,\n verificationKey,\n });\n }\n\n const publicKey = KeylessPublicKey.fromJwtAndPepper({ jwt, pepper, uidKey });\n const address = await lookupOriginalAccountAddress({\n aptosConfig,\n authenticationKey: publicKey.authKey().derivedAddress(),\n });\n return KeylessAccount.create({ ...args, address, proof, pepper, proofFetchCallback, verificationKey });\n}\n\nexport interface JWKS {\n keys: MoveJWK[];\n}\n\nexport async function updateFederatedKeylessJwkSetTransaction(args: {\n aptosConfig: AptosConfig;\n sender: Account;\n iss: string;\n jwksUrl?: string;\n options?: InputGenerateTransactionOptions;\n}): Promise<SimpleTransaction> {\n const { aptosConfig, sender, iss, options } = args;\n\n let { jwksUrl } = args;\n\n if (jwksUrl === undefined) {\n if (FIREBASE_AUTH_ISS_PATTERN.test(iss)) {\n jwksUrl = \"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com\";\n } else {\n jwksUrl = iss.endsWith(\"/\") ? `${iss}.well-known/jwks.json` : `${iss}/.well-known/jwks.json`;\n }\n }\n\n let response: Response;\n\n try {\n response = await fetch(jwksUrl);\n if (!response.ok) {\n throw new Error(`${response.status} ${response.statusText}`);\n }\n } catch (error) {\n let errorMessage: string;\n if (error instanceof Error) {\n errorMessage = `${error.message}`;\n } else {\n errorMessage = `error unknown - ${error}`;\n }\n throw KeylessError.fromErrorType({\n type: KeylessErrorType.JWK_FETCH_FAILED_FEDERATED,\n details: `Failed to fetch JWKS at ${jwksUrl}: ${errorMessage}`,\n });\n }\n\n const jwks: JWKS = await response.json();\n return generateTransaction({\n aptosConfig,\n sender: sender.accountAddress,\n data: {\n function: \"0x1::jwks::update_federated_jwk_set\",\n functionArguments: [\n iss,\n MoveVector.MoveString(jwks.keys.map((key) => key.kid)),\n MoveVector.MoveString(jwks.keys.map((key) => key.alg)),\n MoveVector.MoveString(jwks.keys.map((key) => key.e)),\n MoveVector.MoveString(jwks.keys.map((key) => key.n)),\n ],\n },\n options,\n });\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Account, EphemeralKeyPair, KeylessAccount, ProofFetchCallback } from \"../account\";\nimport { FederatedKeylessAccount } from \"../account/FederatedKeylessAccount\";\nimport { AccountAddressInput, ZeroKnowledgeSig } from \"../core\";\nimport {\n deriveKeylessAccount,\n getPepper,\n getProof,\n updateFederatedKeylessJwkSetTransaction,\n} from \"../internal/keyless\";\nimport { InputGenerateTransactionOptions, SimpleTransaction } from \"../transactions\";\nimport { HexInput } from \"../types\";\nimport { AptosConfig } from \"./aptosConfig\";\n\n/**\n * A class to query all `Keyless` related queries on Aptos.\n *\n * More documentation on how to integrate Keyless Accounts see the below\n * [Aptos Keyless Integration Guide](https://aptos.dev/guides/keyless-accounts/#aptos-keyless-integration-guide).\n * @group Keyless\n */\nexport class Keyless {\n /**\n * Initializes a new instance of the Aptos class with the provided configuration.\n * This allows you to interact with the Aptos blockchain using the specified network settings.\n *\n * @param config - The configuration settings for connecting to the Aptos network.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a new configuration for the Aptos client\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your desired network\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Keyless\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Fetches the pepper from the Aptos pepper service API.\n *\n * @param args - The arguments for fetching the pepper.\n * @param args.jwt - JWT token.\n * @param args.ephemeralKeyPair - The EphemeralKeyPair used to generate the nonce in the JWT token.\n * @param args.derivationPath - A derivation path used for creating multiple accounts per user via the BIP-44 standard. Defaults\n * to \"m/44'/637'/0'/0'/0\".\n * @returns The pepper which is a Uint8Array of length 31.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const ephemeralKeyPair = new EphemeralKeyPair(); // create a new ephemeral key pair\n * const jwt = \"your_jwt_token\"; // replace with a real JWT token\n *\n * // Fetching the pepper using the provided JWT and ephemeral key pair\n * const pepper = await aptos.getPepper({\n * jwt,\n * ephemeralKeyPair,\n * // derivationPath: \"m/44'/637'/0'/0'/0\" // specify your own if needed\n * });\n *\n * console.log(\"Fetched pepper:\", pepper);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Keyless\n */\n async getPepper(args: {\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n derivationPath?: string;\n }): Promise<Uint8Array> {\n return getPepper({ aptosConfig: this.config, ...args });\n }\n\n /**\n * Fetches a proof from the Aptos prover service API.\n *\n * @param args - The arguments for fetching the proof.\n * @param args.jwt - JWT token.\n * @param args.ephemeralKeyPair - The EphemeralKeyPair used to generate the nonce in the JWT token.\n * @param args.pepper - The pepper used for the account. If not provided, it will be fetched from the Aptos pepper service.\n * @param args.uidKey - A key in the JWT token to use to set the uidVal in the IdCommitment.\n *\n * @returns The proof which is represented by a ZeroKnowledgeSig.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, EphemeralKeyPair, getPepper } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const jwt = \"your_jwt_token\"; // replace with a real JWT token\n * const ephemeralKeyPair = new EphemeralKeyPair(); // create a new ephemeral key pair\n *\n * // Fetch the proof using the getProof function\n * const proof = await aptos.getProof({\n * jwt,\n * ephemeralKeyPair,\n * pepper: await getPepper({}), // fetch the pepper if not provided\n * uidKey: \"sub\", // specify the uid key\n * });\n *\n * console.log(\"Fetched proof:\", proof);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Keyless\n */\n async getProof(args: {\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n pepper?: HexInput;\n uidKey?: string;\n }): Promise<ZeroKnowledgeSig> {\n return getProof({ aptosConfig: this.config, ...args });\n }\n\n async deriveKeylessAccount(args: {\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n }): Promise<KeylessAccount>;\n\n async deriveKeylessAccount(args: {\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n jwkAddress: AccountAddressInput;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n }): Promise<FederatedKeylessAccount>;\n\n /**\n * Derives a Keyless Account from the provided JWT token and corresponding EphemeralKeyPair. This function computes the proof\n * via the proving service and can fetch the pepper from the pepper service if not explicitly provided.\n *\n * @param args - The arguments required to derive the Keyless Account.\n * @param args.jwt - The JWT token used for deriving the account.\n * @param args.ephemeralKeyPair - The EphemeralKeyPair used to generate the nonce in the JWT token.\n * @param args.jwkAddress - The address the where the JWKs used to verify signatures are found. Setting the value derives a\n * FederatedKeylessAccount.\n * @param args.uidKey - An optional key in the JWT token to set the uidVal in the IdCommitment.\n * @param args.pepper - An optional pepper value.\n * @param args.proofFetchCallback - An optional callback function for fetching the proof in the background, allowing for a more\n * responsive user experience.\n *\n * @returns A KeylessAccount that can be used to sign transactions.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network, deriveKeylessAccount } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * const jwt = \"your_jwt_token\"; // replace with a real JWT token\n * const ephemeralKeyPair = new EphemeralKeyPair(); // create a new ephemeral key pair\n *\n * // Deriving the Keyless Account\n * const keylessAccount = await deriveKeylessAccount({\n * jwt,\n * ephemeralKeyPair,\n * uidKey: \"your_uid_key\", // optional\n * pepper: \"your_pepper\", // optional\n * });\n *\n * console.log(\"Keyless Account derived:\", keylessAccount);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Keyless\n */\n async deriveKeylessAccount(args: {\n jwt: string;\n ephemeralKeyPair: EphemeralKeyPair;\n jwkAddress?: AccountAddressInput;\n uidKey?: string;\n pepper?: HexInput;\n proofFetchCallback?: ProofFetchCallback;\n }): Promise<KeylessAccount | FederatedKeylessAccount> {\n return deriveKeylessAccount({ aptosConfig: this.config, ...args });\n }\n\n /**\n * This installs a set of FederatedJWKs at an address for a given iss.\n *\n * It will fetch the JSON Web Keyset (JWK) set from the well-known endpoint and update the FederatedJWKs at the sender's address\n * to reflect it.\n *\n * @param args.sender The account that will install the JWKs\n * @param args.iss the iss claim of the federated OIDC provider.\n * @param args.jwksUrl the URL to find the corresponding JWKs. For supported IDP providers this parameter in not necessary.\n *\n * @returns The pending transaction that results from submission.\n * @group Keyless\n */\n async updateFederatedKeylessJwkSetTransaction(args: {\n sender: Account;\n iss: string;\n jwksUrl?: string;\n options?: InputGenerateTransactionOptions;\n }): Promise<SimpleTransaction> {\n return updateFederatedKeylessJwkSetTransaction({ aptosConfig: this.config, ...args });\n }\n}\n","import { AptosConfig } from \"../api/aptosConfig\";\nimport { AccountAddressInput, AccountAddress } from \"../core\";\nimport { PaginationArgs, OrderByArg, GetObjectDataQueryResponse, WhereArg } from \"../types\";\nimport { GetObjectDataQuery } from \"../types/generated/operations\";\nimport { GetObjectData } from \"../types/generated/queries\";\nimport { CurrentObjectsBoolExp } from \"../types/generated/types\";\nimport { queryIndexer } from \"./general\";\n\n/**\n * Retrieves the current objects based on specified filtering and pagination options.\n *\n * @param args - The arguments for retrieving object data.\n * @param args.aptosConfig - The configuration settings for Aptos.\n * @param [args.options] - Optional parameters for pagination and filtering.\n * @param [args.options.offset] - The number of items to skip before starting to collect the result set.\n * @param [args.options.limit] - The maximum number of items to return.\n * @param [args.options.orderBy] - The criteria for ordering the results.\n * @param [args.options.where] - The conditions to filter the results.\n * @returns The current objects that match the specified criteria.\n * @group Implementation\n */\nexport async function getObjectData(args: {\n aptosConfig: AptosConfig;\n options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]> & WhereArg<CurrentObjectsBoolExp>;\n}): Promise<GetObjectDataQueryResponse> {\n const { aptosConfig, options } = args;\n\n const graphqlQuery = {\n query: GetObjectData,\n variables: {\n where_condition: options?.where,\n offset: options?.offset,\n limit: options?.limit,\n order_by: options?.orderBy,\n },\n };\n const data = await queryIndexer<GetObjectDataQuery>({\n aptosConfig,\n query: graphqlQuery,\n originMethod: \"getObjectData\",\n });\n\n return data.current_objects;\n}\n\n/**\n * Retrieves the object data associated with a specific object address.\n * This function allows you to access detailed information about an object in the Aptos blockchain.\n *\n * @param args - The arguments for retrieving object data.\n * @param args.aptosConfig - The configuration for connecting to the Aptos blockchain.\n * @param args.objectAddress - The address of the object whose data is being retrieved.\n * @param args.options - Optional parameters for pagination and ordering of the results.\n * @group Implementation\n */\nexport async function getObjectDataByObjectAddress(args: {\n aptosConfig: AptosConfig;\n objectAddress: AccountAddressInput;\n options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]>;\n}): Promise<GetObjectDataQueryResponse[0]> {\n const { aptosConfig, objectAddress, options } = args;\n const address = AccountAddress.from(objectAddress).toStringLong();\n\n const whereCondition: { object_address: { _eq: string } } = {\n object_address: { _eq: address },\n };\n return (await getObjectData({ aptosConfig, options: { ...options, where: whereCondition } }))[0];\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AnyNumber, GetObjectDataQueryResponse, OrderByArg, PaginationArgs } from \"../types\";\nimport { AccountAddressInput } from \"../core\";\nimport { AptosConfig } from \"./aptosConfig\";\nimport { ProcessorType } from \"../utils\";\nimport { waitForIndexerOnVersion } from \"./utils\";\nimport { getObjectDataByObjectAddress } from \"../internal/object\";\n\n/**\n * A class to query all `Object` related queries on Aptos.\n * @group Object\n */\nexport class AptosObject {\n /**\n * Creates an instance of the Aptos client with the provided configuration.\n * This allows interaction with the Aptos blockchain using the specified settings.\n *\n * @param config - The configuration settings for the Aptos client.\n * @param config.network - The network to connect to (e.g., mainnet, testnet).\n * @param config.nodeUrl - The URL of the Aptos node to connect to.\n * @param config.faucetUrl - The URL of the faucet for funding accounts (optional).\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for the Aptos client\n * const config = new AptosConfig({\n * network: Network.TESTNET, // Specify the desired network\n * nodeUrl: \"https://testnet.aptos.dev\", // Replace with your node URL\n * });\n *\n * // Create an instance of the Aptos client\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client created successfully\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Object\n */\n constructor(readonly config: AptosConfig) {}\n\n /**\n * Fetches the object data based on the specified object address.\n *\n * @param args.objectAddress - The object address to retrieve data for.\n * @param args.minimumLedgerVersion - Optional minimum ledger version to wait for.\n * @param args.options - Optional configuration options for pagination and ordering.\n *\n * @returns The object data corresponding to the provided address.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * const config = new AptosConfig({ network: Network.TESTNET });\n * const aptos = new Aptos(config);\n *\n * async function runExample() {\n * // Fetching object data by object address\n * const objectData = await aptos.getObjectDataByObjectAddress({\n * objectAddress: \"0x1\", // replace with a real object address\n * });\n *\n * console.log(objectData);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Object\n */\n async getObjectDataByObjectAddress(args: {\n objectAddress: AccountAddressInput;\n minimumLedgerVersion?: AnyNumber;\n options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]>;\n }): Promise<GetObjectDataQueryResponse[0]> {\n await waitForIndexerOnVersion({\n config: this.config,\n minimumLedgerVersion: args.minimumLedgerVersion,\n processorType: ProcessorType.OBJECT_PROCESSOR,\n });\n return getObjectDataByObjectAddress({\n aptosConfig: this.config,\n ...args,\n });\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 { Faucet } from \"./faucet\";\nimport { FungibleAsset } from \"./fungibleAsset\";\nimport { General } from \"./general\";\nimport { ANS } from \"./ans\";\nimport { Staking } from \"./staking\";\nimport { Transaction } from \"./transaction\";\nimport { Table } from \"./table\";\nimport { Keyless } from \"./keyless\";\nimport { AptosObject } from \"./object\";\nimport { AccountAbstraction } from \"./account/abstraction\";\n\n/**\n * The main entry point for interacting with the Aptos APIs,\n * providing access to various functionalities organized into\n * distinct namespaces.\n *\n * To utilize the SDK, instantiate a new Aptos object to gain\n * access to the complete range of SDK features.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a configuration for connecting to the Aptos testnet\n * const config = new AptosConfig({ network: Network.TESTNET });\n *\n * // Initialize the Aptos client with the configuration\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Client\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 faucet: Faucet;\n\n readonly fungibleAsset: FungibleAsset;\n\n readonly general: General;\n\n readonly staking: Staking;\n\n readonly transaction: Transaction;\n\n readonly table: Table;\n\n readonly keyless: Keyless;\n\n readonly object: AptosObject;\n\n /**\n * Initializes a new instance of the Aptos client with the provided configuration settings.\n * This allows you to interact with various Aptos functionalities such as accounts, transactions, and events.\n *\n * @param settings - Configuration settings for the Aptos client.\n *\n * @example\n * ```typescript\n * import { Aptos, AptosConfig, Network } from \"@aptos-labs/ts-sdk\";\n *\n * async function runExample() {\n * // Create a new Aptos client with default settings\n * const config = new AptosConfig({ network: Network.TESTNET }); // Specify your own settings if needed\n * const aptos = new Aptos(config);\n *\n * console.log(\"Aptos client initialized:\", aptos);\n * }\n * runExample().catch(console.error);\n * ```\n * @group Client\n */\n constructor(config?: AptosConfig) {\n this.config = config ?? new AptosConfig();\n this.account = new Account(this.config);\n this.abstraction = new AccountAbstraction(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.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 this.table = new Table(this.config);\n this.keyless = new Keyless(this.config);\n this.object = new AptosObject(this.config);\n }\n\n setIgnoreTransactionSubmitter(ignore: boolean) {\n this.config.setIgnoreTransactionSubmitter(ignore);\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 Keyless,\n Staking,\n Table,\n AptosObject,\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 * @group Client\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\n // Define new method that calls through baseClassProp\n Object.defineProperty(targetClass.prototype, propertyName, {\n value: function (...args: any[]) {\n return (this as any)[baseClassProp][propertyName](...args);\n },\n writable: propertyDescriptor.writable,\n configurable: propertyDescriptor.configurable,\n enumerable: propertyDescriptor.enumerable,\n });\n });\n}\n\napplyMixin(Aptos, Account, \"account\");\napplyMixin(Aptos, AccountAbstraction, \"abstraction\");\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\");\napplyMixin(Aptos, Table, \"table\");\napplyMixin(Aptos, Keyless, \"keyless\");\napplyMixin(Aptos, AptosObject, \"object\");\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { AccountPublicKey, PublicKey } from \"./publicKey\";\nimport { Deserializer, Serializer } from \"../../bcs\";\nimport { HexInput, AnyPublicKeyVariant, SigningScheme } from \"../../types\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { AccountAddress, AccountAddressInput } from \"../accountAddress\";\nimport {\n KeylessConfiguration,\n KeylessPublicKey,\n KeylessSignature,\n MoveJWK,\n verifyKeylessSignature,\n verifyKeylessSignatureWithJwkAndConfig,\n} from \"./keyless\";\nimport { AptosConfig } from \"../../api\";\nimport { Signature } from \"..\";\n\n/**\n * Represents the FederatedKeylessPublicKey public key\n *\n * These keys use an on-chain address as a source of truth for the JWK used to verify signatures.\n *\n * FederatedKeylessPublicKey authentication key is represented in the SDK as `AnyPublicKey`.\n * @group Implementation\n * @category Serialization\n */\nexport class FederatedKeylessPublicKey extends AccountPublicKey {\n /**\n * The address that contains the JWK set to be used for verification.\n * @group Implementation\n * @category Serialization\n */\n readonly jwkAddress: AccountAddress;\n\n /**\n * The inner public key which contains the standard Keyless public key.\n * @group Implementation\n * @category Serialization\n */\n readonly keylessPublicKey: KeylessPublicKey;\n\n constructor(jwkAddress: AccountAddressInput, keylessPublicKey: KeylessPublicKey) {\n super();\n this.jwkAddress = AccountAddress.from(jwkAddress);\n this.keylessPublicKey = keylessPublicKey;\n }\n\n /**\n * Get the authentication key for the federated keyless public key\n *\n * @returns AuthenticationKey\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n const serializer = new Serializer();\n serializer.serializeU32AsUleb128(AnyPublicKeyVariant.FederatedKeyless);\n serializer.serializeFixedBytes(this.bcsToBytes());\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: SigningScheme.SingleKey,\n input: serializer.toUint8Array(),\n });\n }\n\n /**\n * Verifies a signed data with a public key\n *\n * @param args.message message\n * @param args.signature The signature\n * @param args.jwk - The JWK to use for verification.\n * @param args.keylessConfig - The keyless configuration to use for verification.\n * @returns true if the signature is valid\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: {\n message: HexInput;\n signature: Signature;\n jwk: MoveJWK;\n keylessConfig: KeylessConfiguration;\n }): boolean {\n try {\n verifyKeylessSignatureWithJwkAndConfig({ ...args, publicKey: this });\n return true;\n } catch (error) {\n return false;\n }\n }\n\n serialize(serializer: Serializer): void {\n this.jwkAddress.serialize(serializer);\n this.keylessPublicKey.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): FederatedKeylessPublicKey {\n const jwkAddress = AccountAddress.deserialize(deserializer);\n const keylessPublicKey = KeylessPublicKey.deserialize(deserializer);\n return new FederatedKeylessPublicKey(jwkAddress, keylessPublicKey);\n }\n\n static isPublicKey(publicKey: PublicKey): publicKey is FederatedKeylessPublicKey {\n return publicKey instanceof FederatedKeylessPublicKey;\n }\n\n /**\n * Verifies a keyless signature for a given message. It will fetch the keyless configuration and the JWK to\n * use for verification from the appropriate network as defined by the aptosConfig.\n *\n * @param args.aptosConfig The aptos config to use for fetching the keyless configuration.\n * @param args.message The message to verify the signature against.\n * @param args.signature The signature to verify.\n * @param args.options.throwErrorWithReason Whether to throw an error with the reason for the failure instead of returning false.\n * @returns true if the signature is valid\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: KeylessSignature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n return verifyKeylessSignature({\n ...args,\n publicKey: this,\n });\n }\n\n /**\n * Creates a FederatedKeylessPublicKey from the JWT components plus pepper\n *\n * @param args.iss the iss of the identity\n * @param args.uidKey the key to use to get the uidVal in the JWT token\n * @param args.uidVal the value of the uidKey in the JWT token\n * @param args.aud the client ID of the application\n * @param args.pepper The pepper used to maintain privacy of the account\n * @returns FederatedKeylessPublicKey\n * @group Implementation\n * @category Serialization\n */\n static create(args: {\n iss: string;\n uidKey: string;\n uidVal: string;\n aud: string;\n pepper: HexInput;\n jwkAddress: AccountAddressInput;\n }): FederatedKeylessPublicKey {\n return new FederatedKeylessPublicKey(args.jwkAddress, KeylessPublicKey.create(args));\n }\n\n static fromJwtAndPepper(args: {\n jwt: string;\n pepper: HexInput;\n jwkAddress: AccountAddressInput;\n uidKey?: string;\n }): FederatedKeylessPublicKey {\n return new FederatedKeylessPublicKey(args.jwkAddress, KeylessPublicKey.fromJwtAndPepper(args));\n }\n\n static isInstance(publicKey: PublicKey) {\n return (\n \"jwkAddress\" in publicKey &&\n publicKey.jwkAddress instanceof AccountAddress &&\n \"keylessPublicKey\" in publicKey &&\n publicKey.keylessPublicKey instanceof KeylessPublicKey\n );\n }\n}\n","import { HexInput, SigningScheme } from \"../../types\";\nimport { Hex } from \"../hex\";\nimport { Ed25519PublicKey } from \"./ed25519\";\nimport { FederatedKeylessPublicKey } from \"./federatedKeyless\";\nimport { KeylessPublicKey } from \"./keyless\";\nimport { MultiEd25519PublicKey } from \"./multiEd25519\";\nimport { MultiKey } from \"./multiKey\";\nimport { AccountPublicKey } from \"./publicKey\";\nimport { AnyPublicKey } from \"./singleKey\";\nimport { BaseAccountPublicKey } from \"./types\";\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 * @group Implementation\n * @category Serialization\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\n if (!isValid.valid) {\n return new TextEncoder().encode(message);\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\nexport const accountPublicKeyToBaseAccountPublicKey = (publicKey: AccountPublicKey): BaseAccountPublicKey => {\n if (\n publicKey instanceof Ed25519PublicKey ||\n publicKey instanceof AnyPublicKey ||\n publicKey instanceof MultiEd25519PublicKey ||\n publicKey instanceof MultiKey\n ) {\n return publicKey;\n }\n if (publicKey instanceof KeylessPublicKey || publicKey instanceof FederatedKeylessPublicKey) {\n return new AnyPublicKey(publicKey);\n }\n throw new Error(`Unknown account public key: ${publicKey}`);\n};\n\nexport const accountPublicKeyToSigningScheme = (publicKey: AccountPublicKey): SigningScheme => {\n const baseAccountPublicKey = accountPublicKeyToBaseAccountPublicKey(publicKey);\n if (baseAccountPublicKey instanceof Ed25519PublicKey) {\n return SigningScheme.Ed25519;\n } else if (baseAccountPublicKey instanceof AnyPublicKey) {\n return SigningScheme.SingleKey;\n } else if (baseAccountPublicKey instanceof MultiEd25519PublicKey) {\n return SigningScheme.MultiEd25519;\n } else if (baseAccountPublicKey instanceof MultiKey) {\n return SigningScheme.MultiKey;\n }\n throw new Error(`Unknown signing scheme: ${baseAccountPublicKey}`);\n};\n","import { Serializer, Deserializer } from \"../../bcs\";\nimport { EphemeralPublicKeyVariant, EphemeralSignatureVariant, HexInput } from \"../../types\";\nimport { PublicKey } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { Ed25519PublicKey, Ed25519Signature } from \"./ed25519\";\nimport { Hex } from \"../hex\";\nimport { AptosConfig } from \"../../api\";\n\n/**\n * Represents ephemeral public keys for Aptos Keyless accounts.\n *\n * These keys are used only temporarily within Keyless accounts and are not utilized as public keys for account identification.\n * @group Implementation\n * @category Serialization\n */\nexport class EphemeralPublicKey extends PublicKey {\n /**\n * The public key itself\n * @group Implementation\n * @category Serialization\n */\n public readonly publicKey: PublicKey;\n\n /**\n * An enum indicating the scheme of the ephemeral public key\n * @group Implementation\n * @category Serialization\n */\n public readonly variant: EphemeralPublicKeyVariant;\n\n /**\n * Creates an instance of EphemeralPublicKey using the provided public key.\n * This constructor ensures that only supported signature types are accepted.\n *\n * @param publicKey - The public key to be used for the ephemeral public key.\n * @throws Error if the signature type is unsupported.\n * @group Implementation\n * @category Serialization\n */\n constructor(publicKey: PublicKey) {\n super();\n const publicKeyType = publicKey.constructor.name;\n switch (publicKeyType) {\n case Ed25519PublicKey.name:\n this.publicKey = publicKey;\n this.variant = EphemeralPublicKeyVariant.Ed25519;\n break;\n default:\n throw new Error(`Unsupported key for EphemeralPublicKey - ${publicKeyType}`);\n }\n }\n\n /**\n * Verifies a signed message using the ephemeral public key.\n *\n * @param args - The arguments for the verification.\n * @param args.message - The message that was signed.\n * @param args.signature - The signature that was signed by the private key of the ephemeral public key.\n * @returns true if the signature is valid, otherwise false.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: { message: HexInput; signature: EphemeralSignature }): boolean {\n const { message, signature } = args;\n return this.publicKey.verifySignature({ message, signature: signature.signature });\n }\n\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: EphemeralSignature;\n }): Promise<boolean> {\n return this.verifySignature(args);\n }\n\n /**\n * Serializes the current instance, specifically handling the Ed25519 signature type.\n * This function ensures that the signature is properly serialized using the provided serializer.\n *\n * @param serializer - The serializer instance used to serialize the signature.\n * @throws Error if the signature type is unknown.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n if (this.publicKey instanceof Ed25519PublicKey) {\n serializer.serializeU32AsUleb128(EphemeralPublicKeyVariant.Ed25519);\n this.publicKey.serialize(serializer);\n } else {\n throw new Error(\"Unknown public key type\");\n }\n }\n\n /**\n * Deserializes an EphemeralSignature from the provided deserializer.\n * This function allows you to retrieve an EphemeralSignature based on the deserialized data.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): EphemeralPublicKey {\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case EphemeralPublicKeyVariant.Ed25519:\n return new EphemeralPublicKey(Ed25519PublicKey.deserialize(deserializer));\n default:\n throw new Error(`Unknown variant index for EphemeralPublicKey: ${index}`);\n }\n }\n\n /**\n * Determines if the provided public key is an instance of `EphemeralPublicKey`.\n *\n * @param publicKey - The public key to check.\n * @returns A boolean indicating whether the public key is an ephemeral type.\n * @group Implementation\n * @category Serialization\n */\n static isPublicKey(publicKey: PublicKey): publicKey is EphemeralPublicKey {\n return publicKey instanceof EphemeralPublicKey;\n }\n}\n\n/**\n * Represents ephemeral signatures used in Aptos Keyless accounts.\n *\n * These signatures are utilized within the KeylessSignature framework.\n * @group Implementation\n * @category Serialization\n */\nexport class EphemeralSignature extends Signature {\n /**\n * The signature signed by the private key of an EphemeralKeyPair\n * @group Implementation\n * @category Serialization\n */\n public readonly signature: Signature;\n\n constructor(signature: Signature) {\n super();\n const signatureType = signature.constructor.name;\n switch (signatureType) {\n case Ed25519Signature.name:\n this.signature = signature;\n break;\n default:\n throw new Error(`Unsupported signature for EphemeralSignature - ${signatureType}`);\n }\n }\n\n /**\n * Deserializes an ephemeral signature from a hexadecimal input.\n * This function allows you to convert a hexadecimal representation of an ephemeral signature into its deserialized form for\n * further processing.\n *\n * @param hexInput - The hexadecimal input representing the ephemeral signature.\n * @group Implementation\n * @category Serialization\n */\n static fromHex(hexInput: HexInput): EphemeralSignature {\n const data = Hex.fromHexInput(hexInput);\n const deserializer = new Deserializer(data.toUint8Array());\n return EphemeralSignature.deserialize(deserializer);\n }\n\n serialize(serializer: Serializer): void {\n if (this.signature instanceof Ed25519Signature) {\n serializer.serializeU32AsUleb128(EphemeralSignatureVariant.Ed25519);\n this.signature.serialize(serializer);\n } else {\n throw new Error(\"Unknown signature type\");\n }\n }\n\n static deserialize(deserializer: Deserializer): EphemeralSignature {\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case EphemeralSignatureVariant.Ed25519:\n return new EphemeralSignature(Ed25519Signature.deserialize(deserializer));\n default:\n throw new Error(`Unknown variant index for EphemeralSignature: ${index}`);\n }\n }\n}\n"],"mappings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ACE,MAAM,IAAI,MAAM,iDAAiDC,CAAK,EAAE,CAC5E,CACF,CAUA,OAAO,YAAYR,EAAuD,CACxE,OAAOA,aAAqBF,CAC9B,CACF,EASaW,GAAN,MAAMC,UAA2BC,CAAU,CAQhD,YAAYN,EAAsB,CAChC,MAAM,EACN,IAAMO,EAAgBP,EAAU,YAAY,KAC5C,OAAQO,EAAe,CACrB,KAAKC,EAAiB,KACpB,KAAK,UAAYR,EACjB,MACF,QACE,MAAM,IAAI,MAAM,kDAAkDO,CAAa,EAAE,CACrF,CACF,CAWA,OAAO,QAAQE,EAAwC,CACrD,IAAMC,EAAOC,EAAI,aAAaF,CAAQ,EAChCP,EAAe,IAAIU,EAAaF,EAAK,aAAa,CAAC,EACzD,OAAOL,EAAmB,YAAYH,CAAY,CACpD,CAEA,UAAUD,EAA8B,CACtC,GAAI,KAAK,qBAAqBO,EAC5BP,EAAW,uBAAuD,EAClE,KAAK,UAAU,UAAUA,CAAU,MAEnC,OAAM,IAAI,MAAM,wBAAwB,CAE5C,CAEA,OAAO,YAAYC,EAAgD,CACjE,IAAMC,EAAQD,EAAa,wBAAwB,EACnD,OAAQC,EAAO,CACb,OACE,OAAO,IAAIE,EAAmBG,EAAiB,YAAYN,CAAY,CAAC,EAC1E,QACE,MAAM,IAAI,MAAM,iDAAiDC,CAAK,EAAE,CAC5E,CACF,CACF","names":["ed25519","jwtDecode","sha3_256","bn254","bytesToNumberBE","encode","sha3_256","secp256k1","HDKey","_Secp256k1PublicKey","PublicKey","hexInput","hex","Hex","length","point","secp256k1","args","message","signature","messageToVerify","convertSigningMessage","messageBytes","messageSha3Bytes","sha3_256","signatureBytes","serializer","deserializer","Secp256k1Signature","bytes","publicKey","Secp256k1PublicKey","_Secp256k1PrivateKey","Serializable","strict","privateKeyHex","PrivateKey","path","mnemonics","isValidBIP44Path","mnemonicToSeed","seed","privateKey","HDKey","messageToSign","messageHashBytes","Secp256k1PrivateKey","_Secp256k1Signature","Signature","data","AnyPublicKey","_AnyPublicKey","AccountPublicKey","publicKey","Ed25519PublicKey","Secp256k1PublicKey","Secp256r1PublicKey","KeylessPublicKey","FederatedKeylessPublicKey","args","message","signature","AnySignature","AuthenticationKey","serializer","deserializer","variantIndex","_AnySignature","Signature","Ed25519Signature","Secp256k1Signature","WebAuthnSignature","KeylessSignature","bitCount","byte","n","MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY","AbstractMultiKey","AccountPublicKey","args","bits","firstBitInByte","bitmap","dupCheckSet","bit","idx","byteOffset","publicKey","index","pk","MultiKey","_MultiKey","publicKeys","signaturesRequired","AnyPublicKey","message","signature","signerIndices","i","singleSignature","MultiKeySignature","error","AuthenticationKey","serializer","deserializer","keys","anyPublicKey","value","_MultiKeySignature","Signature","signatures","AnySignature","nSignatures","acc","_MultiEd25519PublicKey","AbstractMultiKey","args","publicKeys","threshold","message","signature","MultiEd25519Signature","indices","i","j","index","AuthenticationKey","bytes","Ed25519PublicKey","k","serializer","deserializer","keys","begin","length","publicKey","MultiEd25519PublicKey","_MultiEd25519Signature","Signature","signatures","bitmap","Ed25519Signature","bits","firstBitInByte","dupCheckSet","bit","byteOffset","byte","MULTIPLE_DESERIALIZATIONS_ERROR_MSG","deserializePublicKey","publicKey","publicKeyTypes","Ed25519PublicKey","AnyPublicKey","MultiEd25519PublicKey","MultiKey","KeylessPublicKey","FederatedKeylessPublicKey","Secp256k1PublicKey","result","KeyType","deserializer","Deserializer","key","error","deserializeSignature","signature","signatureTypes","Ed25519Signature","AnySignature","MultiEd25519Signature","MultiKeySignature","KeylessSignature","Secp256k1Signature","SignatureType","sig","AccountAuthenticator","Serializable","deserializer","index","AccountAuthenticatorEd25519","AccountAuthenticatorMultiEd25519","AccountAuthenticatorSingleKey","AccountAuthenticatorMultiKey","AccountAuthenticatorNoAccountAuthenticator","AccountAuthenticatorAbstraction","_AccountAuthenticatorEd25519","public_key","signature","serializer","Ed25519PublicKey","Ed25519Signature","_AccountAuthenticatorMultiEd25519","MultiEd25519PublicKey","MultiEd25519Signature","_AccountAuthenticatorSingleKey","AnyPublicKey","AnySignature","_AccountAuthenticatorMultiKey","public_keys","signatures","MultiKey","MultiKeySignature","_AccountAuthenticatorNoAccountAuthenticator","_AccountAuthenticatorAbstraction","functionInfo","signingMessageDigest","abstractionSignature","accountIdentity","isValidFunctionInfo","Hex","moduleAddress","moduleName","functionName","getFunctionParts","AccountAddress","variant","abstractPublicKey","AccountAbstractionMessage","_AccountAbstractionMessage","originalSigningMessage","functionInfoModuleAddress","functionInfoModuleName","functionInfoFunctionName","sha3Hash","ModuleId","_ModuleId","Serializable","address","name","moduleId","parts","AccountAddress","Identifier","serializer","deserializer","TypeTag","_TypeTag","Serializable","deserializer","address","AccountAddress","moduleName","Identifier","name","typeArgs","StructTag","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","structName","_StructTag","module_name","type_args","aptosCoinStructTag","stringStructTag","optionStructTag","objectStructTag","deserializeFromScriptArgument","deserializer","index","U8","U64","U128","AccountAddress","MoveVector","Bool","U16","U32","U256","Serialized","TransactionPayload","Serializable","TransactionPayloadScript","TransactionPayloadEntryFunction","TransactionPayloadMultiSig","TransactionInnerPayload","_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","TransactionInnerPayloadV1","_TransactionInnerPayloadV1","executable","extra_config","TransactionExecutable","TransactionExtraConfig","TransactionExecutableScript","TransactionExecutableEntryFunction","TransactionExecutableEmpty","_TransactionExecutableScript","_TransactionExecutableEntryFunction","_TransactionExecutableEmpty","_","TransactionExtraConfigV1","_TransactionExtraConfigV1","multisigAddress","replayProtectionNonce","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","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","MultiAgentTransaction","_MultiAgentTransaction","Serializable","rawTransaction","secondarySignerAddresses","feePayerAddress","serializer","deserializer","RawTransaction","AccountAddress","feePayerPresent","deriveTransactionType","transaction","FeePayerRawTransaction","MultiAgentRawTransaction","generateSigningMessage","bytes","domainSeparator","hash","sha3Hash","prefix","body","mergedArray","generateSigningMessageForSerializable","serializable","generateSigningMessageForTransaction","rawTxn","RAW_TRANSACTION_WITH_DATA_SALT","RAW_TRANSACTION_SALT","Ed25519Account","_Ed25519Account","args","privateKey","address","AccountAddress","Ed25519PrivateKey","path","mnemonic","message","AccountAuthenticatorEd25519","transaction","generateSigningMessageForTransaction","isSingleKeySigner","obj","SingleKeyAccount","_SingleKeyAccount","args","privateKey","address","AnyPublicKey","AccountAddress","scheme","Ed25519PrivateKey","Secp256k1PrivateKey","path","mnemonic","message","AccountAuthenticatorSingleKey","transaction","AnySignature","generateSigningMessageForTransaction","account","Account","args","scheme","legacy","Ed25519Account","SingleKeyAccount","privateKey","address","Ed25519PrivateKey","mnemonic","path","publicKey","randomBytes","TWO_WEEKS_IN_SECONDS","_EphemeralKeyPair","Serializable","args","privateKey","expiryDateSecs","blinder","EphemeralPublicKey","floorToWholeHour","nowInSeconds","Hex","generateBlinder","fields","padAndPackBytesWithLen","bytesToBigIntLE","nonceHash","poseidonHash","serializer","deserializer","variantIndex","Ed25519PrivateKey","bytes","Deserializer","data","EphemeralSignature","EphemeralKeyPair","randomBytes","EventEmitter","jwtDecode","isKeylessSigner","obj","_AbstractKeylessAccount","Serializable","args","address","ephemeralKeyPair","publicKey","uidKey","uidVal","aud","pepper","proof","proofFetchCallback","jwt","verificationKeyHash","AccountAddress","EventEmitter","ZeroKnowledgeSig","status","pepperBytes","Hex","AnyPublicKey","promise","error","serializer","deserializer","EphemeralKeyPair","message","signature","AnySignature","AccountAuthenticatorSingleKey","transaction","aptosConfig","KeylessError","header","jwtDecode","verificationKey","getKeylessConfig","expiryDateSecs","ephemeralPublicKey","ephemeralSignature","KeylessSignature","base64UrlDecode","EphemeralCertificate","raw","deriveTransactionType","signMess","TransactionAndProof","fetchJWK","AbstractKeylessAccount","generateSigningMessage","KeylessAccount","_KeylessAccount","AbstractKeylessAccount","args","publicKey","KeylessPublicKey","serializer","deserializer","address","proof","ephemeralKeyPair","jwt","uidKey","pepper","verificationKeyHash","iss","aud","uidVal","getIssAudAndUidVal","bytes","Deserializer","Hex","proofFetchCallback","verificationKey","FederatedKeylessAccount","_FederatedKeylessAccount","AbstractKeylessAccount","args","publicKey","FederatedKeylessPublicKey","serializer","deserializer","address","proof","ephemeralKeyPair","jwt","uidKey","pepper","verificationKeyHash","jwkAddress","AccountAddress","iss","aud","uidVal","getIssAudAndUidVal","bytes","Deserializer","proofFetchCallback","verificationKey","MultiKeyAccount","_MultiKeyAccount","args","multiKey","address","signers","signer","Ed25519Account","SingleKeyAccount","AccountAddress","bitPositions","signersAndBitPosition","index","b","value","publicKeys","signaturesRequired","MultiKey","account","message","AccountAuthenticatorMultiKey","transaction","promises","AbstractKeylessAccount","aptosConfig","data","signatures","MultiKeySignature","MultiEd25519Account","args","signers","publicKey","address","AccountAddress","bitPositions","signer","signersAndBitPosition","index","b","value","message","AccountAuthenticatorMultiEd25519","transaction","signatures","MultiEd25519Signature","generateSigningMessageForTransaction","deserializeSchemeAndAddress","deserializer","signingScheme","SigningScheme","AccountAddress","serializeKeylessAccountCommon","account","serializer","deserializeKeylessAccountCommon","deserializer","jwt","uidKey","pepper","ephemeralKeyPair","EphemeralKeyPair","proof","ZeroKnowledgeSig","verificationKeyHash","AccountUtils","toBytes","Serializer","isSingleKeySigner","anyPublicKey","federatedKeylessAccount","multiKeyAccount","signer","toHexStringWithoutPrefix","Hex","toHexString","deserialize","address","signingScheme","deserializeSchemeAndAddress","privateKey","Ed25519PrivateKey","Ed25519Account","variantIndex","SingleKeyAccount","Secp256k1PrivateKey","keylessComponents","jwtClaims","getIssAudAndUidVal","KeylessAccount","jwkAddress","AccountAddress","audless","FederatedKeylessAccount","multiKey","MultiKey","length","signers","i","MultiKeyAccount","keylessAccountFromHex","hex","fromHex","federatedKeylessAccountFromHex","multiKeyAccountFromHex","singleKeyAccountFromHex","ed25519AccountFromHex","Deserializer","fromBytes","bytes","sha3_256","AbstractedAccount","_AbstractedAccount","Account","signer","accountAddress","authenticationFunction","isValidFunctionInfo","AbstractPublicKey","digest","AbstractSignature","serializer","Serializer","message","functionInfo","accountAbstractionMessage","AccountAbstractionMessage","generateSigningMessage","ACCOUNT_ABSTRACTION_SIGNING_DATA_SALT","AccountAuthenticatorAbstraction","sha3_256","transaction","generateSigningMessageForTransaction","sha3_256","_DerivableAbstractedAccount","AbstractedAccount","signer","authenticationFunction","abstractPublicKey","daaAccountAddress","AccountAddress","functionInfo","accountIdentifier","isValidFunctionInfo","moduleAddress","moduleName","functionName","hash","sha3_256","serializer","Serializer","s2","message","AccountAuthenticatorAbstraction","DerivableAbstractedAccount","sha3Hash","isValidIdentifier","str","isValidWhitespaceCharacter","char","isGeneric","isRef","isPrimitive","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","trimmedStr","lowerCaseTrimmed","TypeTagSigner","TypeTagBool","TypeTagAddress","TypeTagU8","TypeTagU16","TypeTagU32","TypeTagU64","TypeTagU128","TypeTagU256","TypeTagVector","actualType","TypeTagReference","TypeTagGeneric","structParts","address","AccountAddress","TypeTagStruct","StructTag","Identifier","isBool","arg","isString","isNumber","convertNumber","isLargeNumber","isEmptyOption","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","TEXT_ENCODER","standardizeTypeTags","typeArguments","typeArg","isString","parseTypeTag","fetchModuleAbi","moduleAddress","moduleName","aptosConfig","getModule","fetchFunctionAbi","functionName","moduleAbi","func","fetchMoveFunctionAbi","functionAbi","params","i","fetchEntryFunctionAbi","numSigners","findFirstNonSignerArg","fetchViewFunctionAbi","returnTypes","convertArgument","functionAbiOrModuleAbi","arg","position","genericTypeParams","options","param","checkOrConvertArgument","isEncodedEntryFunctionArgument","checkType","parseArg","isBool","Bool","throwTypeMismatch","AccountAddress","num","convertNumber","U8","U16","U32","isLargeNumber","U64","U128","U256","genericIndex","MoveVector","item","MoveString","FixedBytes","isEmptyOption","innerParam","TypeTagBool","MoveOption","TypeTagAddress","TypeTagU8","TypeTagU16","TypeTagU32","TypeTagU64","TypeTagU128","TypeTagU256","s","isBcsBool","isBcsAddress","isBcsU8","isBcsU16","isBcsU32","isBcsU64","isBcsU128","isBcsU256","TypeTagStruct","isBcsString","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","replayProtectionNonce","txnPayload","convertPayloadToInnerPayload","RawTransaction","ChainId","TransactionInnerPayloadV1","TransactionExecutableScript","TransactionExtraConfigV1","TransactionExecutableEntryFunction","innerPayload","executable","TransactionExecutableEmpty","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","AccountAuthenticatorMultiKey","TransactionAuthenticatorSingleSender","AccountAuthenticatorNoAccountAuthenticator","accountPublicKey","KeylessPublicKey","FederatedKeylessPublicKey","Secp256k1PublicKey","AnyPublicKey","invalidSignature","Ed25519Signature","Ed25519PublicKey","AnySignature","KeylessSignature","MultiKey","MultiKeySignature","pubKey","_","generateSignedTransaction","additionalSignersAuthenticators","senderAuthenticator","normalizeBundle","AccountAuthenticator","txnAuthenticator","AccountAuthenticatorMultiEd25519","TransactionAuthenticatorMultiEd25519","hashValues","input","hash","sha3Hash","item","TRANSACTION_PREFIX","generateUserTransactionHash","signedTransaction","key","abi","fetch","memoizeAsync","generateTransaction","args","payload","buildTransactionPayload","buildRawTransaction","aptosConfig","data","generateTransactionPayloadData","generateTransactionPayload","sender","options","feePayerAddress","isFeePayerTransactionInput","AccountAddress","isMultiAgentTransactionInput","secondarySignerAddresses","buildTransaction","getSigningMessage","transaction","generateSigningMessageForTransaction","signTransaction","signer","signAsFeePayer","simulateTransaction","signerPublicKey","secondarySignersPublicKeys","feePayerPublicKey","signedTransaction","generateSignedTransactionForSimulation","postAptosFullNode","submitTransaction","transactionSubmitter","maybeTransactionSubmitter","generateSignedTransaction","e","signedTxn","SignedTransaction","Deserializer","KeylessPublicKey","FederatedKeylessPublicKey","AbstractKeylessAccount","signAndSubmitTransaction","feePayer","rest","isKeylessSigner","feePayerAuthenticator","senderAuthenticator","signAndSubmitAsFeePayer","packagePublishAbi","TypeTagVector","publicPackageTransaction","account","metadataBytes","moduleBytecode","totalByteCode","bytecode","MoveVector","getInfo","args","getModules","aptosConfig","accountAddress","options","paginateWithObfuscatedCursor","AccountAddress","getModulesPage","response","cursor","getPageWithObfuscatedCursor","getModule","getTransactions","paginateWithCursor","getResources","getResourcesPage","getResource","resourceType","data","getAptosFullNode","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","faMetadataAddress","coinAssetType","faAddress","APTOS_COIN","createObjectAddress","addr","where","getAccountCoinsData","GetAccountCoinsData","getAccountCoinsCount","GetAccountCoinsCount","getBalance","asset","getAccountOwnedObjects","GetObjectData","deriveAccountFromPrivateKey","privateKey","throwIfNoAccountFound","accounts","deriveOwnedAccountsFromPrivateKey","Account","isAccountExist","authKey","doesAccountExistAtAddress","resources","ownedObjects","accountResource","r","error","rotateAuthKeyAbi","TypeTagU8","TypeTagVector","rotateAuthKey","fromAccount","rotateAuthKeyWithChallenge","Ed25519Account","accountInfo","newAccount","challengeHex","RotationProofChallenge","proofSignedByCurrentKey","proofSignedByNewKey","generateTransaction","U8","MoveVector","rotateAuthKeyUnverifiedAbi","rotateAuthKeyUnverified","toNewPublicKey","accountPublicKeyToSigningScheme","accountPublicKeyToBaseAccountPublicKey","getAccountsForPublicKey","publicKey","noMultiKey","AbstractMultiKey","allPublicKeys","AnyPublicKey","Ed25519PublicKey","defaultAccountData","multiPublicKeys","addressAndLastTxnVersion","getDefaultAccountInfoForPublicKey","getMultiKeysForPublicKey","result","authKeyToPublicKey","key","authKeyAccountAddressPairs","getAccountAddressesForAuthKeys","authKeyAccountAddressPair","a","b","deriveOwnedAccountsFromSigner","signer","Ed25519PrivateKey","Secp256k1PrivateKey","SingleKeyAccount","KeylessAccount","FederatedKeylessAccount","deriveOwnedAccountsFromKeylessSigner","MultiKeyAccount","MultiEd25519Account","keylessAccount","addressesAndPublicKeys","keylessAccountParams","MultiEd25519PublicKey","MultiKey","singleKeyAccount","isLegacy","includeUnverified","anyPublicKey","baseKey","variant","anyPublicKeyVariantToString","GetAuthKeysForPublicKey","entry","Deserializer","authKeys","GetAccountAddressesForAuthKey","AuthenticationKey","Hex","getLatestTransactionVersionForAddress","transactions","derivedAddress","lastTransactionVersion","exists","view","args","aptosConfig","payload","options","viewFunctionPayload","generateViewFunctionPayload","serializer","Serializer","bytes","data","postAptosFullNode","viewJson","addAuthenticationFunctionTransaction","args","aptosConfig","sender","authenticationFunction","options","moduleAddress","moduleName","functionName","getFunctionParts","generateTransaction","TypeTagAddress","TypeTagStruct","stringStructTag","removeAuthenticationFunctionTransaction","removeDispatchableAuthenticatorTransaction","AccountAbstraction","config","args","functionInfos","moduleAddress","moduleName","functionName","getFunctionParts","functionInfo","AccountAddress","accountAddress","authenticationFunction","options","addAuthenticationFunctionTransaction","removeAuthenticationFunctionTransaction","removeDispatchableAuthenticatorTransaction","functionInfoOption","view","TypeTagAddress","Account","config","AccountAbstraction","args","getInfo","getModules","getModulesPage","getModule","getTransactions","getResources","getResourcesPage","getResource","lookupOriginalAccountAddress","waitForIndexerOnVersion","getAccountTokensCount","getAccountOwnedTokens","getAccountOwnedTokensFromCollectionAddress","getAccountCollectionsWithOwnedTokens","getAccountTransactionsCount","getAccountCoinsData","getAccountCoinsCount","APTOS_COIN","APTOS_FA","accountAddress","coinType","faMetadataAddress","coinAssetType","memoizeAsync","pairedCoinTypeStruct","view","isEncodedStruct","parseEncodedStruct","faAddress","AccountAddress","createObjectAddress","addr","balanceStr","getBalance","getAccountOwnedObjects","deriveAccountFromPrivateKey","deriveOwnedAccountsFromSigner","getAccountsForPublicKey","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","GetCollectionData","getCollectionDataByCreatorAddressAndCollectionName","creatorAddress","collectionName","address","getCollectionDataByCreatorAddress","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","creatorAddress","collectionName","options","address","AccountAddress","whereCondition","getCollectionData","getCollectionDataByCreatorAddressAndCollectionName","getCollectionDataByCreatorAddress","getCollectionDataByCollectionId","getCollectionId","getDigitalAssetData","getCurrentDigitalAssetOwnership","getOwnedDigitalAssets","getDigitalAssetActivity","createCollectionTransaction","mintDigitalAssetTransaction","transferDigitalAssetTransaction","mintSoulBoundTransaction","burnDigitalAssetTransaction","freezeDigitalAssetTransferTransaction","unfreezeDigitalAssetTransferTransaction","setDigitalAssetDescriptionTransaction","setDigitalAssetNameTransaction","setDigitalAssetURITransaction","addDigitalAssetPropertyTransaction","removeDigitalAssetPropertyTransaction","updateDigitalAssetPropertyTransaction","addDigitalAssetTypedPropertyTransaction","updateDigitalAssetTypedPropertyTransaction","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","transferFungibleAssetBetweenStores","fromStore","toStore","FungibleAsset","config","args","waitForIndexerOnVersion","getFungibleAssetMetadata","AccountAddress","getFungibleAssetActivities","getCurrentFungibleAssetBalances","transferFungibleAsset","transferFungibleAssetBetweenStores","General","config","getLedgerInfo","args","getBlockByVersion","getBlockByHeight","view","viewJson","getChainTopUserTransactions","queryIndexer","getIndexerLastSuccessVersion","processorType","getProcessorStatus","VALIDATION_RULES_DESCRIPTION","isValidANSSegment","fragment","isValidANSName","name","first","second","rest","SubdomainExpirationPolicy","isActiveANSName","isTLDExpired","isExpired","LOCAL_ANS_ACCOUNT_PK","LOCAL_ANS_ACCOUNT_ADDRESS","NetworkToAnsContract","getRouterAddress","aptosConfig","address","unwrapOption","option","getOwnerAddress","args","routerAddress","domainName","subdomainName","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","getNumberOfDelegators","args","aptosConfig","poolAddress","address","AccountAddress","data","queryIndexer","GetNumberOfDelegators","getNumberOfDelegatorsForAllPools","options","query","getDelegatedStakingActivities","delegatorAddress","GetDelegatedStakingActivities","Staking","config","args","waitForIndexerOnVersion","getNumberOfDelegators","getNumberOfDelegatorsForAllPools","getDelegatedStakingActivities","Build","config","args","generateTransaction","Simulate","config","args","simulateTransaction","__decorateClass","ValidateFeePayerDataOnSimulation","Submit","config","args","validateFeePayerDataOnSubmission","submitTransaction","EventEmitter","AccountSequenceNumber","aptosConfig","account","maxWaitTime","maximumInFlight","sleepTime","sleep","nextNumber","startTime","nowInSeconds","e","sequenceNumber","getInfo","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","Transaction","config","Build","Simulate","Submit","TransactionManagement","args","getTransactions","getTransactionByVersion","getTransactionByHash","isTransactionPending","waitForTransaction","getGasPriceEstimation","getSigningMessage","publicPackageTransaction","rotateAuthKey","rotateAuthKeyUnverified","signTransaction","signAsFeePayer","sender","data","options","error","signAndSubmitTransaction","signAndSubmitAsFeePayer","jwtDecode","getPepper","args","aptosConfig","jwt","ephemeralKeyPair","uidKey","derivationPath","body","Hex","data","postAptosPepperService","getProof","pepper","maxExpHorizonSecs","getKeylessConfig","KeylessAccount","decodedJwt","jwtDecode","json","postAptosProvingService","proofPoints","groth16Zkp","Groth16Zkp","ZeroKnowledgeSig","ZkProof","EphemeralSignature","deriveKeylessAccount","jwkAddress","proofFetchCallback","verificationKey","proofPromise","proof","publicKey","FederatedKeylessPublicKey","address","lookupOriginalAccountAddress","FederatedKeylessAccount","KeylessPublicKey","updateFederatedKeylessJwkSetTransaction","sender","iss","options","jwksUrl","FIREBASE_AUTH_ISS_PATTERN","response","error","errorMessage","KeylessError","jwks","generateTransaction","MoveVector","key","Keyless","config","args","getPepper","getProof","deriveKeylessAccount","updateFederatedKeylessJwkSetTransaction","getObjectData","args","aptosConfig","options","graphqlQuery","GetObjectData","queryIndexer","getObjectDataByObjectAddress","objectAddress","whereCondition","AccountAddress","AptosObject","config","args","waitForIndexerOnVersion","getObjectDataByObjectAddress","Aptos","config","AptosConfig","Account","AccountAbstraction","ANS","Coin","DigitalAsset","Faucet","FungibleAsset","General","Staking","Transaction","Table","Keyless","AptosObject","ignore","applyMixin","targetClass","baseClass","baseClassProp","propertyName","propertyDescriptor","args","EPK_HORIZON_SECS","MAX_AUD_VAL_BYTES","MAX_UID_KEY_BYTES","MAX_UID_VAL_BYTES","MAX_ISS_VAL_BYTES","MAX_EXTRA_FIELD_BYTES","MAX_JWT_HEADER_B64_BYTES","MAX_COMMITED_EPK_BYTES","_KeylessPublicKey","AccountPublicKey","iss","idCommitment","idcBytes","Hex","serializer","Serializer","AuthenticationKey","args","verifyKeylessSignatureWithJwkAndConfig","error","KeylessError","verifyKeylessSignature","deserializer","addressSeed","publicKey","computeIdCommitment","jwt","pepper","uidKey","jwtPayload","jwtDecode","uidVal","KeylessPublicKey","aptosConfig","message","signature","jwk","keylessConfig","getKeylessConfig","options","KeylessSignature","fetchJWK","verificationKey","maxExpHorizonSecs","trainingWheelsPubkey","ZeroKnowledgeSig","zkSig","Groth16Zkp","groth16Proof","nowInSeconds","publicInputsHash","getPublicInputsHash","proofAndStatement","Groth16ProofAndStatement","innerKeylessPublicKey","proof","fields","padAndPackBytesWithLen","bytesToBigIntLE","hashStrToField","encode","poseidonHash","kid","keylessPubKey","allJWKs","jwkAddr","FederatedKeylessPublicKey","getKeylessJWKs","jwksForIssuer","key","aud","bigIntToBytesLE","_KeylessSignature","Signature","jwtHeader","ephemeralCertificate","expiryDateSecs","ephemeralPublicKey","ephemeralSignature","parseJwtHeader","EphemeralCertificate","EphemeralPublicKey","EphemeralSignature","ZkProof","Ed25519PublicKey","Ed25519Signature","_EphemeralCertificate","variant","_G1Bytes","Serializable","data","bytes","point","yFlag","Fp","bn254","x","bytesToBn254FpBE","y","negY","yToUse","G1Bytes","result","bytesToNumberBE","_G2Bytes","x0","x1","Fp2","G2Bytes","_Groth16Zkp","Proof","a","b","c","_Groth16ProofAndStatement","generateSigningMessage","_ZkProof","_ZeroKnowledgeSig","expHorizonSecs","trainingWheelsSignature","extraField","overrideAudVal","Deserializer","KeylessConfiguration","_KeylessConfiguration","maxExtraFieldBytes","maxJwtHeaderB64Bytes","maxIssValBytes","maxCommitedEpkBytes","res","config","Groth16VerificationKey","_Groth16VerificationKey","alphaG1","betaG2","deltaG2","gammaAbcG1","gammaG2","sha3_256","proofA","proofB","proofC","vkAlpha1","vkBeta2","vkGamma2","vkDelta2","vkIC","g1","Fp12","accum","pairingAccumGamma","pairingAB","pairingAlphaBeta","pairingCDelta","product","memoizeAsync","vk","getKeylessConfigurationResource","getGroth16VerificationKeyResource","getIssAudAndUidVal","getErrorMessage","resourceType","getAptosFullNode","AccountAddress","resource","jwkMap","entry","jwks","jwkStruct","jwkData","MoveJWK","hexToAsciiString","_MoveJWK","kty","alg","e","n","struct","uint8Array","base64UrlToBytes","scalars","chunkInto24Bytes","chunk","chunks","i","paddedChunk","header","FederatedKeylessPublicKey","_FederatedKeylessPublicKey","AccountPublicKey","jwkAddress","keylessPublicKey","AccountAddress","serializer","Serializer","AuthenticationKey","args","verifyKeylessSignatureWithJwkAndConfig","deserializer","KeylessPublicKey","publicKey","verifyKeylessSignature","convertSigningMessage","message","Hex","accountPublicKeyToBaseAccountPublicKey","publicKey","Ed25519PublicKey","AnyPublicKey","MultiEd25519PublicKey","MultiKey","KeylessPublicKey","FederatedKeylessPublicKey","accountPublicKeyToSigningScheme","baseAccountPublicKey","L","isCanonicalEd25519Signature","signature","s","i","_Ed25519PublicKey","AccountPublicKey","hexInput","hex","Hex","args","message","messageToVerify","convertSigningMessage","messageBytes","signatureBytes","publicKeyBytes","ed25519","AuthenticationKey","serializer","deserializer","bytes","publicKey","Ed25519PublicKey","_Ed25519PrivateKey","Serializable","strict","privateKeyHex","PrivateKey","keyPair","path","mnemonics","isValidHardenedPath","mnemonicToSeed","seed","offset","HARDENED_OFFSET","key","chainCode","deriveKey","segments","splitPath","el","privateKey","parentKeys","segment","CKDPriv","messageToSign","Ed25519Signature","Ed25519PrivateKey","_Ed25519Signature","Signature","data","EphemeralPublicKey","_EphemeralPublicKey","PublicKey","publicKey","publicKeyType","Ed25519PublicKey","args","message","signature","serializer","deserializer","index","EphemeralSignature","_EphemeralSignature","Signature","signatureType","Ed25519Signature","hexInput","data","Hex","Deserializer"]}
|