@aptos-labs/ts-sdk 5.1.3 → 5.1.4

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 (345) hide show
  1. package/dist/common/{account-nCfrFDHy.d.ts → account-DefhsHe3.d.ts} +232 -1
  2. package/dist/common/chunk-HO5ESTN4.js +4 -0
  3. package/dist/common/{chunk-PW6UQAB2.js.map → chunk-HO5ESTN4.js.map} +1 -1
  4. package/dist/common/cli/index.d.ts +1 -1
  5. package/dist/common/cli/index.js +1 -1
  6. package/dist/common/index.d.ts +2 -2
  7. package/dist/common/index.js +31 -31
  8. package/dist/common/index.js.map +1 -1
  9. package/dist/esm/{Ed25519Account-BgSyStyl.d.mts → Ed25519Account-CVg5T_jc.d.mts} +1 -1
  10. package/dist/esm/account/AbstractKeylessAccount.d.mts +3 -3
  11. package/dist/esm/account/AbstractKeylessAccount.mjs +1 -1
  12. package/dist/esm/account/AbstractedAccount.d.mts +2 -2
  13. package/dist/esm/account/AbstractedAccount.mjs +1 -1
  14. package/dist/esm/account/Account.d.mts +2 -2
  15. package/dist/esm/account/Account.mjs +1 -1
  16. package/dist/esm/account/AccountUtils.d.mts +3 -3
  17. package/dist/esm/account/AccountUtils.mjs +1 -1
  18. package/dist/esm/account/DerivableAbstractedAccount.d.mts +2 -2
  19. package/dist/esm/account/DerivableAbstractedAccount.mjs +1 -1
  20. package/dist/esm/account/Ed25519Account.d.mts +2 -2
  21. package/dist/esm/account/Ed25519Account.mjs +1 -1
  22. package/dist/esm/account/EphemeralKeyPair.d.mts +1 -1
  23. package/dist/esm/account/EphemeralKeyPair.mjs +1 -1
  24. package/dist/esm/account/FederatedKeylessAccount.d.mts +3 -3
  25. package/dist/esm/account/FederatedKeylessAccount.mjs +1 -1
  26. package/dist/esm/account/KeylessAccount.d.mts +3 -3
  27. package/dist/esm/account/KeylessAccount.mjs +1 -1
  28. package/dist/esm/account/MultiEd25519Account.d.mts +2 -2
  29. package/dist/esm/account/MultiEd25519Account.mjs +1 -1
  30. package/dist/esm/account/MultiKeyAccount.d.mts +3 -3
  31. package/dist/esm/account/MultiKeyAccount.mjs +1 -1
  32. package/dist/esm/account/SingleKeyAccount.d.mts +2 -2
  33. package/dist/esm/account/SingleKeyAccount.mjs +1 -1
  34. package/dist/esm/account/index.d.mts +3 -3
  35. package/dist/esm/account/index.mjs +1 -1
  36. package/dist/esm/account/utils.d.mts +1 -1
  37. package/dist/esm/account/utils.mjs +1 -1
  38. package/dist/esm/{account-CAv0-Zs9.d.mts → account-DOs8SpoQ.d.mts} +232 -1
  39. package/dist/esm/api/account/abstraction.d.mts +1 -1
  40. package/dist/esm/api/account/abstraction.mjs +1 -1
  41. package/dist/esm/api/account.d.mts +2 -2
  42. package/dist/esm/api/account.mjs +1 -1
  43. package/dist/esm/api/ans.d.mts +2 -2
  44. package/dist/esm/api/ans.mjs +1 -1
  45. package/dist/esm/api/aptos.d.mts +3 -3
  46. package/dist/esm/api/aptos.mjs +1 -1
  47. package/dist/esm/api/aptosConfig.d.mts +1 -1
  48. package/dist/esm/api/coin.d.mts +1 -1
  49. package/dist/esm/api/coin.mjs +1 -1
  50. package/dist/esm/api/digitalAsset.d.mts +2 -2
  51. package/dist/esm/api/digitalAsset.mjs +1 -1
  52. package/dist/esm/api/faucet.d.mts +1 -1
  53. package/dist/esm/api/faucet.mjs +1 -1
  54. package/dist/esm/api/fungibleAsset.d.mts +2 -2
  55. package/dist/esm/api/fungibleAsset.mjs +1 -1
  56. package/dist/esm/api/general.d.mts +1 -1
  57. package/dist/esm/api/general.mjs +1 -1
  58. package/dist/esm/api/index.d.mts +3 -3
  59. package/dist/esm/api/index.mjs +1 -1
  60. package/dist/esm/api/keyless.d.mts +3 -3
  61. package/dist/esm/api/keyless.mjs +1 -1
  62. package/dist/esm/api/object.d.mts +1 -1
  63. package/dist/esm/api/object.mjs +1 -1
  64. package/dist/esm/api/staking.d.mts +1 -1
  65. package/dist/esm/api/staking.mjs +1 -1
  66. package/dist/esm/api/table.d.mts +1 -1
  67. package/dist/esm/api/table.mjs +1 -1
  68. package/dist/esm/api/transaction.d.mts +2 -2
  69. package/dist/esm/api/transaction.mjs +1 -1
  70. package/dist/esm/api/transactionSubmission/build.d.mts +1 -1
  71. package/dist/esm/api/transactionSubmission/build.mjs +1 -1
  72. package/dist/esm/api/transactionSubmission/helpers.d.mts +1 -1
  73. package/dist/esm/api/transactionSubmission/management.d.mts +2 -2
  74. package/dist/esm/api/transactionSubmission/management.mjs +1 -1
  75. package/dist/esm/api/transactionSubmission/sign.d.mts +2 -2
  76. package/dist/esm/api/transactionSubmission/sign.mjs +1 -1
  77. package/dist/esm/api/transactionSubmission/simulate.d.mts +1 -1
  78. package/dist/esm/api/transactionSubmission/simulate.mjs +1 -1
  79. package/dist/esm/api/transactionSubmission/submit.d.mts +1 -1
  80. package/dist/esm/api/transactionSubmission/submit.mjs +1 -1
  81. package/dist/esm/api/utils.d.mts +1 -1
  82. package/dist/esm/api/utils.mjs +1 -1
  83. package/dist/esm/bcs/consts.d.mts +14 -2
  84. package/dist/esm/bcs/consts.mjs +1 -1
  85. package/dist/esm/bcs/deserializer.d.mts +1 -1
  86. package/dist/esm/bcs/deserializer.mjs +1 -1
  87. package/dist/esm/bcs/index.d.mts +1 -1
  88. package/dist/esm/bcs/index.mjs +1 -1
  89. package/dist/esm/bcs/serializable/entryFunctionBytes.d.mts +1 -1
  90. package/dist/esm/bcs/serializable/entryFunctionBytes.mjs +1 -1
  91. package/dist/esm/bcs/serializable/fixedBytes.d.mts +1 -1
  92. package/dist/esm/bcs/serializable/fixedBytes.mjs +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/bcs/serializer.mjs +1 -1
  99. package/dist/esm/{chunk-DURSBMWP.mjs → chunk-3JDGB4IL.mjs} +2 -2
  100. package/dist/esm/chunk-3JDGB4IL.mjs.map +1 -0
  101. package/dist/esm/{chunk-N6YTF76Q.mjs → chunk-3P474TWM.mjs} +2 -2
  102. package/dist/esm/{chunk-TOBQ5UE6.mjs → chunk-43LWUUXS.mjs} +2 -2
  103. package/dist/esm/chunk-5ABS6RDR.mjs +2 -0
  104. package/dist/esm/chunk-5ABS6RDR.mjs.map +1 -0
  105. package/dist/esm/{chunk-WSR5EBJM.mjs → chunk-5FNZUL2Y.mjs} +2 -2
  106. package/dist/esm/{chunk-XKUIMGKU.mjs → chunk-6IWGTO2J.mjs} +2 -2
  107. package/dist/esm/{chunk-54WUP65H.mjs → chunk-7WIDI4FZ.mjs} +2 -2
  108. package/dist/esm/{chunk-YSP6JG5G.mjs → chunk-AVOTC5EI.mjs} +2 -2
  109. package/dist/esm/{chunk-Q4W3WJ2U.mjs → chunk-BIQOJ3OK.mjs} +2 -2
  110. package/dist/esm/{chunk-ZYE7UTJZ.mjs → chunk-C5UZZHA4.mjs} +2 -2
  111. package/dist/esm/{chunk-MT2RJ7H3.mjs → chunk-DIFSO4N6.mjs} +2 -2
  112. package/dist/esm/{chunk-YZHAI55C.mjs → chunk-G3HAIETV.mjs} +2 -2
  113. package/dist/esm/{chunk-EF4FA5I6.mjs → chunk-GRF3NBRO.mjs} +2 -2
  114. package/dist/esm/{chunk-AGAAGA2X.mjs → chunk-GTRHYHQK.mjs} +2 -2
  115. package/dist/esm/chunk-I42Z32Q2.mjs +2 -0
  116. package/dist/esm/chunk-I42Z32Q2.mjs.map +1 -0
  117. package/dist/esm/{chunk-2XQKGWHQ.mjs → chunk-IKTH33UN.mjs} +2 -2
  118. package/dist/esm/{chunk-M3FCWYLI.mjs → chunk-IQPLJ32K.mjs} +2 -2
  119. package/dist/esm/{chunk-C2ZO2L5W.mjs → chunk-IXRGCQQU.mjs} +2 -2
  120. package/dist/esm/{chunk-BCTM24ZZ.mjs → chunk-JYDVO4K3.mjs} +2 -2
  121. package/dist/esm/chunk-KUF4DKN5.mjs +2 -0
  122. package/dist/esm/chunk-LD3I4CYO.mjs +2 -0
  123. package/dist/esm/{chunk-RGKRCZ36.mjs → chunk-MEG27LEV.mjs} +2 -2
  124. package/dist/esm/{chunk-LA56UDUK.mjs → chunk-PYVKCTUN.mjs} +2 -2
  125. package/dist/esm/{chunk-WCMW2L3P.mjs → chunk-QDJDZ3ON.mjs} +2 -2
  126. package/dist/esm/{chunk-FGFLPH5K.mjs → chunk-RYOICF37.mjs} +2 -2
  127. package/dist/esm/{chunk-ZABLJ2JJ.mjs → chunk-SGZPRMLE.mjs} +2 -2
  128. package/dist/esm/{chunk-I7XT6L7S.mjs → chunk-VO3JD6U6.mjs} +2 -2
  129. package/dist/esm/{chunk-GQ3UIDPQ.mjs → chunk-VS5NYRHW.mjs} +2 -2
  130. package/dist/esm/{chunk-EFQZGHAO.mjs → chunk-VV6OTOMS.mjs} +2 -2
  131. package/dist/esm/chunk-WGRSKMNQ.mjs +2 -0
  132. package/dist/esm/{chunk-EW45LLAP.mjs.map → chunk-WGRSKMNQ.mjs.map} +1 -1
  133. package/dist/esm/{chunk-HX6SDBEX.mjs → chunk-WOEH45Q2.mjs} +2 -2
  134. package/dist/esm/chunk-X2TPNKLV.mjs +2 -0
  135. package/dist/esm/chunk-X2TPNKLV.mjs.map +1 -0
  136. package/dist/esm/{chunk-DRBFLEZL.mjs → chunk-X5BUBEJH.mjs} +2 -2
  137. package/dist/esm/{chunk-FLZPUYXQ.mjs → chunk-Y426VCPM.mjs} +2 -2
  138. package/dist/esm/{chunk-FLZPUYXQ.mjs.map → chunk-Y426VCPM.mjs.map} +1 -1
  139. package/dist/esm/cli/index.d.mts +1 -1
  140. package/dist/esm/cli/index.mjs +1 -1
  141. package/dist/esm/cli/localNode.mjs +1 -1
  142. package/dist/esm/cli/move.d.mts +1 -1
  143. package/dist/esm/client/core.d.mts +1 -1
  144. package/dist/esm/client/core.mjs +1 -1
  145. package/dist/esm/client/get.d.mts +1 -1
  146. package/dist/esm/client/get.mjs +1 -1
  147. package/dist/esm/client/index.d.mts +1 -1
  148. package/dist/esm/client/index.mjs +1 -1
  149. package/dist/esm/client/post.d.mts +1 -1
  150. package/dist/esm/client/post.mjs +1 -1
  151. package/dist/esm/core/account/index.d.mts +1 -1
  152. package/dist/esm/core/account/index.mjs +1 -1
  153. package/dist/esm/core/account/utils/address.d.mts +1 -1
  154. package/dist/esm/core/account/utils/address.mjs +1 -1
  155. package/dist/esm/core/account/utils/index.d.mts +1 -1
  156. package/dist/esm/core/account/utils/index.mjs +1 -1
  157. package/dist/esm/core/accountAddress.d.mts +1 -1
  158. package/dist/esm/core/accountAddress.mjs +1 -1
  159. package/dist/esm/core/authenticationKey.d.mts +1 -1
  160. package/dist/esm/core/authenticationKey.mjs +1 -1
  161. package/dist/esm/core/crypto/abstraction.d.mts +1 -1
  162. package/dist/esm/core/crypto/abstraction.mjs +1 -1
  163. package/dist/esm/core/crypto/deserializationUtils.d.mts +1 -1
  164. package/dist/esm/core/crypto/deserializationUtils.mjs +1 -1
  165. package/dist/esm/core/crypto/ed25519.d.mts +1 -1
  166. package/dist/esm/core/crypto/ed25519.mjs +1 -1
  167. package/dist/esm/core/crypto/ephemeral.d.mts +1 -1
  168. package/dist/esm/core/crypto/ephemeral.mjs +1 -1
  169. package/dist/esm/core/crypto/federatedKeyless.d.mts +2 -2
  170. package/dist/esm/core/crypto/federatedKeyless.mjs +1 -1
  171. package/dist/esm/core/crypto/index.d.mts +2 -2
  172. package/dist/esm/core/crypto/index.mjs +1 -1
  173. package/dist/esm/core/crypto/keyless.d.mts +2 -2
  174. package/dist/esm/core/crypto/keyless.mjs +1 -1
  175. package/dist/esm/core/crypto/multiEd25519.d.mts +1 -1
  176. package/dist/esm/core/crypto/multiEd25519.mjs +1 -1
  177. package/dist/esm/core/crypto/multiKey.d.mts +1 -1
  178. package/dist/esm/core/crypto/multiKey.mjs +1 -1
  179. package/dist/esm/core/crypto/privateKey.d.mts +1 -1
  180. package/dist/esm/core/crypto/privateKey.mjs +1 -1
  181. package/dist/esm/core/crypto/proof.d.mts +1 -1
  182. package/dist/esm/core/crypto/proof.mjs +1 -1
  183. package/dist/esm/core/crypto/publicKey.d.mts +1 -1
  184. package/dist/esm/core/crypto/publicKey.mjs +1 -1
  185. package/dist/esm/core/crypto/secp256k1.d.mts +1 -1
  186. package/dist/esm/core/crypto/secp256k1.mjs +1 -1
  187. package/dist/esm/core/crypto/secp256r1.d.mts +1 -1
  188. package/dist/esm/core/crypto/secp256r1.mjs +1 -1
  189. package/dist/esm/core/crypto/signature.d.mts +1 -1
  190. package/dist/esm/core/crypto/signature.mjs +1 -1
  191. package/dist/esm/core/crypto/singleKey.d.mts +1 -1
  192. package/dist/esm/core/crypto/singleKey.mjs +1 -1
  193. package/dist/esm/core/crypto/types.d.mts +1 -1
  194. package/dist/esm/core/crypto/utils.d.mts +1 -1
  195. package/dist/esm/core/crypto/utils.mjs +1 -1
  196. package/dist/esm/core/hex.d.mts +1 -1
  197. package/dist/esm/core/index.d.mts +2 -2
  198. package/dist/esm/core/index.mjs +1 -1
  199. package/dist/esm/errors/index.d.mts +1 -1
  200. package/dist/esm/errors/index.mjs +1 -1
  201. package/dist/esm/{federatedKeyless-C8KXaSM1.d.mts → federatedKeyless-CxdU4W95.d.mts} +1 -1
  202. package/dist/esm/index.d.mts +3 -3
  203. package/dist/esm/index.mjs +1 -1
  204. package/dist/esm/internal/abstraction.d.mts +1 -1
  205. package/dist/esm/internal/abstraction.mjs +1 -1
  206. package/dist/esm/internal/account.d.mts +2 -2
  207. package/dist/esm/internal/account.mjs +1 -1
  208. package/dist/esm/internal/ans.d.mts +2 -2
  209. package/dist/esm/internal/ans.mjs +1 -1
  210. package/dist/esm/internal/coin.d.mts +1 -1
  211. package/dist/esm/internal/coin.mjs +1 -1
  212. package/dist/esm/internal/digitalAsset.d.mts +2 -2
  213. package/dist/esm/internal/digitalAsset.mjs +1 -1
  214. package/dist/esm/internal/faucet.d.mts +1 -1
  215. package/dist/esm/internal/faucet.mjs +1 -1
  216. package/dist/esm/internal/fungibleAsset.d.mts +2 -2
  217. package/dist/esm/internal/fungibleAsset.mjs +1 -1
  218. package/dist/esm/internal/general.d.mts +1 -1
  219. package/dist/esm/internal/general.mjs +1 -1
  220. package/dist/esm/internal/keyless.d.mts +3 -3
  221. package/dist/esm/internal/keyless.mjs +1 -1
  222. package/dist/esm/internal/object.d.mts +1 -1
  223. package/dist/esm/internal/object.mjs +1 -1
  224. package/dist/esm/internal/staking.d.mts +1 -1
  225. package/dist/esm/internal/staking.mjs +1 -1
  226. package/dist/esm/internal/table.d.mts +1 -1
  227. package/dist/esm/internal/table.mjs +1 -1
  228. package/dist/esm/internal/transaction.d.mts +1 -1
  229. package/dist/esm/internal/transaction.mjs +1 -1
  230. package/dist/esm/internal/transactionSubmission.d.mts +2 -2
  231. package/dist/esm/internal/transactionSubmission.mjs +1 -1
  232. package/dist/esm/internal/utils/index.d.mts +1 -1
  233. package/dist/esm/internal/utils/index.mjs +1 -1
  234. package/dist/esm/internal/utils/utils.d.mts +1 -1
  235. package/dist/esm/internal/utils/utils.mjs +1 -1
  236. package/dist/esm/internal/view.d.mts +1 -1
  237. package/dist/esm/internal/view.mjs +1 -1
  238. package/dist/esm/transactions/authenticator/account.d.mts +1 -1
  239. package/dist/esm/transactions/authenticator/account.mjs +1 -1
  240. package/dist/esm/transactions/authenticator/index.d.mts +1 -1
  241. package/dist/esm/transactions/authenticator/index.mjs +1 -1
  242. package/dist/esm/transactions/authenticator/transaction.d.mts +1 -1
  243. package/dist/esm/transactions/authenticator/transaction.mjs +1 -1
  244. package/dist/esm/transactions/index.d.mts +1 -1
  245. package/dist/esm/transactions/index.mjs +1 -1
  246. package/dist/esm/transactions/instances/chainId.d.mts +1 -1
  247. package/dist/esm/transactions/instances/chainId.mjs +1 -1
  248. package/dist/esm/transactions/instances/identifier.d.mts +1 -1
  249. package/dist/esm/transactions/instances/identifier.mjs +1 -1
  250. package/dist/esm/transactions/instances/index.d.mts +1 -1
  251. package/dist/esm/transactions/instances/index.mjs +1 -1
  252. package/dist/esm/transactions/instances/moduleId.d.mts +1 -1
  253. package/dist/esm/transactions/instances/moduleId.mjs +1 -1
  254. package/dist/esm/transactions/instances/multiAgentTransaction.d.mts +1 -1
  255. package/dist/esm/transactions/instances/multiAgentTransaction.mjs +1 -1
  256. package/dist/esm/transactions/instances/rawTransaction.d.mts +1 -1
  257. package/dist/esm/transactions/instances/rawTransaction.mjs +1 -1
  258. package/dist/esm/transactions/instances/rotationProofChallenge.d.mts +1 -1
  259. package/dist/esm/transactions/instances/rotationProofChallenge.mjs +1 -1
  260. package/dist/esm/transactions/instances/signedTransaction.d.mts +1 -1
  261. package/dist/esm/transactions/instances/signedTransaction.mjs +1 -1
  262. package/dist/esm/transactions/instances/simpleTransaction.d.mts +1 -1
  263. package/dist/esm/transactions/instances/simpleTransaction.mjs +1 -1
  264. package/dist/esm/transactions/instances/transactionArgument.d.mts +1 -1
  265. package/dist/esm/transactions/instances/transactionPayload.d.mts +1 -1
  266. package/dist/esm/transactions/instances/transactionPayload.mjs +1 -1
  267. package/dist/esm/transactions/management/accountSequenceNumber.d.mts +2 -2
  268. package/dist/esm/transactions/management/accountSequenceNumber.mjs +1 -1
  269. package/dist/esm/transactions/management/index.d.mts +2 -2
  270. package/dist/esm/transactions/management/index.mjs +1 -1
  271. package/dist/esm/transactions/management/transactionWorker.d.mts +2 -2
  272. package/dist/esm/transactions/management/transactionWorker.mjs +1 -1
  273. package/dist/esm/transactions/transactionBuilder/helpers.d.mts +1 -1
  274. package/dist/esm/transactions/transactionBuilder/helpers.mjs +1 -1
  275. package/dist/esm/transactions/transactionBuilder/index.d.mts +1 -1
  276. package/dist/esm/transactions/transactionBuilder/index.mjs +1 -1
  277. package/dist/esm/transactions/transactionBuilder/remoteAbi.d.mts +1 -1
  278. package/dist/esm/transactions/transactionBuilder/remoteAbi.mjs +1 -1
  279. package/dist/esm/transactions/transactionBuilder/signingMessage.d.mts +1 -1
  280. package/dist/esm/transactions/transactionBuilder/signingMessage.mjs +1 -1
  281. package/dist/esm/transactions/transactionBuilder/transactionBuilder.d.mts +2 -2
  282. package/dist/esm/transactions/transactionBuilder/transactionBuilder.mjs +1 -1
  283. package/dist/esm/transactions/typeTag/index.d.mts +1 -1
  284. package/dist/esm/transactions/typeTag/index.mjs +1 -1
  285. package/dist/esm/transactions/typeTag/parser.d.mts +1 -1
  286. package/dist/esm/transactions/typeTag/parser.mjs +1 -1
  287. package/dist/esm/transactions/types.d.mts +1 -1
  288. package/dist/esm/types/index.d.mts +1 -1
  289. package/dist/esm/types/index.mjs +1 -1
  290. package/dist/esm/types/types.d.mts +1 -1
  291. package/dist/esm/types/types.mjs +1 -1
  292. package/dist/esm/utils/helpers.d.mts +1 -1
  293. package/dist/esm/utils/helpers.mjs +1 -1
  294. package/dist/esm/utils/index.d.mts +1 -1
  295. package/dist/esm/utils/index.mjs +1 -1
  296. package/dist/esm/utils/normalizeBundle.d.mts +1 -1
  297. package/dist/esm/utils/normalizeBundle.mjs +1 -1
  298. package/dist/esm/version.d.mts +1 -1
  299. package/dist/esm/version.mjs +1 -1
  300. package/package.json +1 -1
  301. package/src/bcs/consts.ts +15 -1
  302. package/src/bcs/deserializer.ts +105 -0
  303. package/src/bcs/serializable/movePrimitives.ts +237 -1
  304. package/src/bcs/serializer.ts +111 -0
  305. package/src/types/types.ts +30 -0
  306. package/src/version.ts +1 -1
  307. package/dist/common/chunk-PW6UQAB2.js +0 -4
  308. package/dist/esm/chunk-56CNRT2K.mjs +0 -2
  309. package/dist/esm/chunk-56CNRT2K.mjs.map +0 -1
  310. package/dist/esm/chunk-CW35YAMN.mjs +0 -2
  311. package/dist/esm/chunk-DURSBMWP.mjs.map +0 -1
  312. package/dist/esm/chunk-EBMEXURY.mjs +0 -2
  313. package/dist/esm/chunk-EBMEXURY.mjs.map +0 -1
  314. package/dist/esm/chunk-EW45LLAP.mjs +0 -2
  315. package/dist/esm/chunk-ORMOQWWH.mjs +0 -2
  316. package/dist/esm/chunk-ORMOQWWH.mjs.map +0 -1
  317. package/dist/esm/chunk-XJJVJOX5.mjs +0 -2
  318. /package/dist/esm/{chunk-N6YTF76Q.mjs.map → chunk-3P474TWM.mjs.map} +0 -0
  319. /package/dist/esm/{chunk-TOBQ5UE6.mjs.map → chunk-43LWUUXS.mjs.map} +0 -0
  320. /package/dist/esm/{chunk-WSR5EBJM.mjs.map → chunk-5FNZUL2Y.mjs.map} +0 -0
  321. /package/dist/esm/{chunk-XKUIMGKU.mjs.map → chunk-6IWGTO2J.mjs.map} +0 -0
  322. /package/dist/esm/{chunk-54WUP65H.mjs.map → chunk-7WIDI4FZ.mjs.map} +0 -0
  323. /package/dist/esm/{chunk-YSP6JG5G.mjs.map → chunk-AVOTC5EI.mjs.map} +0 -0
  324. /package/dist/esm/{chunk-Q4W3WJ2U.mjs.map → chunk-BIQOJ3OK.mjs.map} +0 -0
  325. /package/dist/esm/{chunk-ZYE7UTJZ.mjs.map → chunk-C5UZZHA4.mjs.map} +0 -0
  326. /package/dist/esm/{chunk-MT2RJ7H3.mjs.map → chunk-DIFSO4N6.mjs.map} +0 -0
  327. /package/dist/esm/{chunk-YZHAI55C.mjs.map → chunk-G3HAIETV.mjs.map} +0 -0
  328. /package/dist/esm/{chunk-EF4FA5I6.mjs.map → chunk-GRF3NBRO.mjs.map} +0 -0
  329. /package/dist/esm/{chunk-AGAAGA2X.mjs.map → chunk-GTRHYHQK.mjs.map} +0 -0
  330. /package/dist/esm/{chunk-2XQKGWHQ.mjs.map → chunk-IKTH33UN.mjs.map} +0 -0
  331. /package/dist/esm/{chunk-M3FCWYLI.mjs.map → chunk-IQPLJ32K.mjs.map} +0 -0
  332. /package/dist/esm/{chunk-C2ZO2L5W.mjs.map → chunk-IXRGCQQU.mjs.map} +0 -0
  333. /package/dist/esm/{chunk-BCTM24ZZ.mjs.map → chunk-JYDVO4K3.mjs.map} +0 -0
  334. /package/dist/esm/{chunk-XJJVJOX5.mjs.map → chunk-KUF4DKN5.mjs.map} +0 -0
  335. /package/dist/esm/{chunk-CW35YAMN.mjs.map → chunk-LD3I4CYO.mjs.map} +0 -0
  336. /package/dist/esm/{chunk-RGKRCZ36.mjs.map → chunk-MEG27LEV.mjs.map} +0 -0
  337. /package/dist/esm/{chunk-LA56UDUK.mjs.map → chunk-PYVKCTUN.mjs.map} +0 -0
  338. /package/dist/esm/{chunk-WCMW2L3P.mjs.map → chunk-QDJDZ3ON.mjs.map} +0 -0
  339. /package/dist/esm/{chunk-FGFLPH5K.mjs.map → chunk-RYOICF37.mjs.map} +0 -0
  340. /package/dist/esm/{chunk-ZABLJ2JJ.mjs.map → chunk-SGZPRMLE.mjs.map} +0 -0
  341. /package/dist/esm/{chunk-I7XT6L7S.mjs.map → chunk-VO3JD6U6.mjs.map} +0 -0
  342. /package/dist/esm/{chunk-GQ3UIDPQ.mjs.map → chunk-VS5NYRHW.mjs.map} +0 -0
  343. /package/dist/esm/{chunk-EFQZGHAO.mjs.map → chunk-VV6OTOMS.mjs.map} +0 -0
  344. /package/dist/esm/{chunk-HX6SDBEX.mjs.map → chunk-WOEH45Q2.mjs.map} +0 -0
  345. /package/dist/esm/{chunk-DRBFLEZL.mjs.map → chunk-X5BUBEJH.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kent/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/core/crypto/ed25519.ts","../../src/types/generated/queries.ts","../../src/transactions/typeTag/parser.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","TypeTagI16"],"mappings":"AAAA,2sCAA+nB,IC6ClnBA,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,CAAQ,IAAA,CAAK,MAAA,CAASD,CAAM,CAAA,CACjE,OAAA,IAAA,CAAK,MAAA,EAAUA,CAAAA,CACRC,CACT,CAWA,SAAA,CAAA,CAAoB,CAClB,OAAO,IAAA,CAAK,MAAA,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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;ACjHX4D,IAAAA","file":"/Users/kent/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 abstract getSignaturesRequired(): number;\n}\n\n/**\n * Represents a multi-key authentication scheme for accounts, allowing multiple public keys\n * to be associated with a single account. This class enforces a minimum number of valid signatures\n * required to authorize actions, ensuring enhanced security for multi-agent accounts.\n *\n * The public keys of each individual agent can be any type of public key supported by Aptos.\n * Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263), Aptos supports\n * `Legacy` and `Unified` authentication keys.\n * @group Implementation\n * @category Serialization\n */\nexport class MultiKey extends AbstractMultiKey {\n /**\n * List of any public keys\n * @group Implementation\n * @category Serialization\n */\n public readonly publicKeys: AnyPublicKey[];\n\n /**\n * The minimum number of valid signatures required, for the number of public keys specified\n * @group Implementation\n * @category Serialization\n */\n public readonly signaturesRequired: number;\n\n /**\n * Signature for a K-of-N multi-sig transaction.\n * This constructor initializes a multi-signature transaction with the provided signatures and bitmap.\n *\n * @param args An object containing the parameters for the multi-signature transaction.\n * @param args.signatures A list of signatures.\n * @param args.bitmap A bitmap represented as a Uint8Array or an array of numbers, where each bit indicates whether a\n * corresponding signature is present. A maximum of 32 signatures is supported, and the length of the bitmap must be 4 bytes.\n *\n * @throws Error if the number of signatures exceeds the maximum supported, if the bitmap length is incorrect, or if the number\n * of signatures does not match the bitmap.\n * @group Implementation\n * @category Serialization\n */\n // region Constructors\n constructor(args: { publicKeys: Array<PublicKey>; signaturesRequired: number }) {\n const { publicKeys, signaturesRequired } = args;\n super({ publicKeys });\n\n // Validate number of public keys is greater than signature required\n if (signaturesRequired < 1) {\n throw new Error(\"The number of required signatures needs to be greater than 0\");\n }\n\n // Validate number of public keys is greater than signature required\n if (publicKeys.length < signaturesRequired) {\n throw new Error(\n `Provided ${publicKeys.length} public keys is smaller than the ${signaturesRequired} required signatures`,\n );\n }\n\n // Make sure that all keys are normalized to the SingleKey authentication scheme\n this.publicKeys = publicKeys.map((publicKey) =>\n publicKey instanceof AnyPublicKey ? publicKey : new AnyPublicKey(publicKey),\n );\n if (signaturesRequired > MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY) {\n const keylessCount = this.publicKeys.filter(\n (pk) => pk.variant === AnyPublicKeyVariant.Keyless || pk.variant === AnyPublicKeyVariant.FederatedKeyless,\n ).length;\n if (keylessCount > MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY) {\n throw new Error(\n `Construction of MultiKey with more than ${MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY} keyless public keys is not allowed when signaturesRequired \n is greater than ${MAX_NUM_KEYLESS_PUBLIC_FOR_MULTI_KEY}. This is because a maximum of 3 keyless signatures are supported for a \n K-of-N MultiKey transaction.`,\n );\n }\n }\n\n this.signaturesRequired = signaturesRequired;\n }\n\n getSignaturesRequired(): number {\n return this.signaturesRequired;\n }\n\n // endregion\n\n // region AccountPublicKey\n\n /**\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by checking if the signature is valid.\n *\n * Note: This function will fail if a keyless signature is used. Use `verifySignatureAsync` instead.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: { message: HexInput; signature: MultiKeySignature }): boolean {\n const { message, signature } = args;\n if (signature.signatures.length !== this.signaturesRequired) {\n throw new Error(\"The number of signatures does not match the number of required signatures\");\n }\n const signerIndices = signature.bitMapToSignerIndices();\n for (let i = 0; i < signature.signatures.length; i += 1) {\n const singleSignature = signature.signatures[i];\n const publicKey = this.publicKeys[signerIndices[i]];\n if (!publicKey.verifySignature({ message, signature: singleSignature })) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by checking if the signature is valid.\n *\n * @param args - The arguments for verifying the signature.\n * @param args.aptosConfig - The Aptos configuration to use\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify.\n * @group Implementation\n * @category Serialization\n */\n async verifySignatureAsync(args: {\n aptosConfig: AptosConfig;\n message: HexInput;\n signature: Signature;\n options?: { throwErrorWithReason?: boolean };\n }): Promise<boolean> {\n const { signature } = args;\n try {\n if (!(signature instanceof MultiKeySignature)) {\n throw new Error(\"Signature is not a MultiKeySignature\");\n }\n if (signature.signatures.length !== this.signaturesRequired) {\n throw new Error(\"The number of signatures does not match the number of required signatures\");\n }\n const signerIndices = signature.bitMapToSignerIndices();\n for (let i = 0; i < signature.signatures.length; i += 1) {\n const singleSignature = signature.signatures[i];\n const publicKey = this.publicKeys[signerIndices[i]];\n if (!(await publicKey.verifySignatureAsync({ ...args, signature: singleSignature }))) {\n return false;\n }\n }\n return true;\n } catch (error) {\n if (args.options?.throwErrorWithReason) {\n throw error;\n }\n return false;\n }\n }\n\n /**\n * Generates an authentication key based on the current instance's byte representation.\n * This key can be used for secure authentication processes within the system.\n *\n * @returns {AuthenticationKey} The generated authentication key.\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.MultiKey,\n input: this.toUint8Array(),\n });\n }\n\n // endregion\n\n // region Serializable\n\n /**\n * Serializes the object by writing its signatures and bitmap to the provided serializer.\n * This allows the object to be converted into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeVector(this.publicKeys);\n serializer.serializeU8(this.signaturesRequired);\n }\n\n /**\n * Deserializes a MultiKeySignature from the provided deserializer.\n * This function retrieves the signatures and bitmap necessary for creating a MultiKeySignature object.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): MultiKey {\n const keys = deserializer.deserializeVector(AnyPublicKey);\n const signaturesRequired = deserializer.deserializeU8();\n\n return new MultiKey({ publicKeys: keys, signaturesRequired });\n }\n\n // endregion\n\n /**\n * Get the index of the provided public key.\n *\n * This function retrieves the index of a specified public key within the MultiKey.\n * If the public key does not exist, it throws an error.\n *\n * @param publicKey - The public key to find the index for.\n * @returns The corresponding index of the public key, if it exists.\n * @throws Error - If the public key is not found in the MultiKey.\n * @group Implementation\n */\n getIndex(publicKey: PublicKey): number {\n const anyPublicKey = publicKey instanceof AnyPublicKey ? publicKey : new AnyPublicKey(publicKey);\n return super.getIndex(anyPublicKey);\n }\n\n public static isInstance(value: PublicKey): value is MultiKey {\n return \"publicKeys\" in value && \"signaturesRequired\" in value;\n }\n}\n\n/**\n * Represents a multi-signature transaction using Ed25519 signatures.\n * This class allows for the creation and management of a K-of-N multi-signature scheme,\n * where a specified number of signatures are required to authorize a transaction.\n *\n * It includes functionality to validate the number of signatures against a bitmap,\n * which indicates which public keys have signed the transaction.\n * @group Implementation\n * @category Serialization\n */\nexport class MultiKeySignature extends Signature {\n /**\n * Number of bytes in the bitmap representing who signed the transaction (32-bits)\n * @group Implementation\n * @category Serialization\n */\n static BITMAP_LEN: number = 4;\n\n /**\n * Maximum number of Ed25519 signatures supported\n * @group Implementation\n * @category Serialization\n */\n static MAX_SIGNATURES_SUPPORTED = MultiKeySignature.BITMAP_LEN * 8;\n\n /**\n * The list of underlying Ed25519 signatures\n * @group Implementation\n * @category Serialization\n */\n public readonly signatures: AnySignature[];\n\n /**\n * 32-bit Bitmap representing who signed the transaction\n *\n * This is represented where each public key can be masked to determine whether the message was signed by that key.\n * @group Implementation\n * @category Serialization\n */\n public readonly bitmap: Uint8Array;\n\n /**\n * Signature for a K-of-N multi-sig transaction.\n *\n * @see {@link\n * https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}\n *\n * @param args.signatures A list of signatures\n * @param args.bitmap 4 bytes, at most 32 signatures are supported. If Nth bit value is `1`, the Nth\n * signature should be provided in `signatures`. Bits are read from left to right\n * @group Implementation\n * @category Serialization\n */\n constructor(args: { signatures: Array<Signature | AnySignature>; bitmap: Uint8Array | number[] }) {\n super();\n const { signatures, bitmap } = args;\n\n if (signatures.length > MultiKeySignature.MAX_SIGNATURES_SUPPORTED) {\n throw new Error(`The number of signatures cannot be greater than ${MultiKeySignature.MAX_SIGNATURES_SUPPORTED}`);\n }\n\n // Make sure that all signatures are normalized to the SingleKey authentication scheme\n this.signatures = signatures.map((signature) =>\n signature instanceof AnySignature ? signature : new AnySignature(signature),\n );\n\n if (!(bitmap instanceof Uint8Array)) {\n this.bitmap = MultiKeySignature.createBitmap({ bits: bitmap });\n } else if (bitmap.length !== MultiKeySignature.BITMAP_LEN) {\n throw new Error(`\"bitmap\" length should be ${MultiKeySignature.BITMAP_LEN}`);\n } else {\n this.bitmap = bitmap;\n }\n\n const nSignatures = this.bitmap.reduce((acc, byte) => acc + bitCount(byte), 0);\n if (nSignatures !== this.signatures.length) {\n throw new Error(`Expecting ${nSignatures} signatures from the bitmap, but got ${this.signatures.length}`);\n }\n }\n\n /**\n * Helper method to create a bitmap out of the specified bit positions\n * @param args.bits The bitmap positions that should be set. A position starts at index 0.\n * Valid position should range between 0 and 31.\n * @example\n * Here's an example of valid `bits`\n * ```\n * [0, 2, 31]\n * ```\n * `[0, 2, 31]` means the 1st, 3rd and 32nd bits should be set in the bitmap.\n * The result bitmap should be 0b1010000000000000000000000000001\n *\n * @returns bitmap that is 32bit long\n * @group Implementation\n * @category Serialization\n */\n static createBitmap(args: { bits: number[] }): Uint8Array {\n const { bits } = args;\n // Bits are read from left to right. e.g. 0b10000000 represents the first bit is set in one byte.\n // The decimal value of 0b10000000 is 128.\n const firstBitInByte = 128;\n const bitmap = new Uint8Array([0, 0, 0, 0]);\n\n // Check if duplicates exist in bits\n const dupCheckSet = new Set();\n\n bits.forEach((bit: number) => {\n if (bit >= MultiKeySignature.MAX_SIGNATURES_SUPPORTED) {\n throw new Error(`Cannot have a signature larger than ${MultiKeySignature.MAX_SIGNATURES_SUPPORTED - 1}.`);\n }\n\n if (dupCheckSet.has(bit)) {\n throw new Error(\"Duplicate bits detected.\");\n }\n\n dupCheckSet.add(bit);\n\n const byteOffset = Math.floor(bit / 8);\n\n let byte = bitmap[byteOffset];\n\n // eslint-disable-next-line no-bitwise\n byte |= firstBitInByte >> bit % 8;\n\n bitmap[byteOffset] = byte;\n });\n\n return bitmap;\n }\n\n /**\n * Converts the bitmap to an array of signer indices.\n *\n * Example:\n *\n * bitmap: [0b10001000, 0b01000000, 0b00000000, 0b00000000]\n * signerIndices: [0, 4, 9]\n *\n * @returns An array of signer indices.\n * @group Implementation\n * @category Serialization\n */\n bitMapToSignerIndices(): number[] {\n const signerIndices: number[] = [];\n for (let i = 0; i < this.bitmap.length; i += 1) {\n const byte = this.bitmap[i];\n for (let bit = 0; bit < 8; bit += 1) {\n if ((byte & (128 >> bit)) !== 0) {\n signerIndices.push(i * 8 + bit);\n }\n }\n }\n return signerIndices;\n }\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n // Note: we should not need to serialize the vector length, as it can be derived from the bitmap\n serializer.serializeVector(this.signatures);\n serializer.serializeBytes(this.bitmap);\n }\n\n static deserialize(deserializer: Deserializer): MultiKeySignature {\n const signatures = deserializer.deserializeVector(AnySignature);\n const bitmap = deserializer.deserializeBytes();\n return new MultiKeySignature({ signatures, bitmap });\n }\n\n // endregion\n}\n","// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Hex } from \"../hex\";\nimport { HexInput, SigningScheme as AuthenticationKeyScheme, PrivateKeyVariants } from \"../../types\";\nimport { CKDPriv, deriveKey, HARDENED_OFFSET, isValidHardenedPath, mnemonicToSeed, splitPath } from \"./hdKey\";\nimport { PrivateKey } from \"./privateKey\";\nimport { AccountPublicKey, PublicKey, VerifySignatureArgs, VerifySignatureAsyncArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { convertSigningMessage } from \"./utils\";\n\n/**\n * L is the value that greater than or equal to will produce a non-canonical signature, and must be rejected\n * @group Implementation\n * @category Serialization\n */\nconst L: number[] = [\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\n];\n\n/**\n * Checks if an ED25519 signature is non-canonical.\n * This function helps determine the validity of a signature by verifying its canonical form.\n *\n * @param signature - The signature to be checked for canonicality.\n * @returns A boolean indicating whether the signature is non-canonical.\n *\n * Comes from Aptos Core\n * https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-crypto/src/ed25519/ed25519_sigs.rs#L47-L85\n * @group Implementation\n * @category Serialization\n */\nexport function isCanonicalEd25519Signature(signature: Signature): boolean {\n const s = signature.toUint8Array().slice(32);\n for (let i = L.length - 1; i >= 0; i -= 1) {\n if (s[i] < L[i]) {\n return true;\n }\n if (s[i] > L[i]) {\n return false;\n }\n }\n // As this stage S == L which implies a non-canonical S.\n return false;\n}\n\n/**\n * Represents the public key of an Ed25519 key pair.\n *\n * Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports\n * `Legacy` and `Unified` authentication keys.\n *\n * Ed25519 scheme is represented in the SDK as `Legacy authentication key` and also\n * as `AnyPublicKey` that represents any `Unified authentication key`.\n * @group Implementation\n * @category Serialization\n */\nexport class Ed25519PublicKey extends AccountPublicKey {\n /**\n * Length of an Ed25519 public key\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH: number = 32;\n\n /**\n * Bytes of the public key\n * @private\n * @group Implementation\n * @category Serialization\n */\n private readonly key: Hex;\n\n /**\n * Creates an instance of the Ed25519Signature class from a hex input.\n * This constructor validates the length of the signature to ensure it meets the required specifications.\n *\n * @param hexInput - The hex input representing the Ed25519 signature.\n * @throws Error if the signature length is not equal to Ed25519Signature.LENGTH.\n * @group Implementation\n * @category Serialization\n */\n constructor(hexInput: HexInput) {\n super();\n\n const hex = Hex.fromHexInput(hexInput);\n if (hex.toUint8Array().length !== Ed25519PublicKey.LENGTH) {\n throw new Error(`PublicKey length should be ${Ed25519PublicKey.LENGTH}`);\n }\n this.key = hex;\n }\n\n // region AccountPublicKey\n\n /**\n * Verifies a signed message using a public key.\n *\n * @param args - The arguments for verification.\n * @param args.message - A signed message as a Hex string or Uint8Array.\n * @param args.signature - The signature of the message.\n * @group Implementation\n * @category Serialization\n */\n verifySignature(args: VerifySignatureArgs): boolean {\n const { message, signature } = args;\n // Verify malleability\n if (!isCanonicalEd25519Signature(signature)) {\n return false;\n }\n\n const messageToVerify = convertSigningMessage(message);\n const messageBytes = Hex.fromHexInput(messageToVerify).toUint8Array();\n const signatureBytes = signature.toUint8Array();\n const publicKeyBytes = this.key.toUint8Array();\n return ed25519.verify(signatureBytes, messageBytes, publicKeyBytes);\n }\n\n /**\n * Note: Ed25519Signatures can be verified syncronously.\n *\n * Verifies the provided signature against the given message.\n * This function helps ensure the integrity and authenticity of the message by confirming that the signature is valid.\n *\n * @param args - The arguments for signature verification.\n * @param args.aptosConfig - The configuration object for connecting to the Aptos network\n * @param args.message - The message that was signed.\n * @param args.signature - The signature to verify, which must be an instance of Secp256k1Signature.\n * @returns A boolean indicating whether the signature is valid for the given message.\n * @group Implementation\n * @category Serialization\n */\n async verifySignatureAsync(args: VerifySignatureAsyncArgs): Promise<boolean> {\n return this.verifySignature(args);\n }\n\n /**\n * Generates an authentication key from the public key using the Ed25519 scheme.\n * This function is essential for creating a secure authentication key that can be used for further cryptographic operations.\n *\n * @returns {AuthenticationKey} The generated authentication key.\n * @group Implementation\n * @category Serialization\n */\n authKey(): AuthenticationKey {\n return AuthenticationKey.fromSchemeAndBytes({\n scheme: AuthenticationKeyScheme.Ed25519,\n input: this.toUint8Array(),\n });\n }\n\n /**\n * Convert the internal data representation to a Uint8Array.\n *\n * @returns Uint8Array representation of the data.\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.key.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n /**\n * Serializes the data into a byte array using the provided serializer.\n * This allows for the conversion of data into a format suitable for transmission or storage.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Serialization\n */\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.key.toUint8Array());\n }\n\n /**\n * Deserialize bytes into an Ed25519Signature object.\n * This function is used to convert serialized byte data into a usable Ed25519Signature instance.\n *\n * @param deserializer - The deserializer instance used to read the byte data.\n * @group Implementation\n * @category Serialization\n */\n static deserialize(deserializer: Deserializer): Ed25519PublicKey {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519PublicKey(bytes);\n }\n\n // endregion\n\n /**\n * Determine if the provided public key is an instance of Ed25519PublicKey.\n *\n * @param publicKey - The public key to check.\n * @returns True if the public key is an instance of Ed25519PublicKey, otherwise false.\n * @deprecated use `instanceof Ed25519PublicKey` instead.\n * @group Implementation\n * @category Serialization\n */\n static isPublicKey(publicKey: AccountPublicKey): publicKey is Ed25519PublicKey {\n return publicKey instanceof Ed25519PublicKey;\n }\n\n /**\n * Determines if the provided public key is a valid Ed25519 public key.\n * This function checks for the presence of the \"key\" property and verifies that its data length matches the expected length\n * for Ed25519 public keys.\n *\n * @param publicKey - The public key to validate.\n * @returns A boolean indicating whether the public key is a valid Ed25519 public key.\n * @group Implementation\n * @category Serialization\n */\n static isInstance(publicKey: PublicKey): publicKey is Ed25519PublicKey {\n return \"key\" in publicKey && (publicKey.key as any)?.data?.length === Ed25519PublicKey.LENGTH;\n }\n}\n\n/**\n * Represents the private key of an Ed25519 key pair.\n * @group Implementation\n * @category Serialization\n */\nexport class Ed25519PrivateKey extends Serializable implements PrivateKey {\n /**\n * Length of an Ed25519 private key\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH: number = 32;\n\n /**\n * The Ed25519 key seed to use for BIP-32 compatibility\n * See more {@link https://github.com/satoshilabs/slips/blob/master/slip-0010.md}\n * @group Implementation\n * @category Serialization\n */\n static readonly SLIP_0010_SEED = \"ed25519 seed\";\n\n /**\n * The Ed25519 signing key\n * @private\n * @group Implementation\n * @category Serialization\n */\n private readonly signingKey: Hex;\n\n // region Constructors\n\n /**\n * Create a new PrivateKey instance from a Uint8Array or String.\n *\n * [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)\n *\n * @param hexInput HexInput (string or Uint8Array)\n * @param strict If true, private key must AIP-80 compliant.\n * @group Implementation\n * @category Serialization\n */\n constructor(hexInput: HexInput, strict?: boolean) {\n super();\n\n const privateKeyHex = PrivateKey.parseHexInput(hexInput, PrivateKeyVariants.Ed25519, strict);\n if (privateKeyHex.toUint8Array().length !== Ed25519PrivateKey.LENGTH) {\n throw new Error(`PrivateKey length should be ${Ed25519PrivateKey.LENGTH}`);\n }\n\n // Create keyPair from Private key in Uint8Array format\n this.signingKey = privateKeyHex;\n }\n\n /**\n * Generate a new random private key.\n *\n * @returns Ed25519PrivateKey A newly generated Ed25519 private key.\n * @group Implementation\n * @category Serialization\n */\n static generate(): Ed25519PrivateKey {\n const keyPair = ed25519.utils.randomPrivateKey();\n return new Ed25519PrivateKey(keyPair, false);\n }\n\n /**\n * Derives a private key from a mnemonic seed phrase using a specified BIP44 path.\n * To derive multiple keys from the same phrase, change the path\n *\n * IMPORTANT: Ed25519 supports hardened derivation only, as it lacks a key homomorphism, making non-hardened derivation impossible.\n *\n * @param path - The BIP44 path used for key derivation.\n * @param mnemonics - The mnemonic seed phrase from which the key will be derived.\n * @throws Error if the provided path is not a valid hardened path.\n * @group Implementation\n * @category Serialization\n */\n static fromDerivationPath(path: string, mnemonics: string): Ed25519PrivateKey {\n if (!isValidHardenedPath(path)) {\n throw new Error(`Invalid derivation path ${path}`);\n }\n return Ed25519PrivateKey.fromDerivationPathInner(path, mnemonicToSeed(mnemonics));\n }\n\n /**\n * Derives a child private key from a given BIP44 path and seed.\n * A private inner function so we can separate from the main fromDerivationPath() method\n * to add tests to verify we create the keys correctly.\n *\n * @param path - The BIP44 path used for key derivation.\n * @param seed - The seed phrase created by the mnemonics, represented as a Uint8Array.\n * @param offset - The offset used for key derivation, defaults to HARDENED_OFFSET.\n * @returns An instance of Ed25519PrivateKey derived from the specified path and seed.\n * @group Implementation\n * @category Serialization\n */\n private static fromDerivationPathInner(path: string, seed: Uint8Array, offset = HARDENED_OFFSET): Ed25519PrivateKey {\n const { key, chainCode } = deriveKey(Ed25519PrivateKey.SLIP_0010_SEED, seed);\n\n const segments = splitPath(path).map((el) => parseInt(el, 10));\n\n // Derive the child key based on the path\n const { key: privateKey } = segments.reduce((parentKeys, segment) => CKDPriv(parentKeys, segment + offset), {\n key,\n chainCode,\n });\n return new Ed25519PrivateKey(privateKey, false);\n }\n\n // endregion\n\n // region PrivateKey\n\n /**\n * Derive the Ed25519PublicKey for this private key.\n *\n * @returns Ed25519PublicKey - The derived public key corresponding to the private key.\n * @group Implementation\n * @category Serialization\n */\n publicKey(): Ed25519PublicKey {\n const bytes = ed25519.getPublicKey(this.signingKey.toUint8Array());\n return new Ed25519PublicKey(bytes);\n }\n\n /**\n * Sign the given message with the private key.\n * This function generates a digital signature for the specified message, ensuring its authenticity and integrity.\n *\n * @param message - A message as a string or Uint8Array in HexInput format.\n * @returns A digital signature for the provided message.\n * @group Implementation\n * @category Serialization\n */\n sign(message: HexInput): Ed25519Signature {\n const messageToSign = convertSigningMessage(message);\n const messageBytes = Hex.fromHexInput(messageToSign).toUint8Array();\n const signatureBytes = ed25519.sign(messageBytes, this.signingKey.toUint8Array());\n return new Ed25519Signature(signatureBytes);\n }\n\n /**\n * Get the private key in bytes (Uint8Array).\n *\n * @returns Uint8Array representation of the private key\n * @group Implementation\n * @category Serialization\n */\n toUint8Array(): Uint8Array {\n return this.signingKey.toUint8Array();\n }\n\n /**\n * Get the private key as a hex string with the 0x prefix.\n *\n * @returns string representation of the private key.\n * @group Implementation\n * @category Serialization\n */\n toString(): string {\n return this.toAIP80String();\n }\n\n /**\n * Get the private key as a hex string with the 0x prefix.\n *\n * @returns string representation of the private key.\n */\n toHexString(): string {\n return this.signingKey.toString();\n }\n\n /**\n * Get the private key as a AIP-80 compliant hex string.\n *\n * [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)\n *\n * @returns AIP-80 compliant string representation of the private key.\n */\n toAIP80String(): string {\n return PrivateKey.formatPrivateKey(this.signingKey.toString(), PrivateKeyVariants.Ed25519);\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Ed25519PrivateKey {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519PrivateKey(bytes, false);\n }\n\n // endregion\n\n /**\n * Determines if the provided private key is an instance of Ed25519PrivateKey.\n *\n * @param privateKey - The private key to check.\n * @returns A boolean indicating whether the private key is an Ed25519PrivateKey.\n *\n * @deprecated Use `instanceof Ed25519PrivateKey` instead.\n * @group Implementation\n * @category Serialization\n */\n static isPrivateKey(privateKey: PrivateKey): privateKey is Ed25519PrivateKey {\n return privateKey instanceof Ed25519PrivateKey;\n }\n}\n\n/**\n * Represents a signature of a message signed using an Ed25519 private key.\n * @group Implementation\n * @category Serialization\n */\nexport class Ed25519Signature extends Signature {\n /**\n * Length of an Ed25519 signature, which is 64 bytes.\n * @group Implementation\n * @category Serialization\n */\n static readonly LENGTH = 64;\n\n /**\n * The signature bytes\n * @private\n * @group Implementation\n * @category Serialization\n */\n private readonly data: Hex;\n\n // region Constructors\n\n constructor(hexInput: HexInput) {\n super();\n const data = Hex.fromHexInput(hexInput);\n if (data.toUint8Array().length !== Ed25519Signature.LENGTH) {\n throw new Error(`Signature length should be ${Ed25519Signature.LENGTH}`);\n }\n this.data = data;\n }\n\n // endregion\n\n // region Signature\n\n toUint8Array(): Uint8Array {\n return this.data.toUint8Array();\n }\n\n // endregion\n\n // region Serializable\n\n serialize(serializer: Serializer): void {\n serializer.serializeBytes(this.data.toUint8Array());\n }\n\n static deserialize(deserializer: Deserializer): Ed25519Signature {\n const bytes = deserializer.deserializeBytes();\n return new Ed25519Signature(bytes);\n }\n\n // endregion\n}\n","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 TypeTagI8,\n TypeTagI16,\n TypeTagI32,\n TypeTagI64,\n TypeTagI128,\n TypeTagI256,\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 case \"i8\":\n case \"i16\":\n case \"i32\":\n case \"i64\":\n case \"i128\":\n case \"i256\":\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 \"i8\":\n return new TypeTagI8();\n case \"i16\":\n return new TypeTagI16();\n case \"i32\":\n return new TypeTagI32();\n case \"i64\":\n return new TypeTagI64();\n case \"i128\":\n return new TypeTagI128();\n case \"i256\":\n return new TypeTagI256();\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"]}
1
+ {"version":3,"sources":["/Users/kent/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/transactionBuilder/remoteAbi.ts"],"names":["Deserializer","_Deserializer","data","hex","Hex","length","bytes","value","type","len","bool","low","high","unsigned","signBit","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","I8","_I8","MIN_I8_NUMBER","MAX_I8_NUMBER","I16","_I16","MIN_I16_NUMBER","MAX_I16_NUMBER","I32","_I32","MIN_I32_NUMBER","MAX_I32_NUMBER","I64","_I64","MIN_I64_BIG_INT","MAX_I64_BIG_INT","I128","_I128","MIN_I128_BIG_INT","MAX_I128_BIG_INT","I256","_I256","MIN_I256_BIG_INT","MAX_I256_BIG_INT","MoveVector","_MoveVector","values","Serialized","numbers","v","MoveString","i","_Serialized","vec","_MoveString","fixedStringBytes","MoveOption","_MoveOption","_AuthenticationKey","args","negY"],"mappings":"AAAA,2sCAA2uB,IC6C9tBA,CAAAA,CAAN,MAAMC,CAAa,CAaxB,WAAA,CAAYC,CAAAA,CAAkB,CAE5B,IAAA,CAAK,MAAA,CAAS,IAAI,WAAA,CAAYA,CAAAA,CAAK,MAAM,CAA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AAA;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;ACjUyC,IAAA","file":"/Users/kent/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 an 8-bit signed integer from the binary data.\n * BCS layout for \"int8\": One byte. Binary format in little-endian representation.\n *\n * @returns {number} The deserialized int8 number.\n * @group Implementation\n * @category BCS\n */\n deserializeI8(): number {\n return new DataView(this.read(1)).getInt8(0);\n }\n\n /**\n * Deserializes a 16-bit signed integer from a binary format in little-endian representation.\n * BCS layout for \"int16\": Two bytes.\n *\n * @returns {number} The deserialized int16 number.\n * @group Implementation\n * @category BCS\n */\n deserializeI16(): number {\n return new DataView(this.read(2)).getInt16(0, true);\n }\n\n /**\n * Deserializes a 32-bit signed integer from a binary format in little-endian representation.\n * BCS layout for \"int32\": Four bytes.\n *\n * @returns {number} The deserialized int32 number.\n * @group Implementation\n * @category BCS\n */\n deserializeI32(): number {\n return new DataView(this.read(4)).getInt32(0, true);\n }\n\n /**\n * Deserializes a 64-bit signed integer.\n * This function combines two 32-bit values to return a 64-bit signed integer in little-endian representation.\n *\n * @returns {bigint} The deserialized int64 number.\n * @group Implementation\n * @category BCS\n */\n deserializeI64(): bigint {\n const low = this.deserializeU32();\n const high = this.deserializeU32();\n\n // combine the two 32-bit values (little endian)\n const unsigned = BigInt((BigInt(high) << BigInt(32)) | BigInt(low));\n\n // Convert from unsigned to signed using two's complement\n const signBit = BigInt(1) << BigInt(63);\n if (unsigned >= signBit) {\n return unsigned - (BigInt(1) << BigInt(64));\n }\n return unsigned;\n }\n\n /**\n * Deserializes a 128-bit signed integer from its binary representation.\n * This function combines two 64-bit values to return a single int128 value in little-endian format.\n *\n * @returns {bigint} The deserialized int128 number.\n * @group Implementation\n * @category BCS\n */\n deserializeI128(): bigint {\n const low = this.deserializeU64();\n const high = this.deserializeU64();\n\n // combine the two 64-bit values (little endian)\n const unsigned = BigInt((high << BigInt(64)) | low);\n\n // Convert from unsigned to signed using two's complement\n const signBit = BigInt(1) << BigInt(127);\n if (unsigned >= signBit) {\n return unsigned - (BigInt(1) << BigInt(128));\n }\n return unsigned;\n }\n\n /**\n * Deserializes a 256-bit signed integer from its binary representation.\n * BCS layout for \"int256\": Thirty-two bytes in little-endian format.\n *\n * @returns {bigint} The deserialized int256 number.\n * @group Implementation\n * @category BCS\n */\n deserializeI256(): bigint {\n const low = this.deserializeU128();\n const high = this.deserializeU128();\n\n // combine the two 128-bit values (little endian)\n const unsigned = BigInt((high << BigInt(128)) | low);\n\n // Convert from unsigned to signed using two's complement\n const signBit = BigInt(1) << BigInt(255);\n if (unsigned >= signBit) {\n return unsigned - (BigInt(1) << BigInt(256));\n }\n return unsigned;\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 MIN_I8_NUMBER,\n MAX_I8_NUMBER,\n MIN_I16_NUMBER,\n MAX_I16_NUMBER,\n MIN_I32_NUMBER,\n MAX_I32_NUMBER,\n MIN_I64_BIG_INT,\n MAX_I64_BIG_INT,\n MIN_I128_BIG_INT,\n MAX_I128_BIG_INT,\n MIN_I256_BIG_INT,\n MAX_I256_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, Int8, Int16, Int32, 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\n/**\n * Represents an 8-bit signed integer (I8) value.\n * This class extends the Serializable class and provides methods for serialization and deserialization of I8 values.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class I8 extends Serializable implements TransactionArgument {\n public readonly value: Int8;\n\n constructor(value: Int8) {\n super();\n validateNumberInRange(value, MIN_I8_NUMBER, MAX_I8_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeI8(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 // Note: Script functions don't have variants for signed integers yet\n // This will serialize as bytes\n const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n static deserialize(deserializer: Deserializer): I8 {\n return new I8(deserializer.deserializeI8());\n }\n}\n\n/**\n * Represents a 16-bit signed integer (I16) value.\n * This class extends the Serializable class and provides methods for serialization\n * and deserialization of the I16 value.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class I16 extends Serializable implements TransactionArgument {\n public readonly value: Int16;\n\n constructor(value: Int16) {\n super();\n validateNumberInRange(value, MIN_I16_NUMBER, MAX_I16_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeI16(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 const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n static deserialize(deserializer: Deserializer): I16 {\n return new I16(deserializer.deserializeI16());\n }\n}\n\n/**\n * Represents a 32-bit signed integer (I32) that can be serialized and deserialized.\n * This class ensures that the value is within the valid range for an I32.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class I32 extends Serializable implements TransactionArgument {\n public readonly value: Int32;\n\n constructor(value: Int32) {\n super();\n validateNumberInRange(value, MIN_I32_NUMBER, MAX_I32_NUMBER);\n this.value = value;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeI32(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 const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n static deserialize(deserializer: Deserializer): I32 {\n return new I32(deserializer.deserializeI32());\n }\n}\n\n/**\n * Represents a 64-bit signed integer (I64) and provides methods for serialization.\n *\n * This class ensures that the value is within the valid range for an I64 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 I64 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, MIN_I64_BIG_INT, MAX_I64_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeI64(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 const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n static deserialize(deserializer: Deserializer): I64 {\n return new I64(deserializer.deserializeI64());\n }\n}\n\n/**\n * Represents a 128-bit signed integer value.\n * This class provides methods for serialization and deserialization\n * of I128 values, ensuring that the values are within the valid range.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class I128 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, MIN_I128_BIG_INT, MAX_I128_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeI128(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 const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n static deserialize(deserializer: Deserializer): I128 {\n return new I128(deserializer.deserializeI128());\n }\n}\n\n/**\n * Represents a 256-bit signed integer (I256) that extends the Serializable class.\n * This class provides methods for serialization and deserialization of I256 values,\n * ensuring that the values are within the valid range.\n *\n * @extends Serializable\n * @group Implementation\n * @category BCS\n */\nexport class I256 extends Serializable implements TransactionArgument {\n public readonly value: bigint;\n\n constructor(value: AnyNumber) {\n super();\n validateNumberInRange(value, MIN_I256_BIG_INT, MAX_I256_BIG_INT);\n this.value = BigInt(value);\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeI256(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 const bcsBytes = this.bcsToBytes();\n serializer.serializeBytes(bcsBytes);\n }\n\n static deserialize(deserializer: Deserializer): I256 {\n return new I256(deserializer.deserializeI256());\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 { AASigningDataVariant, AbstractAuthenticationDataVariant } from \"../../types/abstraction\";\nimport { AccountAddress, Hex } from \"../../core\";\nimport { getFunctionParts, isValidFunctionInfo } from \"../../utils/helpers\";\n\n/**\n * Represents an account authenticator that can handle multiple authentication variants.\n * This class serves as a base for different types of account authenticators, allowing for serialization\n * and deserialization of various authenticator types.\n *\n * @extends Serializable\n * @group Implementation\n * @category Transactions\n */\nexport abstract class AccountAuthenticator extends Serializable {\n abstract serialize(serializer: Serializer): void;\n\n /**\n * Deserializes an AccountAuthenticator from the provided deserializer.\n * This function helps in reconstructing the AccountAuthenticator object based on the variant index.\n *\n * @param deserializer - The deserializer instance used to read the serialized data.\n * @group Implementation\n * @category Transactions\n */\n static deserialize(deserializer: Deserializer): AccountAuthenticator {\n const index = deserializer.deserializeUleb128AsU32();\n switch (index) {\n case AccountAuthenticatorVariant.Ed25519:\n return AccountAuthenticatorEd25519.load(deserializer);\n case AccountAuthenticatorVariant.MultiEd25519:\n return AccountAuthenticatorMultiEd25519.load(deserializer);\n case AccountAuthenticatorVariant.SingleKey:\n return AccountAuthenticatorSingleKey.load(deserializer);\n case AccountAuthenticatorVariant.MultiKey:\n return AccountAuthenticatorMultiKey.load(deserializer);\n case AccountAuthenticatorVariant.NoAccountAuthenticator:\n return AccountAuthenticatorNoAccountAuthenticator.load(deserializer);\n case AccountAuthenticatorVariant.Abstraction:\n return AccountAuthenticatorAbstraction.load(deserializer);\n default:\n throw new Error(`Unknown variant index for AccountAuthenticator: ${index}`);\n }\n }\n\n /**\n * Determines if the current instance is an Ed25519 account authenticator.\n *\n * @returns {boolean} True if the instance is of type AccountAuthenticatorEd25519, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isEd25519(): this is AccountAuthenticatorEd25519 {\n return this instanceof AccountAuthenticatorEd25519;\n }\n\n /**\n * Determines if the current instance is of type AccountAuthenticatorMultiEd25519.\n *\n * @returns {boolean} True if the instance is a multi-signature Ed25519 account authenticator, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isMultiEd25519(): this is AccountAuthenticatorMultiEd25519 {\n return this instanceof AccountAuthenticatorMultiEd25519;\n }\n\n /**\n * Determines if the current instance is of the type AccountAuthenticatorSingleKey.\n *\n * @returns {boolean} True if the instance is an AccountAuthenticatorSingleKey, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isSingleKey(): this is AccountAuthenticatorSingleKey {\n return this instanceof AccountAuthenticatorSingleKey;\n }\n\n /**\n * Determine if the current instance is of type AccountAuthenticatorMultiKey.\n *\n * @returns {boolean} Returns true if the instance is an AccountAuthenticatorMultiKey, otherwise false.\n * @group Implementation\n * @category Transactions\n */\n isMultiKey(): this is AccountAuthenticatorMultiKey {\n return this instanceof AccountAuthenticatorMultiKey;\n }\n}\n\n/**\n * Represents an Ed25519 transaction authenticator for multi-signer transactions.\n * This class encapsulates the account's Ed25519 public key and signature.\n *\n * @param public_key - The Ed25519 public key associated with the account.\n * @param signature - The Ed25519 signature for the account.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorEd25519 extends AccountAuthenticator {\n public readonly public_key: Ed25519PublicKey;\n\n public readonly signature: Ed25519Signature;\n\n /**\n * Creates an instance of the class with the specified public keys and signatures.\n *\n * @param public_key The public key used for verification.\n * @param signature The signatures corresponding to the public keys.\n * @group Implementation\n * @category Transactions\n */\n constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n /**\n * Serializes the account authenticator data into the provided serializer.\n * This function captures the multi-key variant, public keys, and signatures for serialization.\n *\n * @param serializer - The serializer instance used to perform the serialization.\n * @group Implementation\n * @category Transactions\n */\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.Ed25519);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n /**\n * Loads an instance of AccountAuthenticatorMultiKey from the provided deserializer.\n * This function helps in reconstructing the authenticator object using the deserialized public keys and signatures.\n *\n * @param deserializer - The deserializer used to extract the necessary data for loading the authenticator.\n * @group Implementation\n * @category Transactions\n */\n static load(deserializer: Deserializer): AccountAuthenticatorEd25519 {\n const public_key = Ed25519PublicKey.deserialize(deserializer);\n const signature = Ed25519Signature.deserialize(deserializer);\n return new AccountAuthenticatorEd25519(public_key, signature);\n }\n}\n\n/**\n * Represents a transaction authenticator for Multi Ed25519, designed for multi-signer transactions.\n *\n * @param public_key - The MultiEd25519 public key of the account.\n * @param signature - The MultiEd25519 signature of the account.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorMultiEd25519 extends AccountAuthenticator {\n public readonly public_key: MultiEd25519PublicKey;\n\n public readonly signature: MultiEd25519Signature;\n\n constructor(public_key: MultiEd25519PublicKey, signature: MultiEd25519Signature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.MultiEd25519);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorMultiEd25519 {\n const public_key = MultiEd25519PublicKey.deserialize(deserializer);\n const signature = MultiEd25519Signature.deserialize(deserializer);\n return new AccountAuthenticatorMultiEd25519(public_key, signature);\n }\n}\n\n/**\n * Represents an account authenticator that utilizes a single key for signing.\n * This class is designed to handle authentication using a public key and its corresponding signature.\n *\n * @param public_key - The public key used for authentication.\n * @param signature - The signature associated with the public key.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorSingleKey extends AccountAuthenticator {\n public readonly public_key: AnyPublicKey;\n\n public readonly signature: AnySignature;\n\n constructor(public_key: AnyPublicKey, signature: AnySignature) {\n super();\n this.public_key = public_key;\n this.signature = signature;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.SingleKey);\n this.public_key.serialize(serializer);\n this.signature.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorSingleKey {\n const public_key = AnyPublicKey.deserialize(deserializer);\n const signature = AnySignature.deserialize(deserializer);\n return new AccountAuthenticatorSingleKey(public_key, signature);\n }\n}\n\n/**\n * Represents an account authenticator that supports multiple keys and signatures for multi-signature scenarios.\n *\n * @param public_keys - The public keys used for authentication.\n * @param signatures - The signatures corresponding to the public keys.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorMultiKey extends AccountAuthenticator {\n public readonly public_keys: MultiKey;\n\n public readonly signatures: MultiKeySignature;\n\n constructor(public_keys: MultiKey, signatures: MultiKeySignature) {\n super();\n this.public_keys = public_keys;\n this.signatures = signatures;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.MultiKey);\n this.public_keys.serialize(serializer);\n this.signatures.serialize(serializer);\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorMultiKey {\n const public_keys = MultiKey.deserialize(deserializer);\n const signatures = MultiKeySignature.deserialize(deserializer);\n return new AccountAuthenticatorMultiKey(public_keys, signatures);\n }\n}\n\n/**\n * AccountAuthenticatorNoAccountAuthenticator for no account authenticator\n * It represents the absence of a public key for transaction simulation.\n * It allows skipping the public/auth key check during the simulation.\n */\nexport class AccountAuthenticatorNoAccountAuthenticator extends AccountAuthenticator {\n // eslint-disable-next-line class-methods-use-this\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.NoAccountAuthenticator);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static load(deserializer: Deserializer): AccountAuthenticatorNoAccountAuthenticator {\n return new AccountAuthenticatorNoAccountAuthenticator();\n }\n}\n\n/**\n * Represents an account authenticator that supports abstract authentication.\n *\n * @param functionInfo - The function info of the authentication function.\n * @param signingMessageDigest - The digest of the signing message.\n * @param abstractionSignature - The signature of the authentication function.\n * @param accountIdentity - optional. The account identity for DAA.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAuthenticatorAbstraction extends AccountAuthenticator {\n public readonly functionInfo: string;\n\n public readonly signingMessageDigest: Hex;\n\n public readonly abstractionSignature: Uint8Array;\n\n /**\n * DAA, which is extended of the AA module, requires an account identity\n */\n public readonly accountIdentity?: Uint8Array;\n\n constructor(\n functionInfo: string,\n signingMessageDigest: HexInput,\n abstractionSignature: Uint8Array,\n accountIdentity?: Uint8Array,\n ) {\n super();\n if (!isValidFunctionInfo(functionInfo)) {\n throw new Error(`Invalid function info ${functionInfo} passed into AccountAuthenticatorAbstraction`);\n }\n this.functionInfo = functionInfo;\n this.abstractionSignature = abstractionSignature;\n this.signingMessageDigest = Hex.fromHexInput(Hex.fromHexInput(signingMessageDigest).toUint8Array());\n this.accountIdentity = accountIdentity;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AccountAuthenticatorVariant.Abstraction);\n const { moduleAddress, moduleName, functionName } = getFunctionParts(this.functionInfo as MoveFunctionId);\n AccountAddress.fromString(moduleAddress).serialize(serializer);\n serializer.serializeStr(moduleName);\n serializer.serializeStr(functionName);\n if (this.accountIdentity) {\n serializer.serializeU32AsUleb128(AbstractAuthenticationDataVariant.DerivableV1);\n } else {\n serializer.serializeU32AsUleb128(AbstractAuthenticationDataVariant.V1);\n }\n serializer.serializeBytes(this.signingMessageDigest.toUint8Array());\n if (this.accountIdentity) {\n serializer.serializeBytes(this.abstractionSignature);\n } else {\n serializer.serializeFixedBytes(this.abstractionSignature);\n }\n\n if (this.accountIdentity) {\n serializer.serializeBytes(this.accountIdentity);\n }\n }\n\n static load(deserializer: Deserializer): AccountAuthenticatorAbstraction {\n // deserialize the function info\n const moduleAddress = AccountAddress.deserialize(deserializer);\n const moduleName = deserializer.deserializeStr();\n const functionName = deserializer.deserializeStr();\n // deserialize the variant\n const variant = deserializer.deserializeUleb128AsU32();\n // deserialize the signing message digest\n const signingMessageDigest = deserializer.deserializeBytes();\n\n if (variant === AbstractAuthenticationDataVariant.V1) {\n const abstractionSignature = deserializer.deserializeFixedBytes(deserializer.remaining());\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n abstractionSignature,\n );\n }\n if (variant === AbstractAuthenticationDataVariant.DerivableV1) {\n const abstractionSignature = deserializer.deserializeBytes();\n const abstractPublicKey = deserializer.deserializeBytes();\n return new AccountAuthenticatorAbstraction(\n `${moduleAddress}::${moduleName}::${functionName}`,\n signingMessageDigest,\n abstractionSignature,\n abstractPublicKey,\n );\n }\n throw new Error(`Unknown variant index for AccountAuthenticatorAbstraction: ${variant}`);\n }\n}\n\n/**\n * Represents an account abstraction message that contains the original signing message and the function info.\n *\n * @param originalSigningMessage - The original signing message.\n * @param functionInfo - The function info of the authentication function.\n * @group Implementation\n * @category Transactions\n */\nexport class AccountAbstractionMessage extends Serializable {\n public readonly originalSigningMessage: Hex;\n\n public readonly functionInfo: string;\n\n constructor(originalSigningMessage: HexInput, functionInfo: string) {\n super();\n this.originalSigningMessage = Hex.fromHexInput(Hex.fromHexInput(originalSigningMessage).toUint8Array());\n this.functionInfo = functionInfo;\n }\n\n serialize(serializer: Serializer): void {\n serializer.serializeU32AsUleb128(AASigningDataVariant.V1);\n serializer.serializeBytes(this.originalSigningMessage.toUint8Array());\n const { moduleAddress, moduleName, functionName } = getFunctionParts(this.functionInfo as MoveFunctionId);\n AccountAddress.fromString(moduleAddress).serialize(serializer);\n serializer.serializeStr(moduleName);\n serializer.serializeStr(functionName);\n }\n\n static deserialize(deserializer: Deserializer): AccountAbstractionMessage {\n const variant = deserializer.deserializeUleb128AsU32();\n if (variant !== AASigningDataVariant.V1) {\n throw new Error(`Unknown variant index for AccountAbstractionMessage: ${variant}`);\n }\n const originalSigningMessage = deserializer.deserializeBytes();\n const functionInfoModuleAddress = AccountAddress.deserialize(deserializer);\n const functionInfoModuleName = deserializer.deserializeStr();\n const functionInfoFunctionName = deserializer.deserializeStr();\n const functionInfo = `${functionInfoModuleAddress}::${functionInfoModuleName}::${functionInfoFunctionName}`;\n return new AccountAbstractionMessage(originalSigningMessage, functionInfo);\n }\n}\n","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 { parseTypeTag } from \"../typeTag/parser\";\nimport {\n TypeTag,\n TypeTagAddress,\n TypeTagBool,\n TypeTagStruct,\n TypeTagU128,\n TypeTagU16,\n TypeTagU256,\n TypeTagU32,\n TypeTagU64,\n TypeTagU8,\n} from \"../typeTag\";\nimport { AptosConfig } from \"../../api/aptosConfig\";\nimport {\n EntryFunctionArgumentTypes,\n SimpleEntryFunctionArgumentTypes,\n EntryFunctionABI,\n ViewFunctionABI,\n FunctionABI,\n TypeArgument,\n} from \"../types\";\nimport { Bool, FixedBytes, MoveOption, MoveString, MoveVector, U128, U16, U256, U32, U64, U8 } from \"../../bcs\";\nimport { AccountAddress } from \"../../core\";\nimport { getModule } from \"../../internal/account\";\nimport {\n findFirstNonSignerArg,\n isBcsAddress,\n isBcsBool,\n isBcsString,\n isBcsU128,\n isBcsU16,\n isBcsU256,\n isBcsU32,\n isBcsU64,\n isBcsU8,\n isBool,\n isEncodedEntryFunctionArgument,\n isLargeNumber,\n isEmptyOption,\n isString,\n throwTypeMismatch,\n convertNumber,\n} from \"./helpers\";\nimport { MoveFunction, MoveModule } from \"../../types\";\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * Convert type arguments to only type tags, allowing for string representations of type tags.\n *\n * @param typeArguments - An optional array of type arguments that may include string representations.\n * @returns An array of TypeTag objects derived from the provided type arguments.\n * @group Implementation\n * @category Transactions\n */\nexport function standardizeTypeTags(typeArguments?: Array<TypeArgument>): Array<TypeTag> {\n return (\n typeArguments?.map((typeArg: TypeArgument): TypeTag => {\n // Convert to TypeTag if it's a string representation\n if (isString(typeArg)) {\n return parseTypeTag(typeArg);\n }\n return typeArg;\n }) ?? []\n );\n}\n\n/**\n * Fetches the ABI of a specified module from the on-chain module ABI.\n *\n * @param moduleAddress - The address of the module from which to fetch the ABI.\n * @param moduleName - The name of the module containing the ABI.\n * @param aptosConfig - The configuration settings for Aptos.\n * @group Implementation\n * @category Transactions\n */\nexport async function fetchModuleAbi(\n moduleAddress: string,\n moduleName: string,\n aptosConfig: AptosConfig,\n): Promise<MoveModule | undefined> {\n const moduleBytecode = await getModule({ aptosConfig, accountAddress: moduleAddress, moduleName });\n return moduleBytecode.abi;\n}\n\n/**\n * Fetches the ABI of a specified function from the on-chain module ABI. This function allows you to access the details of a\n * specific function within a module.\n *\n * @param moduleAddress - The address of the module from which to fetch the function ABI.\n * @param moduleName - The name of the module containing the function.\n * @param functionName - The name of the function whose ABI is to be fetched.\n * @param aptosConfig - The configuration settings for Aptos.\n * @group Implementation\n * @category Transactions\n */\nexport async function fetchFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<MoveFunction | undefined> {\n const moduleAbi = await fetchModuleAbi(moduleAddress, moduleName, aptosConfig);\n if (!moduleAbi) throw new Error(`Could not find module ABI for '${moduleAddress}::${moduleName}'`);\n return moduleAbi.exposed_functions.find((func) => func.name === functionName);\n}\n\n/**\n * @deprecated Use `fetchFunctionAbi` instead and manually parse the type tags.\n */\nexport async function fetchMoveFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<FunctionABI> {\n const functionAbi = await fetchFunctionAbi(moduleAddress, moduleName, functionName, aptosConfig);\n if (!functionAbi) {\n throw new Error(`Could not find function ABI for '${moduleAddress}::${moduleName}::${functionName}'`);\n }\n const params: TypeTag[] = [];\n for (let i = 0; i < functionAbi.params.length; i += 1) {\n params.push(parseTypeTag(functionAbi.params[i], { allowGenerics: true }));\n }\n\n return {\n typeParameters: functionAbi.generic_type_params,\n parameters: params,\n };\n}\n\n/**\n * Fetches the ABI for an entry function from the specified module address.\n * This function validates if the ABI corresponds to an entry function and retrieves its parameters.\n *\n * @param moduleAddress - The address of the module containing the entry function.\n * @param moduleName - The name of the module containing the entry function.\n * @param functionName - The name of the entry function to fetch the ABI for.\n * @param aptosConfig - The configuration settings for Aptos.\n * @returns An object containing the number of signers, type parameters, and function parameters.\n * @throws Error if the ABI cannot be found or if the function is not an entry function.\n * @group Implementation\n * @category Transactions\n */\nexport async function fetchEntryFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<EntryFunctionABI> {\n const functionAbi = await fetchFunctionAbi(moduleAddress, moduleName, functionName, aptosConfig);\n\n // If there's no ABI, then the function is invalid\n if (!functionAbi) {\n throw new Error(`Could not find entry function ABI for '${moduleAddress}::${moduleName}::${functionName}'`);\n }\n\n // Non-entry functions also can't be used\n if (!functionAbi.is_entry) {\n throw new Error(`'${moduleAddress}::${moduleName}::${functionName}' is not an entry function`);\n }\n\n // Remove the signer arguments\n const numSigners = findFirstNonSignerArg(functionAbi);\n const params: TypeTag[] = [];\n for (let i = numSigners; i < functionAbi.params.length; i += 1) {\n params.push(parseTypeTag(functionAbi.params[i], { allowGenerics: true }));\n }\n\n return {\n signers: numSigners,\n typeParameters: functionAbi.generic_type_params,\n parameters: params,\n };\n}\n\n/**\n * Fetches the ABI for a view function from the specified module address.\n * This function ensures that the ABI is valid and retrieves the type parameters, parameters, and return types for the view function.\n *\n * @param moduleAddress - The address of the module containing the view function.\n * @param moduleName - The name of the module containing the view function.\n * @param functionName - The name of the view function for which to fetch the ABI.\n * @param aptosConfig - The configuration settings for Aptos.\n * @returns An object containing the type parameters, parameters, and return types of the view function.\n * @throws Error if the ABI cannot be found or if the function is not a view function.\n * @group Implementation\n * @category Transactions\n */\nexport async function fetchViewFunctionAbi(\n moduleAddress: string,\n moduleName: string,\n functionName: string,\n aptosConfig: AptosConfig,\n): Promise<ViewFunctionABI> {\n const functionAbi = await fetchFunctionAbi(moduleAddress, moduleName, functionName, aptosConfig);\n\n // If there's no ABI, then the function is invalid\n if (!functionAbi) {\n throw new Error(`Could not find view function ABI for '${moduleAddress}::${moduleName}::${functionName}'`);\n }\n\n // Non-view functions can't be used\n if (!functionAbi.is_view) {\n throw new Error(`'${moduleAddress}::${moduleName}::${functionName}' is not an view function`);\n }\n\n // Type tag parameters for the function\n const params: TypeTag[] = [];\n for (let i = 0; i < functionAbi.params.length; i += 1) {\n params.push(parseTypeTag(functionAbi.params[i], { allowGenerics: true }));\n }\n\n // The return types of the view function\n const returnTypes: TypeTag[] = [];\n for (let i = 0; i < functionAbi.return.length; i += 1) {\n returnTypes.push(parseTypeTag(functionAbi.return[i], { allowGenerics: true }));\n }\n\n return {\n typeParameters: functionAbi.generic_type_params,\n parameters: params,\n returnTypes,\n };\n}\n\n/**\n * Converts a non-BCS encoded argument into BCS encoded, if necessary.\n * This function checks the provided argument against the expected parameter type and converts it accordingly.\n *\n * @param functionName - The name of the function for which the argument is being converted.\n * @param functionAbiOrModuleAbi - The ABI (Application Binary Interface) of the function, which defines its parameters.\n * @param arg - The argument to be converted, which can be of various types.\n * @param position - The index of the argument in the function's parameter list.\n * @param genericTypeParams - An array of type tags for any generic type parameters.\n * @param options - Options for the conversion process.\n * @param options.allowUnknownStructs - If true, unknown structs will be allowed and converted to a `FixedBytes`.\n * @group Implementation\n * @category Transactions\n */\nexport function convertArgument(\n functionName: string,\n functionAbiOrModuleAbi: MoveModule | FunctionABI,\n arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes,\n position: number,\n genericTypeParams: Array<TypeTag>,\n options?: { allowUnknownStructs?: boolean },\n) {\n let param: TypeTag;\n\n if (\"exposed_functions\" in functionAbiOrModuleAbi) {\n const functionAbi = functionAbiOrModuleAbi.exposed_functions.find((func) => func.name === functionName);\n if (!functionAbi) {\n throw new Error(\n `Could not find function ABI for '${functionAbiOrModuleAbi.address}::${functionAbiOrModuleAbi.name}::${functionName}'`,\n );\n }\n\n if (position >= functionAbi.params.length) {\n throw new Error(`Too many arguments for '${functionName}', expected ${functionAbi.params.length}`);\n }\n\n param = parseTypeTag(functionAbi.params[position], { allowGenerics: true });\n } else {\n if (position >= functionAbiOrModuleAbi.parameters.length) {\n throw new Error(`Too many arguments for '${functionName}', expected ${functionAbiOrModuleAbi.parameters.length}`);\n }\n\n param = functionAbiOrModuleAbi.parameters[position];\n }\n\n return checkOrConvertArgument(\n arg,\n param,\n position,\n genericTypeParams,\n \"exposed_functions\" in functionAbiOrModuleAbi ? functionAbiOrModuleAbi : undefined,\n options,\n );\n}\n\n/**\n * Checks if the provided argument is BCS encoded and converts it if necessary, ensuring type compatibility with the ABI.\n * This function helps in validating and converting arguments for entry functions based on their expected types.\n *\n * @param arg - The argument to check or convert, which can be either a simple or entry function argument type.\n * @param param - The expected type tag for the argument.\n * @param position - The position of the argument in the function call.\n * @param genericTypeParams - An array of generic type parameters that may be used for conversion.\n * @group Implementation\n * @category Transactions\n */\nexport function checkOrConvertArgument(\n arg: SimpleEntryFunctionArgumentTypes | EntryFunctionArgumentTypes,\n param: TypeTag,\n position: number,\n genericTypeParams: Array<TypeTag>,\n moduleAbi?: MoveModule,\n options?: { allowUnknownStructs?: boolean },\n) {\n // If the argument is bcs encoded, we can just use it directly\n if (isEncodedEntryFunctionArgument(arg)) {\n // Ensure the type matches the ABI\n\n /**\n * Checks the type of the provided argument against the expected type.\n * This function helps validate that the argument conforms to the specified type requirements.\n *\n * @param typeArgs - The expected type arguments.\n * @param arg - The argument to be checked.\n * @param position - The position of the argument in the context of the check.\n * @param moduleAbi - The ABI of the module containing the function, used for type checking.\n * This will typically have information about structs, enums, and other types.\n * @group Implementation\n * @category Transactions\n */\n checkType(param, arg, position);\n return arg;\n }\n\n // If it is not BCS encoded, we will need to convert it with the ABI\n return parseArg(arg, param, position, genericTypeParams, moduleAbi, options);\n}\n\n/**\n * Parses a non-BCS encoded argument into a BCS encoded argument recursively.\n * This function helps convert various types of input arguments into their corresponding BCS encoded formats based on the\n * specified parameter type.\n *\n * @param arg - The argument to be parsed, which can be of various types.\n * @param param - The type tag that defines the expected type of the argument.\n * @param position - The position of the argument in the function call, used for error reporting.\n * @param genericTypeParams - An array of type tags for generic type parameters, used when the parameter type is generic.\n * @param moduleAbi - The ABI of the module containing the function, used for type checking.\n * This will typically have information about structs, enums, and other types.\n * @param options - Options for the conversion process.\n * @param options.allowUnknownStructs - If true, unknown structs will be allowed and converted to a `FixedBytes`.\n * @group Implementation\n * @category Transactions\n */\nfunction parseArg(\n arg: SimpleEntryFunctionArgumentTypes,\n param: TypeTag,\n position: number,\n genericTypeParams: Array<TypeTag>,\n moduleAbi?: MoveModule,\n options?: { allowUnknownStructs?: boolean },\n): EntryFunctionArgumentTypes {\n if (param.isBool()) {\n if (isBool(arg)) {\n return new Bool(arg);\n }\n if (isString(arg)) {\n if (arg === \"true\") return new Bool(true);\n if (arg === \"false\") return new Bool(false);\n }\n\n /**\n * Throws a type mismatch error for the specified move option.\n *\n * @param moveOption - The name of the move option that caused the type mismatch.\n * @param position - The position where the error occurred.\n * @group Implementation\n * @category Transactions\n */\n throwTypeMismatch(\"boolean\", position);\n }\n if (param.isAddress()) {\n if (isString(arg)) {\n return AccountAddress.fromString(arg);\n }\n // Support for Uint8Array coming from external sources\n // Usually, dapps will be getting the account address as a Uint8Array from the wallet (following\n // the wallet standard).\n if (arg && typeof arg === \"object\" && \"data\" in arg && arg.data instanceof Uint8Array) {\n return new AccountAddress(arg.data);\n }\n throwTypeMismatch(\"string | AccountAddress\", position);\n }\n if (param.isU8()) {\n const num = convertNumber(arg);\n if (num !== undefined) {\n return new U8(num);\n }\n throwTypeMismatch(\"number | string\", position);\n }\n if (param.isU16()) {\n const num = convertNumber(arg);\n if (num !== undefined) {\n return new U16(num);\n }\n throwTypeMismatch(\"number | string\", position);\n }\n if (param.isU32()) {\n const num = convertNumber(arg);\n if (num !== undefined) {\n return new U32(num);\n }\n throwTypeMismatch(\"number | string\", position);\n }\n if (param.isU64()) {\n if (isLargeNumber(arg)) {\n return new U64(BigInt(arg));\n }\n throwTypeMismatch(\"bigint | number | string\", position);\n }\n if (param.isU128()) {\n if (isLargeNumber(arg)) {\n return new U128(BigInt(arg));\n }\n throwTypeMismatch(\"bigint | number | string\", position);\n }\n if (param.isU256()) {\n if (isLargeNumber(arg)) {\n return new U256(BigInt(arg));\n }\n throwTypeMismatch(\"bigint | number | string\", position);\n }\n\n // Generic needs to use the subtype\n if (param.isGeneric()) {\n const genericIndex = param.value;\n if (genericIndex < 0 || genericIndex >= genericTypeParams.length) {\n throw new Error(`Generic argument ${param.toString()} is invalid for argument ${position}`);\n }\n\n return checkOrConvertArgument(arg, genericTypeParams[genericIndex], position, genericTypeParams, moduleAbi);\n }\n\n // We have to special case some vectors for Vector<u8>\n if (param.isVector()) {\n // Check special case for Vector<u8>\n if (param.value.isU8()) {\n // We don't allow vector<u8>, but we convert strings to UTF8 Uint8Array\n // This is legacy behavior from the original SDK\n if (isString(arg)) {\n return MoveVector.U8(TEXT_ENCODER.encode(arg));\n }\n if (arg instanceof Uint8Array) {\n return MoveVector.U8(arg);\n }\n if (arg instanceof ArrayBuffer) {\n return MoveVector.U8(new Uint8Array(arg));\n }\n }\n\n if (isString(arg)) {\n // In a web env, arguments are passing as strings\n if (arg.startsWith(\"[\")) {\n return checkOrConvertArgument(JSON.parse(arg), param, position, genericTypeParams);\n }\n }\n\n // TODO: Support Uint16Array, Uint32Array, BigUint64Array?\n\n if (Array.isArray(arg)) {\n return new MoveVector(\n arg.map((item) => checkOrConvertArgument(item, param.value, position, genericTypeParams, moduleAbi)),\n );\n }\n\n throw new Error(`Type mismatch for argument ${position}, type '${param.toString()}'`);\n }\n\n // Handle structs as they're more complex\n if (param.isStruct()) {\n if (param.isString()) {\n if (isString(arg)) {\n return new MoveString(arg);\n }\n throwTypeMismatch(\"string\", position);\n }\n if (param.isObject()) {\n // The inner type of Object doesn't matter, since it's just syntactic sugar\n if (isString(arg)) {\n return AccountAddress.fromString(arg);\n }\n // Support for Uint8Array coming from external sources\n if (arg && typeof arg === \"object\" && \"data\" in arg && arg.data instanceof Uint8Array) {\n return new AccountAddress(arg.data);\n }\n throwTypeMismatch(\"string | AccountAddress\", position);\n }\n // Handle known enum types from Aptos framework\n if (param.isDelegationKey() || param.isRateLimiter()) {\n if (arg instanceof Uint8Array) {\n return new FixedBytes(arg);\n }\n throwTypeMismatch(\"Uint8Array\", position);\n }\n\n if (param.isOption()) {\n if (isEmptyOption(arg)) {\n // Here we attempt to reconstruct the underlying type\n // Note, for some reason the `isBool` etc. does not work with the compiler\n const innerParam = param.value.typeArgs[0];\n if (innerParam instanceof TypeTagBool) {\n return new MoveOption<Bool>(null);\n }\n if (innerParam instanceof TypeTagAddress) {\n return new MoveOption<AccountAddress>(null);\n }\n if (innerParam instanceof TypeTagU8) {\n return new MoveOption<U8>(null);\n }\n if (innerParam instanceof TypeTagU16) {\n return new MoveOption<U16>(null);\n }\n if (innerParam instanceof TypeTagU32) {\n return new MoveOption<U32>(null);\n }\n if (innerParam instanceof TypeTagU64) {\n return new MoveOption<U64>(null);\n }\n if (innerParam instanceof TypeTagU128) {\n return new MoveOption<U128>(null);\n }\n if (innerParam instanceof TypeTagU256) {\n return new MoveOption<U256>(null);\n }\n\n // In all other cases, we will use a placeholder, it doesn't actually matter what the type is, but it will be obvious\n // Note: This is a placeholder U8 type, and does not match the actual type, as that can't be dynamically grabbed\n return new MoveOption<MoveString>(null);\n }\n\n return new MoveOption(\n checkOrConvertArgument(arg, param.value.typeArgs[0], position, genericTypeParams, moduleAbi),\n );\n }\n\n // We are assuming that fieldless structs are enums, and therefore we cannot typecheck any further due\n // to limited information from the ABI. This does not work for structs on other modules.\n const structDefinition = moduleAbi?.structs.find((s) => s.name === param.value.name.identifier);\n if (structDefinition?.fields.length === 0 && arg instanceof Uint8Array) {\n return new FixedBytes(arg);\n }\n\n if (arg instanceof Uint8Array && options?.allowUnknownStructs) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `Unsupported struct input type for argument ${position}. Continuing since 'allowUnknownStructs' is enabled.`,\n );\n return new FixedBytes(arg);\n }\n\n throw new Error(`Unsupported struct input type for argument ${position}, type '${param.toString()}'`);\n }\n\n throw new Error(`Type mismatch for argument ${position}, type '${param.toString()}'`);\n}\n\n/**\n * Checks that the type of the BCS encoded argument matches the ABI\n * @param param\n * @param arg\n * @param position\n * @group Implementation\n * @category Transactions\n */\nfunction checkType(param: TypeTag, arg: EntryFunctionArgumentTypes, position: number) {\n if (param.isBool()) {\n if (isBcsBool(arg)) {\n return;\n }\n throwTypeMismatch(\"Bool\", position);\n }\n if (param.isAddress()) {\n if (isBcsAddress(arg)) {\n return;\n }\n throwTypeMismatch(\"AccountAddress\", position);\n }\n if (param.isU8()) {\n if (isBcsU8(arg)) {\n return;\n }\n throwTypeMismatch(\"U8\", position);\n }\n if (param.isU16()) {\n if (isBcsU16(arg)) {\n return;\n }\n throwTypeMismatch(\"U16\", position);\n }\n if (param.isU32()) {\n if (isBcsU32(arg)) {\n return;\n }\n throwTypeMismatch(\"U32\", position);\n }\n if (param.isU64()) {\n if (isBcsU64(arg)) {\n return;\n }\n throwTypeMismatch(\"U64\", position);\n }\n if (param.isU128()) {\n if (isBcsU128(arg)) {\n return;\n }\n throwTypeMismatch(\"U128\", position);\n }\n if (param.isU256()) {\n if (isBcsU256(arg)) {\n return;\n }\n throwTypeMismatch(\"U256\", position);\n }\n if (param.isVector()) {\n if (arg instanceof MoveVector) {\n // If there's anything in it, check that the inner types match\n // Note that since it's typed, the first item should be the same as the rest\n if (arg.values.length > 0) {\n checkType(param.value, arg.values[0], position);\n }\n\n return;\n }\n throwTypeMismatch(\"MoveVector\", position);\n }\n\n // Handle structs as they're more complex\n if (param instanceof TypeTagStruct) {\n if (param.isString()) {\n if (isBcsString(arg)) {\n return;\n }\n throwTypeMismatch(\"MoveString\", position);\n }\n if (param.isObject()) {\n if (isBcsAddress(arg)) {\n return;\n }\n throwTypeMismatch(\"AccountAddress\", position);\n }\n if (param.isOption()) {\n if (arg instanceof MoveOption) {\n // If there's a value, we can check the inner type (otherwise it doesn't really matter)\n if (arg.value !== undefined) {\n checkType(param.value.typeArgs[0], arg.value, position);\n }\n return;\n }\n throwTypeMismatch(\"MoveOption\", position);\n }\n }\n\n throw new Error(`Type mismatch for argument ${position}, expected '${param.toString()}'`);\n}\n"]}