@aptos-labs/ts-sdk 3.0.0 → 3.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.
Files changed (645) hide show
  1. package/dist/common/{account-CEmLe1wW.d.ts → account-Bb5REyaT.d.ts} +60 -11
  2. package/dist/common/chunk-6MMUUJHX.js +4 -0
  3. package/dist/common/chunk-6MMUUJHX.js.map +1 -0
  4. package/dist/common/cli/index.d.ts +1 -1
  5. package/dist/common/cli/index.js +1 -1
  6. package/dist/common/cli/index.js.map +1 -1
  7. package/dist/common/index.d.ts +121 -9
  8. package/dist/common/index.js +53 -32
  9. package/dist/common/index.js.map +1 -1
  10. package/dist/esm/{Ed25519Account-Ccxj1zdx.d.mts → Ed25519Account-ndmdpFe9.d.mts} +1 -1
  11. package/dist/esm/account/AbstractKeylessAccount.d.mts +3 -3
  12. package/dist/esm/account/AbstractKeylessAccount.mjs +1 -1
  13. package/dist/esm/account/AbstractedAccount.d.mts +2 -2
  14. package/dist/esm/account/AbstractedAccount.mjs +1 -1
  15. package/dist/esm/account/Account.d.mts +2 -2
  16. package/dist/esm/account/Account.mjs +1 -1
  17. package/dist/esm/account/AccountUtils.d.mts +3 -3
  18. package/dist/esm/account/AccountUtils.mjs +1 -1
  19. package/dist/esm/account/DerivableAbstractedAccount.d.mts +2 -2
  20. package/dist/esm/account/DerivableAbstractedAccount.mjs +1 -1
  21. package/dist/esm/account/Ed25519Account.d.mts +2 -2
  22. package/dist/esm/account/Ed25519Account.mjs +1 -1
  23. package/dist/esm/account/EphemeralKeyPair.d.mts +1 -1
  24. package/dist/esm/account/EphemeralKeyPair.mjs +1 -1
  25. package/dist/esm/account/FederatedKeylessAccount.d.mts +4 -3
  26. package/dist/esm/account/FederatedKeylessAccount.mjs +1 -1
  27. package/dist/esm/account/KeylessAccount.d.mts +4 -3
  28. package/dist/esm/account/KeylessAccount.mjs +1 -1
  29. package/dist/esm/account/MultiEd25519Account.d.mts +2 -2
  30. package/dist/esm/account/MultiEd25519Account.mjs +1 -1
  31. package/dist/esm/account/MultiKeyAccount.d.mts +3 -3
  32. package/dist/esm/account/MultiKeyAccount.mjs +1 -1
  33. package/dist/esm/account/SingleKeyAccount.d.mts +2 -2
  34. package/dist/esm/account/SingleKeyAccount.mjs +1 -1
  35. package/dist/esm/account/index.d.mts +3 -3
  36. package/dist/esm/account/index.mjs +1 -1
  37. package/dist/esm/account/utils.d.mts +1 -1
  38. package/dist/esm/account/utils.mjs +1 -1
  39. package/dist/esm/{account-9G6tix5T.d.mts → account--Q9z_xMN.d.mts} +37 -3
  40. package/dist/esm/api/account/abstraction.d.mts +1 -1
  41. package/dist/esm/api/account/abstraction.mjs +1 -1
  42. package/dist/esm/api/account.d.mts +94 -3
  43. package/dist/esm/api/account.mjs +1 -1
  44. package/dist/esm/api/ans.d.mts +2 -2
  45. package/dist/esm/api/ans.mjs +1 -1
  46. package/dist/esm/api/aptos.d.mts +6 -4
  47. package/dist/esm/api/aptos.mjs +1 -1
  48. package/dist/esm/api/aptosConfig.d.mts +1 -1
  49. package/dist/esm/api/aptosConfig.mjs +1 -1
  50. package/dist/esm/api/coin.d.mts +1 -1
  51. package/dist/esm/api/coin.mjs +1 -1
  52. package/dist/esm/api/digitalAsset.d.mts +2 -2
  53. package/dist/esm/api/digitalAsset.mjs +1 -1
  54. package/dist/esm/api/event.d.mts +1 -1
  55. package/dist/esm/api/event.mjs +1 -1
  56. package/dist/esm/api/faucet.d.mts +1 -1
  57. package/dist/esm/api/faucet.mjs +1 -1
  58. package/dist/esm/api/fungibleAsset.d.mts +2 -2
  59. package/dist/esm/api/fungibleAsset.mjs +1 -1
  60. package/dist/esm/api/general.d.mts +1 -1
  61. package/dist/esm/api/general.mjs +1 -1
  62. package/dist/esm/api/index.d.mts +6 -4
  63. package/dist/esm/api/index.mjs +1 -1
  64. package/dist/esm/api/keyless.d.mts +3 -3
  65. package/dist/esm/api/keyless.mjs +1 -1
  66. package/dist/esm/api/object.d.mts +1 -1
  67. package/dist/esm/api/object.mjs +1 -1
  68. package/dist/esm/api/staking.d.mts +1 -1
  69. package/dist/esm/api/staking.mjs +1 -1
  70. package/dist/esm/api/table.d.mts +1 -1
  71. package/dist/esm/api/table.mjs +1 -1
  72. package/dist/esm/api/transaction.d.mts +3 -2
  73. package/dist/esm/api/transaction.mjs +1 -1
  74. package/dist/esm/api/transactionSubmission/build.d.mts +1 -1
  75. package/dist/esm/api/transactionSubmission/build.mjs +1 -1
  76. package/dist/esm/api/transactionSubmission/management.d.mts +2 -2
  77. package/dist/esm/api/transactionSubmission/management.mjs +1 -1
  78. package/dist/esm/api/transactionSubmission/sign.d.mts +2 -2
  79. package/dist/esm/api/transactionSubmission/sign.mjs +1 -1
  80. package/dist/esm/api/transactionSubmission/sign.mjs.map +1 -1
  81. package/dist/esm/api/transactionSubmission/simulate.d.mts +1 -1
  82. package/dist/esm/api/transactionSubmission/simulate.mjs +1 -1
  83. package/dist/esm/api/transactionSubmission/submit.d.mts +1 -1
  84. package/dist/esm/api/transactionSubmission/submit.mjs +1 -1
  85. package/dist/esm/api/utils.d.mts +1 -1
  86. package/dist/esm/api/utils.mjs +1 -1
  87. package/dist/esm/bcs/consts.d.mts +1 -1
  88. package/dist/esm/bcs/deserializer.d.mts +1 -1
  89. package/dist/esm/bcs/index.d.mts +1 -1
  90. package/dist/esm/bcs/index.mjs +1 -1
  91. package/dist/esm/bcs/serializable/entryFunctionBytes.d.mts +1 -1
  92. package/dist/esm/bcs/serializable/fixedBytes.d.mts +1 -1
  93. package/dist/esm/bcs/serializable/movePrimitives.d.mts +1 -1
  94. package/dist/esm/bcs/serializable/movePrimitives.mjs +1 -1
  95. package/dist/esm/bcs/serializable/moveStructs.d.mts +1 -1
  96. package/dist/esm/bcs/serializable/moveStructs.mjs +1 -1
  97. package/dist/esm/bcs/serializer.d.mts +1 -1
  98. package/dist/esm/{chunk-Q4W3WJ2U.mjs → chunk-2BOHKN33.mjs} +2 -2
  99. package/dist/esm/{chunk-SAMHWS73.mjs → chunk-4COLMDT3.mjs} +2 -2
  100. package/dist/esm/chunk-5HXLZHDW.mjs +1 -0
  101. package/dist/esm/chunk-5HXLZHDW.mjs.map +1 -0
  102. package/dist/esm/{chunk-5ZRPV4YI.mjs → chunk-5URUYE6H.mjs} +2 -2
  103. package/dist/esm/chunk-ACNHLCQQ.mjs +6 -0
  104. package/dist/esm/chunk-ACNHLCQQ.mjs.map +1 -0
  105. package/dist/esm/{chunk-2XQKGWHQ.mjs → chunk-FYYEPFML.mjs} +2 -2
  106. package/dist/esm/chunk-HUWKPKPQ.mjs +2 -0
  107. package/dist/esm/{chunk-HMUIOIBG.mjs.map → chunk-HUWKPKPQ.mjs.map} +1 -1
  108. package/dist/esm/chunk-IJE2LVZG.mjs +2 -0
  109. package/dist/esm/chunk-IJE2LVZG.mjs.map +1 -0
  110. package/dist/esm/chunk-JCFTAG5Z.mjs +2 -0
  111. package/dist/esm/{chunk-RJ7F4JDV.mjs.map → chunk-JCFTAG5Z.mjs.map} +1 -1
  112. package/dist/esm/{chunk-YHGGNYYL.mjs → chunk-MML57K5H.mjs} +2 -2
  113. package/dist/esm/{chunk-PFXXFUBL.mjs → chunk-MNDTFHDB.mjs} +2 -2
  114. package/dist/esm/{chunk-FSP4QM2T.mjs → chunk-SLWIGOQL.mjs} +2 -2
  115. package/dist/esm/{chunk-7T62PEFI.mjs → chunk-TYYVB2A6.mjs} +2 -2
  116. package/dist/esm/{chunk-WOTQ7227.mjs → chunk-U3GMNXO4.mjs} +2 -2
  117. package/dist/esm/{chunk-VHNX2NUR.mjs → chunk-UL777LTI.mjs} +47 -26
  118. package/dist/esm/chunk-UL777LTI.mjs.map +1 -0
  119. package/dist/esm/{chunk-IDHVW7HS.mjs → chunk-XZ75T7Q7.mjs} +2 -2
  120. package/dist/esm/{chunk-UIVX6WSC.mjs → chunk-Y7ZQTLH4.mjs} +2 -2
  121. package/dist/esm/{chunk-R7NQJWDG.mjs → chunk-Z5URUE4U.mjs} +2 -2
  122. package/dist/esm/cli/index.d.mts +1 -1
  123. package/dist/esm/cli/index.mjs +1 -1
  124. package/dist/esm/cli/localNode.mjs +1 -1
  125. package/dist/esm/cli/move.d.mts +1 -1
  126. package/dist/esm/client/core.d.mts +1 -1
  127. package/dist/esm/client/core.mjs +1 -1
  128. package/dist/esm/client/get.d.mts +1 -1
  129. package/dist/esm/client/get.mjs +1 -1
  130. package/dist/esm/client/index.d.mts +1 -1
  131. package/dist/esm/client/index.mjs +1 -1
  132. package/dist/esm/client/post.d.mts +1 -1
  133. package/dist/esm/client/post.mjs +1 -1
  134. package/dist/esm/core/account/index.d.mts +1 -1
  135. package/dist/esm/core/account/index.mjs +1 -1
  136. package/dist/esm/core/account/utils/address.d.mts +1 -1
  137. package/dist/esm/core/account/utils/address.mjs +1 -1
  138. package/dist/esm/core/account/utils/index.d.mts +1 -1
  139. package/dist/esm/core/account/utils/index.mjs +1 -1
  140. package/dist/esm/core/accountAddress.d.mts +1 -1
  141. package/dist/esm/core/accountAddress.mjs +1 -1
  142. package/dist/esm/core/authenticationKey.d.mts +1 -1
  143. package/dist/esm/core/authenticationKey.mjs +1 -1
  144. package/dist/esm/core/crypto/abstraction.d.mts +1 -1
  145. package/dist/esm/core/crypto/abstraction.mjs +1 -1
  146. package/dist/esm/core/crypto/deserializationUtils.d.mts +1 -1
  147. package/dist/esm/core/crypto/deserializationUtils.mjs +1 -1
  148. package/dist/esm/core/crypto/ed25519.d.mts +1 -1
  149. package/dist/esm/core/crypto/ed25519.mjs +1 -1
  150. package/dist/esm/core/crypto/ephemeral.d.mts +1 -1
  151. package/dist/esm/core/crypto/ephemeral.mjs +1 -1
  152. package/dist/esm/core/crypto/federatedKeyless.d.mts +2 -2
  153. package/dist/esm/core/crypto/federatedKeyless.mjs +1 -1
  154. package/dist/esm/core/crypto/index.d.mts +3 -2
  155. package/dist/esm/core/crypto/index.mjs +1 -1
  156. package/dist/esm/core/crypto/keyless.d.mts +2 -2
  157. package/dist/esm/core/crypto/keyless.mjs +1 -1
  158. package/dist/esm/core/crypto/multiEd25519.d.mts +1 -1
  159. package/dist/esm/core/crypto/multiEd25519.mjs +1 -1
  160. package/dist/esm/core/crypto/multiKey.d.mts +1 -1
  161. package/dist/esm/core/crypto/multiKey.mjs +1 -1
  162. package/dist/esm/core/crypto/privateKey.d.mts +1 -1
  163. package/dist/esm/core/crypto/privateKey.mjs +1 -1
  164. package/dist/esm/core/crypto/proof.d.mts +1 -1
  165. package/dist/esm/core/crypto/proof.mjs +1 -1
  166. package/dist/esm/core/crypto/publicKey.d.mts +1 -1
  167. package/dist/esm/core/crypto/publicKey.mjs +1 -1
  168. package/dist/esm/core/crypto/secp256k1.d.mts +1 -1
  169. package/dist/esm/core/crypto/secp256k1.mjs +1 -1
  170. package/dist/esm/core/crypto/signature.d.mts +1 -1
  171. package/dist/esm/core/crypto/signature.mjs +1 -1
  172. package/dist/esm/core/crypto/singleKey.d.mts +1 -1
  173. package/dist/esm/core/crypto/singleKey.mjs +1 -1
  174. package/dist/esm/core/crypto/types.d.mts +11 -0
  175. package/dist/esm/core/crypto/types.mjs +2 -0
  176. package/dist/esm/core/crypto/types.mjs.map +1 -0
  177. package/dist/esm/core/crypto/utils.d.mts +1 -1
  178. package/dist/esm/core/hex.d.mts +1 -1
  179. package/dist/esm/core/index.d.mts +3 -2
  180. package/dist/esm/core/index.mjs +1 -1
  181. package/dist/esm/errors/index.d.mts +1 -1
  182. package/dist/esm/errors/index.mjs +1 -1
  183. package/dist/esm/{federatedKeyless-CVKW5pnz.d.mts → federatedKeyless-CiyplsOB.d.mts} +1 -1
  184. package/dist/esm/index.d.mts +6 -4
  185. package/dist/esm/index.mjs +1 -1
  186. package/dist/esm/internal/abstraction.d.mts +1 -1
  187. package/dist/esm/internal/abstraction.mjs +1 -1
  188. package/dist/esm/internal/account.d.mts +38 -8
  189. package/dist/esm/internal/account.mjs +1 -1
  190. package/dist/esm/internal/ans.d.mts +2 -2
  191. package/dist/esm/internal/ans.mjs +1 -1
  192. package/dist/esm/internal/coin.d.mts +1 -1
  193. package/dist/esm/internal/coin.mjs +1 -1
  194. package/dist/esm/internal/digitalAsset.d.mts +2 -2
  195. package/dist/esm/internal/digitalAsset.mjs +1 -1
  196. package/dist/esm/internal/event.d.mts +1 -1
  197. package/dist/esm/internal/event.mjs +1 -1
  198. package/dist/esm/internal/faucet.d.mts +1 -1
  199. package/dist/esm/internal/faucet.mjs +1 -1
  200. package/dist/esm/internal/fungibleAsset.d.mts +2 -2
  201. package/dist/esm/internal/fungibleAsset.mjs +1 -1
  202. package/dist/esm/internal/general.d.mts +1 -1
  203. package/dist/esm/internal/general.mjs +1 -1
  204. package/dist/esm/internal/keyless.d.mts +12 -3
  205. package/dist/esm/internal/keyless.mjs +1 -1
  206. package/dist/esm/internal/object.d.mts +1 -1
  207. package/dist/esm/internal/object.mjs +1 -1
  208. package/dist/esm/internal/staking.d.mts +1 -1
  209. package/dist/esm/internal/staking.mjs +1 -1
  210. package/dist/esm/internal/table.d.mts +1 -1
  211. package/dist/esm/internal/table.mjs +1 -1
  212. package/dist/esm/internal/transaction.d.mts +1 -1
  213. package/dist/esm/internal/transaction.mjs +1 -1
  214. package/dist/esm/internal/transactionSubmission.d.mts +2 -2
  215. package/dist/esm/internal/transactionSubmission.mjs +1 -1
  216. package/dist/esm/internal/utils/index.d.mts +1 -1
  217. package/dist/esm/internal/utils/index.mjs +1 -1
  218. package/dist/esm/internal/utils/utils.d.mts +1 -1
  219. package/dist/esm/internal/utils/utils.mjs +1 -1
  220. package/dist/esm/internal/view.d.mts +1 -1
  221. package/dist/esm/internal/view.mjs +1 -1
  222. package/dist/esm/transactions/authenticator/account.d.mts +1 -1
  223. package/dist/esm/transactions/authenticator/account.mjs +1 -1
  224. package/dist/esm/transactions/authenticator/index.d.mts +1 -1
  225. package/dist/esm/transactions/authenticator/index.mjs +1 -1
  226. package/dist/esm/transactions/authenticator/transaction.d.mts +1 -1
  227. package/dist/esm/transactions/authenticator/transaction.mjs +1 -1
  228. package/dist/esm/transactions/index.d.mts +1 -1
  229. package/dist/esm/transactions/index.mjs +1 -1
  230. package/dist/esm/transactions/instances/chainId.d.mts +1 -1
  231. package/dist/esm/transactions/instances/identifier.d.mts +1 -1
  232. package/dist/esm/transactions/instances/index.d.mts +1 -1
  233. package/dist/esm/transactions/instances/index.mjs +1 -1
  234. package/dist/esm/transactions/instances/moduleId.d.mts +1 -1
  235. package/dist/esm/transactions/instances/moduleId.mjs +1 -1
  236. package/dist/esm/transactions/instances/multiAgentTransaction.d.mts +1 -1
  237. package/dist/esm/transactions/instances/multiAgentTransaction.mjs +1 -1
  238. package/dist/esm/transactions/instances/rawTransaction.d.mts +1 -1
  239. package/dist/esm/transactions/instances/rawTransaction.mjs +1 -1
  240. package/dist/esm/transactions/instances/rotationProofChallenge.d.mts +1 -1
  241. package/dist/esm/transactions/instances/rotationProofChallenge.mjs +1 -1
  242. package/dist/esm/transactions/instances/signedTransaction.d.mts +1 -1
  243. package/dist/esm/transactions/instances/signedTransaction.mjs +1 -1
  244. package/dist/esm/transactions/instances/simpleTransaction.d.mts +1 -1
  245. package/dist/esm/transactions/instances/simpleTransaction.mjs +1 -1
  246. package/dist/esm/transactions/instances/transactionArgument.d.mts +1 -1
  247. package/dist/esm/transactions/instances/transactionPayload.d.mts +1 -1
  248. package/dist/esm/transactions/instances/transactionPayload.mjs +1 -1
  249. package/dist/esm/transactions/management/accountSequenceNumber.d.mts +2 -2
  250. package/dist/esm/transactions/management/accountSequenceNumber.mjs +1 -1
  251. package/dist/esm/transactions/management/index.d.mts +2 -2
  252. package/dist/esm/transactions/management/index.mjs +1 -1
  253. package/dist/esm/transactions/management/transactionWorker.d.mts +2 -2
  254. package/dist/esm/transactions/management/transactionWorker.mjs +1 -1
  255. package/dist/esm/transactions/transactionBuilder/helpers.d.mts +1 -1
  256. package/dist/esm/transactions/transactionBuilder/helpers.mjs +1 -1
  257. package/dist/esm/transactions/transactionBuilder/index.d.mts +1 -1
  258. package/dist/esm/transactions/transactionBuilder/index.mjs +1 -1
  259. package/dist/esm/transactions/transactionBuilder/remoteAbi.d.mts +1 -1
  260. package/dist/esm/transactions/transactionBuilder/remoteAbi.mjs +1 -1
  261. package/dist/esm/transactions/transactionBuilder/signingMessage.d.mts +1 -1
  262. package/dist/esm/transactions/transactionBuilder/signingMessage.mjs +1 -1
  263. package/dist/esm/transactions/transactionBuilder/transactionBuilder.d.mts +1 -1
  264. package/dist/esm/transactions/transactionBuilder/transactionBuilder.mjs +1 -1
  265. package/dist/esm/transactions/typeTag/index.d.mts +1 -1
  266. package/dist/esm/transactions/typeTag/index.mjs +1 -1
  267. package/dist/esm/transactions/typeTag/parser.d.mts +1 -1
  268. package/dist/esm/transactions/typeTag/parser.mjs +1 -1
  269. package/dist/esm/transactions/types.d.mts +1 -1
  270. package/dist/esm/types/generated/operations.d.mts +37 -10
  271. package/dist/esm/types/generated/queries.d.mts +6 -2
  272. package/dist/esm/types/generated/queries.mjs +1 -1
  273. package/dist/esm/types/generated/types.d.mts +584 -1172
  274. package/dist/esm/types/generated/types.mjs +1 -1
  275. package/dist/esm/types/generated/types.mjs.map +1 -1
  276. package/dist/esm/types/index.d.mts +2 -2
  277. package/dist/esm/types/index.mjs +1 -1
  278. package/dist/esm/types/indexer.d.mts +8 -2
  279. package/dist/esm/types/types.d.mts +1 -1
  280. package/dist/esm/types/types.mjs +1 -1
  281. package/dist/esm/utils/const.d.mts +1 -0
  282. package/dist/esm/utils/const.mjs +1 -1
  283. package/dist/esm/utils/helpers.d.mts +1 -1
  284. package/dist/esm/utils/helpers.mjs +1 -1
  285. package/dist/esm/utils/index.d.mts +1 -1
  286. package/dist/esm/utils/index.mjs +1 -1
  287. package/dist/esm/utils/normalizeBundle.d.mts +1 -1
  288. package/dist/esm/utils/normalizeBundle.mjs +1 -1
  289. package/dist/esm/version.d.mts +1 -1
  290. package/dist/esm/version.mjs +1 -1
  291. package/package.json +19 -18
  292. package/src/account/FederatedKeylessAccount.ts +7 -1
  293. package/src/account/KeylessAccount.ts +17 -2
  294. package/src/api/account.ts +135 -2
  295. package/src/api/transaction.ts +1 -0
  296. package/src/core/crypto/index.ts +1 -0
  297. package/src/core/crypto/multiEd25519.ts +26 -0
  298. package/src/core/crypto/multiKey.ts +6 -0
  299. package/src/core/crypto/types.ts +9 -0
  300. package/src/internal/account.ts +526 -59
  301. package/src/internal/keyless.ts +10 -0
  302. package/src/internal/move/jwks/build/jwk/BuildInfo.yaml +56 -0
  303. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/account.mv +0 -0
  304. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/aggregator.mv +0 -0
  305. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/aggregator_factory.mv +0 -0
  306. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv +0 -0
  307. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/aptos_account.mv +0 -0
  308. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv +0 -0
  309. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv +0 -0
  310. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/block.mv +0 -0
  311. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/chain_id.mv +0 -0
  312. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/chain_status.mv +0 -0
  313. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/code.mv +0 -0
  314. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/coin.mv +0 -0
  315. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/config_buffer.mv +0 -0
  316. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/consensus_config.mv +0 -0
  317. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/create_signer.mv +0 -0
  318. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv +0 -0
  319. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/dispatchable_fungible_asset.mv +0 -0
  320. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/dkg.mv +0 -0
  321. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/event.mv +0 -0
  322. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/execution_config.mv +0 -0
  323. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/function_info.mv +0 -0
  324. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/fungible_asset.mv +0 -0
  325. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/gas_schedule.mv +0 -0
  326. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/genesis.mv +0 -0
  327. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv +0 -0
  328. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/guid.mv +0 -0
  329. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/jwk_consensus_config.mv +0 -0
  330. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/jwks.mv +0 -0
  331. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/keyless_account.mv +0 -0
  332. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/managed_coin.mv +0 -0
  333. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/multisig_account.mv +0 -0
  334. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/object.mv +0 -0
  335. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/object_code_deployment.mv +0 -0
  336. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/optional_aggregator.mv +0 -0
  337. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv +0 -0
  338. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/randomness.mv +0 -0
  339. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/randomness_api_v0_config.mv +0 -0
  340. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/randomness_config.mv +0 -0
  341. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/randomness_config_seqnum.mv +0 -0
  342. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/reconfiguration.mv +0 -0
  343. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/reconfiguration_state.mv +0 -0
  344. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/reconfiguration_with_dkg.mv +0 -0
  345. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/resource_account.mv +0 -0
  346. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/stake.mv +0 -0
  347. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/staking_config.mv +0 -0
  348. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/staking_contract.mv +0 -0
  349. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv +0 -0
  350. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/state_storage.mv +0 -0
  351. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/storage_gas.mv +0 -0
  352. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/system_addresses.mv +0 -0
  353. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/timestamp.mv +0 -0
  354. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/transaction_context.mv +0 -0
  355. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/transaction_fee.mv +0 -0
  356. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv +0 -0
  357. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/util.mv +0 -0
  358. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/validator_consensus_info.mv +0 -0
  359. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/version.mv +0 -0
  360. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/vesting.mv +0 -0
  361. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosFramework/voting.mv +0 -0
  362. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/any.mv +0 -0
  363. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv +0 -0
  364. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/big_vector.mv +0 -0
  365. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/bls12381.mv +0 -0
  366. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv +0 -0
  367. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/bn254_algebra.mv +0 -0
  368. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/capability.mv +0 -0
  369. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/comparator.mv +0 -0
  370. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv +0 -0
  371. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/crypto_algebra.mv +0 -0
  372. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/debug.mv +0 -0
  373. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/ed25519.mv +0 -0
  374. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv +0 -0
  375. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/from_bcs.mv +0 -0
  376. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/math128.mv +0 -0
  377. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/math64.mv +0 -0
  378. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv +0 -0
  379. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv +0 -0
  380. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv +0 -0
  381. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv +0 -0
  382. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv +0 -0
  383. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv +0 -0
  384. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv +0 -0
  385. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/ristretto255_elgamal.mv +0 -0
  386. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv +0 -0
  387. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv +0 -0
  388. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/simple_map.mv +0 -0
  389. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/smart_table.mv +0 -0
  390. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv +0 -0
  391. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/string_utils.mv +0 -0
  392. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/table.mv +0 -0
  393. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv +0 -0
  394. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/AptosStdlib/type_info.mv +0 -0
  395. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/acl.mv +0 -0
  396. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/bcs.mv +0 -0
  397. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/bit_vector.mv +0 -0
  398. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/error.mv +0 -0
  399. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/features.mv +0 -0
  400. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv +0 -0
  401. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/hash.mv +0 -0
  402. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/option.mv +0 -0
  403. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/signer.mv +0 -0
  404. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/string.mv +0 -0
  405. package/src/internal/move/jwks/build/jwk/bytecode_modules/dependencies/MoveStdlib/vector.mv +0 -0
  406. package/src/internal/move/jwks/build/jwk/bytecode_scripts/main.mv +0 -0
  407. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/account.mvsm +0 -0
  408. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/aggregator.mvsm +0 -0
  409. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm +0 -0
  410. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm +0 -0
  411. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/aptos_account.mvsm +0 -0
  412. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/aptos_coin.mvsm +0 -0
  413. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/aptos_governance.mvsm +0 -0
  414. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/block.mvsm +0 -0
  415. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/chain_id.mvsm +0 -0
  416. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/chain_status.mvsm +0 -0
  417. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/code.mvsm +0 -0
  418. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/coin.mvsm +0 -0
  419. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/config_buffer.mvsm +0 -0
  420. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/consensus_config.mvsm +0 -0
  421. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/create_signer.mvsm +0 -0
  422. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/delegation_pool.mvsm +0 -0
  423. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/dispatchable_fungible_asset.mvsm +0 -0
  424. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/dkg.mvsm +0 -0
  425. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/event.mvsm +0 -0
  426. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/execution_config.mvsm +0 -0
  427. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/function_info.mvsm +0 -0
  428. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/fungible_asset.mvsm +0 -0
  429. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/gas_schedule.mvsm +0 -0
  430. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/genesis.mvsm +0 -0
  431. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/governance_proposal.mvsm +0 -0
  432. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/guid.mvsm +0 -0
  433. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/jwk_consensus_config.mvsm +0 -0
  434. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/jwks.mvsm +0 -0
  435. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/keyless_account.mvsm +0 -0
  436. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/managed_coin.mvsm +0 -0
  437. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/multisig_account.mvsm +0 -0
  438. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/object.mvsm +0 -0
  439. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/object_code_deployment.mvsm +0 -0
  440. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm +0 -0
  441. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm +0 -0
  442. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/randomness.mvsm +0 -0
  443. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/randomness_api_v0_config.mvsm +0 -0
  444. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/randomness_config.mvsm +0 -0
  445. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/randomness_config_seqnum.mvsm +0 -0
  446. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/reconfiguration.mvsm +0 -0
  447. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/reconfiguration_state.mvsm +0 -0
  448. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/reconfiguration_with_dkg.mvsm +0 -0
  449. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/resource_account.mvsm +0 -0
  450. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/stake.mvsm +0 -0
  451. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/staking_config.mvsm +0 -0
  452. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/staking_contract.mvsm +0 -0
  453. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/staking_proxy.mvsm +0 -0
  454. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/state_storage.mvsm +0 -0
  455. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/storage_gas.mvsm +0 -0
  456. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/system_addresses.mvsm +0 -0
  457. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/timestamp.mvsm +0 -0
  458. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/transaction_context.mvsm +0 -0
  459. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/transaction_fee.mvsm +0 -0
  460. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/transaction_validation.mvsm +0 -0
  461. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/util.mvsm +0 -0
  462. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/validator_consensus_info.mvsm +0 -0
  463. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/version.mvsm +0 -0
  464. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/vesting.mvsm +0 -0
  465. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosFramework/voting.mvsm +0 -0
  466. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/any.mvsm +0 -0
  467. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/aptos_hash.mvsm +0 -0
  468. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/big_vector.mvsm +0 -0
  469. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/bls12381.mvsm +0 -0
  470. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/bls12381_algebra.mvsm +0 -0
  471. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/bn254_algebra.mvsm +0 -0
  472. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/capability.mvsm +0 -0
  473. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/comparator.mvsm +0 -0
  474. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/copyable_any.mvsm +0 -0
  475. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm +0 -0
  476. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/debug.mvsm +0 -0
  477. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/ed25519.mvsm +0 -0
  478. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm +0 -0
  479. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/from_bcs.mvsm +0 -0
  480. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/math128.mvsm +0 -0
  481. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/math64.mvsm +0 -0
  482. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/math_fixed.mvsm +0 -0
  483. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm +0 -0
  484. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/multi_ed25519.mvsm +0 -0
  485. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/pool_u64.mvsm +0 -0
  486. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/pool_u64_unbound.mvsm +0 -0
  487. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/ristretto255.mvsm +0 -0
  488. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/ristretto255_bulletproofs.mvsm +0 -0
  489. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/ristretto255_elgamal.mvsm +0 -0
  490. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/ristretto255_pedersen.mvsm +0 -0
  491. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/secp256k1.mvsm +0 -0
  492. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/simple_map.mvsm +0 -0
  493. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/smart_table.mvsm +0 -0
  494. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/smart_vector.mvsm +0 -0
  495. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/string_utils.mvsm +0 -0
  496. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/table.mvsm +0 -0
  497. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/table_with_length.mvsm +0 -0
  498. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/AptosStdlib/type_info.mvsm +0 -0
  499. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/acl.mvsm +0 -0
  500. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/bcs.mvsm +0 -0
  501. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/bit_vector.mvsm +0 -0
  502. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/error.mvsm +0 -0
  503. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/features.mvsm +0 -0
  504. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm +0 -0
  505. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/hash.mvsm +0 -0
  506. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/option.mvsm +0 -0
  507. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/signer.mvsm +0 -0
  508. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/string.mvsm +0 -0
  509. package/src/internal/move/jwks/build/jwk/source_maps/dependencies/MoveStdlib/vector.mvsm +0 -0
  510. package/src/internal/move/jwks/build/jwk/source_maps/main.mvsm +0 -0
  511. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/account.move +1533 -0
  512. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/aggregator.move +48 -0
  513. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/aggregator_factory.move +66 -0
  514. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/aggregator_v2.move +280 -0
  515. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/aptos_account.move +443 -0
  516. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/aptos_coin.move +204 -0
  517. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/aptos_governance.move +1387 -0
  518. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/block.move +394 -0
  519. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/chain_id.move +41 -0
  520. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/chain_status.move +48 -0
  521. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/code.move +367 -0
  522. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/coin.move +2214 -0
  523. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/config_buffer.move +101 -0
  524. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/consensus_config.move +77 -0
  525. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/create_signer.move +21 -0
  526. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/delegation_pool.move +5568 -0
  527. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/dispatchable_fungible_asset.move +228 -0
  528. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/dkg.move +121 -0
  529. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/event.move +92 -0
  530. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/execution_config.move +66 -0
  531. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/function_info.move +100 -0
  532. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/fungible_asset.move +1566 -0
  533. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/gas_schedule.move +176 -0
  534. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/genesis.move +550 -0
  535. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/governance_proposal.move +23 -0
  536. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/guid.move +68 -0
  537. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/jwk_consensus_config.move +148 -0
  538. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/jwks.move +817 -0
  539. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/keyless_account.move +312 -0
  540. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/managed_coin.move +205 -0
  541. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/multisig_account.move +2477 -0
  542. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/object.move +1073 -0
  543. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/object_code_deployment.move +147 -0
  544. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/optional_aggregator.move +295 -0
  545. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/primary_fungible_store.move +405 -0
  546. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/randomness.move +574 -0
  547. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/randomness_api_v0_config.move +57 -0
  548. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/randomness_config.move +153 -0
  549. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/randomness_config_seqnum.move +49 -0
  550. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/reconfiguration.move +237 -0
  551. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/reconfiguration_state.move +132 -0
  552. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/reconfiguration_with_dkg.move +69 -0
  553. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/resource_account.move +267 -0
  554. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/stake.move +3286 -0
  555. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/staking_config.move +686 -0
  556. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/staking_contract.move +1618 -0
  557. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/staking_proxy.move +228 -0
  558. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/state_storage.move +90 -0
  559. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/storage_gas.move +622 -0
  560. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/system_addresses.move +82 -0
  561. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/timestamp.move +88 -0
  562. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/transaction_context.move +262 -0
  563. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/transaction_fee.move +457 -0
  564. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/transaction_validation.move +501 -0
  565. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/util.move +16 -0
  566. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/validator_consensus_info.move +42 -0
  567. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/version.move +115 -0
  568. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/vesting.move +2183 -0
  569. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosFramework/voting.move +1279 -0
  570. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/any.move +57 -0
  571. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/aptos_hash.move +253 -0
  572. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/big_vector.move +469 -0
  573. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/bls12381.move +985 -0
  574. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/bls12381_algebra.move +802 -0
  575. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/bn254_algebra.move +855 -0
  576. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/capability.move +193 -0
  577. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/comparator.move +173 -0
  578. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/copyable_any.move +45 -0
  579. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/crypto_algebra.move +351 -0
  580. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/debug.move +278 -0
  581. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/ed25519.move +262 -0
  582. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/fixed_point64.move +447 -0
  583. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/from_bcs.move +91 -0
  584. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/math128.move +381 -0
  585. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/math64.move +336 -0
  586. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/math_fixed.move +139 -0
  587. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/math_fixed64.move +142 -0
  588. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/multi_ed25519.move +482 -0
  589. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/pool_u64.move +571 -0
  590. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/pool_u64_unbound.move +270 -0
  591. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/ristretto255.move +1310 -0
  592. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move +253 -0
  593. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/ristretto255_elgamal.move +234 -0
  594. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/ristretto255_pedersen.move +158 -0
  595. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/secp256k1.move +114 -0
  596. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/simple_map.move +319 -0
  597. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/smart_table.move +769 -0
  598. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/smart_vector.move +766 -0
  599. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/string_utils.move +148 -0
  600. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/table.move +152 -0
  601. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/table_with_length.move +141 -0
  602. package/src/internal/move/jwks/build/jwk/sources/dependencies/AptosStdlib/type_info.move +351 -0
  603. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/acl.move +46 -0
  604. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/bcs.move +27 -0
  605. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/bit_vector.move +239 -0
  606. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/error.move +88 -0
  607. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/features.move +780 -0
  608. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/fixed_point32.move +295 -0
  609. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/hash.move +8 -0
  610. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/option.move +356 -0
  611. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/signer.move +21 -0
  612. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/string.move +93 -0
  613. package/src/internal/move/jwks/build/jwk/sources/dependencies/MoveStdlib/vector.move +669 -0
  614. package/src/internal/move/jwks/build/jwk/sources/main.move +20 -0
  615. package/src/internal/queries/getAccountAddressesForAuthKey.graphql +8 -0
  616. package/src/internal/queries/getAuthKeysForPublicKey.graphql +11 -0
  617. package/src/types/codegen.yaml +1 -1
  618. package/src/types/generated/operations.ts +39 -8
  619. package/src/types/generated/queries.ts +53 -0
  620. package/src/types/generated/types.ts +620 -1239
  621. package/src/types/indexer.ts +8 -0
  622. package/src/types/types.ts +40 -3
  623. package/src/utils/const.ts +1 -0
  624. package/src/version.ts +1 -1
  625. package/dist/common/chunk-5JIJXVJ5.js +0 -4
  626. package/dist/common/chunk-5JIJXVJ5.js.map +0 -1
  627. package/dist/esm/chunk-4H2RMR7D.mjs +0 -2
  628. package/dist/esm/chunk-4H2RMR7D.mjs.map +0 -1
  629. package/dist/esm/chunk-GMDBBVDH.mjs +0 -6
  630. package/dist/esm/chunk-GMDBBVDH.mjs.map +0 -1
  631. package/dist/esm/chunk-HMUIOIBG.mjs +0 -2
  632. package/dist/esm/chunk-RJ7F4JDV.mjs +0 -2
  633. package/dist/esm/chunk-VHNX2NUR.mjs.map +0 -1
  634. /package/dist/esm/{chunk-Q4W3WJ2U.mjs.map → chunk-2BOHKN33.mjs.map} +0 -0
  635. /package/dist/esm/{chunk-SAMHWS73.mjs.map → chunk-4COLMDT3.mjs.map} +0 -0
  636. /package/dist/esm/{chunk-5ZRPV4YI.mjs.map → chunk-5URUYE6H.mjs.map} +0 -0
  637. /package/dist/esm/{chunk-2XQKGWHQ.mjs.map → chunk-FYYEPFML.mjs.map} +0 -0
  638. /package/dist/esm/{chunk-YHGGNYYL.mjs.map → chunk-MML57K5H.mjs.map} +0 -0
  639. /package/dist/esm/{chunk-PFXXFUBL.mjs.map → chunk-MNDTFHDB.mjs.map} +0 -0
  640. /package/dist/esm/{chunk-FSP4QM2T.mjs.map → chunk-SLWIGOQL.mjs.map} +0 -0
  641. /package/dist/esm/{chunk-7T62PEFI.mjs.map → chunk-TYYVB2A6.mjs.map} +0 -0
  642. /package/dist/esm/{chunk-WOTQ7227.mjs.map → chunk-U3GMNXO4.mjs.map} +0 -0
  643. /package/dist/esm/{chunk-IDHVW7HS.mjs.map → chunk-XZ75T7Q7.mjs.map} +0 -0
  644. /package/dist/esm/{chunk-UIVX6WSC.mjs.map → chunk-Y7ZQTLH4.mjs.map} +0 -0
  645. /package/dist/esm/{chunk-R7NQJWDG.mjs.map → chunk-Z5URUE4U.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/dport/a/aptos-ts-sdk/dist/common/index.js","../../src/bcs/deserializer.ts","../../src/bcs/serializable/fixedBytes.ts","../../src/bcs/serializable/entryFunctionBytes.ts","../../src/bcs/serializable/movePrimitives.ts","../../src/bcs/serializable/moveStructs.ts","../../src/core/authenticationKey.ts","../../src/errors/index.ts","../../src/core/crypto/keyless.ts","../../src/core/crypto/multiKey.ts","../../src/transactions/authenticator/account.ts","../../src/types/generated/queries.ts","../../src/transactions/typeTag/parser.ts","../../src/api/account.ts","../../src/internal/digitalAsset.ts"],"names":["Deserializer","_Deserializer","data","hex","Hex","length","bytes","value","type","len","bool","low","high","shift","MAX_U32_NUMBER","byte","cls","vector","FixedBytes","_FixedBytes","Serializable","serializer","deserializer","EntryFunctionBytes","_EntryFunctionBytes","fixedBytes","Bool","_Bool","ensureBoolean","bcsBytes","U256","U8","_U8","validateNumberInRange","MAX_U8_NUMBER","U16","_U16","MAX_U16_NUMBER","U32","_U32","U64","_U64","MAX_U64_BIG_INT","U128","_U128","MAX_U128_BIG_INT","_U256","MAX_U256_BIG_INT","MoveVector","_MoveVector","values","Serialized","numbers","v","MoveString","i","_Serialized","vec","_MoveString","fixedStringBytes","MoveOption","_MoveOption","_AuthenticationKey","args","publicKey"],"mappings":"AAAA,2sCAAsmB,IC6CzlBA,CAAAA,CAAN,MAAMC,CAAa,CAaxB,WAAA,CAAYC,CAAAA,CAAkB,CAE5B,IAAA,CAAK,MAAA,CAAS,IAAI,WAAA,CAAYA,CAAAA,CAAK,MAAM,CAAA,CACzC,IAAI,UAAA,CAAW,IAAA,CAAK,MAAM,CAAA,CAAE,GAAA,CAAIA,CAAAA,CAAM,CAAC,CAAA,CACvC,IAAA,CAAK,MAAA,CAAS,CAChB,CAEA,OAAO,OAAA,CAAQC,CAAAA,CAA6B,CAC1C,IAAMD,CAAAA,CAAOE,kBAAAA,CAAI,oBAAA,CAAqBD,CAAG,CAAA,CACzC,OAAO,IAAIF,CAAAA,CAAaC,CAAI,CAC9B,CAUQ,IAAA,CAAKG,CAAAA,CAA6B,CACxC,EAAA,CAAI,IAAA,CAAK,MAAA,CAASA,CAAAA,CAAS,IAAA,CAAK,MAAA,CAAO,UAAA,CACrC,MAAM,IAAI,KAAA,CAAM,8BAA8B,CAAA,CAGhD,IAAMC,CAAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,MAAA,CA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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BF,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBhB,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYa,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQR,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBK,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASD,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBI,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcL,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYQ,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYZ,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACvGc,IAAA;ACyclC;ACvIgC,0CAAA","file":"/Users/dport/a/aptos-ts-sdk/dist/common/index.js","sourcesContent":[null,"// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable no-bitwise */\nimport { MAX_U32_NUMBER } from \"./consts\";\nimport { Uint8, Uint16, Uint32, Uint64, Uint128, Uint256, HexInput } from \"../types\";\nimport { Hex } from \"../core/hex\";\n\n/**\n * This interface exists to define Deserializable<T> inputs for functions that\n * deserialize a byte buffer into a type T.\n * It is not intended to be implemented or extended, because Typescript has no support\n * for static methods in interfaces.\n *\n * @template T - The type that this will deserialize into.\n * @group Implementation\n * @category BCS\n */\nexport interface Deserializable<T> {\n /**\n * Deserializes the buffered bytes into an instance of the specified class type.\n * This function provides an alternative syntax for deserialization, allowing users to call\n * `deserializer.deserialize(MyClass)` instead of `MyClass.deserialize(deserializer)`.\n *\n * @param deserializer - The deserializer instance with the buffered bytes.\n * @returns The deserialized value of class type T.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([1, 2, 3]));\n * const value = deserializer.deserialize(MyClass); // where MyClass has a `deserialize` function\n * // value is now an instance of MyClass\n * // equivalent to `const value = MyClass.deserialize(deserializer)`\n * ```\n * @group Implementation\n * @category BCS\n */\n deserialize(deserializer: Deserializer): T;\n}\n\n/**\n * A class that provides methods for deserializing various data types from a byte buffer.\n * It supports deserialization of primitive types, strings, and complex objects using a BCS (Binary Common Serialization) layout.\n * @group Implementation\n * @category BCS\n */\nexport class Deserializer {\n private buffer: ArrayBuffer;\n\n private offset: number;\n\n /**\n * Creates a new instance of the class with a copy of the provided data buffer.\n * This prevents outside mutation of the buffer.\n *\n * @param data - The data to be copied into the internal buffer as a Uint8Array.\n * @group Implementation\n * @category BCS\n */\n constructor(data: Uint8Array) {\n // copies data to prevent outside mutation of buffer.\n this.buffer = new ArrayBuffer(data.length);\n new Uint8Array(this.buffer).set(data, 0);\n this.offset = 0;\n }\n\n static fromHex(hex: HexInput): Deserializer {\n const data = Hex.hexInputToUint8Array(hex);\n return new Deserializer(data);\n }\n\n /**\n * Reads a specified number of bytes from the buffer and advances the offset.\n *\n * @param length - The number of bytes to read from the buffer.\n * @throws Throws an error if the read operation exceeds the buffer's length.\n * @group Implementation\n * @category BCS\n */\n private read(length: number): ArrayBuffer {\n if (this.offset + length > this.buffer.byteLength) {\n throw new Error(\"Reached to the end of buffer\");\n }\n\n const bytes = this.buffer.slice(this.offset, this.offset + length);\n this.offset += length;\n return bytes;\n }\n\n /**\n * Returns the number of bytes remaining in the buffer.\n *\n * This information is useful to determine if there's more data to be read.\n *\n * @returns The number of bytes remaining in the buffer.\n * @group Implementation\n * @category BCS\n */\n remaining(): number {\n return this.buffer.byteLength - this.offset;\n }\n\n /**\n * Asserts that the buffer has no remaining bytes.\n *\n * @throws {Error} Throws an error if there are remaining bytes in the buffer.\n * @group Implementation\n * @category BCS\n */\n assertFinished(): void {\n if (this.remaining() !== 0) {\n throw new Error(\"Buffer has remaining bytes\");\n }\n }\n\n /**\n * Deserializes a UTF-8 encoded string from a byte array. It first reads the length of the string in bytes,\n * followed by the actual byte content, and decodes it into a string.\n *\n * BCS layout for \"string\": string_length | string_content\n * where string_length is a u32 integer encoded as a uleb128 integer, equal to the number of bytes in string_content.\n *\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([8, 49, 50, 51, 52, 97, 98, 99, 100]));\n * assert(deserializer.deserializeStr() === \"1234abcd\");\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeStr(): string {\n const value = this.deserializeBytes();\n const textDecoder = new TextDecoder();\n return textDecoder.decode(value);\n }\n\n /**\n * @deprecated use `deserializeOption(\"string\")` instead.\n *\n * The BCS layout for Optional<String> is 0 if none, else 1 followed by the string length and string content.\n * @returns The deserialized string if it exists, otherwise undefined.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x00]));\n * assert(deserializer.deserializeOptionStr() === undefined);\n * const deserializer = new Deserializer(new Uint8Array([1, 8, 49, 50, 51, 52, 97, 98, 99, 100]));\n * assert(deserializer.deserializeOptionStr() === \"1234abcd\");\n * ```\n */\n deserializeOptionStr(): string | undefined {\n return this.deserializeOption(\"string\");\n }\n\n /**\n * Deserializes an optional value from the buffer.\n *\n * The BCS layout for Optional<T> starts with a boolean byte (0 if none, 1 if some),\n * followed by the value if present.\n *\n * @template T - The type of the value to deserialize\n * @param type - Either a Deserializable class or one of the string literals: \"string\", \"bytes\", or \"fixedBytes\"\n * @param len - Required length when type is \"fixedBytes\", ignored otherwise\n * @returns The deserialized value if present, undefined otherwise\n *\n * @throws {Error} When \"fixedBytes\" is specified without a length\n *\n * @example\n * ```typescript\n * // Deserialize an optional string\n * const deserializer = new Deserializer(new Uint8Array([1, 3, 97, 98, 99]));\n * const optStr = deserializer.deserializeOption(\"string\");\n * // optStr === \"abc\"\n *\n * // Deserialize an optional custom type\n * const deserializer = new Deserializer(new Uint8Array([0]));\n * const optValue = deserializer.deserializeOption(MyClass);\n * // optValue === undefined\n *\n * // Deserialize optional bytes\n * const deserializer = new Deserializer(new Uint8Array([1, 3, 1, 2, 3]));\n * const optBytes = deserializer.deserializeOption(\"bytes\");\n * // optBytes === Uint8Array[1, 2, 3]\n *\n * // Deserialize optional fixed bytes\n * const deserializer = new Deserializer(new Uint8Array([1, 1, 2, 3, 4]));\n * const optBytes = deserializer.deserializeOption(\"fixedBytes\", 4);\n * // optBytes === Uint8Array[1, 2, 3, 4]\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeOption(type: \"string\"): string | undefined;\n deserializeOption(type: \"bytes\"): Uint8Array | undefined;\n deserializeOption(type: \"fixedBytes\", len: number): Uint8Array | undefined;\n deserializeOption<T>(type: Deserializable<T>): T | undefined;\n deserializeOption<T>(\n type: Deserializable<T> | \"string\" | \"bytes\" | \"fixedBytes\",\n len?: number,\n ): T | string | Uint8Array | undefined {\n const exists = this.deserializeBool();\n if (!exists) return undefined;\n\n if (type === \"string\") {\n return this.deserializeStr();\n }\n if (type === \"bytes\") {\n return this.deserializeBytes();\n }\n if (type === \"fixedBytes\") {\n if (len === undefined) {\n throw new Error(\"Fixed bytes length not provided\");\n }\n return this.deserializeFixedBytes(len);\n }\n\n return this.deserialize(type);\n }\n\n /**\n * Deserializes an array of bytes.\n *\n * The BCS layout for \"bytes\" consists of a bytes_length followed by the bytes themselves, where bytes_length is a u32 integer\n * encoded as a uleb128 integer, indicating the length of the bytes array.\n *\n * @returns {Uint8Array} The deserialized array of bytes.\n * @group Implementation\n * @category BCS\n */\n deserializeBytes(): Uint8Array {\n const len = this.deserializeUleb128AsU32();\n return new Uint8Array(this.read(len));\n }\n\n /**\n * Deserializes an array of bytes of a specified length.\n *\n * @param len - The number of bytes to read from the source.\n * @group Implementation\n * @category BCS\n */\n deserializeFixedBytes(len: number): Uint8Array {\n return new Uint8Array(this.read(len));\n }\n\n /**\n * Deserializes a boolean value from a byte stream.\n *\n * The BCS layout for a boolean uses one byte, where \"0x01\" represents true and \"0x00\" represents false.\n * An error is thrown if the byte value is not valid.\n *\n * @returns The deserialized boolean value.\n * @throws Throws an error if the boolean value is invalid.\n * @group Implementation\n * @category BCS\n */\n deserializeBool(): boolean {\n const bool = new Uint8Array(this.read(1))[0];\n if (bool !== 1 && bool !== 0) {\n throw new Error(\"Invalid boolean value\");\n }\n return bool === 1;\n }\n\n /**\n * Deserializes a uint8 number from the binary data.\n *\n * BCS layout for \"uint8\": One byte. Binary format in little-endian representation.\n *\n * @returns {number} The deserialized uint8 number.\n * @group Implementation\n * @category BCS\n */\n deserializeU8(): Uint8 {\n return new DataView(this.read(1)).getUint8(0);\n }\n\n /**\n * Deserializes a uint16 number from a binary format in little-endian representation.\n *\n * BCS layout for \"uint16\": Two bytes.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x34, 0x12]));\n * assert(deserializer.deserializeU16() === 4660);\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeU16(): Uint16 {\n return new DataView(this.read(2)).getUint16(0, true);\n }\n\n /**\n * Deserializes a uint32 number from a binary format in little-endian representation.\n *\n * BCS layout for \"uint32\": Four bytes.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x78, 0x56, 0x34, 0x12]));\n * assert(deserializer.deserializeU32() === 305419896);\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeU32(): Uint32 {\n return new DataView(this.read(4)).getUint32(0, true);\n }\n\n /**\n * Deserializes a uint64 number.\n *\n * This function combines two 32-bit values to return a 64-bit unsigned integer in little-endian representation.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x00, 0xEF, 0xCD, 0xAB, 0x78, 0x56, 0x34, 0x12]));\n * assert(deserializer.deserializeU64() === 1311768467750121216);\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeU64(): Uint64 {\n const low = this.deserializeU32();\n const high = this.deserializeU32();\n\n // combine the two 32-bit values and return (little endian)\n return BigInt((BigInt(high) << BigInt(32)) | BigInt(low));\n }\n\n /**\n * Deserializes a uint128 number from its binary representation.\n * This function combines two 64-bit values to return a single uint128 value in little-endian format.\n *\n * @returns {BigInt} The deserialized uint128 number.\n * @group Implementation\n * @category BCS\n */\n deserializeU128(): Uint128 {\n const low = this.deserializeU64();\n const high = this.deserializeU64();\n\n // combine the two 64-bit values and return (little endian)\n return BigInt((high << BigInt(64)) | low);\n }\n\n /**\n * Deserializes a uint256 number from its binary representation.\n *\n * The BCS layout for \"uint256\" consists of thirty-two bytes in little-endian format.\n *\n * @returns {BigInt} The deserialized uint256 number.\n * @group Implementation\n * @category BCS\n */\n deserializeU256(): Uint256 {\n const low = this.deserializeU128();\n const high = this.deserializeU128();\n\n // combine the two 128-bit values and return (little endian)\n return BigInt((high << BigInt(128)) | low);\n }\n\n /**\n * Deserializes a uleb128 encoded uint32 number.\n *\n * This function is used for interpreting lengths of variable-length sequences and tags of enum values in BCS encoding.\n *\n * @throws {Error} Throws an error if the parsed value exceeds the maximum uint32 number.\n * @returns {number} The deserialized uint32 value.\n * @group Implementation\n * @category BCS\n */\n deserializeUleb128AsU32(): Uint32 {\n let value: bigint = BigInt(0);\n let shift = 0;\n\n while (value < MAX_U32_NUMBER) {\n const byte = this.deserializeU8();\n value |= BigInt(byte & 0x7f) << BigInt(shift);\n\n if ((byte & 0x80) === 0) {\n break;\n }\n shift += 7;\n }\n\n if (value > MAX_U32_NUMBER) {\n throw new Error(\"Overflow while parsing uleb128-encoded uint32 value\");\n }\n\n return Number(value);\n }\n\n /**\n * Helper function that primarily exists to support alternative syntax for deserialization.\n * That is, if we have a `const deserializer: new Deserializer(...)`, instead of having to use\n * `MyClass.deserialize(deserializer)`, we can call `deserializer.deserialize(MyClass)`.\n *\n * @example const deserializer = new Deserializer(new Uint8Array([1, 2, 3]));\n * const value = deserializer.deserialize(MyClass); // where MyClass has a `deserialize` function\n * // value is now an instance of MyClass\n * // equivalent to `const value = MyClass.deserialize(deserializer)`\n * @param cls The BCS-deserializable class to deserialize the buffered bytes into.\n *\n * @returns the deserialized value of class type T\n * @group Implementation\n * @category BCS\n */\n deserialize<T>(cls: Deserializable<T>): T {\n // NOTE: `deserialize` in `cls.deserialize(this)` here is a static method defined in `cls`,\n // It is separate from the `deserialize` instance method defined here in Deserializer.\n return cls.deserialize(this);\n }\n\n /**\n * Deserializes an array of BCS Deserializable values given an existing Deserializer instance with a loaded byte buffer.\n *\n * @param cls The BCS-deserializable class to deserialize the buffered bytes into.\n * @returns An array of deserialized values of type T.\n * @example\n * // serialize a vector of addresses\n * const addresses = new Array<AccountAddress>(\n * AccountAddress.from(\"0x1\"),\n * AccountAddress.from(\"0x2\"),\n * AccountAddress.from(\"0xa\"),\n * AccountAddress.from(\"0xb\"),\n * );\n * const serializer = new Serializer();\n * serializer.serializeVector(addresses);\n * const serializedBytes = serializer.toUint8Array();\n *\n * // deserialize the bytes into an array of addresses\n * const deserializer = new Deserializer(serializedBytes);\n * const deserializedAddresses = deserializer.deserializeVector(AccountAddress);\n * // deserializedAddresses is now an array of AccountAddress instances\n * @group Implementation\n * @category BCS\n */\n deserializeVector<T>(cls: Deserializable<T>): Array<T> {\n const length = this.deserializeUleb128AsU32();\n const vector = new Array<T>();\n for (let i = 0; i < length; i += 1) {\n vector.push(this.deserialize(cls));\n }\n return vector;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../serializer\";\nimport { Deserializer } from \"../deserializer\";\nimport { HexInput } from \"../../types\";\nimport { Hex } from \"../../core/hex\";\nimport { TransactionArgument } from \"../../transactions/instances/transactionArgument\";\n\n/**\n * Represents a contiguous sequence of already serialized BCS bytes.\n * \n * This class differs from most other Serializable classes in that its internal byte buffer is serialized to BCS\n * bytes exactly as-is, without prepending the length of the bytes. It is ideal for scenarios where custom serialization\n * is required, such as passing serialized bytes as transaction arguments. Additionally, it serves as a representation \n * of type-agnostic BCS bytes, akin to a vector<u8>.\n * \n * An example use case includes handling bytes resulting from entry function arguments that have been serialized \n * for an entry function.\n * \n * @example\n * const yourCustomSerializedBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);\n * const fixedBytes = new FixedBytes(yourCustomSerializedBytes);\n * const payload = await generateTransactionPayload({\n * function: \"0xbeefcafe::your_module::your_function_that_requires_custom_serialization\",\n * functionArguments: [yourCustomBytes],\n * });\n * \n * This class is particularly useful when you want to handle a fixed-size byte array without the overhead of \n * length prepending, such as when dealing with 32-byte addresses stored as U8 in a MoveVector<U8>.\n\n * For example, if you store each of the 32 bytes for an address as a U8 in a MoveVector<U8>, when you\n * serialize that MoveVector<U8>, it will be serialized to 33 bytes. If you solely want to pass around\n * the 32 bytes as a Serializable class that *does not* prepend the length to the BCS-serialized representation,\n * use this class.* \n * @param value - HexInput representing a sequence of Uint8 bytes.\n * @returns A Serializable FixedBytes instance, which when serialized, does not prepend the length of the bytes.\n * @see EntryFunctionBytes\n * @group Implementation\n * @category BCS\n */\nexport class FixedBytes extends Serializable implements TransactionArgument {\n public value: Uint8Array;\n\n /**\n * Creates an instance of the class with a specified hexadecimal input.\n * The value is converted from hexadecimal format to a Uint8Array.\n *\n * @param value - The hexadecimal input to be converted.\n * @group Implementation\n * @category BCS\n */\n constructor(value: HexInput) {\n super();\n this.value = Hex.fromHexInput(value).toUint8Array();\n }\n\n /**\n * Serializes the fixed bytes value using the provided serializer.\n * This function is essential for converting the fixed bytes into a format suitable for storage or transmission.\n *\n * @param serializer - The serializer instance used for serialization.\n * @group Implementation\n * @category BCS\n */\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.value);\n }\n\n /**\n * Serializes the current instance for an entry function using the provided serializer.\n * This allows the instance to be converted into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n serializer.serialize(this);\n }\n\n /**\n * Serializes the current instance using the provided serializer.\n * This function is essential for preparing data to be passed as arguments in script functions.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serialize(this);\n }\n\n /**\n * Deserializes a fixed-length byte array from the provided deserializer.\n * This function helps in reconstructing a FixedBytes object from the serialized data.\n *\n * @param deserializer - The deserializer instance used to read the byte data.\n * @param length - The length of the byte array to be deserialized.\n * @group Implementation\n * @category BCS\n */\n static deserialize(deserializer: Deserializer, length: number): FixedBytes {\n const bytes = deserializer.deserializeFixedBytes(length);\n return new FixedBytes(bytes);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../serializer\";\nimport { Deserializer } from \"../deserializer\";\nimport { FixedBytes } from \"./fixedBytes\";\nimport { EntryFunctionArgument } from \"../../transactions/instances/transactionArgument\";\nimport { HexInput } from \"../../types\";\n\n/**\n * This class exists solely to represent a sequence of fixed bytes as a serialized entry function, because\n * serializing an entry function appends a prefix that's *only* used for entry function arguments.\n *\n * NOTE: Using this class for serialized script functions will lead to erroneous and unexpected behavior.\n *\n * If you wish to convert this class back to a TransactionArgument, you must know the type\n * of the argument beforehand, and use the appropriate class to deserialize the bytes within\n * an instance of this class.\n * @group Implementation\n * @category BCS\n */\nexport class EntryFunctionBytes extends Serializable implements EntryFunctionArgument {\n public readonly value: FixedBytes;\n\n /**\n * Creates an instance of the class with a specified hexadecimal input value.\n *\n * @param value - The hexadecimal input to be converted into FixedBytes.\n * @group Implementation\n * @category BCS\n */\n private constructor(value: HexInput) {\n super();\n this.value = new FixedBytes(value);\n }\n\n // Note that to see the Move, BCS-serialized representation of the underlying fixed byte vector,\n // we must not serialize the length prefix.\n //\n // In other words, this class is only used to represent a sequence of bytes that are already\n // BCS-serialized as a type. To represent those bytes accurately, the BCS-serialized form is the same exact\n // representation.\n\n /**\n * Serializes the value using the provided serializer.\n * This function is essential for accurately representing a sequence of bytes that are already BCS-serialized as a type.\n *\n * Note that to see the Move, BCS-serialized representation of the underlying fixed byte vector,\n * we must not serialize the length prefix.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serialize(serializer: Serializer): void {\n serializer.serialize(this.value);\n }\n\n // When we serialize these bytes as an entry function argument, we need to\n // serialize the length prefix. This essentially converts the underlying fixed byte vector to a type-agnostic\n // byte vector to an `any` type.\n // NOTE: This, and the lack of a `serializeForScriptFunction`, is the only meaningful difference between this\n // class and FixedBytes.\n\n /**\n * Serializes the current instance for use as an entry function argument by converting the underlying fixed byte vector to a\n * type-agnostic byte vector.\n * This process includes serializing the length prefix of the byte vector.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.value.value.length);\n serializer.serialize(this);\n }\n\n /**\n * The only way to create an instance of this class is to use this static method.\n * This function should only be used when deserializing a sequence of EntryFunctionPayload arguments.\n * @param deserializer - The deserializer instance with the buffered bytes.\n * @param length - The length of the bytes to deserialize.\n * @returns An instance of this class, which will now only be usable as an EntryFunctionArgument.\n * @group Implementation\n * @category BCS\n */\n static deserialize(deserializer: Deserializer, length: number): EntryFunctionBytes {\n const fixedBytes = FixedBytes.deserialize(deserializer, length);\n return new EntryFunctionBytes(fixedBytes.value);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n MAX_U128_BIG_INT,\n MAX_U16_NUMBER,\n MAX_U32_NUMBER,\n MAX_U64_BIG_INT,\n MAX_U8_NUMBER,\n MAX_U256_BIG_INT,\n} from \"../consts\";\nimport { Deserializer } from \"../deserializer\";\nimport { Serializable, Serializer, ensureBoolean, validateNumberInRange } from \"../serializer\";\nimport { TransactionArgument } from \"../../transactions/instances/transactionArgument\";\nimport { AnyNumber, Uint16, Uint32, Uint8, ScriptTransactionArgumentVariants } from \"../../types\";\n\n/**\n * Represents a boolean value that can be serialized and deserialized.\n * This class extends the Serializable class and provides methods to serialize\n * the boolean value for different contexts, such as entry functions and script functions.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class Bool extends Serializable implements TransactionArgument {\n public readonly value: boolean;\n\n /**\n * Constructs a new instance with a specified value.\n * This ensures that the value is validated to be within the acceptable range.\n *\n * @param value - The number to be validated and assigned, which must be between 0 and MAX_U256_BIG_INT.\n * @group Implementation\n * @category BCS\n */\n constructor(value: boolean) {\n super();\n\n /**\n * Ensures that the provided value is of type boolean.\n * This function throws an error if the value is not a boolean, helping to enforce type safety in your code.\n *\n * @param value - The value to be checked for boolean type.\n * @throws {Error} Throws an error if the value is not a boolean.\n * @group Implementation\n * @category BCS\n */\n ensureBoolean(value);\n this.value = value;\n }\n\n /**\n * Serializes the value using the provided serializer.\n * This function is essential for converting the value 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 BCS\n */\n serialize(serializer: Serializer): void {\n serializer.serializeBool(this.value);\n }\n\n /**\n * Serializes the current instance for use in an entry function by converting it to a byte sequence.\n * This allows the instance to be properly formatted for serialization in transactions.\n *\n * @param serializer - The serializer instance used to serialize the byte sequence.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * Serializes the current instance for use in a script function.\n * This allows for the conversion of the instance into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.Bool);\n serializer.serialize(this);\n }\n\n /**\n * Deserializes a U256 value from the provided deserializer.\n *\n * @param deserializer - The deserializer instance used to read the U256 data.\n * @group Implementation\n * @category BCS\n */\n // eslint-disable-next-line class-methods-use-this\n deserialize(deserializer: Deserializer) {\n return new U256(deserializer.deserializeU256());\n }\n\n static deserialize(deserializer: Deserializer): Bool {\n return new Bool(deserializer.deserializeBool());\n }\n}\n\n/**\n * Represents an unsigned 8-bit integer (U8) value.\n * This class extends the Serializable class and provides methods for serialization and deserialization of U8 values.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U8 extends Serializable implements TransactionArgument {\n public readonly value: Uint8;\n\n constructor(value: Uint8) {\n super();\n validateNumberInRange(value, 0, MAX_U8_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU8(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U8);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U8 {\n return new U8(deserializer.deserializeU8());\n }\n}\n\n/**\n * Represents a 16-bit unsigned integer (U16) value.\n * This class extends the Serializable class and provides methods for serialization\n * and deserialization of the U16 value.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U16 extends Serializable implements TransactionArgument {\n public readonly value: Uint16;\n\n constructor(value: Uint16) {\n super();\n validateNumberInRange(value, 0, MAX_U16_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU16(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U16);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U16 {\n return new U16(deserializer.deserializeU16());\n }\n}\n\n/**\n * Represents a 32-bit unsigned integer (U32) that can be serialized and deserialized.\n * This class ensures that the value is within the valid range for a U32.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U32 extends Serializable implements TransactionArgument {\n public readonly value: Uint32;\n\n constructor(value: Uint32) {\n super();\n validateNumberInRange(value, 0, MAX_U32_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U32);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U32 {\n return new U32(deserializer.deserializeU32());\n }\n}\n\n/**\n * Represents a 64-bit unsigned integer (U64) and provides methods for serialization.\n *\n * This class ensures that the value is within the valid range for a U64 and provides\n * functionality to serialize the value for various use cases, including entry functions\n * and script functions.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U64 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U64_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU64(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U64);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U64 {\n return new U64(deserializer.deserializeU64());\n }\n}\n\n/**\n * Represents a 128-bit unsigned integer value.\n * This class provides methods for serialization and deserialization\n * of U128 values, ensuring that the values are within the valid range.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U128 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U128_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU128(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U128);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U128 {\n return new U128(deserializer.deserializeU128());\n }\n}\n\n/**\n * Represents a 256-bit unsigned integer (U256) that extends the Serializable class.\n * This class provides methods for serialization and deserialization of U256 values,\n * ensuring that the values are within the valid range.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U256 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U256_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU256(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U256);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U256 {\n return new U256(deserializer.deserializeU256());\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Bool, U128, U16, U256, U32, U64, U8 } from \"./movePrimitives\";\nimport { Serializable, Serializer } from \"../serializer\";\nimport { Deserializable, Deserializer } from \"../deserializer\";\nimport { AnyNumber, HexInput, ScriptTransactionArgumentVariants } from \"../../types\";\nimport { Hex } from \"../../core/hex\";\nimport { EntryFunctionArgument, TransactionArgument } from \"../../transactions/instances/transactionArgument\";\n\n/**\n * This class is the Aptos Typescript SDK representation of a Move `vector<T>`,\n * where `T` represents either a primitive type (`bool`, `u8`, `u64`, ...)\n * or a BCS-serializable struct itself.\n *\n * It is a BCS-serializable, array-like type that contains an array of values of type `T`,\n * where `T` is a class that implements `Serializable`.\n *\n * The purpose of this class is to facilitate easy construction of BCS-serializable\n * Move `vector<T>` types.\n *\n * @example\n * // in Move: `vector<u8> [1, 2, 3, 4];`\n * const vecOfU8s = new MoveVector<U8>([new U8(1), new U8(2), new U8(3), new U8(4)]);\n * // in Move: `std::bcs::to_bytes(vector<u8> [1, 2, 3, 4]);`\n * const bcsBytes = vecOfU8s.toUint8Array();\n *\n * // vector<vector<u8>> [ vector<u8> [1], vector<u8> [1, 2, 3, 4], vector<u8> [5, 6, 7, 8] ];\n * const vecOfVecs = new MoveVector<MoveVector<U8>>([\n * new MoveVector<U8>([new U8(1)]),\n * MoveVector.U8([1, 2, 3, 4]),\n * MoveVector.U8([5, 6, 7, 8]),\n * ]);\n *\n * // vector<Option<u8>> [ std::option::some<u8>(1), std::option::some<u8>(2) ];\n * const vecOfOptionU8s = new MoveVector<MoveOption<U8>>([\n * MoveOption.U8(1),\n * MoveOption.U8(2),\n * ]);\n *\n * // vector<MoveString> [ std::string::utf8(b\"hello\"), std::string::utf8(b\"world\") ];\n * const vecOfStrings = new MoveVector([new MoveString(\"hello\"), new MoveString(\"world\")]);\n * const vecOfStrings2 = MoveVector.MoveString([\"hello\", \"world\"]);\n *\n * @param values an Array<T> of values where T is a class that implements Serializable\n * @returns a `MoveVector<T>` with the values `values`\n * @group Implementation\n * @category BCS\n */\nexport class MoveVector<T extends Serializable & EntryFunctionArgument>\n extends Serializable\n implements TransactionArgument\n{\n public values: Array<T>;\n\n /**\n * Initializes a new instance of the class with an optional value.\n * This constructor sets up the internal vector based on the provided value.\n *\n * @param values - The initial value to be stored in the vector, or null to initialize an empty vector.\n * @group Implementation\n * @category BCS\n */\n constructor(values: Array<T>) {\n super();\n this.values = values;\n }\n\n /**\n * Serializes the current instance into a byte sequence suitable for entry functions.\n * This allows the data to be properly formatted for transmission or storage.\n *\n * @param serializer - The serializer instance used to serialize the byte sequence.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * NOTE: This function will only work when the inner values in the `MoveVector` are `U8`s.\n * @param serializer\n * @group Implementation\n * @category BCS\n */\n\n /**\n * Serialize the string as a fixed byte string without the length prefix for use in a script function.\n * @param serializer - The serializer used to convert the byte vector into a format suitable for a script function.\n * @group Implementation\n * @category BCS\n */\n serializeForScriptFunction(serializer: Serializer): void {\n // This checks if the type of a non-empty vector is of type other than U8. If so, we use the Serialized\n // transaction argument type to serialize the argument.\n if (this.values[0] !== undefined && !(this.values[0] instanceof U8)) {\n const serialized = new Serialized(this.bcsToBytes());\n serialized.serializeForScriptFunction(serializer);\n return;\n }\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U8Vector);\n serializer.serialize(this);\n }\n\n /**\n * Factory method to generate a MoveVector<U8> from a `number` or `undefined`.\n *\n * This method allows you to create a MoveVector that encapsulates a U8 value, enabling you to handle optional U8 values\n * effectively.\n *\n * @param values - The values used to fill the MoveVector. If `values` is undefined or null, the resulting MoveVector's\n * `.isSome()` method will return false.\n * @returns A MoveVector<U8> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U8([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U8(values: Array<number> | HexInput): MoveVector<U8> {\n let numbers: Array<number>;\n\n if (Array.isArray(values) && values.length === 0) {\n // Handle empty array, since it won't have a \"first value\"\n numbers = [];\n } else if (Array.isArray(values) && typeof values[0] === \"number\") {\n numbers = values;\n } else if (typeof values === \"string\") {\n const hex = Hex.fromHexInput(values);\n numbers = Array.from(hex.toUint8Array());\n } else if (values instanceof Uint8Array) {\n numbers = Array.from(values);\n } else {\n throw new Error(\"Invalid input type, must be an number[], Uint8Array, or hex string\");\n }\n\n return new MoveVector<U8>(numbers.map((v) => new U8(v)));\n }\n\n /**\n * Factory method to generate a MoveOption<U16> from a `number` or `null`.\n *\n * This method allows you to create a MoveVector that can either hold a U16 value or be empty.\n *\n * @param values - The value used to fill the MoveVector. If `value` is null or undefined, the resulting MoveVector's\n * `.isSome()` method will return false.\n * @returns A MoveVector<U16> with an inner value `value`.\n * @example\n * ```typescript\n * const v = MoveVector.U16([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n\n */\n static U16(values: Array<number>): MoveVector<U16> {\n return new MoveVector<U16>(values.map((v) => new U16(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U32> from a `number` or `null`.\n *\n * This method allows you to create a MoveVector that can either hold a U32 value or be empty.\n *\n * @param values - The value used to fill the MoveVector. If `value` is null or undefined,\n * the resulting MoveVector's .isSome() method will return false.\n * @returns A MoveVector<U32> with an inner value `value`.\n *\n * @example\n * ```\n * const v = MoveVector.U32([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n\n */\n static U32(values: Array<number>): MoveVector<U32> {\n return new MoveVector<U32>(values.map((v) => new U32(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U64> from a number, bigint, or null/undefined.\n * This allows for the creation of an optional U64 value that can be checked for presence.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined or null, the resulting MoveVector's\n * `.isSome()` method will return false.\n * @returns A MoveVector<U64> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U64([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U64(values: Array<AnyNumber>): MoveVector<U64> {\n return new MoveVector<U64>(values.map((v) => new U64(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U128> from a number, bigint, or undefined.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's `.isSome()`\n * method will return false.\n * @returns A MoveVector<U128> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U128([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U128(values: Array<AnyNumber>): MoveVector<U128> {\n return new MoveVector<U128>(values.map((v) => new U128(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U256> from a number, bigint, or null/undefined.\n * This allows for the creation of an optional U256 value, enabling checks for presence or absence of a value.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined or null,\n * the resulting MoveVector's .isSome() method will return false.\n * @returns A MoveVector<U256> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U256([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U256(values: Array<AnyNumber>): MoveVector<U256> {\n return new MoveVector<U256>(values.map((v) => new U256(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<Bool> from a `boolean` or `undefined`.\n * This method allows you to create an optional boolean value that can be used in various contexts where a boolean may or may\n * not be present.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's .isSome() method\n * will return false.\n * @returns A MoveVector<Bool> with an inner value `value`.\n *\n * @example\n * * const v = MoveVector.Bool([true, false, true, false]);\n * @group Implementation\n * @category BCS\n */\n static Bool(values: Array<boolean>): MoveVector<Bool> {\n return new MoveVector<Bool>(values.map((v) => new Bool(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<MoveString> from a `string` or `undefined`.\n * This function creates a MoveVector that encapsulates a MoveString if the provided value is not null or undefined.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's .isSome() method\n * will return false.\n * @returns A MoveVector<MoveString> with an inner value `value`.\n *\n * @example\n * const v = MoveVector.MoveString([\"hello\", \"world\"]);\n * @group Implementation\n * @category BCS\n */\n static MoveString(values: Array<string>): MoveVector<MoveString> {\n return new MoveVector<MoveString>(values.map((v) => new MoveString(v)));\n }\n\n /**\n * Serializes the current object using the provided serializer.\n * This function will serialize the value if it is present.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serialize(serializer: Serializer): void;\n serialize(serializer: Serializer): void {\n serializer.serializeVector(this.values);\n }\n\n /**\n * Deserialize a MoveVector of type T, specifically where T is a Serializable and Deserializable type.\n *\n * NOTE: This only works with a depth of one. Generics will not work.\n *\n * NOTE: This will not work with types that aren't of the Serializable class.\n *\n * If you're looking for a more flexible deserialization function, you can use the deserializeVector function\n * in the Deserializer class.\n *\n * @example\n * const vec = MoveVector.deserialize(deserializer, U64);\n * @param deserializer the Deserializer instance to use, with bytes loaded into it already.\n * @param cls the class to typecast the input values to, must be a Serializable and Deserializable type.\n * @returns a MoveVector of the corresponding class T\n *\n * @group Implementation\n * @category BCS\n */\n static deserialize<T extends Serializable & EntryFunctionArgument>(\n deserializer: Deserializer,\n cls: Deserializable<T>,\n ): MoveVector<T> {\n const length = deserializer.deserializeUleb128AsU32();\n const values = new Array<T>();\n for (let i = 0; i < length; i += 1) {\n values.push(cls.deserialize(deserializer));\n }\n return new MoveVector(values);\n }\n}\n\n/**\n * Represents a serialized data structure that encapsulates a byte array.\n * This class extends the Serializable class and provides methods for serialization\n * and deserialization of byte data, as well as converting to a MoveVector.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class Serialized extends Serializable implements TransactionArgument {\n public readonly value: Uint8Array;\n\n constructor(value: HexInput) {\n super();\n this.value = Hex.fromHexInput(value).toUint8Array();\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n this.serialize(serializer);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.Serialized);\n this.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): Serialized {\n return new Serialized(deserializer.deserializeBytes());\n }\n\n /**\n * Deserialize the bytecode into a MoveVector of the specified type.\n * This function allows you to convert serialized data into a usable MoveVector format.\n *\n * @param cls - The class type of the elements in the MoveVector.\n * @group Implementation\n * @category BCS\n */\n toMoveVector<T extends Serializable & EntryFunctionArgument>(cls: Deserializable<T>): MoveVector<T> {\n const deserializer = new Deserializer(this.bcsToBytes());\n deserializer.deserializeUleb128AsU32();\n const vec = deserializer.deserializeVector(cls);\n return new MoveVector(vec);\n }\n}\n\n/**\n * Represents a string value that can be serialized and deserialized.\n * This class extends the Serializable base class and provides methods\n * for serializing the string in different contexts, such as for entry\n * functions and script functions.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class MoveString extends Serializable implements TransactionArgument {\n public value: string;\n\n constructor(value: string) {\n super();\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeStr(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n // Serialize the string as a fixed byte string, i.e., without the length prefix\n const textEncoder = new TextEncoder();\n const fixedStringBytes = textEncoder.encode(this.value);\n // Put those bytes into a vector<u8> and serialize it as a script function argument\n const vectorU8 = MoveVector.U8(fixedStringBytes);\n vectorU8.serializeForScriptFunction(serializer);\n }\n\n static deserialize(deserializer: Deserializer): MoveString {\n return new MoveString(deserializer.deserializeStr());\n }\n}\n\nexport class MoveOption<T extends Serializable & EntryFunctionArgument>\n extends Serializable\n implements EntryFunctionArgument\n{\n private vec: MoveVector<T>;\n\n public readonly value?: T;\n\n constructor(value?: T | null) {\n super();\n if (typeof value !== \"undefined\" && value !== null) {\n this.vec = new MoveVector([value]);\n } else {\n this.vec = new MoveVector([]);\n }\n\n [this.value] = this.vec.values;\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * Retrieves the inner value of the MoveOption.\n *\n * This method is inspired by Rust's `Option<T>.unwrap()`, where attempting to unwrap a `None` value results in a panic.\n * This method will throw an error if the value is not present.\n *\n * @example\n * const option = new MoveOption<Bool>(new Bool(true));\n * const value = option.unwrap(); // Returns the Bool instance\n *\n * @throws {Error} Throws an error if the MoveOption does not contain a value.\n *\n * @returns {T} The contained value if present.\n * @group Implementation\n * @category BCS\n */\n unwrap(): T {\n if (!this.isSome()) {\n throw new Error(\"Called unwrap on a MoveOption with no value\");\n } else {\n return this.vec.values[0];\n }\n }\n\n /**\n * Check if the MoveOption has a value.\n *\n * @returns {boolean} Returns true if there is exactly one value in the MoveOption.\n * @group Implementation\n * @category BCS\n */\n isSome(): boolean {\n return this.vec.values.length === 1;\n }\n\n serialize(serializer: Serializer): void {\n // serialize 0 or 1\n // if 1, serialize the value\n this.vec.serialize(serializer);\n }\n\n /**\n * Factory method to generate a MoveOption<U8> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U8(1).isSome() === true;\n * MoveOption.U8().isSome() === false;\n * MoveOption.U8(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U8> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U8(value?: number | null): MoveOption<U8> {\n return new MoveOption<U8>(value !== null && value !== undefined ? new U8(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U16> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U16(1).isSome() === true;\n * MoveOption.U16().isSome() === false;\n * MoveOption.U16(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U16> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U16(value?: number | null): MoveOption<U16> {\n return new MoveOption<U16>(value !== null && value !== undefined ? new U16(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U32> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U32(1).isSome() === true;\n * MoveOption.U32().isSome() === false;\n * MoveOption.U32(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U32> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U32(value?: number | null): MoveOption<U32> {\n return new MoveOption<U32>(value !== null && value !== undefined ? new U32(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U64> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U64(1).isSome() === true;\n * MoveOption.U64().isSome() === false;\n * MoveOption.U64(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U64> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U64(value?: AnyNumber | null): MoveOption<U64> {\n return new MoveOption<U64>(value !== null && value !== undefined ? new U64(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U128> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U128(1).isSome() === true;\n * MoveOption.U128().isSome() === false;\n * MoveOption.U128(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U128> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U128(value?: AnyNumber | null): MoveOption<U128> {\n return new MoveOption<U128>(value !== null && value !== undefined ? new U128(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U256> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U256(1).isSome() === true;\n * MoveOption.U256().isSome() === false;\n * MoveOption.U256(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U256> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U256(value?: AnyNumber | null): MoveOption<U256> {\n return new MoveOption<U256>(value !== null && value !== undefined ? new U256(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<Bool> from a `boolean` or `undefined`.\n *\n * @example\n * MoveOption.Bool(true).isSome() === true;\n * MoveOption.Bool().isSome() === false;\n * MoveOption.Bool(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<Bool> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static Bool(value?: boolean | null): MoveOption<Bool> {\n return new MoveOption<Bool>(value !== null && value !== undefined ? new Bool(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<MoveString> from a `string` or `undefined`.\n *\n * @example\n * MoveOption.MoveString(\"hello\").isSome() === true;\n * MoveOption.MoveString(\"\").isSome() === true;\n * MoveOption.MoveString().isSome() === false;\n * MoveOption.MoveString(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<MoveString> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static MoveString(value?: string | null): MoveOption<MoveString> {\n return new MoveOption<MoveString>(value !== null && value !== undefined ? new MoveString(value) : undefined);\n }\n\n static deserialize<U extends Serializable & EntryFunctionArgument>(\n deserializer: Deserializer,\n cls: Deserializable<U>,\n ): MoveOption<U> {\n const vector = MoveVector.deserialize(deserializer, cls);\n return new MoveOption(vector.values[0]);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { sha3_256 as sha3Hash } from \"@noble/hashes/sha3\";\nimport { AccountAddress } from \"./accountAddress\";\nimport type { AccountPublicKey } from \"./crypto\";\nimport { Hex } from \"./hex\";\nimport { AuthenticationKeyScheme, HexInput } from \"../types\";\nimport { Serializable, Serializer } from \"../bcs/serializer\";\nimport { Deserializer } from \"../bcs/deserializer\";\n\n/**\n * Represents an authentication key used for account management. Each account stores an authentication key that enables account\n * owners to rotate their private key(s) without changing the address that hosts their account. The authentication key is a\n * SHA3-256 hash of data and is always 32 bytes in length.\n *\n * @see {@link https://aptos.dev/concepts/accounts | Account Basics}\n *\n * Account addresses can be derived from the AuthenticationKey.\n * @group Implementation\n * @category Serialization\n */\nexport class AuthenticationKey extends Serializable {\n /**\n * An authentication key is always a SHA3-256 hash of data, and is always 32 bytes.\n *\n * The data to hash depends on the underlying public key type and the derivation scheme.\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The raw bytes of the authentication key.\n * @group Implementation\n * @category Serialization\n */\n public readonly data: Hex;\n\n /**\n * Creates an instance of the AuthenticationKey using the provided hex input.\n * This ensures that the hex input is valid and conforms to the required length for an Authentication Key.\n *\n * @param args - The arguments for constructing the AuthenticationKey.\n * @param args.data - The hex input data to be used for the Authentication Key.\n * @throws {Error} Throws an error if the length of the provided hex input is not equal to the required Authentication Key\n * length.\n * @group Implementation\n * @category Serialization\n */\n constructor(args: { data: HexInput }) {\n super();\n const { data } = args;\n const hex = Hex.fromHexInput(data);\n if (hex.toUint8Array().length !== AuthenticationKey.LENGTH) {\n throw new Error(`Authentication Key length should be ${AuthenticationKey.LENGTH}`);\n }\n this.data = hex;\n }\n\n /**\n * Serializes the fixed bytes 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.serializeFixedBytes(this.data.toUint8Array());\n }\n\n /**\n * Deserialize an AuthenticationKey from the byte buffer in a Deserializer instance.\n * @param deserializer - The deserializer to deserialize the AuthenticationKey from.\n * @returns An instance of AuthenticationKey.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): AuthenticationKey {\n const bytes = deserializer.deserializeFixedBytes(AuthenticationKey.LENGTH);\n return new AuthenticationKey({ data: bytes });\n }\n\n /**\n * Convert the internal data representation to a Uint8Array.\n *\n * This function is useful for obtaining a byte representation of the data, which can be utilized for serialization or transmission.\n *\n * @returns Uint8Array representation of the internal data.\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.data.toUint8Array();\n }\n\n /**\n * Generates an AuthenticationKey from the specified scheme and input bytes.\n * This function is essential for creating a valid authentication key based on a given scheme.\n *\n * @param args - The arguments for generating the AuthenticationKey.\n * @param args.scheme - The authentication key scheme to use.\n * @param args.input - The input data in hexadecimal format to derive the key.\n * @returns An instance of AuthenticationKey containing the generated key data.\n * @group Implementation\n * @category Serialization\n */\n static fromSchemeAndBytes(args: { scheme: AuthenticationKeyScheme; input: HexInput }): AuthenticationKey {\n const { scheme, input } = args;\n const inputBytes = Hex.fromHexInput(input).toUint8Array();\n const hashInput = new Uint8Array([...inputBytes, scheme]);\n const hash = sha3Hash.create();\n hash.update(hashInput);\n const hashDigest = hash.digest();\n return new AuthenticationKey({ data: hashDigest });\n }\n\n /**\n * Derives an AuthenticationKey from the provided public key using a specified derivation scheme.\n *\n * @deprecated Use `fromPublicKey` instead.\n * @param args - The arguments for deriving the authentication key.\n * @param args.publicKey - The public key used for the derivation.\n * @param args.scheme - The scheme to use for deriving the authentication key.\n * @group Implementation\n * @category Serialization\n */\n public static fromPublicKeyAndScheme(args: { publicKey: AccountPublicKey; scheme: AuthenticationKeyScheme }) {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Converts a PublicKey to an AuthenticationKey using the derivation scheme inferred from the provided PublicKey instance.\n *\n * @param args - The arguments for the function.\n * @param args.publicKey - The PublicKey to be converted.\n * @returns AuthenticationKey - The derived AuthenticationKey.\n * @group Implementation\n * @category Serialization\n */\n static fromPublicKey(args: { publicKey: AccountPublicKey }): AuthenticationKey {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Derives an account address from an AuthenticationKey by translating the AuthenticationKey bytes directly to an AccountAddress.\n *\n * @returns AccountAddress - The derived account address.\n * @group Implementation\n * @category Serialization\n */\n derivedAddress(): AccountAddress {\n return new AccountAddress(this.data.toUint8Array());\n }\n}\n","import { AptosApiType } from \"../utils/const\";\nimport { getErrorMessage } from \"../utils/helpers\";\nimport { AptosRequest, AptosResponse } from \"../types\";\n\nexport enum KeylessErrorCategory {\n API_ERROR,\n EXTERNAL_API_ERROR,\n SESSION_EXPIRED,\n INVALID_STATE,\n INVALID_SIGNATURE,\n UNKNOWN,\n}\n\nexport enum KeylessErrorResolutionTip {\n REAUTHENTICATE = \"Re-authentiate to continue using your keyless account\",\n // eslint-disable-next-line max-len\n REAUTHENTICATE_UNSURE = \"Try re-authentiating. If the error persists join the telegram group at https://t.me/+h5CN-W35yUFiYzkx for further support\",\n UPDATE_REQUEST_PARAMS = \"Update the invalid request parameters and reauthenticate.\",\n // eslint-disable-next-line max-len\n RATE_LIMIT_EXCEEDED = \"Cache the keyless account and reuse it to avoid making too many requests. Keyless accounts are valid until either the EphemeralKeyPair expires, when the JWK is rotated, or when the proof verifying key is changed, whichever comes soonest.\",\n // eslint-disable-next-line max-len\n SERVER_ERROR = \"Try again later. See aptosApiError error for more context. For additional support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx\",\n // eslint-disable-next-line max-len\n CALL_PRECHECK = \"Call `await account.checkKeylessAccountValidity()` to wait for asyncronous changes and check for account validity before signing or serializing.\",\n REINSTANTIATE = \"Try instantiating the account again. Avoid manipulating the account object directly\",\n JOIN_SUPPORT_GROUP = \"For support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx\",\n UNKNOWN = \"Error unknown. For support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx\",\n}\n\nexport enum KeylessErrorType {\n EPHEMERAL_KEY_PAIR_EXPIRED,\n\n PROOF_NOT_FOUND,\n\n ASYNC_PROOF_FETCH_FAILED,\n\n INVALID_PROOF_VERIFICATION_FAILED,\n\n INVALID_PROOF_VERIFICATION_KEY_NOT_FOUND,\n\n INVALID_JWT_SIG,\n\n INVALID_JWT_JWK_NOT_FOUND,\n\n INVALID_JWT_ISS_NOT_RECOGNIZED,\n\n INVALID_JWT_FEDERATED_ISS_NOT_SUPPORTED,\n\n INVALID_TW_SIG_VERIFICATION_FAILED,\n\n INVALID_TW_SIG_PUBLIC_KEY_NOT_FOUND,\n\n INVALID_EXPIRY_HORIZON,\n\n JWT_PARSING_ERROR,\n\n JWK_FETCH_FAILED,\n\n JWK_FETCH_FAILED_FEDERATED,\n\n RATE_LIMIT_EXCEEDED,\n\n PEPPER_SERVICE_INTERNAL_ERROR,\n\n PEPPER_SERVICE_BAD_REQUEST,\n\n PEPPER_SERVICE_OTHER,\n\n PROVER_SERVICE_INTERNAL_ERROR,\n\n PROVER_SERVICE_BAD_REQUEST,\n\n PROVER_SERVICE_OTHER,\n\n FULL_NODE_CONFIG_LOOKUP_ERROR,\n\n FULL_NODE_VERIFICATION_KEY_LOOKUP_ERROR,\n\n FULL_NODE_JWKS_LOOKUP_ERROR,\n\n FULL_NODE_OTHER,\n\n SIGNATURE_TYPE_INVALID,\n\n SIGNATURE_EXPIRED,\n\n MAX_EXPIRY_HORIZON_EXCEEDED,\n\n EPHEMERAL_SIGNATURE_VERIFICATION_FAILED,\n\n TRAINING_WHEELS_SIGNATURE_MISSING,\n\n TRAINING_WHEELS_SIGNATURE_VERIFICATION_FAILED,\n\n PROOF_VERIFICATION_FAILED,\n\n UNKNOWN,\n}\n\nconst KeylessErrors: { [key in KeylessErrorType]: [string, KeylessErrorCategory, KeylessErrorResolutionTip] } = {\n [KeylessErrorType.EPHEMERAL_KEY_PAIR_EXPIRED]: [\n \"The ephemeral keypair has expired.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.PROOF_NOT_FOUND]: [\n \"The required proof could not be found.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.CALL_PRECHECK,\n ],\n [KeylessErrorType.ASYNC_PROOF_FETCH_FAILED]: [\n \"The required proof failed to fetch.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_PROOF_VERIFICATION_FAILED]: [\n \"The provided proof is invalid.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_PROOF_VERIFICATION_KEY_NOT_FOUND]: [\n \"The verification key used to authenticate was updated.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.INVALID_JWT_SIG]: [\n \"The JWK was found, but JWT failed verification\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_JWT_JWK_NOT_FOUND]: [\n \"The JWK required to verify the JWT could not be found. The JWK may have been rotated out.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.INVALID_JWT_ISS_NOT_RECOGNIZED]: [\n \"The JWT issuer is not recognized.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.UPDATE_REQUEST_PARAMS,\n ],\n [KeylessErrorType.INVALID_JWT_FEDERATED_ISS_NOT_SUPPORTED]: [\n \"The JWT issuer is not supported by the Federated Keyless \",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_TW_SIG_VERIFICATION_FAILED]: [\n \"The training wheels signature is invalid.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_TW_SIG_PUBLIC_KEY_NOT_FOUND]: [\n \"The public key used to verify the training wheels signature was not found.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.INVALID_EXPIRY_HORIZON]: [\n \"The expiry horizon is invalid.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.JWK_FETCH_FAILED]: [\n \"Failed to fetch JWKS.\",\n KeylessErrorCategory.EXTERNAL_API_ERROR,\n KeylessErrorResolutionTip.JOIN_SUPPORT_GROUP,\n ],\n [KeylessErrorType.JWK_FETCH_FAILED_FEDERATED]: [\n \"Failed to fetch JWKS for Federated Keyless provider.\",\n KeylessErrorCategory.EXTERNAL_API_ERROR,\n KeylessErrorResolutionTip.JOIN_SUPPORT_GROUP,\n ],\n [KeylessErrorType.RATE_LIMIT_EXCEEDED]: [\n \"Rate limit exceeded. Too many requests in a short period.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.RATE_LIMIT_EXCEEDED,\n ],\n [KeylessErrorType.PEPPER_SERVICE_INTERNAL_ERROR]: [\n \"Internal error from Pepper service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.PEPPER_SERVICE_BAD_REQUEST]: [\n \"Bad request sent to Pepper service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.UPDATE_REQUEST_PARAMS,\n ],\n [KeylessErrorType.PEPPER_SERVICE_OTHER]: [\n \"Unknown error from Pepper service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.PROVER_SERVICE_INTERNAL_ERROR]: [\n \"Internal error from Prover service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.PROVER_SERVICE_BAD_REQUEST]: [\n \"Bad request sent to Prover service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.UPDATE_REQUEST_PARAMS,\n ],\n [KeylessErrorType.PROVER_SERVICE_OTHER]: [\n \"Unknown error from Prover service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.JWT_PARSING_ERROR]: [\n \"Error when parsing JWT. This should never happen. Join https://t.me/+h5CN-W35yUFiYzkx for support\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REINSTANTIATE,\n ],\n [KeylessErrorType.FULL_NODE_CONFIG_LOOKUP_ERROR]: [\n \"Error when looking up on-chain keyless configuration.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.FULL_NODE_VERIFICATION_KEY_LOOKUP_ERROR]: [\n \"Error when looking up on-chain verification key.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.FULL_NODE_JWKS_LOOKUP_ERROR]: [\n \"Error when looking up on-chain JWKS.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.FULL_NODE_OTHER]: [\n \"Unknown error from full node.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.SIGNATURE_TYPE_INVALID]: [\n \"The signature is not a valid Keyless signature.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.JOIN_SUPPORT_GROUP,\n ],\n [KeylessErrorType.SIGNATURE_EXPIRED]: [\n \"The ephemeral key pair used to sign the message has expired.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.MAX_EXPIRY_HORIZON_EXCEEDED]: [\n \"The expiry horizon on the signature exceeds the maximum allowed value.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.EPHEMERAL_SIGNATURE_VERIFICATION_FAILED]: [\n \"Failed to verify the ephemeral signature with the ephemeral public key.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.TRAINING_WHEELS_SIGNATURE_MISSING]: [\n \"The training wheels signature is missing but is required by the Keyless configuration.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.TRAINING_WHEELS_SIGNATURE_VERIFICATION_FAILED]: [\n \"Failed to verify the training wheels signature with the training wheels public key.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.PROOF_VERIFICATION_FAILED]: [\n \"The proof verification failed.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.UNKNOWN]: [\n \"An unknown error has occurred.\",\n KeylessErrorCategory.UNKNOWN,\n KeylessErrorResolutionTip.UNKNOWN,\n ],\n};\n\nexport class KeylessError extends Error {\n readonly innerError?: unknown;\n\n readonly category: KeylessErrorCategory;\n\n readonly resolutionTip: KeylessErrorResolutionTip;\n\n readonly type: KeylessErrorType;\n\n readonly details?: string;\n\n /** @internal this constructor is for sdk internal use - do not instantiate outside of the SDK codebase */\n constructor(args: {\n innerError?: unknown;\n category: KeylessErrorCategory;\n resolutionTip: KeylessErrorResolutionTip;\n type: KeylessErrorType;\n message?: string;\n details?: string;\n }) {\n const { innerError, category, resolutionTip, type, message = KeylessErrors[type][0], details } = args;\n super(message);\n this.name = \"KeylessError\";\n this.innerError = innerError;\n this.category = category;\n this.resolutionTip = resolutionTip;\n this.type = type;\n this.details = details;\n this.message = KeylessError.constructMessage(message, resolutionTip, innerError, details);\n }\n\n static constructMessage(\n message: string,\n tip: KeylessErrorResolutionTip,\n innerError?: unknown,\n details?: string,\n ): string {\n let result = `\\nMessage: ${message}`;\n if (details) {\n result += `\\nDetails: ${details}`;\n }\n if (innerError instanceof AptosApiError) {\n result += `\\nAptosApiError: ${innerError.message}`;\n } else if (innerError !== undefined) {\n result += `\\nError: ${getErrorMessage(innerError)}`;\n }\n result += `\\nKeylessErrorResolutionTip: ${tip}`;\n return result;\n }\n\n /**\n * Static constructor that creates a KeylessError instance using the KeylessErrors constant\n * @param args.type The type of KeylessError\n * @param args.aptosApiError optional AptosApiError supplied for api errors\n * @param args.details optional details to include in the error message\n * @returns A new KeylessError instance\n */\n static fromErrorType(args: { type: KeylessErrorType; error?: unknown; details?: string }): KeylessError {\n const { error, type, details } = args;\n\n const [message, category, resolutionTip] = KeylessErrors[type];\n return new KeylessError({\n message,\n details,\n innerError: error,\n category,\n resolutionTip,\n type,\n });\n }\n}\n\n/**\n * Options for handling errors in the Aptos API.\n */\ntype AptosApiErrorOpts = {\n apiType: AptosApiType;\n aptosRequest: AptosRequest;\n aptosResponse: AptosResponse<any, any>;\n};\n\n/**\n * Represents an error returned from the Aptos API.\n * This class encapsulates the details of the error, including the request URL, response status, and additional data.\n *\n * @param name - The name of the error, which is always \"AptosApiError\".\n * @param url - The URL to which the request was made.\n * @param status - The HTTP response status code (e.g., 400).\n * @param statusText - The message associated with the response status.\n * @param data - The response data returned from the API.\n * @param request - The original AptosRequest that triggered the error.\n */\nexport class AptosApiError extends Error {\n readonly url: string;\n\n readonly status: number;\n\n readonly statusText: string;\n\n readonly data: any;\n\n readonly request: AptosRequest;\n\n /**\n * Constructs an instance of AptosApiError with relevant error details.\n *\n * @param opts - The options for creating the AptosApiError.\n * @param opts.apiType - The type of API that generated the error.\n * @param opts.aptosRequest - The request object that caused the error.\n * @param opts.aptosResponse - The response object containing error details.\n *\n * @internal This constructor is for SDK internal use - do not instantiate outside the SDK codebase.\n */\n constructor({ apiType, aptosRequest, aptosResponse }: AptosApiErrorOpts) {\n super(deriveErrorMessage({ apiType, aptosRequest, aptosResponse }));\n\n this.name = \"AptosApiError\";\n this.url = aptosResponse.url;\n this.status = aptosResponse.status;\n this.statusText = aptosResponse.statusText;\n this.data = aptosResponse.data;\n this.request = aptosRequest;\n }\n}\n\n/**\n * Derives an error message from the Aptos API response, providing context for debugging.\n * This function helps in understanding the nature of the error encountered during an API request.\n *\n * @param {AptosApiErrorOpts} opts - The options for deriving the error message.\n * @param {AptosApiType} opts.apiType - The type of API being called.\n * @param {AptosRequest} opts.aptosRequest - The original request made to the Aptos API.\n * @param {AptosResponse} opts.aptosResponse - The response received from the Aptos API.\n */\nfunction deriveErrorMessage({ apiType, aptosRequest, aptosResponse }: AptosApiErrorOpts): string {\n // eslint-disable-next-line max-len\n // extract the W3C trace_id from the response headers if it exists. Some services set this in the response, and it's useful for debugging.\n // See https://www.w3.org/TR/trace-context/#relationship-between-the-headers .\n const traceId = aptosResponse.headers?.traceparent?.split(\"-\")[1];\n const traceIdString = traceId ? `(trace_id:${traceId}) ` : \"\";\n\n const errorPrelude: string = `Request to [${apiType}]: ${aptosRequest.method} ${\n aptosResponse.url ?? aptosRequest.url\n } ${traceIdString}failed with`;\n\n // handle graphql responses from indexer api and extract the error message of the first error\n if (apiType === AptosApiType.INDEXER && aptosResponse.data?.errors?.[0]?.message != null) {\n return `${errorPrelude}: ${aptosResponse.data.errors[0].message}`;\n }\n\n // Received well-known structured error response body - simply serialize and return it.\n // We don't need http status codes etc. in this case.\n if (aptosResponse.data?.message != null && aptosResponse.data?.error_code != null) {\n return `${errorPrelude}: ${JSON.stringify(aptosResponse.data)}`;\n }\n\n // This is the generic/catch-all case. We received some response from the API, but it doesn't appear to be a well-known structure.\n // We print http status codes and the response body (after some trimming),\n // in the hope that this gives enough context what went wrong without printing overly huge messages.\n return `${errorPrelude} status: ${aptosResponse.statusText}(code:${\n aptosResponse.status\n }) and response body: ${serializeAnyPayloadForErrorMessage(aptosResponse.data)}`;\n}\n\nconst SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH = 400;\n\n/**\n * This function accepts a payload of any type (probably an object) and serializes it to a string\n * Since we don't know the type or size of the payload, and we don't want to add a huge object in full to the error message\n * we limit the to the first 200 and last 200 characters of the serialized payload and put a \"...\" in the middle.\n * @param payload - The payload to serialize, which can be of any type.\n *\n * @returns A string representation of the serialized payload, potentially truncated.\n */\nfunction serializeAnyPayloadForErrorMessage(payload: any): string {\n const serializedPayload = JSON.stringify(payload);\n if (serializedPayload.length <= SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH) {\n return serializedPayload;\n }\n return `truncated(original_size:${serializedPayload.length}): ${serializedPayload.slice(\n 0,\n SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH / 2,\n )}...${serializedPayload.slice(-SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH / 2)}`;\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","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\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 // 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\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 { AbstractionAuthDataVariant } 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\nexport class AccountAuthenticatorAbstraction extends AccountAuthenticator {\n public readonly functionInfo: string;\n\n public readonly signingMessageDigest: Hex;\n\n public readonly authenticator: 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 authenticator: 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.authenticator = authenticator;\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(AbstractionAuthDataVariant.DerivableV1);\n } else {\n serializer.serializeU32AsUleb128(AbstractionAuthDataVariant.V1);\n }\n serializer.serializeBytes(this.signingMessageDigest.toUint8Array());\n if (this.accountIdentity) {\n serializer.serializeBytes(this.authenticator);\n } else {\n serializer.serializeFixedBytes(this.authenticator);\n }\n\n if (this.accountIdentity) {\n serializer.serializeBytes(this.accountIdentity);\n }\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorAbstraction {\n const moduleAddress = AccountAddress.deserialize(deserializer);\n const moduleName = deserializer.deserializeStr();\n const functionName = deserializer.deserializeStr();\n const variant = deserializer.deserializeUleb128AsU32();\n if (variant === AbstractionAuthDataVariant.V1) {\n const signingMessageDigest = deserializer.deserializeBytes();\n const authenticator = deserializer.deserializeFixedBytes(deserializer.remaining());\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n authenticator,\n );\n }\n if (variant === AbstractionAuthDataVariant.DerivableV1) {\n const signingMessageDigest = deserializer.deserializeBytes();\n const abstractSignature = deserializer.deserializeBytes();\n\n const abstractPublicKey = deserializer.deserializeBytes();\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n abstractSignature,\n abstractPublicKey,\n );\n }\n throw new Error(`Unknown variant index for AccountAuthenticatorAbstraction: ${variant}`);\n }\n}\n","import * as Types from \"./operations\";\n\nimport { GraphQLClient, RequestOptions } from \"graphql-request\";\ntype GraphQLClientRequestHeaders = RequestOptions[\"requestHeaders\"];\nexport const TokenActivitiesFieldsFragmentDoc = `\n fragment TokenActivitiesFields on token_activities_v2 {\n after_value\n before_value\n entry_function_id_str\n event_account_address\n event_index\n from_address\n is_fungible_v2\n property_version_v1\n to_address\n token_amount\n token_data_id\n token_standard\n transaction_timestamp\n transaction_version\n type\n}\n `;\nexport const AnsTokenFragmentFragmentDoc = `\n fragment AnsTokenFragment on current_aptos_names {\n domain\n expiration_timestamp\n registered_address\n subdomain\n token_standard\n is_primary\n owner_address\n subdomain_expiration_policy\n domain_expiration_timestamp\n}\n `;\nexport const CurrentTokenOwnershipFieldsFragmentDoc = `\n fragment CurrentTokenOwnershipFields on current_token_ownerships_v2 {\n token_standard\n token_properties_mutated_v1\n token_data_id\n table_type_v1\n storage_id\n property_version_v1\n owner_address\n last_transaction_version\n last_transaction_timestamp\n is_soulbound_v2\n is_fungible_v2\n amount\n current_token_data {\n collection_id\n description\n is_fungible_v2\n largest_property_version_v1\n last_transaction_timestamp\n last_transaction_version\n maximum\n supply\n token_data_id\n token_name\n token_properties\n token_standard\n token_uri\n decimals\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n }\n}\n `;\nexport const GetAccountCoinsCount = `\n query getAccountCoinsCount($address: String) {\n current_fungible_asset_balances_aggregate(\n where: {owner_address: {_eq: $address}}\n ) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAccountCoinsData = `\n query getAccountCoinsData($where_condition: current_fungible_asset_balances_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_fungible_asset_balances_order_by!]) {\n current_fungible_asset_balances(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n amount\n asset_type\n is_frozen\n is_primary\n last_transaction_timestamp\n last_transaction_version\n owner_address\n storage_id\n token_standard\n metadata {\n token_standard\n symbol\n supply_aggregator_table_key_v1\n supply_aggregator_table_handle_v1\n project_uri\n name\n last_transaction_version\n last_transaction_timestamp\n icon_uri\n decimals\n creator_address\n asset_type\n }\n }\n}\n `;\nexport const GetAccountCollectionsWithOwnedTokens = `\n query getAccountCollectionsWithOwnedTokens($where_condition: current_collection_ownership_v2_view_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_collection_ownership_v2_view_order_by!]) {\n current_collection_ownership_v2_view(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n mutable_description\n max_supply\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n collection_id\n collection_name\n collection_uri\n creator_address\n distinct_tokens\n last_transaction_version\n owner_address\n single_token_uri\n }\n}\n `;\nexport const GetAccountOwnedTokens = `\n query getAccountOwnedTokens($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountOwnedTokensByTokenData = `\n query getAccountOwnedTokensByTokenData($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountOwnedTokensFromCollection = `\n query getAccountOwnedTokensFromCollection($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountTokensCount = `\n query getAccountTokensCount($where_condition: current_token_ownerships_v2_bool_exp, $offset: Int, $limit: Int) {\n current_token_ownerships_v2_aggregate(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAccountTransactionsCount = `\n query getAccountTransactionsCount($address: String) {\n account_transactions_aggregate(where: {account_address: {_eq: $address}}) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetChainTopUserTransactions = `\n query getChainTopUserTransactions($limit: Int) {\n user_transactions(limit: $limit, order_by: {version: desc}) {\n version\n }\n}\n `;\nexport const GetCollectionData = `\n query getCollectionData($where_condition: current_collections_v2_bool_exp!) {\n current_collections_v2(where: $where_condition) {\n uri\n total_minted_v2\n token_standard\n table_handle_v1\n mutable_uri\n mutable_description\n max_supply\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n cdn_asset_uris {\n cdn_image_uri\n asset_uri\n animation_optimizer_retry_count\n cdn_animation_uri\n cdn_json_uri\n image_optimizer_retry_count\n json_parser_retry_count\n raw_animation_uri\n raw_image_uri\n }\n }\n}\n `;\nexport const GetCurrentFungibleAssetBalances = `\n query getCurrentFungibleAssetBalances($where_condition: current_fungible_asset_balances_bool_exp, $offset: Int, $limit: Int) {\n current_fungible_asset_balances(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n amount\n asset_type\n is_frozen\n is_primary\n last_transaction_timestamp\n last_transaction_version\n owner_address\n storage_id\n token_standard\n }\n}\n `;\nexport const GetDelegatedStakingActivities = `\n query getDelegatedStakingActivities($delegatorAddress: String, $poolAddress: String) {\n delegated_staking_activities(\n where: {delegator_address: {_eq: $delegatorAddress}, pool_address: {_eq: $poolAddress}}\n ) {\n amount\n delegator_address\n event_index\n event_type\n pool_address\n transaction_version\n }\n}\n `;\nexport const GetEvents = `\n query getEvents($where_condition: events_bool_exp, $offset: Int, $limit: Int, $order_by: [events_order_by!]) {\n events(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n account_address\n creation_number\n data\n event_index\n sequence_number\n transaction_block_height\n transaction_version\n type\n indexed_type\n }\n}\n `;\nexport const GetFungibleAssetActivities = `\n query getFungibleAssetActivities($where_condition: fungible_asset_activities_bool_exp, $offset: Int, $limit: Int) {\n fungible_asset_activities(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n amount\n asset_type\n block_height\n entry_function_id_str\n event_index\n gas_fee_payer_address\n is_frozen\n is_gas_fee\n is_transaction_success\n owner_address\n storage_id\n storage_refund_amount\n token_standard\n transaction_timestamp\n transaction_version\n type\n }\n}\n `;\nexport const GetFungibleAssetMetadata = `\n query getFungibleAssetMetadata($where_condition: fungible_asset_metadata_bool_exp, $offset: Int, $limit: Int) {\n fungible_asset_metadata(where: $where_condition, offset: $offset, limit: $limit) {\n icon_uri\n project_uri\n supply_aggregator_table_handle_v1\n supply_aggregator_table_key_v1\n creator_address\n asset_type\n decimals\n last_transaction_timestamp\n last_transaction_version\n name\n symbol\n token_standard\n supply_v2\n maximum_v2\n }\n}\n `;\nexport const GetNames = `\n query getNames($offset: Int, $limit: Int, $where_condition: current_aptos_names_bool_exp, $order_by: [current_aptos_names_order_by!]) {\n current_aptos_names(\n limit: $limit\n where: $where_condition\n order_by: $order_by\n offset: $offset\n ) {\n ...AnsTokenFragment\n }\n}\n ${AnsTokenFragmentFragmentDoc}`;\nexport const GetNumberOfDelegators = `\n query getNumberOfDelegators($where_condition: num_active_delegator_per_pool_bool_exp, $order_by: [num_active_delegator_per_pool_order_by!]) {\n num_active_delegator_per_pool(where: $where_condition, order_by: $order_by) {\n num_active_delegator\n pool_address\n }\n}\n `;\nexport const GetObjectData = `\n query getObjectData($where_condition: current_objects_bool_exp, $offset: Int, $limit: Int, $order_by: [current_objects_order_by!]) {\n current_objects(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n allow_ungated_transfer\n state_key_hash\n owner_address\n object_address\n last_transaction_version\n last_guid_creation_num\n is_deleted\n }\n}\n `;\nexport const GetProcessorStatus = `\n query getProcessorStatus($where_condition: processor_status_bool_exp) {\n processor_status(where: $where_condition) {\n last_success_version\n processor\n last_updated\n }\n}\n `;\nexport const GetTableItemsData = `\n query getTableItemsData($where_condition: table_items_bool_exp!, $offset: Int, $limit: Int, $order_by: [table_items_order_by!]) {\n table_items(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n decoded_key\n decoded_value\n key\n table_handle\n transaction_version\n write_set_change_index\n }\n}\n `;\nexport const GetTableItemsMetadata = `\n query getTableItemsMetadata($where_condition: table_metadatas_bool_exp!, $offset: Int, $limit: Int, $order_by: [table_metadatas_order_by!]) {\n table_metadatas(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n handle\n key_type\n value_type\n }\n}\n `;\nexport const GetTokenActivity = `\n query getTokenActivity($where_condition: token_activities_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [token_activities_v2_order_by!]) {\n token_activities_v2(\n where: $where_condition\n order_by: $order_by\n offset: $offset\n limit: $limit\n ) {\n ...TokenActivitiesFields\n }\n}\n ${TokenActivitiesFieldsFragmentDoc}`;\nexport const GetCurrentTokenOwnership = `\n query getCurrentTokenOwnership($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetTokenData = `\n query getTokenData($where_condition: current_token_datas_v2_bool_exp, $offset: Int, $limit: Int, $order_by: [current_token_datas_v2_order_by!]) {\n current_token_datas_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n collection_id\n description\n is_fungible_v2\n largest_property_version_v1\n last_transaction_timestamp\n last_transaction_version\n maximum\n supply\n token_data_id\n token_name\n token_properties\n token_standard\n token_uri\n decimals\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n }\n}\n `;\n\nexport type SdkFunctionWrapper = <T>(\n action: (requestHeaders?: Record<string, string>) => Promise<T>,\n operationName: string,\n operationType?: string,\n variables?: any,\n) => Promise<T>;\n\nconst defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationType, _variables) => action();\n\nexport function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {\n return {\n getAccountCoinsCount(\n variables?: Types.GetAccountCoinsCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCoinsCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCoinsCountQuery>(GetAccountCoinsCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountCoinsCount\",\n \"query\",\n variables,\n );\n },\n getAccountCoinsData(\n variables: Types.GetAccountCoinsDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCoinsDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCoinsDataQuery>(GetAccountCoinsData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountCoinsData\",\n \"query\",\n variables,\n );\n },\n getAccountCollectionsWithOwnedTokens(\n variables: Types.GetAccountCollectionsWithOwnedTokensQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCollectionsWithOwnedTokensQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCollectionsWithOwnedTokensQuery>(\n GetAccountCollectionsWithOwnedTokens,\n variables,\n { ...requestHeaders, ...wrappedRequestHeaders },\n ),\n \"getAccountCollectionsWithOwnedTokens\",\n \"query\",\n variables,\n );\n },\n getAccountOwnedTokens(\n variables: Types.GetAccountOwnedTokensQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensQuery>(GetAccountOwnedTokens, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedTokens\",\n \"query\",\n variables,\n );\n },\n getAccountOwnedTokensByTokenData(\n variables: Types.GetAccountOwnedTokensByTokenDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensByTokenDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensByTokenDataQuery>(GetAccountOwnedTokensByTokenData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedTokensByTokenData\",\n \"query\",\n variables,\n );\n },\n getAccountOwnedTokensFromCollection(\n variables: Types.GetAccountOwnedTokensFromCollectionQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensFromCollectionQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensFromCollectionQuery>(\n GetAccountOwnedTokensFromCollection,\n variables,\n { ...requestHeaders, ...wrappedRequestHeaders },\n ),\n \"getAccountOwnedTokensFromCollection\",\n \"query\",\n variables,\n );\n },\n getAccountTokensCount(\n variables?: Types.GetAccountTokensCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountTokensCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountTokensCountQuery>(GetAccountTokensCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountTokensCount\",\n \"query\",\n variables,\n );\n },\n getAccountTransactionsCount(\n variables?: Types.GetAccountTransactionsCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountTransactionsCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountTransactionsCountQuery>(GetAccountTransactionsCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountTransactionsCount\",\n \"query\",\n variables,\n );\n },\n getChainTopUserTransactions(\n variables?: Types.GetChainTopUserTransactionsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetChainTopUserTransactionsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetChainTopUserTransactionsQuery>(GetChainTopUserTransactions, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getChainTopUserTransactions\",\n \"query\",\n variables,\n );\n },\n getCollectionData(\n variables: Types.GetCollectionDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCollectionDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCollectionDataQuery>(GetCollectionData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCollectionData\",\n \"query\",\n variables,\n );\n },\n getCurrentFungibleAssetBalances(\n variables?: Types.GetCurrentFungibleAssetBalancesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCurrentFungibleAssetBalancesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCurrentFungibleAssetBalancesQuery>(GetCurrentFungibleAssetBalances, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCurrentFungibleAssetBalances\",\n \"query\",\n variables,\n );\n },\n getDelegatedStakingActivities(\n variables?: Types.GetDelegatedStakingActivitiesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetDelegatedStakingActivitiesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetDelegatedStakingActivitiesQuery>(GetDelegatedStakingActivities, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getDelegatedStakingActivities\",\n \"query\",\n variables,\n );\n },\n getEvents(\n variables?: Types.GetEventsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetEventsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetEventsQuery>(GetEvents, variables, { ...requestHeaders, ...wrappedRequestHeaders }),\n \"getEvents\",\n \"query\",\n variables,\n );\n },\n getFungibleAssetActivities(\n variables?: Types.GetFungibleAssetActivitiesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetFungibleAssetActivitiesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetFungibleAssetActivitiesQuery>(GetFungibleAssetActivities, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getFungibleAssetActivities\",\n \"query\",\n variables,\n );\n },\n getFungibleAssetMetadata(\n variables?: Types.GetFungibleAssetMetadataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetFungibleAssetMetadataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetFungibleAssetMetadataQuery>(GetFungibleAssetMetadata, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getFungibleAssetMetadata\",\n \"query\",\n variables,\n );\n },\n getNames(\n variables?: Types.GetNamesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetNamesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetNamesQuery>(GetNames, variables, { ...requestHeaders, ...wrappedRequestHeaders }),\n \"getNames\",\n \"query\",\n variables,\n );\n },\n getNumberOfDelegators(\n variables?: Types.GetNumberOfDelegatorsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetNumberOfDelegatorsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetNumberOfDelegatorsQuery>(GetNumberOfDelegators, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getNumberOfDelegators\",\n \"query\",\n variables,\n );\n },\n getObjectData(\n variables?: Types.GetObjectDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetObjectDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetObjectDataQuery>(GetObjectData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getObjectData\",\n \"query\",\n variables,\n );\n },\n getProcessorStatus(\n variables?: Types.GetProcessorStatusQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetProcessorStatusQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetProcessorStatusQuery>(GetProcessorStatus, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getProcessorStatus\",\n \"query\",\n variables,\n );\n },\n getTableItemsData(\n variables: Types.GetTableItemsDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTableItemsDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTableItemsDataQuery>(GetTableItemsData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTableItemsData\",\n \"query\",\n variables,\n );\n },\n getTableItemsMetadata(\n variables: Types.GetTableItemsMetadataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTableItemsMetadataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTableItemsMetadataQuery>(GetTableItemsMetadata, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTableItemsMetadata\",\n \"query\",\n variables,\n );\n },\n getTokenActivity(\n variables: Types.GetTokenActivityQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTokenActivityQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTokenActivityQuery>(GetTokenActivity, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTokenActivity\",\n \"query\",\n variables,\n );\n },\n getCurrentTokenOwnership(\n variables: Types.GetCurrentTokenOwnershipQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCurrentTokenOwnershipQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCurrentTokenOwnershipQuery>(GetCurrentTokenOwnership, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCurrentTokenOwnership\",\n \"query\",\n variables,\n );\n },\n getTokenData(\n variables?: Types.GetTokenDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTokenDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTokenDataQuery>(GetTokenData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTokenData\",\n \"query\",\n variables,\n );\n },\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;\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 { Account as AccountModule } from \"../account\";\nimport { AccountAddress, PrivateKey, AccountAddressInput, createObjectAddress } 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 getAccountTokensCount,\n getAccountTransactionsCount,\n getInfo,\n getModule,\n getModules,\n getModulesPage,\n getResource,\n getResources,\n getResourcesPage,\n getTransactions,\n lookupOriginalAccountAddress,\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 * @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 * @param args.minimumLedgerVersion Not used anymore, here for backward compatibility\n * see https://github.com/aptos-labs/aptos-ts-sdk/pull/519, will be removed in the near future.\n * Optional ledger version to sync up to before querying.\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 * // Query the account's coin amount for a specific coin type\n * const accountCoinAmount = await aptos.getAccountCoinAmount({\n * accountAddress: \"0x1\", // replace with a real account address\n * coinType: \"0x1::aptos_coin::AptosCoin\" // specify the coin type\n * });\n *\n * console.log(`Account coin amount: ${accountCoinAmount}`);\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 minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n const { accountAddress, coinType, faMetadataAddress, minimumLedgerVersion } = args;\n\n if (minimumLedgerVersion) {\n // eslint-disable-next-line no-console\n console.warn(\n `minimumLedgerVersion is not used anymore, here for backward \n compatibility see https://github.com/aptos-labs/aptos-ts-sdk/pull/519, \n will be removed in the near future`,\n );\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({\n aptosConfig: this.config,\n payload: { function: \"0x1::coin::paired_coin\", functionArguments: [faMetadataAddress] },\n })\n ).at(0) as { vec: MoveValue[] };\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]) as MoveStructId;\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 * 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: { privateKey: PrivateKey }): Promise<AccountModule> {\n return deriveAccountFromPrivateKey({ aptosConfig: this.config, ...args });\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * This file contains the underlying implementations for exposed API surface in\n * the {@link api/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"]}
1
+ {"version":3,"sources":["/Users/oliverhe/aptos-ts-sdk-2/dist/common/index.js","../../src/bcs/deserializer.ts","../../src/bcs/serializable/fixedBytes.ts","../../src/bcs/serializable/entryFunctionBytes.ts","../../src/bcs/serializable/movePrimitives.ts","../../src/bcs/serializable/moveStructs.ts","../../src/core/authenticationKey.ts","../../src/errors/index.ts","../../src/core/crypto/keyless.ts","../../src/core/crypto/multiKey.ts","../../src/transactions/authenticator/account.ts","../../src/types/generated/queries.ts","../../src/transactions/typeTag/parser.ts","../../src/api/account.ts","../../src/internal/digitalAsset.ts"],"names":["Deserializer","_Deserializer","data","hex","Hex","length","bytes","value","type","len","bool","low","high","shift","MAX_U32_NUMBER","byte","cls","vector","FixedBytes","_FixedBytes","Serializable","serializer","deserializer","EntryFunctionBytes","_EntryFunctionBytes","fixedBytes","Bool","_Bool","ensureBoolean","bcsBytes","U256","U8","_U8","validateNumberInRange","MAX_U8_NUMBER","U16","_U16","MAX_U16_NUMBER","U32","_U32","U64","_U64","MAX_U64_BIG_INT","U128","_U128","MAX_U128_BIG_INT","_U256","MAX_U256_BIG_INT","MoveVector","_MoveVector","values","Serialized","numbers","v","MoveString","i","_Serialized","vec","_MoveString","fixedStringBytes","MoveOption","_MoveOption","_AuthenticationKey","args"],"mappings":"AAAA,2sCAAwnB,IC6C3mBA,CAAAA,CAAN,MAAMC,CAAa,CAaxB,WAAA,CAAYC,CAAAA,CAAkB,CAE5B,IAAA,CAAK,MAAA,CAAS,IAAI,WAAA,CAAYA,CAAAA,CAAK,MAAM,CAAA,CACzC,IAAI,UAAA,CAAW,IAAA,CAAK,MAAM,CAAA,CAAE,GAAA,CAAIA,CAAAA,CAAM,CAAC,CAAA,CACvC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AA;AAcL,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYQ,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYZ,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AC9Hc,IAAA;ACkdlC;ACvOJ,0CAAA","file":"/Users/oliverhe/aptos-ts-sdk-2/dist/common/index.js","sourcesContent":[null,"// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\n/* eslint-disable no-bitwise */\nimport { MAX_U32_NUMBER } from \"./consts\";\nimport { Uint8, Uint16, Uint32, Uint64, Uint128, Uint256, HexInput } from \"../types\";\nimport { Hex } from \"../core/hex\";\n\n/**\n * This interface exists to define Deserializable<T> inputs for functions that\n * deserialize a byte buffer into a type T.\n * It is not intended to be implemented or extended, because Typescript has no support\n * for static methods in interfaces.\n *\n * @template T - The type that this will deserialize into.\n * @group Implementation\n * @category BCS\n */\nexport interface Deserializable<T> {\n /**\n * Deserializes the buffered bytes into an instance of the specified class type.\n * This function provides an alternative syntax for deserialization, allowing users to call\n * `deserializer.deserialize(MyClass)` instead of `MyClass.deserialize(deserializer)`.\n *\n * @param deserializer - The deserializer instance with the buffered bytes.\n * @returns The deserialized value of class type T.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([1, 2, 3]));\n * const value = deserializer.deserialize(MyClass); // where MyClass has a `deserialize` function\n * // value is now an instance of MyClass\n * // equivalent to `const value = MyClass.deserialize(deserializer)`\n * ```\n * @group Implementation\n * @category BCS\n */\n deserialize(deserializer: Deserializer): T;\n}\n\n/**\n * A class that provides methods for deserializing various data types from a byte buffer.\n * It supports deserialization of primitive types, strings, and complex objects using a BCS (Binary Common Serialization) layout.\n * @group Implementation\n * @category BCS\n */\nexport class Deserializer {\n private buffer: ArrayBuffer;\n\n private offset: number;\n\n /**\n * Creates a new instance of the class with a copy of the provided data buffer.\n * This prevents outside mutation of the buffer.\n *\n * @param data - The data to be copied into the internal buffer as a Uint8Array.\n * @group Implementation\n * @category BCS\n */\n constructor(data: Uint8Array) {\n // copies data to prevent outside mutation of buffer.\n this.buffer = new ArrayBuffer(data.length);\n new Uint8Array(this.buffer).set(data, 0);\n this.offset = 0;\n }\n\n static fromHex(hex: HexInput): Deserializer {\n const data = Hex.hexInputToUint8Array(hex);\n return new Deserializer(data);\n }\n\n /**\n * Reads a specified number of bytes from the buffer and advances the offset.\n *\n * @param length - The number of bytes to read from the buffer.\n * @throws Throws an error if the read operation exceeds the buffer's length.\n * @group Implementation\n * @category BCS\n */\n private read(length: number): ArrayBuffer {\n if (this.offset + length > this.buffer.byteLength) {\n throw new Error(\"Reached to the end of buffer\");\n }\n\n const bytes = this.buffer.slice(this.offset, this.offset + length);\n this.offset += length;\n return bytes;\n }\n\n /**\n * Returns the number of bytes remaining in the buffer.\n *\n * This information is useful to determine if there's more data to be read.\n *\n * @returns The number of bytes remaining in the buffer.\n * @group Implementation\n * @category BCS\n */\n remaining(): number {\n return this.buffer.byteLength - this.offset;\n }\n\n /**\n * Asserts that the buffer has no remaining bytes.\n *\n * @throws {Error} Throws an error if there are remaining bytes in the buffer.\n * @group Implementation\n * @category BCS\n */\n assertFinished(): void {\n if (this.remaining() !== 0) {\n throw new Error(\"Buffer has remaining bytes\");\n }\n }\n\n /**\n * Deserializes a UTF-8 encoded string from a byte array. It first reads the length of the string in bytes,\n * followed by the actual byte content, and decodes it into a string.\n *\n * BCS layout for \"string\": string_length | string_content\n * where string_length is a u32 integer encoded as a uleb128 integer, equal to the number of bytes in string_content.\n *\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([8, 49, 50, 51, 52, 97, 98, 99, 100]));\n * assert(deserializer.deserializeStr() === \"1234abcd\");\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeStr(): string {\n const value = this.deserializeBytes();\n const textDecoder = new TextDecoder();\n return textDecoder.decode(value);\n }\n\n /**\n * @deprecated use `deserializeOption(\"string\")` instead.\n *\n * The BCS layout for Optional<String> is 0 if none, else 1 followed by the string length and string content.\n * @returns The deserialized string if it exists, otherwise undefined.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x00]));\n * assert(deserializer.deserializeOptionStr() === undefined);\n * const deserializer = new Deserializer(new Uint8Array([1, 8, 49, 50, 51, 52, 97, 98, 99, 100]));\n * assert(deserializer.deserializeOptionStr() === \"1234abcd\");\n * ```\n */\n deserializeOptionStr(): string | undefined {\n return this.deserializeOption(\"string\");\n }\n\n /**\n * Deserializes an optional value from the buffer.\n *\n * The BCS layout for Optional<T> starts with a boolean byte (0 if none, 1 if some),\n * followed by the value if present.\n *\n * @template T - The type of the value to deserialize\n * @param type - Either a Deserializable class or one of the string literals: \"string\", \"bytes\", or \"fixedBytes\"\n * @param len - Required length when type is \"fixedBytes\", ignored otherwise\n * @returns The deserialized value if present, undefined otherwise\n *\n * @throws {Error} When \"fixedBytes\" is specified without a length\n *\n * @example\n * ```typescript\n * // Deserialize an optional string\n * const deserializer = new Deserializer(new Uint8Array([1, 3, 97, 98, 99]));\n * const optStr = deserializer.deserializeOption(\"string\");\n * // optStr === \"abc\"\n *\n * // Deserialize an optional custom type\n * const deserializer = new Deserializer(new Uint8Array([0]));\n * const optValue = deserializer.deserializeOption(MyClass);\n * // optValue === undefined\n *\n * // Deserialize optional bytes\n * const deserializer = new Deserializer(new Uint8Array([1, 3, 1, 2, 3]));\n * const optBytes = deserializer.deserializeOption(\"bytes\");\n * // optBytes === Uint8Array[1, 2, 3]\n *\n * // Deserialize optional fixed bytes\n * const deserializer = new Deserializer(new Uint8Array([1, 1, 2, 3, 4]));\n * const optBytes = deserializer.deserializeOption(\"fixedBytes\", 4);\n * // optBytes === Uint8Array[1, 2, 3, 4]\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeOption(type: \"string\"): string | undefined;\n deserializeOption(type: \"bytes\"): Uint8Array | undefined;\n deserializeOption(type: \"fixedBytes\", len: number): Uint8Array | undefined;\n deserializeOption<T>(type: Deserializable<T>): T | undefined;\n deserializeOption<T>(\n type: Deserializable<T> | \"string\" | \"bytes\" | \"fixedBytes\",\n len?: number,\n ): T | string | Uint8Array | undefined {\n const exists = this.deserializeBool();\n if (!exists) return undefined;\n\n if (type === \"string\") {\n return this.deserializeStr();\n }\n if (type === \"bytes\") {\n return this.deserializeBytes();\n }\n if (type === \"fixedBytes\") {\n if (len === undefined) {\n throw new Error(\"Fixed bytes length not provided\");\n }\n return this.deserializeFixedBytes(len);\n }\n\n return this.deserialize(type);\n }\n\n /**\n * Deserializes an array of bytes.\n *\n * The BCS layout for \"bytes\" consists of a bytes_length followed by the bytes themselves, where bytes_length is a u32 integer\n * encoded as a uleb128 integer, indicating the length of the bytes array.\n *\n * @returns {Uint8Array} The deserialized array of bytes.\n * @group Implementation\n * @category BCS\n */\n deserializeBytes(): Uint8Array {\n const len = this.deserializeUleb128AsU32();\n return new Uint8Array(this.read(len));\n }\n\n /**\n * Deserializes an array of bytes of a specified length.\n *\n * @param len - The number of bytes to read from the source.\n * @group Implementation\n * @category BCS\n */\n deserializeFixedBytes(len: number): Uint8Array {\n return new Uint8Array(this.read(len));\n }\n\n /**\n * Deserializes a boolean value from a byte stream.\n *\n * The BCS layout for a boolean uses one byte, where \"0x01\" represents true and \"0x00\" represents false.\n * An error is thrown if the byte value is not valid.\n *\n * @returns The deserialized boolean value.\n * @throws Throws an error if the boolean value is invalid.\n * @group Implementation\n * @category BCS\n */\n deserializeBool(): boolean {\n const bool = new Uint8Array(this.read(1))[0];\n if (bool !== 1 && bool !== 0) {\n throw new Error(\"Invalid boolean value\");\n }\n return bool === 1;\n }\n\n /**\n * Deserializes a uint8 number from the binary data.\n *\n * BCS layout for \"uint8\": One byte. Binary format in little-endian representation.\n *\n * @returns {number} The deserialized uint8 number.\n * @group Implementation\n * @category BCS\n */\n deserializeU8(): Uint8 {\n return new DataView(this.read(1)).getUint8(0);\n }\n\n /**\n * Deserializes a uint16 number from a binary format in little-endian representation.\n *\n * BCS layout for \"uint16\": Two bytes.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x34, 0x12]));\n * assert(deserializer.deserializeU16() === 4660);\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeU16(): Uint16 {\n return new DataView(this.read(2)).getUint16(0, true);\n }\n\n /**\n * Deserializes a uint32 number from a binary format in little-endian representation.\n *\n * BCS layout for \"uint32\": Four bytes.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x78, 0x56, 0x34, 0x12]));\n * assert(deserializer.deserializeU32() === 305419896);\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeU32(): Uint32 {\n return new DataView(this.read(4)).getUint32(0, true);\n }\n\n /**\n * Deserializes a uint64 number.\n *\n * This function combines two 32-bit values to return a 64-bit unsigned integer in little-endian representation.\n * @example\n * ```typescript\n * const deserializer = new Deserializer(new Uint8Array([0x00, 0xEF, 0xCD, 0xAB, 0x78, 0x56, 0x34, 0x12]));\n * assert(deserializer.deserializeU64() === 1311768467750121216);\n * ```\n * @group Implementation\n * @category BCS\n */\n deserializeU64(): Uint64 {\n const low = this.deserializeU32();\n const high = this.deserializeU32();\n\n // combine the two 32-bit values and return (little endian)\n return BigInt((BigInt(high) << BigInt(32)) | BigInt(low));\n }\n\n /**\n * Deserializes a uint128 number from its binary representation.\n * This function combines two 64-bit values to return a single uint128 value in little-endian format.\n *\n * @returns {BigInt} The deserialized uint128 number.\n * @group Implementation\n * @category BCS\n */\n deserializeU128(): Uint128 {\n const low = this.deserializeU64();\n const high = this.deserializeU64();\n\n // combine the two 64-bit values and return (little endian)\n return BigInt((high << BigInt(64)) | low);\n }\n\n /**\n * Deserializes a uint256 number from its binary representation.\n *\n * The BCS layout for \"uint256\" consists of thirty-two bytes in little-endian format.\n *\n * @returns {BigInt} The deserialized uint256 number.\n * @group Implementation\n * @category BCS\n */\n deserializeU256(): Uint256 {\n const low = this.deserializeU128();\n const high = this.deserializeU128();\n\n // combine the two 128-bit values and return (little endian)\n return BigInt((high << BigInt(128)) | low);\n }\n\n /**\n * Deserializes a uleb128 encoded uint32 number.\n *\n * This function is used for interpreting lengths of variable-length sequences and tags of enum values in BCS encoding.\n *\n * @throws {Error} Throws an error if the parsed value exceeds the maximum uint32 number.\n * @returns {number} The deserialized uint32 value.\n * @group Implementation\n * @category BCS\n */\n deserializeUleb128AsU32(): Uint32 {\n let value: bigint = BigInt(0);\n let shift = 0;\n\n while (value < MAX_U32_NUMBER) {\n const byte = this.deserializeU8();\n value |= BigInt(byte & 0x7f) << BigInt(shift);\n\n if ((byte & 0x80) === 0) {\n break;\n }\n shift += 7;\n }\n\n if (value > MAX_U32_NUMBER) {\n throw new Error(\"Overflow while parsing uleb128-encoded uint32 value\");\n }\n\n return Number(value);\n }\n\n /**\n * Helper function that primarily exists to support alternative syntax for deserialization.\n * That is, if we have a `const deserializer: new Deserializer(...)`, instead of having to use\n * `MyClass.deserialize(deserializer)`, we can call `deserializer.deserialize(MyClass)`.\n *\n * @example const deserializer = new Deserializer(new Uint8Array([1, 2, 3]));\n * const value = deserializer.deserialize(MyClass); // where MyClass has a `deserialize` function\n * // value is now an instance of MyClass\n * // equivalent to `const value = MyClass.deserialize(deserializer)`\n * @param cls The BCS-deserializable class to deserialize the buffered bytes into.\n *\n * @returns the deserialized value of class type T\n * @group Implementation\n * @category BCS\n */\n deserialize<T>(cls: Deserializable<T>): T {\n // NOTE: `deserialize` in `cls.deserialize(this)` here is a static method defined in `cls`,\n // It is separate from the `deserialize` instance method defined here in Deserializer.\n return cls.deserialize(this);\n }\n\n /**\n * Deserializes an array of BCS Deserializable values given an existing Deserializer instance with a loaded byte buffer.\n *\n * @param cls The BCS-deserializable class to deserialize the buffered bytes into.\n * @returns An array of deserialized values of type T.\n * @example\n * // serialize a vector of addresses\n * const addresses = new Array<AccountAddress>(\n * AccountAddress.from(\"0x1\"),\n * AccountAddress.from(\"0x2\"),\n * AccountAddress.from(\"0xa\"),\n * AccountAddress.from(\"0xb\"),\n * );\n * const serializer = new Serializer();\n * serializer.serializeVector(addresses);\n * const serializedBytes = serializer.toUint8Array();\n *\n * // deserialize the bytes into an array of addresses\n * const deserializer = new Deserializer(serializedBytes);\n * const deserializedAddresses = deserializer.deserializeVector(AccountAddress);\n * // deserializedAddresses is now an array of AccountAddress instances\n * @group Implementation\n * @category BCS\n */\n deserializeVector<T>(cls: Deserializable<T>): Array<T> {\n const length = this.deserializeUleb128AsU32();\n const vector = new Array<T>();\n for (let i = 0; i < length; i += 1) {\n vector.push(this.deserialize(cls));\n }\n return vector;\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../serializer\";\nimport { Deserializer } from \"../deserializer\";\nimport { HexInput } from \"../../types\";\nimport { Hex } from \"../../core/hex\";\nimport { TransactionArgument } from \"../../transactions/instances/transactionArgument\";\n\n/**\n * Represents a contiguous sequence of already serialized BCS bytes.\n * \n * This class differs from most other Serializable classes in that its internal byte buffer is serialized to BCS\n * bytes exactly as-is, without prepending the length of the bytes. It is ideal for scenarios where custom serialization\n * is required, such as passing serialized bytes as transaction arguments. Additionally, it serves as a representation \n * of type-agnostic BCS bytes, akin to a vector<u8>.\n * \n * An example use case includes handling bytes resulting from entry function arguments that have been serialized \n * for an entry function.\n * \n * @example\n * const yourCustomSerializedBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);\n * const fixedBytes = new FixedBytes(yourCustomSerializedBytes);\n * const payload = await generateTransactionPayload({\n * function: \"0xbeefcafe::your_module::your_function_that_requires_custom_serialization\",\n * functionArguments: [yourCustomBytes],\n * });\n * \n * This class is particularly useful when you want to handle a fixed-size byte array without the overhead of \n * length prepending, such as when dealing with 32-byte addresses stored as U8 in a MoveVector<U8>.\n\n * For example, if you store each of the 32 bytes for an address as a U8 in a MoveVector<U8>, when you\n * serialize that MoveVector<U8>, it will be serialized to 33 bytes. If you solely want to pass around\n * the 32 bytes as a Serializable class that *does not* prepend the length to the BCS-serialized representation,\n * use this class.* \n * @param value - HexInput representing a sequence of Uint8 bytes.\n * @returns A Serializable FixedBytes instance, which when serialized, does not prepend the length of the bytes.\n * @see EntryFunctionBytes\n * @group Implementation\n * @category BCS\n */\nexport class FixedBytes extends Serializable implements TransactionArgument {\n public value: Uint8Array;\n\n /**\n * Creates an instance of the class with a specified hexadecimal input.\n * The value is converted from hexadecimal format to a Uint8Array.\n *\n * @param value - The hexadecimal input to be converted.\n * @group Implementation\n * @category BCS\n */\n constructor(value: HexInput) {\n super();\n this.value = Hex.fromHexInput(value).toUint8Array();\n }\n\n /**\n * Serializes the fixed bytes value using the provided serializer.\n * This function is essential for converting the fixed bytes into a format suitable for storage or transmission.\n *\n * @param serializer - The serializer instance used for serialization.\n * @group Implementation\n * @category BCS\n */\n serialize(serializer: Serializer): void {\n serializer.serializeFixedBytes(this.value);\n }\n\n /**\n * Serializes the current instance for an entry function using the provided serializer.\n * This allows the instance to be converted into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n serializer.serialize(this);\n }\n\n /**\n * Serializes the current instance using the provided serializer.\n * This function is essential for preparing data to be passed as arguments in script functions.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serialize(this);\n }\n\n /**\n * Deserializes a fixed-length byte array from the provided deserializer.\n * This function helps in reconstructing a FixedBytes object from the serialized data.\n *\n * @param deserializer - The deserializer instance used to read the byte data.\n * @param length - The length of the byte array to be deserialized.\n * @group Implementation\n * @category BCS\n */\n static deserialize(deserializer: Deserializer, length: number): FixedBytes {\n const bytes = deserializer.deserializeFixedBytes(length);\n return new FixedBytes(bytes);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Serializer, Serializable } from \"../serializer\";\nimport { Deserializer } from \"../deserializer\";\nimport { FixedBytes } from \"./fixedBytes\";\nimport { EntryFunctionArgument } from \"../../transactions/instances/transactionArgument\";\nimport { HexInput } from \"../../types\";\n\n/**\n * This class exists solely to represent a sequence of fixed bytes as a serialized entry function, because\n * serializing an entry function appends a prefix that's *only* used for entry function arguments.\n *\n * NOTE: Using this class for serialized script functions will lead to erroneous and unexpected behavior.\n *\n * If you wish to convert this class back to a TransactionArgument, you must know the type\n * of the argument beforehand, and use the appropriate class to deserialize the bytes within\n * an instance of this class.\n * @group Implementation\n * @category BCS\n */\nexport class EntryFunctionBytes extends Serializable implements EntryFunctionArgument {\n public readonly value: FixedBytes;\n\n /**\n * Creates an instance of the class with a specified hexadecimal input value.\n *\n * @param value - The hexadecimal input to be converted into FixedBytes.\n * @group Implementation\n * @category BCS\n */\n private constructor(value: HexInput) {\n super();\n this.value = new FixedBytes(value);\n }\n\n // Note that to see the Move, BCS-serialized representation of the underlying fixed byte vector,\n // we must not serialize the length prefix.\n //\n // In other words, this class is only used to represent a sequence of bytes that are already\n // BCS-serialized as a type. To represent those bytes accurately, the BCS-serialized form is the same exact\n // representation.\n\n /**\n * Serializes the value using the provided serializer.\n * This function is essential for accurately representing a sequence of bytes that are already BCS-serialized as a type.\n *\n * Note that to see the Move, BCS-serialized representation of the underlying fixed byte vector,\n * we must not serialize the length prefix.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serialize(serializer: Serializer): void {\n serializer.serialize(this.value);\n }\n\n // When we serialize these bytes as an entry function argument, we need to\n // serialize the length prefix. This essentially converts the underlying fixed byte vector to a type-agnostic\n // byte vector to an `any` type.\n // NOTE: This, and the lack of a `serializeForScriptFunction`, is the only meaningful difference between this\n // class and FixedBytes.\n\n /**\n * Serializes the current instance for use as an entry function argument by converting the underlying fixed byte vector to a\n * type-agnostic byte vector.\n * This process includes serializing the length prefix of the byte vector.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(this.value.value.length);\n serializer.serialize(this);\n }\n\n /**\n * The only way to create an instance of this class is to use this static method.\n * This function should only be used when deserializing a sequence of EntryFunctionPayload arguments.\n * @param deserializer - The deserializer instance with the buffered bytes.\n * @param length - The length of the bytes to deserialize.\n * @returns An instance of this class, which will now only be usable as an EntryFunctionArgument.\n * @group Implementation\n * @category BCS\n */\n static deserialize(deserializer: Deserializer, length: number): EntryFunctionBytes {\n const fixedBytes = FixedBytes.deserialize(deserializer, length);\n return new EntryFunctionBytes(fixedBytes.value);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n MAX_U128_BIG_INT,\n MAX_U16_NUMBER,\n MAX_U32_NUMBER,\n MAX_U64_BIG_INT,\n MAX_U8_NUMBER,\n MAX_U256_BIG_INT,\n} from \"../consts\";\nimport { Deserializer } from \"../deserializer\";\nimport { Serializable, Serializer, ensureBoolean, validateNumberInRange } from \"../serializer\";\nimport { TransactionArgument } from \"../../transactions/instances/transactionArgument\";\nimport { AnyNumber, Uint16, Uint32, Uint8, ScriptTransactionArgumentVariants } from \"../../types\";\n\n/**\n * Represents a boolean value that can be serialized and deserialized.\n * This class extends the Serializable class and provides methods to serialize\n * the boolean value for different contexts, such as entry functions and script functions.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class Bool extends Serializable implements TransactionArgument {\n public readonly value: boolean;\n\n /**\n * Constructs a new instance with a specified value.\n * This ensures that the value is validated to be within the acceptable range.\n *\n * @param value - The number to be validated and assigned, which must be between 0 and MAX_U256_BIG_INT.\n * @group Implementation\n * @category BCS\n */\n constructor(value: boolean) {\n super();\n\n /**\n * Ensures that the provided value is of type boolean.\n * This function throws an error if the value is not a boolean, helping to enforce type safety in your code.\n *\n * @param value - The value to be checked for boolean type.\n * @throws {Error} Throws an error if the value is not a boolean.\n * @group Implementation\n * @category BCS\n */\n ensureBoolean(value);\n this.value = value;\n }\n\n /**\n * Serializes the value using the provided serializer.\n * This function is essential for converting the value 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 BCS\n */\n serialize(serializer: Serializer): void {\n serializer.serializeBool(this.value);\n }\n\n /**\n * Serializes the current instance for use in an entry function by converting it to a byte sequence.\n * This allows the instance to be properly formatted for serialization in transactions.\n *\n * @param serializer - The serializer instance used to serialize the byte sequence.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * Serializes the current instance for use in a script function.\n * This allows for the conversion of the instance into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.Bool);\n serializer.serialize(this);\n }\n\n /**\n * Deserializes a U256 value from the provided deserializer.\n *\n * @param deserializer - The deserializer instance used to read the U256 data.\n * @group Implementation\n * @category BCS\n */\n // eslint-disable-next-line class-methods-use-this\n deserialize(deserializer: Deserializer) {\n return new U256(deserializer.deserializeU256());\n }\n\n static deserialize(deserializer: Deserializer): Bool {\n return new Bool(deserializer.deserializeBool());\n }\n}\n\n/**\n * Represents an unsigned 8-bit integer (U8) value.\n * This class extends the Serializable class and provides methods for serialization and deserialization of U8 values.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U8 extends Serializable implements TransactionArgument {\n public readonly value: Uint8;\n\n constructor(value: Uint8) {\n super();\n validateNumberInRange(value, 0, MAX_U8_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU8(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U8);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U8 {\n return new U8(deserializer.deserializeU8());\n }\n}\n\n/**\n * Represents a 16-bit unsigned integer (U16) value.\n * This class extends the Serializable class and provides methods for serialization\n * and deserialization of the U16 value.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U16 extends Serializable implements TransactionArgument {\n public readonly value: Uint16;\n\n constructor(value: Uint16) {\n super();\n validateNumberInRange(value, 0, MAX_U16_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU16(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U16);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U16 {\n return new U16(deserializer.deserializeU16());\n }\n}\n\n/**\n * Represents a 32-bit unsigned integer (U32) that can be serialized and deserialized.\n * This class ensures that the value is within the valid range for a U32.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U32 extends Serializable implements TransactionArgument {\n public readonly value: Uint32;\n\n constructor(value: Uint32) {\n super();\n validateNumberInRange(value, 0, MAX_U32_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U32);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U32 {\n return new U32(deserializer.deserializeU32());\n }\n}\n\n/**\n * Represents a 64-bit unsigned integer (U64) and provides methods for serialization.\n *\n * This class ensures that the value is within the valid range for a U64 and provides\n * functionality to serialize the value for various use cases, including entry functions\n * and script functions.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U64 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U64_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU64(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U64);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U64 {\n return new U64(deserializer.deserializeU64());\n }\n}\n\n/**\n * Represents a 128-bit unsigned integer value.\n * This class provides methods for serialization and deserialization\n * of U128 values, ensuring that the values are within the valid range.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U128 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U128_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU128(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U128);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U128 {\n return new U128(deserializer.deserializeU128());\n }\n}\n\n/**\n * Represents a 256-bit unsigned integer (U256) that extends the Serializable class.\n * This class provides methods for serialization and deserialization of U256 values,\n * ensuring that the values are within the valid range.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class U256 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, BigInt(0), MAX_U256_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU256(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U256);\n serializer.serialize(this);\n }\n\n static deserialize(deserializer: Deserializer): U256 {\n return new U256(deserializer.deserializeU256());\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Bool, U128, U16, U256, U32, U64, U8 } from \"./movePrimitives\";\nimport { Serializable, Serializer } from \"../serializer\";\nimport { Deserializable, Deserializer } from \"../deserializer\";\nimport { AnyNumber, HexInput, ScriptTransactionArgumentVariants } from \"../../types\";\nimport { Hex } from \"../../core/hex\";\nimport { EntryFunctionArgument, TransactionArgument } from \"../../transactions/instances/transactionArgument\";\n\n/**\n * This class is the Aptos Typescript SDK representation of a Move `vector<T>`,\n * where `T` represents either a primitive type (`bool`, `u8`, `u64`, ...)\n * or a BCS-serializable struct itself.\n *\n * It is a BCS-serializable, array-like type that contains an array of values of type `T`,\n * where `T` is a class that implements `Serializable`.\n *\n * The purpose of this class is to facilitate easy construction of BCS-serializable\n * Move `vector<T>` types.\n *\n * @example\n * // in Move: `vector<u8> [1, 2, 3, 4];`\n * const vecOfU8s = new MoveVector<U8>([new U8(1), new U8(2), new U8(3), new U8(4)]);\n * // in Move: `std::bcs::to_bytes(vector<u8> [1, 2, 3, 4]);`\n * const bcsBytes = vecOfU8s.toUint8Array();\n *\n * // vector<vector<u8>> [ vector<u8> [1], vector<u8> [1, 2, 3, 4], vector<u8> [5, 6, 7, 8] ];\n * const vecOfVecs = new MoveVector<MoveVector<U8>>([\n * new MoveVector<U8>([new U8(1)]),\n * MoveVector.U8([1, 2, 3, 4]),\n * MoveVector.U8([5, 6, 7, 8]),\n * ]);\n *\n * // vector<Option<u8>> [ std::option::some<u8>(1), std::option::some<u8>(2) ];\n * const vecOfOptionU8s = new MoveVector<MoveOption<U8>>([\n * MoveOption.U8(1),\n * MoveOption.U8(2),\n * ]);\n *\n * // vector<MoveString> [ std::string::utf8(b\"hello\"), std::string::utf8(b\"world\") ];\n * const vecOfStrings = new MoveVector([new MoveString(\"hello\"), new MoveString(\"world\")]);\n * const vecOfStrings2 = MoveVector.MoveString([\"hello\", \"world\"]);\n *\n * @param values an Array<T> of values where T is a class that implements Serializable\n * @returns a `MoveVector<T>` with the values `values`\n * @group Implementation\n * @category BCS\n */\nexport class MoveVector<T extends Serializable & EntryFunctionArgument>\n extends Serializable\n implements TransactionArgument\n{\n public values: Array<T>;\n\n /**\n * Initializes a new instance of the class with an optional value.\n * This constructor sets up the internal vector based on the provided value.\n *\n * @param values - The initial value to be stored in the vector, or null to initialize an empty vector.\n * @group Implementation\n * @category BCS\n */\n constructor(values: Array<T>) {\n super();\n this.values = values;\n }\n\n /**\n * Serializes the current instance into a byte sequence suitable for entry functions.\n * This allows the data to be properly formatted for transmission or storage.\n *\n * @param serializer - The serializer instance used to serialize the byte sequence.\n * @group Implementation\n * @category BCS\n */\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * NOTE: This function will only work when the inner values in the `MoveVector` are `U8`s.\n * @param serializer\n * @group Implementation\n * @category BCS\n */\n\n /**\n * Serialize the string as a fixed byte string without the length prefix for use in a script function.\n * @param serializer - The serializer used to convert the byte vector into a format suitable for a script function.\n * @group Implementation\n * @category BCS\n */\n serializeForScriptFunction(serializer: Serializer): void {\n // This checks if the type of a non-empty vector is of type other than U8. If so, we use the Serialized\n // transaction argument type to serialize the argument.\n if (this.values[0] !== undefined && !(this.values[0] instanceof U8)) {\n const serialized = new Serialized(this.bcsToBytes());\n serialized.serializeForScriptFunction(serializer);\n return;\n }\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.U8Vector);\n serializer.serialize(this);\n }\n\n /**\n * Factory method to generate a MoveVector<U8> from a `number` or `undefined`.\n *\n * This method allows you to create a MoveVector that encapsulates a U8 value, enabling you to handle optional U8 values\n * effectively.\n *\n * @param values - The values used to fill the MoveVector. If `values` is undefined or null, the resulting MoveVector's\n * `.isSome()` method will return false.\n * @returns A MoveVector<U8> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U8([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U8(values: Array<number> | HexInput): MoveVector<U8> {\n let numbers: Array<number>;\n\n if (Array.isArray(values) && values.length === 0) {\n // Handle empty array, since it won't have a \"first value\"\n numbers = [];\n } else if (Array.isArray(values) && typeof values[0] === \"number\") {\n numbers = values;\n } else if (typeof values === \"string\") {\n const hex = Hex.fromHexInput(values);\n numbers = Array.from(hex.toUint8Array());\n } else if (values instanceof Uint8Array) {\n numbers = Array.from(values);\n } else {\n throw new Error(\"Invalid input type, must be an number[], Uint8Array, or hex string\");\n }\n\n return new MoveVector<U8>(numbers.map((v) => new U8(v)));\n }\n\n /**\n * Factory method to generate a MoveOption<U16> from a `number` or `null`.\n *\n * This method allows you to create a MoveVector that can either hold a U16 value or be empty.\n *\n * @param values - The value used to fill the MoveVector. If `value` is null or undefined, the resulting MoveVector's\n * `.isSome()` method will return false.\n * @returns A MoveVector<U16> with an inner value `value`.\n * @example\n * ```typescript\n * const v = MoveVector.U16([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n\n */\n static U16(values: Array<number>): MoveVector<U16> {\n return new MoveVector<U16>(values.map((v) => new U16(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U32> from a `number` or `null`.\n *\n * This method allows you to create a MoveVector that can either hold a U32 value or be empty.\n *\n * @param values - The value used to fill the MoveVector. If `value` is null or undefined,\n * the resulting MoveVector's .isSome() method will return false.\n * @returns A MoveVector<U32> with an inner value `value`.\n *\n * @example\n * ```\n * const v = MoveVector.U32([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n\n */\n static U32(values: Array<number>): MoveVector<U32> {\n return new MoveVector<U32>(values.map((v) => new U32(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U64> from a number, bigint, or null/undefined.\n * This allows for the creation of an optional U64 value that can be checked for presence.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined or null, the resulting MoveVector's\n * `.isSome()` method will return false.\n * @returns A MoveVector<U64> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U64([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U64(values: Array<AnyNumber>): MoveVector<U64> {\n return new MoveVector<U64>(values.map((v) => new U64(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U128> from a number, bigint, or undefined.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's `.isSome()`\n * method will return false.\n * @returns A MoveVector<U128> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U128([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U128(values: Array<AnyNumber>): MoveVector<U128> {\n return new MoveVector<U128>(values.map((v) => new U128(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<U256> from a number, bigint, or null/undefined.\n * This allows for the creation of an optional U256 value, enabling checks for presence or absence of a value.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined or null,\n * the resulting MoveVector's .isSome() method will return false.\n * @returns A MoveVector<U256> with an inner value `value`.\n *\n * @example\n * ```typescript\n * const v = MoveVector.U256([1, 2, 3, 4]);\n * ```\n * @group Implementation\n * @category BCS\n */\n static U256(values: Array<AnyNumber>): MoveVector<U256> {\n return new MoveVector<U256>(values.map((v) => new U256(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<Bool> from a `boolean` or `undefined`.\n * This method allows you to create an optional boolean value that can be used in various contexts where a boolean may or may\n * not be present.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's .isSome() method\n * will return false.\n * @returns A MoveVector<Bool> with an inner value `value`.\n *\n * @example\n * * const v = MoveVector.Bool([true, false, true, false]);\n * @group Implementation\n * @category BCS\n */\n static Bool(values: Array<boolean>): MoveVector<Bool> {\n return new MoveVector<Bool>(values.map((v) => new Bool(v)));\n }\n\n /**\n * Factory method to generate a MoveVector<MoveString> from a `string` or `undefined`.\n * This function creates a MoveVector that encapsulates a MoveString if the provided value is not null or undefined.\n *\n * @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's .isSome() method\n * will return false.\n * @returns A MoveVector<MoveString> with an inner value `value`.\n *\n * @example\n * const v = MoveVector.MoveString([\"hello\", \"world\"]);\n * @group Implementation\n * @category BCS\n */\n static MoveString(values: Array<string>): MoveVector<MoveString> {\n return new MoveVector<MoveString>(values.map((v) => new MoveString(v)));\n }\n\n /**\n * Serializes the current object using the provided serializer.\n * This function will serialize the value if it is present.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category BCS\n */\n serialize(serializer: Serializer): void;\n serialize(serializer: Serializer): void {\n serializer.serializeVector(this.values);\n }\n\n /**\n * Deserialize a MoveVector of type T, specifically where T is a Serializable and Deserializable type.\n *\n * NOTE: This only works with a depth of one. Generics will not work.\n *\n * NOTE: This will not work with types that aren't of the Serializable class.\n *\n * If you're looking for a more flexible deserialization function, you can use the deserializeVector function\n * in the Deserializer class.\n *\n * @example\n * const vec = MoveVector.deserialize(deserializer, U64);\n * @param deserializer the Deserializer instance to use, with bytes loaded into it already.\n * @param cls the class to typecast the input values to, must be a Serializable and Deserializable type.\n * @returns a MoveVector of the corresponding class T\n *\n * @group Implementation\n * @category BCS\n */\n static deserialize<T extends Serializable & EntryFunctionArgument>(\n deserializer: Deserializer,\n cls: Deserializable<T>,\n ): MoveVector<T> {\n const length = deserializer.deserializeUleb128AsU32();\n const values = new Array<T>();\n for (let i = 0; i < length; i += 1) {\n values.push(cls.deserialize(deserializer));\n }\n return new MoveVector(values);\n }\n}\n\n/**\n * Represents a serialized data structure that encapsulates a byte array.\n * This class extends the Serializable class and provides methods for serialization\n * and deserialization of byte data, as well as converting to a MoveVector.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class Serialized extends Serializable implements TransactionArgument {\n public readonly value: Uint8Array;\n\n constructor(value: HexInput) {\n super();\n this.value = Hex.fromHexInput(value).toUint8Array();\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n this.serialize(serializer);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(ScriptTransactionArgumentVariants.Serialized);\n this.serialize(serializer);\n }\n\n static deserialize(deserializer: Deserializer): Serialized {\n return new Serialized(deserializer.deserializeBytes());\n }\n\n /**\n * Deserialize the bytecode into a MoveVector of the specified type.\n * This function allows you to convert serialized data into a usable MoveVector format.\n *\n * @param cls - The class type of the elements in the MoveVector.\n * @group Implementation\n * @category BCS\n */\n toMoveVector<T extends Serializable & EntryFunctionArgument>(cls: Deserializable<T>): MoveVector<T> {\n const deserializer = new Deserializer(this.bcsToBytes());\n deserializer.deserializeUleb128AsU32();\n const vec = deserializer.deserializeVector(cls);\n return new MoveVector(vec);\n }\n}\n\n/**\n * Represents a string value that can be serialized and deserialized.\n * This class extends the Serializable base class and provides methods\n * for serializing the string in different contexts, such as for entry\n * functions and script functions.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class MoveString extends Serializable implements TransactionArgument {\n public value: string;\n\n constructor(value: string) {\n super();\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeStr(this.value);\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n serializeForScriptFunction(serializer: Serializer): void {\n // Serialize the string as a fixed byte string, i.e., without the length prefix\n const textEncoder = new TextEncoder();\n const fixedStringBytes = textEncoder.encode(this.value);\n // Put those bytes into a vector<u8> and serialize it as a script function argument\n const vectorU8 = MoveVector.U8(fixedStringBytes);\n vectorU8.serializeForScriptFunction(serializer);\n }\n\n static deserialize(deserializer: Deserializer): MoveString {\n return new MoveString(deserializer.deserializeStr());\n }\n}\n\nexport class MoveOption<T extends Serializable & EntryFunctionArgument>\n extends Serializable\n implements EntryFunctionArgument\n{\n private vec: MoveVector<T>;\n\n public readonly value?: T;\n\n constructor(value?: T | null) {\n super();\n if (typeof value !== \"undefined\" && value !== null) {\n this.vec = new MoveVector([value]);\n } else {\n this.vec = new MoveVector([]);\n }\n\n [this.value] = this.vec.values;\n }\n\n serializeForEntryFunction(serializer: Serializer): void {\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n /**\n * Retrieves the inner value of the MoveOption.\n *\n * This method is inspired by Rust's `Option<T>.unwrap()`, where attempting to unwrap a `None` value results in a panic.\n * This method will throw an error if the value is not present.\n *\n * @example\n * const option = new MoveOption<Bool>(new Bool(true));\n * const value = option.unwrap(); // Returns the Bool instance\n *\n * @throws {Error} Throws an error if the MoveOption does not contain a value.\n *\n * @returns {T} The contained value if present.\n * @group Implementation\n * @category BCS\n */\n unwrap(): T {\n if (!this.isSome()) {\n throw new Error(\"Called unwrap on a MoveOption with no value\");\n } else {\n return this.vec.values[0];\n }\n }\n\n /**\n * Check if the MoveOption has a value.\n *\n * @returns {boolean} Returns true if there is exactly one value in the MoveOption.\n * @group Implementation\n * @category BCS\n */\n isSome(): boolean {\n return this.vec.values.length === 1;\n }\n\n serialize(serializer: Serializer): void {\n // serialize 0 or 1\n // if 1, serialize the value\n this.vec.serialize(serializer);\n }\n\n /**\n * Factory method to generate a MoveOption<U8> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U8(1).isSome() === true;\n * MoveOption.U8().isSome() === false;\n * MoveOption.U8(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U8> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U8(value?: number | null): MoveOption<U8> {\n return new MoveOption<U8>(value !== null && value !== undefined ? new U8(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U16> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U16(1).isSome() === true;\n * MoveOption.U16().isSome() === false;\n * MoveOption.U16(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U16> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U16(value?: number | null): MoveOption<U16> {\n return new MoveOption<U16>(value !== null && value !== undefined ? new U16(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U32> from a `number` or `undefined`.\n *\n * @example\n * MoveOption.U32(1).isSome() === true;\n * MoveOption.U32().isSome() === false;\n * MoveOption.U32(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U32> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U32(value?: number | null): MoveOption<U32> {\n return new MoveOption<U32>(value !== null && value !== undefined ? new U32(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U64> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U64(1).isSome() === true;\n * MoveOption.U64().isSome() === false;\n * MoveOption.U64(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U64> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U64(value?: AnyNumber | null): MoveOption<U64> {\n return new MoveOption<U64>(value !== null && value !== undefined ? new U64(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U128> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U128(1).isSome() === true;\n * MoveOption.U128().isSome() === false;\n * MoveOption.U128(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U128> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U128(value?: AnyNumber | null): MoveOption<U128> {\n return new MoveOption<U128>(value !== null && value !== undefined ? new U128(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<U256> from a `number` or a `bigint` or `undefined`.\n *\n * @example\n * MoveOption.U256(1).isSome() === true;\n * MoveOption.U256().isSome() === false;\n * MoveOption.U256(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<U256> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static U256(value?: AnyNumber | null): MoveOption<U256> {\n return new MoveOption<U256>(value !== null && value !== undefined ? new U256(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<Bool> from a `boolean` or `undefined`.\n *\n * @example\n * MoveOption.Bool(true).isSome() === true;\n * MoveOption.Bool().isSome() === false;\n * MoveOption.Bool(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<Bool> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static Bool(value?: boolean | null): MoveOption<Bool> {\n return new MoveOption<Bool>(value !== null && value !== undefined ? new Bool(value) : undefined);\n }\n\n /**\n * Factory method to generate a MoveOption<MoveString> from a `string` or `undefined`.\n *\n * @example\n * MoveOption.MoveString(\"hello\").isSome() === true;\n * MoveOption.MoveString(\"\").isSome() === true;\n * MoveOption.MoveString().isSome() === false;\n * MoveOption.MoveString(undefined).isSome() === false;\n * @param value the value used to fill the MoveOption. If `value` is undefined\n * the resulting MoveOption's .isSome() method will return false.\n * @returns a MoveOption<MoveString> with an inner value `value`\n * @group Implementation\n * @category BCS\n */\n static MoveString(value?: string | null): MoveOption<MoveString> {\n return new MoveOption<MoveString>(value !== null && value !== undefined ? new MoveString(value) : undefined);\n }\n\n static deserialize<U extends Serializable & EntryFunctionArgument>(\n deserializer: Deserializer,\n cls: Deserializable<U>,\n ): MoveOption<U> {\n const vector = MoveVector.deserialize(deserializer, cls);\n return new MoveOption(vector.values[0]);\n }\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { sha3_256 as sha3Hash } from \"@noble/hashes/sha3\";\nimport { AccountAddress } from \"./accountAddress\";\nimport type { AccountPublicKey } from \"./crypto\";\nimport { Hex } from \"./hex\";\nimport { AuthenticationKeyScheme, HexInput } from \"../types\";\nimport { Serializable, Serializer } from \"../bcs/serializer\";\nimport { Deserializer } from \"../bcs/deserializer\";\n\n/**\n * Represents an authentication key used for account management. Each account stores an authentication key that enables account\n * owners to rotate their private key(s) without changing the address that hosts their account. The authentication key is a\n * SHA3-256 hash of data and is always 32 bytes in length.\n *\n * @see {@link https://aptos.dev/concepts/accounts | Account Basics}\n *\n * Account addresses can be derived from the AuthenticationKey.\n * @group Implementation\n * @category Serialization\n */\nexport class AuthenticationKey extends Serializable {\n /**\n * An authentication key is always a SHA3-256 hash of data, and is always 32 bytes.\n *\n * The data to hash depends on the underlying public key type and the derivation scheme.\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The raw bytes of the authentication key.\n * @group Implementation\n * @category Serialization\n */\n public readonly data: Hex;\n\n /**\n * Creates an instance of the AuthenticationKey using the provided hex input.\n * This ensures that the hex input is valid and conforms to the required length for an Authentication Key.\n *\n * @param args - The arguments for constructing the AuthenticationKey.\n * @param args.data - The hex input data to be used for the Authentication Key.\n * @throws {Error} Throws an error if the length of the provided hex input is not equal to the required Authentication Key\n * length.\n * @group Implementation\n * @category Serialization\n */\n constructor(args: { data: HexInput }) {\n super();\n const { data } = args;\n const hex = Hex.fromHexInput(data);\n if (hex.toUint8Array().length !== AuthenticationKey.LENGTH) {\n throw new Error(`Authentication Key length should be ${AuthenticationKey.LENGTH}`);\n }\n this.data = hex;\n }\n\n /**\n * Serializes the fixed bytes 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.serializeFixedBytes(this.data.toUint8Array());\n }\n\n /**\n * Deserialize an AuthenticationKey from the byte buffer in a Deserializer instance.\n * @param deserializer - The deserializer to deserialize the AuthenticationKey from.\n * @returns An instance of AuthenticationKey.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): AuthenticationKey {\n const bytes = deserializer.deserializeFixedBytes(AuthenticationKey.LENGTH);\n return new AuthenticationKey({ data: bytes });\n }\n\n /**\n * Convert the internal data representation to a Uint8Array.\n *\n * This function is useful for obtaining a byte representation of the data, which can be utilized for serialization or transmission.\n *\n * @returns Uint8Array representation of the internal data.\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.data.toUint8Array();\n }\n\n /**\n * Generates an AuthenticationKey from the specified scheme and input bytes.\n * This function is essential for creating a valid authentication key based on a given scheme.\n *\n * @param args - The arguments for generating the AuthenticationKey.\n * @param args.scheme - The authentication key scheme to use.\n * @param args.input - The input data in hexadecimal format to derive the key.\n * @returns An instance of AuthenticationKey containing the generated key data.\n * @group Implementation\n * @category Serialization\n */\n static fromSchemeAndBytes(args: { scheme: AuthenticationKeyScheme; input: HexInput }): AuthenticationKey {\n const { scheme, input } = args;\n const inputBytes = Hex.fromHexInput(input).toUint8Array();\n const hashInput = new Uint8Array([...inputBytes, scheme]);\n const hash = sha3Hash.create();\n hash.update(hashInput);\n const hashDigest = hash.digest();\n return new AuthenticationKey({ data: hashDigest });\n }\n\n /**\n * Derives an AuthenticationKey from the provided public key using a specified derivation scheme.\n *\n * @deprecated Use `fromPublicKey` instead.\n * @param args - The arguments for deriving the authentication key.\n * @param args.publicKey - The public key used for the derivation.\n * @param args.scheme - The scheme to use for deriving the authentication key.\n * @group Implementation\n * @category Serialization\n */\n public static fromPublicKeyAndScheme(args: { publicKey: AccountPublicKey; scheme: AuthenticationKeyScheme }) {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Converts a PublicKey to an AuthenticationKey using the derivation scheme inferred from the provided PublicKey instance.\n *\n * @param args - The arguments for the function.\n * @param args.publicKey - The PublicKey to be converted.\n * @returns AuthenticationKey - The derived AuthenticationKey.\n * @group Implementation\n * @category Serialization\n */\n static fromPublicKey(args: { publicKey: AccountPublicKey }): AuthenticationKey {\n const { publicKey } = args;\n return publicKey.authKey();\n }\n\n /**\n * Derives an account address from an AuthenticationKey by translating the AuthenticationKey bytes directly to an AccountAddress.\n *\n * @returns AccountAddress - The derived account address.\n * @group Implementation\n * @category Serialization\n */\n derivedAddress(): AccountAddress {\n return new AccountAddress(this.data.toUint8Array());\n }\n}\n","import { AptosApiType } from \"../utils/const\";\nimport { getErrorMessage } from \"../utils/helpers\";\nimport { AptosRequest, AptosResponse } from \"../types\";\n\nexport enum KeylessErrorCategory {\n API_ERROR,\n EXTERNAL_API_ERROR,\n SESSION_EXPIRED,\n INVALID_STATE,\n INVALID_SIGNATURE,\n UNKNOWN,\n}\n\nexport enum KeylessErrorResolutionTip {\n REAUTHENTICATE = \"Re-authentiate to continue using your keyless account\",\n // eslint-disable-next-line max-len\n REAUTHENTICATE_UNSURE = \"Try re-authentiating. If the error persists join the telegram group at https://t.me/+h5CN-W35yUFiYzkx for further support\",\n UPDATE_REQUEST_PARAMS = \"Update the invalid request parameters and reauthenticate.\",\n // eslint-disable-next-line max-len\n RATE_LIMIT_EXCEEDED = \"Cache the keyless account and reuse it to avoid making too many requests. Keyless accounts are valid until either the EphemeralKeyPair expires, when the JWK is rotated, or when the proof verifying key is changed, whichever comes soonest.\",\n // eslint-disable-next-line max-len\n SERVER_ERROR = \"Try again later. See aptosApiError error for more context. For additional support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx\",\n // eslint-disable-next-line max-len\n CALL_PRECHECK = \"Call `await account.checkKeylessAccountValidity()` to wait for asyncronous changes and check for account validity before signing or serializing.\",\n REINSTANTIATE = \"Try instantiating the account again. Avoid manipulating the account object directly\",\n JOIN_SUPPORT_GROUP = \"For support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx\",\n UNKNOWN = \"Error unknown. For support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx\",\n}\n\nexport enum KeylessErrorType {\n EPHEMERAL_KEY_PAIR_EXPIRED,\n\n PROOF_NOT_FOUND,\n\n ASYNC_PROOF_FETCH_FAILED,\n\n INVALID_PROOF_VERIFICATION_FAILED,\n\n INVALID_PROOF_VERIFICATION_KEY_NOT_FOUND,\n\n INVALID_JWT_SIG,\n\n INVALID_JWT_JWK_NOT_FOUND,\n\n INVALID_JWT_ISS_NOT_RECOGNIZED,\n\n INVALID_JWT_FEDERATED_ISS_NOT_SUPPORTED,\n\n INVALID_TW_SIG_VERIFICATION_FAILED,\n\n INVALID_TW_SIG_PUBLIC_KEY_NOT_FOUND,\n\n INVALID_EXPIRY_HORIZON,\n\n JWT_PARSING_ERROR,\n\n JWK_FETCH_FAILED,\n\n JWK_FETCH_FAILED_FEDERATED,\n\n RATE_LIMIT_EXCEEDED,\n\n PEPPER_SERVICE_INTERNAL_ERROR,\n\n PEPPER_SERVICE_BAD_REQUEST,\n\n PEPPER_SERVICE_OTHER,\n\n PROVER_SERVICE_INTERNAL_ERROR,\n\n PROVER_SERVICE_BAD_REQUEST,\n\n PROVER_SERVICE_OTHER,\n\n FULL_NODE_CONFIG_LOOKUP_ERROR,\n\n FULL_NODE_VERIFICATION_KEY_LOOKUP_ERROR,\n\n FULL_NODE_JWKS_LOOKUP_ERROR,\n\n FULL_NODE_OTHER,\n\n SIGNATURE_TYPE_INVALID,\n\n SIGNATURE_EXPIRED,\n\n MAX_EXPIRY_HORIZON_EXCEEDED,\n\n EPHEMERAL_SIGNATURE_VERIFICATION_FAILED,\n\n TRAINING_WHEELS_SIGNATURE_MISSING,\n\n TRAINING_WHEELS_SIGNATURE_VERIFICATION_FAILED,\n\n PROOF_VERIFICATION_FAILED,\n\n UNKNOWN,\n}\n\nconst KeylessErrors: { [key in KeylessErrorType]: [string, KeylessErrorCategory, KeylessErrorResolutionTip] } = {\n [KeylessErrorType.EPHEMERAL_KEY_PAIR_EXPIRED]: [\n \"The ephemeral keypair has expired.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.PROOF_NOT_FOUND]: [\n \"The required proof could not be found.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.CALL_PRECHECK,\n ],\n [KeylessErrorType.ASYNC_PROOF_FETCH_FAILED]: [\n \"The required proof failed to fetch.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_PROOF_VERIFICATION_FAILED]: [\n \"The provided proof is invalid.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_PROOF_VERIFICATION_KEY_NOT_FOUND]: [\n \"The verification key used to authenticate was updated.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.INVALID_JWT_SIG]: [\n \"The JWK was found, but JWT failed verification\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_JWT_JWK_NOT_FOUND]: [\n \"The JWK required to verify the JWT could not be found. The JWK may have been rotated out.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.INVALID_JWT_ISS_NOT_RECOGNIZED]: [\n \"The JWT issuer is not recognized.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.UPDATE_REQUEST_PARAMS,\n ],\n [KeylessErrorType.INVALID_JWT_FEDERATED_ISS_NOT_SUPPORTED]: [\n \"The JWT issuer is not supported by the Federated Keyless \",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_TW_SIG_VERIFICATION_FAILED]: [\n \"The training wheels signature is invalid.\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REAUTHENTICATE_UNSURE,\n ],\n [KeylessErrorType.INVALID_TW_SIG_PUBLIC_KEY_NOT_FOUND]: [\n \"The public key used to verify the training wheels signature was not found.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.INVALID_EXPIRY_HORIZON]: [\n \"The expiry horizon is invalid.\",\n KeylessErrorCategory.SESSION_EXPIRED,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.JWK_FETCH_FAILED]: [\n \"Failed to fetch JWKS.\",\n KeylessErrorCategory.EXTERNAL_API_ERROR,\n KeylessErrorResolutionTip.JOIN_SUPPORT_GROUP,\n ],\n [KeylessErrorType.JWK_FETCH_FAILED_FEDERATED]: [\n \"Failed to fetch JWKS for Federated Keyless provider.\",\n KeylessErrorCategory.EXTERNAL_API_ERROR,\n KeylessErrorResolutionTip.JOIN_SUPPORT_GROUP,\n ],\n [KeylessErrorType.RATE_LIMIT_EXCEEDED]: [\n \"Rate limit exceeded. Too many requests in a short period.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.RATE_LIMIT_EXCEEDED,\n ],\n [KeylessErrorType.PEPPER_SERVICE_INTERNAL_ERROR]: [\n \"Internal error from Pepper service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.PEPPER_SERVICE_BAD_REQUEST]: [\n \"Bad request sent to Pepper service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.UPDATE_REQUEST_PARAMS,\n ],\n [KeylessErrorType.PEPPER_SERVICE_OTHER]: [\n \"Unknown error from Pepper service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.PROVER_SERVICE_INTERNAL_ERROR]: [\n \"Internal error from Prover service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.PROVER_SERVICE_BAD_REQUEST]: [\n \"Bad request sent to Prover service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.UPDATE_REQUEST_PARAMS,\n ],\n [KeylessErrorType.PROVER_SERVICE_OTHER]: [\n \"Unknown error from Prover service.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.JWT_PARSING_ERROR]: [\n \"Error when parsing JWT. This should never happen. Join https://t.me/+h5CN-W35yUFiYzkx for support\",\n KeylessErrorCategory.INVALID_STATE,\n KeylessErrorResolutionTip.REINSTANTIATE,\n ],\n [KeylessErrorType.FULL_NODE_CONFIG_LOOKUP_ERROR]: [\n \"Error when looking up on-chain keyless configuration.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.FULL_NODE_VERIFICATION_KEY_LOOKUP_ERROR]: [\n \"Error when looking up on-chain verification key.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.FULL_NODE_JWKS_LOOKUP_ERROR]: [\n \"Error when looking up on-chain JWKS.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.FULL_NODE_OTHER]: [\n \"Unknown error from full node.\",\n KeylessErrorCategory.API_ERROR,\n KeylessErrorResolutionTip.SERVER_ERROR,\n ],\n [KeylessErrorType.SIGNATURE_TYPE_INVALID]: [\n \"The signature is not a valid Keyless signature.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.JOIN_SUPPORT_GROUP,\n ],\n [KeylessErrorType.SIGNATURE_EXPIRED]: [\n \"The ephemeral key pair used to sign the message has expired.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.MAX_EXPIRY_HORIZON_EXCEEDED]: [\n \"The expiry horizon on the signature exceeds the maximum allowed value.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.EPHEMERAL_SIGNATURE_VERIFICATION_FAILED]: [\n \"Failed to verify the ephemeral signature with the ephemeral public key.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.TRAINING_WHEELS_SIGNATURE_MISSING]: [\n \"The training wheels signature is missing but is required by the Keyless configuration.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.TRAINING_WHEELS_SIGNATURE_VERIFICATION_FAILED]: [\n \"Failed to verify the training wheels signature with the training wheels public key.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.PROOF_VERIFICATION_FAILED]: [\n \"The proof verification failed.\",\n KeylessErrorCategory.INVALID_SIGNATURE,\n KeylessErrorResolutionTip.REAUTHENTICATE,\n ],\n [KeylessErrorType.UNKNOWN]: [\n \"An unknown error has occurred.\",\n KeylessErrorCategory.UNKNOWN,\n KeylessErrorResolutionTip.UNKNOWN,\n ],\n};\n\nexport class KeylessError extends Error {\n readonly innerError?: unknown;\n\n readonly category: KeylessErrorCategory;\n\n readonly resolutionTip: KeylessErrorResolutionTip;\n\n readonly type: KeylessErrorType;\n\n readonly details?: string;\n\n /** @internal this constructor is for sdk internal use - do not instantiate outside of the SDK codebase */\n constructor(args: {\n innerError?: unknown;\n category: KeylessErrorCategory;\n resolutionTip: KeylessErrorResolutionTip;\n type: KeylessErrorType;\n message?: string;\n details?: string;\n }) {\n const { innerError, category, resolutionTip, type, message = KeylessErrors[type][0], details } = args;\n super(message);\n this.name = \"KeylessError\";\n this.innerError = innerError;\n this.category = category;\n this.resolutionTip = resolutionTip;\n this.type = type;\n this.details = details;\n this.message = KeylessError.constructMessage(message, resolutionTip, innerError, details);\n }\n\n static constructMessage(\n message: string,\n tip: KeylessErrorResolutionTip,\n innerError?: unknown,\n details?: string,\n ): string {\n let result = `\\nMessage: ${message}`;\n if (details) {\n result += `\\nDetails: ${details}`;\n }\n if (innerError instanceof AptosApiError) {\n result += `\\nAptosApiError: ${innerError.message}`;\n } else if (innerError !== undefined) {\n result += `\\nError: ${getErrorMessage(innerError)}`;\n }\n result += `\\nKeylessErrorResolutionTip: ${tip}`;\n return result;\n }\n\n /**\n * Static constructor that creates a KeylessError instance using the KeylessErrors constant\n * @param args.type The type of KeylessError\n * @param args.aptosApiError optional AptosApiError supplied for api errors\n * @param args.details optional details to include in the error message\n * @returns A new KeylessError instance\n */\n static fromErrorType(args: { type: KeylessErrorType; error?: unknown; details?: string }): KeylessError {\n const { error, type, details } = args;\n\n const [message, category, resolutionTip] = KeylessErrors[type];\n return new KeylessError({\n message,\n details,\n innerError: error,\n category,\n resolutionTip,\n type,\n });\n }\n}\n\n/**\n * Options for handling errors in the Aptos API.\n */\ntype AptosApiErrorOpts = {\n apiType: AptosApiType;\n aptosRequest: AptosRequest;\n aptosResponse: AptosResponse<any, any>;\n};\n\n/**\n * Represents an error returned from the Aptos API.\n * This class encapsulates the details of the error, including the request URL, response status, and additional data.\n *\n * @param name - The name of the error, which is always \"AptosApiError\".\n * @param url - The URL to which the request was made.\n * @param status - The HTTP response status code (e.g., 400).\n * @param statusText - The message associated with the response status.\n * @param data - The response data returned from the API.\n * @param request - The original AptosRequest that triggered the error.\n */\nexport class AptosApiError extends Error {\n readonly url: string;\n\n readonly status: number;\n\n readonly statusText: string;\n\n readonly data: any;\n\n readonly request: AptosRequest;\n\n /**\n * Constructs an instance of AptosApiError with relevant error details.\n *\n * @param opts - The options for creating the AptosApiError.\n * @param opts.apiType - The type of API that generated the error.\n * @param opts.aptosRequest - The request object that caused the error.\n * @param opts.aptosResponse - The response object containing error details.\n *\n * @internal This constructor is for SDK internal use - do not instantiate outside the SDK codebase.\n */\n constructor({ apiType, aptosRequest, aptosResponse }: AptosApiErrorOpts) {\n super(deriveErrorMessage({ apiType, aptosRequest, aptosResponse }));\n\n this.name = \"AptosApiError\";\n this.url = aptosResponse.url;\n this.status = aptosResponse.status;\n this.statusText = aptosResponse.statusText;\n this.data = aptosResponse.data;\n this.request = aptosRequest;\n }\n}\n\n/**\n * Derives an error message from the Aptos API response, providing context for debugging.\n * This function helps in understanding the nature of the error encountered during an API request.\n *\n * @param {AptosApiErrorOpts} opts - The options for deriving the error message.\n * @param {AptosApiType} opts.apiType - The type of API being called.\n * @param {AptosRequest} opts.aptosRequest - The original request made to the Aptos API.\n * @param {AptosResponse} opts.aptosResponse - The response received from the Aptos API.\n */\nfunction deriveErrorMessage({ apiType, aptosRequest, aptosResponse }: AptosApiErrorOpts): string {\n // eslint-disable-next-line max-len\n // extract the W3C trace_id from the response headers if it exists. Some services set this in the response, and it's useful for debugging.\n // See https://www.w3.org/TR/trace-context/#relationship-between-the-headers .\n const traceId = aptosResponse.headers?.traceparent?.split(\"-\")[1];\n const traceIdString = traceId ? `(trace_id:${traceId}) ` : \"\";\n\n const errorPrelude: string = `Request to [${apiType}]: ${aptosRequest.method} ${\n aptosResponse.url ?? aptosRequest.url\n } ${traceIdString}failed with`;\n\n // handle graphql responses from indexer api and extract the error message of the first error\n if (apiType === AptosApiType.INDEXER && aptosResponse.data?.errors?.[0]?.message != null) {\n return `${errorPrelude}: ${aptosResponse.data.errors[0].message}`;\n }\n\n // Received well-known structured error response body - simply serialize and return it.\n // We don't need http status codes etc. in this case.\n if (aptosResponse.data?.message != null && aptosResponse.data?.error_code != null) {\n return `${errorPrelude}: ${JSON.stringify(aptosResponse.data)}`;\n }\n\n // This is the generic/catch-all case. We received some response from the API, but it doesn't appear to be a well-known structure.\n // We print http status codes and the response body (after some trimming),\n // in the hope that this gives enough context what went wrong without printing overly huge messages.\n return `${errorPrelude} status: ${aptosResponse.statusText}(code:${\n aptosResponse.status\n }) and response body: ${serializeAnyPayloadForErrorMessage(aptosResponse.data)}`;\n}\n\nconst SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH = 400;\n\n/**\n * This function accepts a payload of any type (probably an object) and serializes it to a string\n * Since we don't know the type or size of the payload, and we don't want to add a huge object in full to the error message\n * we limit the to the first 200 and last 200 characters of the serialized payload and put a \"...\" in the middle.\n * @param payload - The payload to serialize, which can be of any type.\n *\n * @returns A string representation of the serialized payload, potentially truncated.\n */\nfunction serializeAnyPayloadForErrorMessage(payload: any): string {\n const serializedPayload = JSON.stringify(payload);\n if (serializedPayload.length <= SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH) {\n return serializedPayload;\n }\n return `truncated(original_size:${serializedPayload.length}): ${serializedPayload.slice(\n 0,\n SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH / 2,\n )}...${serializedPayload.slice(-SERIALIZED_PAYLOAD_TRIM_TO_MAX_LENGTH / 2)}`;\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","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\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 { AbstractionAuthDataVariant } 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\nexport class AccountAuthenticatorAbstraction extends AccountAuthenticator {\n public readonly functionInfo: string;\n\n public readonly signingMessageDigest: Hex;\n\n public readonly authenticator: 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 authenticator: 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.authenticator = authenticator;\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(AbstractionAuthDataVariant.DerivableV1);\n } else {\n serializer.serializeU32AsUleb128(AbstractionAuthDataVariant.V1);\n }\n serializer.serializeBytes(this.signingMessageDigest.toUint8Array());\n if (this.accountIdentity) {\n serializer.serializeBytes(this.authenticator);\n } else {\n serializer.serializeFixedBytes(this.authenticator);\n }\n\n if (this.accountIdentity) {\n serializer.serializeBytes(this.accountIdentity);\n }\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorAbstraction {\n const moduleAddress = AccountAddress.deserialize(deserializer);\n const moduleName = deserializer.deserializeStr();\n const functionName = deserializer.deserializeStr();\n const variant = deserializer.deserializeUleb128AsU32();\n if (variant === AbstractionAuthDataVariant.V1) {\n const signingMessageDigest = deserializer.deserializeBytes();\n const authenticator = deserializer.deserializeFixedBytes(deserializer.remaining());\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n authenticator,\n );\n }\n if (variant === AbstractionAuthDataVariant.DerivableV1) {\n const signingMessageDigest = deserializer.deserializeBytes();\n const abstractSignature = deserializer.deserializeBytes();\n\n const abstractPublicKey = deserializer.deserializeBytes();\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n abstractSignature,\n abstractPublicKey,\n );\n }\n throw new Error(`Unknown variant index for AccountAuthenticatorAbstraction: ${variant}`);\n }\n}\n","import * as Types from \"./operations\";\n\nimport { GraphQLClient, RequestOptions } from \"graphql-request\";\ntype GraphQLClientRequestHeaders = RequestOptions[\"requestHeaders\"];\nexport const TokenActivitiesFieldsFragmentDoc = `\n fragment TokenActivitiesFields on token_activities_v2 {\n after_value\n before_value\n entry_function_id_str\n event_account_address\n event_index\n from_address\n is_fungible_v2\n property_version_v1\n to_address\n token_amount\n token_data_id\n token_standard\n transaction_timestamp\n transaction_version\n type\n}\n `;\nexport const AnsTokenFragmentFragmentDoc = `\n fragment AnsTokenFragment on current_aptos_names {\n domain\n expiration_timestamp\n registered_address\n subdomain\n token_standard\n is_primary\n owner_address\n subdomain_expiration_policy\n domain_expiration_timestamp\n}\n `;\nexport const CurrentTokenOwnershipFieldsFragmentDoc = `\n fragment CurrentTokenOwnershipFields on current_token_ownerships_v2 {\n token_standard\n token_properties_mutated_v1\n token_data_id\n table_type_v1\n storage_id\n property_version_v1\n owner_address\n last_transaction_version\n last_transaction_timestamp\n is_soulbound_v2\n is_fungible_v2\n amount\n current_token_data {\n collection_id\n description\n is_fungible_v2\n largest_property_version_v1\n last_transaction_timestamp\n last_transaction_version\n maximum\n supply\n token_data_id\n token_name\n token_properties\n token_standard\n token_uri\n decimals\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n }\n}\n `;\nexport const GetAccountAddressesForAuthKey = `\n query getAccountAddressesForAuthKey($where_condition: auth_key_account_addresses_bool_exp, $order_by: [auth_key_account_addresses_order_by!]) {\n auth_key_account_addresses(where: $where_condition, order_by: $order_by) {\n auth_key\n account_address\n last_transaction_version\n is_auth_key_used\n }\n}\n `;\nexport const GetAccountCoinsCount = `\n query getAccountCoinsCount($address: String) {\n current_fungible_asset_balances_aggregate(\n where: {owner_address: {_eq: $address}}\n ) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAccountCoinsData = `\n query getAccountCoinsData($where_condition: current_fungible_asset_balances_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_fungible_asset_balances_order_by!]) {\n current_fungible_asset_balances(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n amount\n asset_type\n is_frozen\n is_primary\n last_transaction_timestamp\n last_transaction_version\n owner_address\n storage_id\n token_standard\n metadata {\n token_standard\n symbol\n supply_aggregator_table_key_v1\n supply_aggregator_table_handle_v1\n project_uri\n name\n last_transaction_version\n last_transaction_timestamp\n icon_uri\n decimals\n creator_address\n asset_type\n }\n }\n}\n `;\nexport const GetAccountCollectionsWithOwnedTokens = `\n query getAccountCollectionsWithOwnedTokens($where_condition: current_collection_ownership_v2_view_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_collection_ownership_v2_view_order_by!]) {\n current_collection_ownership_v2_view(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n mutable_description\n max_supply\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n collection_id\n collection_name\n collection_uri\n creator_address\n distinct_tokens\n last_transaction_version\n owner_address\n single_token_uri\n }\n}\n `;\nexport const GetAccountOwnedTokens = `\n query getAccountOwnedTokens($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountOwnedTokensByTokenData = `\n query getAccountOwnedTokensByTokenData($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountOwnedTokensFromCollection = `\n query getAccountOwnedTokensFromCollection($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetAccountTokensCount = `\n query getAccountTokensCount($where_condition: current_token_ownerships_v2_bool_exp, $offset: Int, $limit: Int) {\n current_token_ownerships_v2_aggregate(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAccountTransactionsCount = `\n query getAccountTransactionsCount($address: String) {\n account_transactions_aggregate(where: {account_address: {_eq: $address}}) {\n aggregate {\n count\n }\n }\n}\n `;\nexport const GetAuthKeysForPublicKey = `\n query getAuthKeysForPublicKey($where_condition: public_key_auth_keys_bool_exp, $order_by: [public_key_auth_keys_order_by!]) {\n public_key_auth_keys(where: $where_condition, order_by: $order_by) {\n public_key\n public_key_type\n auth_key\n account_public_key\n last_transaction_version\n is_public_key_used\n signature_type\n }\n}\n `;\nexport const GetChainTopUserTransactions = `\n query getChainTopUserTransactions($limit: Int) {\n user_transactions(limit: $limit, order_by: {version: desc}) {\n version\n }\n}\n `;\nexport const GetCollectionData = `\n query getCollectionData($where_condition: current_collections_v2_bool_exp!) {\n current_collections_v2(where: $where_condition) {\n uri\n total_minted_v2\n token_standard\n table_handle_v1\n mutable_uri\n mutable_description\n max_supply\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n cdn_asset_uris {\n cdn_image_uri\n asset_uri\n animation_optimizer_retry_count\n cdn_animation_uri\n cdn_json_uri\n image_optimizer_retry_count\n json_parser_retry_count\n raw_animation_uri\n raw_image_uri\n }\n }\n}\n `;\nexport const GetCurrentFungibleAssetBalances = `\n query getCurrentFungibleAssetBalances($where_condition: current_fungible_asset_balances_bool_exp, $offset: Int, $limit: Int) {\n current_fungible_asset_balances(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n amount\n asset_type\n is_frozen\n is_primary\n last_transaction_timestamp\n last_transaction_version\n owner_address\n storage_id\n token_standard\n }\n}\n `;\nexport const GetDelegatedStakingActivities = `\n query getDelegatedStakingActivities($delegatorAddress: String, $poolAddress: String) {\n delegated_staking_activities(\n where: {delegator_address: {_eq: $delegatorAddress}, pool_address: {_eq: $poolAddress}}\n ) {\n amount\n delegator_address\n event_index\n event_type\n pool_address\n transaction_version\n }\n}\n `;\nexport const GetEvents = `\n query getEvents($where_condition: events_bool_exp, $offset: Int, $limit: Int, $order_by: [events_order_by!]) {\n events(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n account_address\n creation_number\n data\n event_index\n sequence_number\n transaction_block_height\n transaction_version\n type\n indexed_type\n }\n}\n `;\nexport const GetFungibleAssetActivities = `\n query getFungibleAssetActivities($where_condition: fungible_asset_activities_bool_exp, $offset: Int, $limit: Int) {\n fungible_asset_activities(\n where: $where_condition\n offset: $offset\n limit: $limit\n ) {\n amount\n asset_type\n block_height\n entry_function_id_str\n event_index\n gas_fee_payer_address\n is_frozen\n is_gas_fee\n is_transaction_success\n owner_address\n storage_id\n storage_refund_amount\n token_standard\n transaction_timestamp\n transaction_version\n type\n }\n}\n `;\nexport const GetFungibleAssetMetadata = `\n query getFungibleAssetMetadata($where_condition: fungible_asset_metadata_bool_exp, $offset: Int, $limit: Int) {\n fungible_asset_metadata(where: $where_condition, offset: $offset, limit: $limit) {\n icon_uri\n project_uri\n supply_aggregator_table_handle_v1\n supply_aggregator_table_key_v1\n creator_address\n asset_type\n decimals\n last_transaction_timestamp\n last_transaction_version\n name\n symbol\n token_standard\n supply_v2\n maximum_v2\n }\n}\n `;\nexport const GetNames = `\n query getNames($offset: Int, $limit: Int, $where_condition: current_aptos_names_bool_exp, $order_by: [current_aptos_names_order_by!]) {\n current_aptos_names(\n limit: $limit\n where: $where_condition\n order_by: $order_by\n offset: $offset\n ) {\n ...AnsTokenFragment\n }\n}\n ${AnsTokenFragmentFragmentDoc}`;\nexport const GetNumberOfDelegators = `\n query getNumberOfDelegators($where_condition: num_active_delegator_per_pool_bool_exp, $order_by: [num_active_delegator_per_pool_order_by!]) {\n num_active_delegator_per_pool(where: $where_condition, order_by: $order_by) {\n num_active_delegator\n pool_address\n }\n}\n `;\nexport const GetObjectData = `\n query getObjectData($where_condition: current_objects_bool_exp, $offset: Int, $limit: Int, $order_by: [current_objects_order_by!]) {\n current_objects(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n allow_ungated_transfer\n state_key_hash\n owner_address\n object_address\n last_transaction_version\n last_guid_creation_num\n is_deleted\n }\n}\n `;\nexport const GetProcessorStatus = `\n query getProcessorStatus($where_condition: processor_status_bool_exp) {\n processor_status(where: $where_condition) {\n last_success_version\n processor\n last_updated\n }\n}\n `;\nexport const GetTableItemsData = `\n query getTableItemsData($where_condition: table_items_bool_exp!, $offset: Int, $limit: Int, $order_by: [table_items_order_by!]) {\n table_items(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n decoded_key\n decoded_value\n key\n table_handle\n transaction_version\n write_set_change_index\n }\n}\n `;\nexport const GetTableItemsMetadata = `\n query getTableItemsMetadata($where_condition: table_metadatas_bool_exp!, $offset: Int, $limit: Int, $order_by: [table_metadatas_order_by!]) {\n table_metadatas(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n handle\n key_type\n value_type\n }\n}\n `;\nexport const GetTokenActivity = `\n query getTokenActivity($where_condition: token_activities_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [token_activities_v2_order_by!]) {\n token_activities_v2(\n where: $where_condition\n order_by: $order_by\n offset: $offset\n limit: $limit\n ) {\n ...TokenActivitiesFields\n }\n}\n ${TokenActivitiesFieldsFragmentDoc}`;\nexport const GetCurrentTokenOwnership = `\n query getCurrentTokenOwnership($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {\n current_token_ownerships_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n ...CurrentTokenOwnershipFields\n }\n}\n ${CurrentTokenOwnershipFieldsFragmentDoc}`;\nexport const GetTokenData = `\n query getTokenData($where_condition: current_token_datas_v2_bool_exp, $offset: Int, $limit: Int, $order_by: [current_token_datas_v2_order_by!]) {\n current_token_datas_v2(\n where: $where_condition\n offset: $offset\n limit: $limit\n order_by: $order_by\n ) {\n collection_id\n description\n is_fungible_v2\n largest_property_version_v1\n last_transaction_timestamp\n last_transaction_version\n maximum\n supply\n token_data_id\n token_name\n token_properties\n token_standard\n token_uri\n decimals\n current_collection {\n collection_id\n collection_name\n creator_address\n current_supply\n description\n last_transaction_timestamp\n last_transaction_version\n max_supply\n mutable_description\n mutable_uri\n table_handle_v1\n token_standard\n total_minted_v2\n uri\n }\n }\n}\n `;\n\nexport type SdkFunctionWrapper = <T>(\n action: (requestHeaders?: Record<string, string>) => Promise<T>,\n operationName: string,\n operationType?: string,\n variables?: any,\n) => Promise<T>;\n\nconst defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationType, _variables) => action();\n\nexport function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {\n return {\n getAccountAddressesForAuthKey(\n variables?: Types.GetAccountAddressesForAuthKeyQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountAddressesForAuthKeyQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountAddressesForAuthKeyQuery>(GetAccountAddressesForAuthKey, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountAddressesForAuthKey\",\n \"query\",\n variables,\n );\n },\n getAccountCoinsCount(\n variables?: Types.GetAccountCoinsCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCoinsCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCoinsCountQuery>(GetAccountCoinsCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountCoinsCount\",\n \"query\",\n variables,\n );\n },\n getAccountCoinsData(\n variables: Types.GetAccountCoinsDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCoinsDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCoinsDataQuery>(GetAccountCoinsData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountCoinsData\",\n \"query\",\n variables,\n );\n },\n getAccountCollectionsWithOwnedTokens(\n variables: Types.GetAccountCollectionsWithOwnedTokensQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountCollectionsWithOwnedTokensQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountCollectionsWithOwnedTokensQuery>(\n GetAccountCollectionsWithOwnedTokens,\n variables,\n { ...requestHeaders, ...wrappedRequestHeaders },\n ),\n \"getAccountCollectionsWithOwnedTokens\",\n \"query\",\n variables,\n );\n },\n getAccountOwnedTokens(\n variables: Types.GetAccountOwnedTokensQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensQuery>(GetAccountOwnedTokens, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedTokens\",\n \"query\",\n variables,\n );\n },\n getAccountOwnedTokensByTokenData(\n variables: Types.GetAccountOwnedTokensByTokenDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensByTokenDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensByTokenDataQuery>(GetAccountOwnedTokensByTokenData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountOwnedTokensByTokenData\",\n \"query\",\n variables,\n );\n },\n getAccountOwnedTokensFromCollection(\n variables: Types.GetAccountOwnedTokensFromCollectionQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountOwnedTokensFromCollectionQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountOwnedTokensFromCollectionQuery>(\n GetAccountOwnedTokensFromCollection,\n variables,\n { ...requestHeaders, ...wrappedRequestHeaders },\n ),\n \"getAccountOwnedTokensFromCollection\",\n \"query\",\n variables,\n );\n },\n getAccountTokensCount(\n variables?: Types.GetAccountTokensCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountTokensCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountTokensCountQuery>(GetAccountTokensCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountTokensCount\",\n \"query\",\n variables,\n );\n },\n getAccountTransactionsCount(\n variables?: Types.GetAccountTransactionsCountQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAccountTransactionsCountQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAccountTransactionsCountQuery>(GetAccountTransactionsCount, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAccountTransactionsCount\",\n \"query\",\n variables,\n );\n },\n getAuthKeysForPublicKey(\n variables?: Types.GetAuthKeysForPublicKeyQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetAuthKeysForPublicKeyQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetAuthKeysForPublicKeyQuery>(GetAuthKeysForPublicKey, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getAuthKeysForPublicKey\",\n \"query\",\n variables,\n );\n },\n getChainTopUserTransactions(\n variables?: Types.GetChainTopUserTransactionsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetChainTopUserTransactionsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetChainTopUserTransactionsQuery>(GetChainTopUserTransactions, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getChainTopUserTransactions\",\n \"query\",\n variables,\n );\n },\n getCollectionData(\n variables: Types.GetCollectionDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCollectionDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCollectionDataQuery>(GetCollectionData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCollectionData\",\n \"query\",\n variables,\n );\n },\n getCurrentFungibleAssetBalances(\n variables?: Types.GetCurrentFungibleAssetBalancesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCurrentFungibleAssetBalancesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCurrentFungibleAssetBalancesQuery>(GetCurrentFungibleAssetBalances, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCurrentFungibleAssetBalances\",\n \"query\",\n variables,\n );\n },\n getDelegatedStakingActivities(\n variables?: Types.GetDelegatedStakingActivitiesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetDelegatedStakingActivitiesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetDelegatedStakingActivitiesQuery>(GetDelegatedStakingActivities, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getDelegatedStakingActivities\",\n \"query\",\n variables,\n );\n },\n getEvents(\n variables?: Types.GetEventsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetEventsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetEventsQuery>(GetEvents, variables, { ...requestHeaders, ...wrappedRequestHeaders }),\n \"getEvents\",\n \"query\",\n variables,\n );\n },\n getFungibleAssetActivities(\n variables?: Types.GetFungibleAssetActivitiesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetFungibleAssetActivitiesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetFungibleAssetActivitiesQuery>(GetFungibleAssetActivities, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getFungibleAssetActivities\",\n \"query\",\n variables,\n );\n },\n getFungibleAssetMetadata(\n variables?: Types.GetFungibleAssetMetadataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetFungibleAssetMetadataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetFungibleAssetMetadataQuery>(GetFungibleAssetMetadata, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getFungibleAssetMetadata\",\n \"query\",\n variables,\n );\n },\n getNames(\n variables?: Types.GetNamesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetNamesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetNamesQuery>(GetNames, variables, { ...requestHeaders, ...wrappedRequestHeaders }),\n \"getNames\",\n \"query\",\n variables,\n );\n },\n getNumberOfDelegators(\n variables?: Types.GetNumberOfDelegatorsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetNumberOfDelegatorsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetNumberOfDelegatorsQuery>(GetNumberOfDelegators, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getNumberOfDelegators\",\n \"query\",\n variables,\n );\n },\n getObjectData(\n variables?: Types.GetObjectDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetObjectDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetObjectDataQuery>(GetObjectData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getObjectData\",\n \"query\",\n variables,\n );\n },\n getProcessorStatus(\n variables?: Types.GetProcessorStatusQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetProcessorStatusQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetProcessorStatusQuery>(GetProcessorStatus, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getProcessorStatus\",\n \"query\",\n variables,\n );\n },\n getTableItemsData(\n variables: Types.GetTableItemsDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTableItemsDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTableItemsDataQuery>(GetTableItemsData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTableItemsData\",\n \"query\",\n variables,\n );\n },\n getTableItemsMetadata(\n variables: Types.GetTableItemsMetadataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTableItemsMetadataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTableItemsMetadataQuery>(GetTableItemsMetadata, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTableItemsMetadata\",\n \"query\",\n variables,\n );\n },\n getTokenActivity(\n variables: Types.GetTokenActivityQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTokenActivityQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTokenActivityQuery>(GetTokenActivity, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTokenActivity\",\n \"query\",\n variables,\n );\n },\n getCurrentTokenOwnership(\n variables: Types.GetCurrentTokenOwnershipQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetCurrentTokenOwnershipQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetCurrentTokenOwnershipQuery>(GetCurrentTokenOwnership, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getCurrentTokenOwnership\",\n \"query\",\n variables,\n );\n },\n getTokenData(\n variables?: Types.GetTokenDataQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n ): Promise<Types.GetTokenDataQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<Types.GetTokenDataQuery>(GetTokenData, variables, {\n ...requestHeaders,\n ...wrappedRequestHeaders,\n }),\n \"getTokenData\",\n \"query\",\n variables,\n );\n },\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;\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 { 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 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 * @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 * @param args.minimumLedgerVersion Not used anymore, here for backward compatibility\n * see https://github.com/aptos-labs/aptos-ts-sdk/pull/519, will be removed in the near future.\n * Optional ledger version to sync up to before querying.\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 * // Query the account's coin amount for a specific coin type\n * const accountCoinAmount = await aptos.getAccountCoinAmount({\n * accountAddress: \"0x1\", // replace with a real account address\n * coinType: \"0x1::aptos_coin::AptosCoin\" // specify the coin type\n * });\n *\n * console.log(`Account coin amount: ${accountCoinAmount}`);\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 minimumLedgerVersion?: AnyNumber;\n }): Promise<number> {\n const { accountAddress, coinType, faMetadataAddress, minimumLedgerVersion } = args;\n\n if (minimumLedgerVersion) {\n // eslint-disable-next-line no-console\n console.warn(\n `minimumLedgerVersion is not used anymore, here for backward \n compatibility see https://github.com/aptos-labs/aptos-ts-sdk/pull/519, \n will be removed in the near future`,\n );\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({\n aptosConfig: this.config,\n payload: { function: \"0x1::coin::paired_coin\", functionArguments: [faMetadataAddress] },\n })\n ).at(0) as { vec: MoveValue[] };\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]) as MoveStructId;\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 * 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","// 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"]}