@aptos-labs/ts-sdk 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +144 -0
  3. package/dist/browser/index.global.js +410 -0
  4. package/dist/browser/index.global.js.map +1 -0
  5. package/dist/cjs/index.d.ts +4965 -0
  6. package/dist/cjs/index.js +4762 -0
  7. package/dist/cjs/index.js.map +1 -0
  8. package/dist/esm/index.d.ts +4965 -0
  9. package/dist/esm/index.mjs +4645 -0
  10. package/dist/esm/index.mjs.map +1 -0
  11. package/dist/types/index.d.ts +1247 -0
  12. package/dist/types/index.js +151 -0
  13. package/dist/types/index.js.map +1 -0
  14. package/package.json +79 -0
  15. package/src/api/account.ts +360 -0
  16. package/src/api/aptos.ts +103 -0
  17. package/src/api/aptosConfig.ts +77 -0
  18. package/src/api/coin.ts +39 -0
  19. package/src/api/digitalAsset.ts +192 -0
  20. package/src/api/event.ts +78 -0
  21. package/src/api/faucet.ts +30 -0
  22. package/src/api/fungibleAsset.ts +82 -0
  23. package/src/api/general.ts +188 -0
  24. package/src/api/index.ts +5 -0
  25. package/src/api/staking.ts +58 -0
  26. package/src/api/transaction.ts +135 -0
  27. package/src/api/transactionSubmission.ts +168 -0
  28. package/src/bcs/consts.ts +12 -0
  29. package/src/bcs/deserializer.ts +248 -0
  30. package/src/bcs/index.ts +9 -0
  31. package/src/bcs/serializable/entryFunctionBytes.ts +61 -0
  32. package/src/bcs/serializable/fixedBytes.ts +65 -0
  33. package/src/bcs/serializable/movePrimitives.ts +211 -0
  34. package/src/bcs/serializable/moveStructs.ts +462 -0
  35. package/src/bcs/serializer.ts +353 -0
  36. package/src/client/core.ts +106 -0
  37. package/src/client/get.ts +109 -0
  38. package/src/client/index.ts +7 -0
  39. package/src/client/post.ts +90 -0
  40. package/src/client/types.ts +58 -0
  41. package/src/core/account.ts +180 -0
  42. package/src/core/accountAddress.ts +407 -0
  43. package/src/core/authenticationKey.ts +102 -0
  44. package/src/core/common.ts +40 -0
  45. package/src/core/crypto/asymmetricCrypto.ts +77 -0
  46. package/src/core/crypto/ed25519.ts +224 -0
  47. package/src/core/crypto/index.ts +7 -0
  48. package/src/core/crypto/multiEd25519.ts +251 -0
  49. package/src/core/crypto/secp256k1.ts +227 -0
  50. package/src/core/hex.ts +177 -0
  51. package/src/core/index.ts +9 -0
  52. package/src/index.ts +12 -0
  53. package/src/internal/account.ts +484 -0
  54. package/src/internal/coin.ts +32 -0
  55. package/src/internal/digitalAsset.ts +302 -0
  56. package/src/internal/event.ts +88 -0
  57. package/src/internal/faucet.ts +41 -0
  58. package/src/internal/fungibleAsset.ts +114 -0
  59. package/src/internal/general.ts +160 -0
  60. package/src/internal/queries/TokenActivitiesFieldsFragment.graphql +17 -0
  61. package/src/internal/queries/currentTokenOwnershipFieldsFragment.graphql +45 -0
  62. package/src/internal/queries/getAccountCoinCount.graphql +7 -0
  63. package/src/internal/queries/getAccountCoinsData.graphql +32 -0
  64. package/src/internal/queries/getAccountCollectionsWithOwnedTokens.graphql +33 -0
  65. package/src/internal/queries/getAccountOwnedObjects.graphql +16 -0
  66. package/src/internal/queries/getAccountOwnedTokens.graphql +11 -0
  67. package/src/internal/queries/getAccountOwnedTokensByTokenData.graphql +11 -0
  68. package/src/internal/queries/getAccountOwnedTokensFromCollectionAddress.graphql +11 -0
  69. package/src/internal/queries/getAccountTokensCount.graphql +7 -0
  70. package/src/internal/queries/getAccountTransactionsCount.graphql +7 -0
  71. package/src/internal/queries/getChainTopUserTransactions.graphql +5 -0
  72. package/src/internal/queries/getCollectionData.graphql +20 -0
  73. package/src/internal/queries/getCurrentFungibleAssetBalances.graphql +17 -0
  74. package/src/internal/queries/getDelegatedStakingActivities.graphql +12 -0
  75. package/src/internal/queries/getEvents.graphql +12 -0
  76. package/src/internal/queries/getFungibleAssetActivities.graphql +20 -0
  77. package/src/internal/queries/getFungibleAssetMetadata.graphql +16 -0
  78. package/src/internal/queries/getNumberOfDelegatorsQuery.graphql +9 -0
  79. package/src/internal/queries/getProcessorStatus.graphql +7 -0
  80. package/src/internal/queries/getTokenActivity.graphql +11 -0
  81. package/src/internal/queries/getTokenCurrentOwner.graphql +11 -0
  82. package/src/internal/queries/getTokenData.graphql +38 -0
  83. package/src/internal/staking.ts +68 -0
  84. package/src/internal/transaction.ts +245 -0
  85. package/src/internal/transactionSubmission.ts +162 -0
  86. package/src/transactions/authenticator/account.ts +121 -0
  87. package/src/transactions/authenticator/transaction.ts +222 -0
  88. package/src/transactions/instances/chainId.ts +26 -0
  89. package/src/transactions/instances/identifier.ts +28 -0
  90. package/src/transactions/instances/index.ts +9 -0
  91. package/src/transactions/instances/moduleId.ts +53 -0
  92. package/src/transactions/instances/rawTransaction.ts +199 -0
  93. package/src/transactions/instances/signedTransaction.ts +43 -0
  94. package/src/transactions/instances/transactionArgument.ts +37 -0
  95. package/src/transactions/instances/transactionPayload.ts +407 -0
  96. package/src/transactions/transaction_builder/transaction_builder.ts +541 -0
  97. package/src/transactions/typeTag/typeTag.ts +487 -0
  98. package/src/transactions/types.ts +262 -0
  99. package/src/types/codegen.yaml +33 -0
  100. package/src/types/generated/operations.ts +623 -0
  101. package/src/types/generated/queries.ts +737 -0
  102. package/src/types/generated/types.ts +10387 -0
  103. package/src/types/index.ts +944 -0
  104. package/src/types/indexer.ts +93 -0
  105. package/src/utils/apiEndpoints.ts +36 -0
  106. package/src/utils/const.ts +51 -0
  107. package/src/utils/hdKey.ts +113 -0
  108. package/src/utils/helpers.ts +12 -0
  109. package/src/utils/memoize.ts +68 -0
  110. package/src/version.ts +9 -0
@@ -0,0 +1,4762 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var __decorateClass = (decorators, target, key, kind) => {
26
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
27
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
28
+ if (decorator = decorators[i])
29
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
30
+ if (kind && result)
31
+ __defProp(target, key, result);
32
+ return result;
33
+ };
34
+
35
+ // src/index.ts
36
+ var src_exports = {};
37
+ __export(src_exports, {
38
+ APTOS_PATH_REGEX: () => APTOS_PATH_REGEX,
39
+ Account: () => Account,
40
+ AccountAddress: () => AccountAddress,
41
+ AccountAuthenticatorVariant: () => AccountAuthenticatorVariant,
42
+ AddressInvalidReason: () => AddressInvalidReason,
43
+ Aptos: () => Aptos,
44
+ AptosApiError: () => AptosApiError,
45
+ AptosConfig: () => AptosConfig,
46
+ AuthenticationKey: () => AuthenticationKey,
47
+ Bool: () => Bool,
48
+ DeriveScheme: () => DeriveScheme,
49
+ Deserializer: () => Deserializer,
50
+ Ed25519PrivateKey: () => Ed25519PrivateKey,
51
+ Ed25519PublicKey: () => Ed25519PublicKey,
52
+ Ed25519Signature: () => Ed25519Signature,
53
+ EntryFunctionBytes: () => EntryFunctionBytes,
54
+ FixedBytes: () => FixedBytes,
55
+ Hex: () => Hex,
56
+ HexInvalidReason: () => HexInvalidReason,
57
+ KeyType: () => KeyType,
58
+ MimeType: () => MimeType,
59
+ MoveAbility: () => MoveAbility,
60
+ MoveFunctionVisibility: () => MoveFunctionVisibility,
61
+ MoveObject: () => MoveObject,
62
+ MoveOption: () => MoveOption,
63
+ MoveString: () => MoveString,
64
+ MoveVector: () => MoveVector,
65
+ MultiEd25519PublicKey: () => MultiEd25519PublicKey,
66
+ MultiEd25519Signature: () => MultiEd25519Signature,
67
+ Network: () => Network,
68
+ NetworkToChainId: () => NetworkToChainId,
69
+ NetworkToFaucetAPI: () => NetworkToFaucetAPI,
70
+ NetworkToIndexerAPI: () => NetworkToIndexerAPI,
71
+ NetworkToNodeAPI: () => NetworkToNodeAPI,
72
+ ParsingError: () => ParsingError,
73
+ PrivateKey: () => PrivateKey,
74
+ PublicKey: () => PublicKey,
75
+ RoleType: () => RoleType,
76
+ ScriptTransactionArgumentVariants: () => ScriptTransactionArgumentVariants,
77
+ Secp256k1PrivateKey: () => Secp256k1PrivateKey,
78
+ Secp256k1PublicKey: () => Secp256k1PublicKey,
79
+ Secp256k1Signature: () => Secp256k1Signature,
80
+ Serializable: () => Serializable,
81
+ Serializer: () => Serializer,
82
+ Signature: () => Signature,
83
+ SigningScheme: () => SigningScheme,
84
+ StructTag: () => StructTag,
85
+ TransactionAuthenticatorVariant: () => TransactionAuthenticatorVariant,
86
+ TransactionPayloadVariants: () => TransactionPayloadVariants,
87
+ TransactionResponseType: () => TransactionResponseType,
88
+ TransactionVariants: () => TransactionVariants,
89
+ TypeTag: () => TypeTag,
90
+ TypeTagAddress: () => TypeTagAddress,
91
+ TypeTagBool: () => TypeTagBool,
92
+ TypeTagParser: () => TypeTagParser,
93
+ TypeTagParserError: () => TypeTagParserError,
94
+ TypeTagSigner: () => TypeTagSigner,
95
+ TypeTagStruct: () => TypeTagStruct,
96
+ TypeTagU128: () => TypeTagU128,
97
+ TypeTagU16: () => TypeTagU16,
98
+ TypeTagU256: () => TypeTagU256,
99
+ TypeTagU32: () => TypeTagU32,
100
+ TypeTagU64: () => TypeTagU64,
101
+ TypeTagU8: () => TypeTagU8,
102
+ TypeTagVariants: () => TypeTagVariants,
103
+ TypeTagVector: () => TypeTagVector,
104
+ U128: () => U128,
105
+ U16: () => U16,
106
+ U256: () => U256,
107
+ U32: () => U32,
108
+ U64: () => U64,
109
+ U8: () => U8,
110
+ aptosRequest: () => aptosRequest,
111
+ derivePrivateKeyFromMnemonic: () => derivePrivateKeyFromMnemonic,
112
+ ensureBoolean: () => ensureBoolean,
113
+ get: () => get,
114
+ getAptosFullNode: () => getAptosFullNode,
115
+ isValidPath: () => isValidPath,
116
+ objectStructTag: () => objectStructTag,
117
+ optionStructTag: () => optionStructTag,
118
+ outOfRangeErrorMessage: () => outOfRangeErrorMessage,
119
+ paginateWithCursor: () => paginateWithCursor,
120
+ post: () => post,
121
+ postAptosFaucet: () => postAptosFaucet,
122
+ postAptosFullNode: () => postAptosFullNode,
123
+ postAptosIndexer: () => postAptosIndexer,
124
+ stringStructTag: () => stringStructTag,
125
+ validateNumberInRange: () => validateNumberInRange
126
+ });
127
+ module.exports = __toCommonJS(src_exports);
128
+
129
+ // src/client/core.ts
130
+ var import_aptos_client = __toESM(require("@aptos-labs/aptos-client"));
131
+
132
+ // src/client/types.ts
133
+ var AptosApiError = class extends Error {
134
+ constructor(request2, response, message) {
135
+ super(message);
136
+ this.name = "AptosApiError";
137
+ this.url = response.url;
138
+ this.status = response.status;
139
+ this.statusText = response.statusText;
140
+ this.data = response.data;
141
+ this.request = request2;
142
+ }
143
+ };
144
+
145
+ // src/types/index.ts
146
+ var MimeType = /* @__PURE__ */ ((MimeType2) => {
147
+ MimeType2["JSON"] = "application/json";
148
+ MimeType2["BCS"] = "application/x-bcs";
149
+ MimeType2["BCS_SIGNED_TRANSACTION"] = "application/x.aptos.signed_transaction+bcs";
150
+ return MimeType2;
151
+ })(MimeType || {});
152
+ var TypeTagVariants = /* @__PURE__ */ ((TypeTagVariants2) => {
153
+ TypeTagVariants2[TypeTagVariants2["Bool"] = 0] = "Bool";
154
+ TypeTagVariants2[TypeTagVariants2["U8"] = 1] = "U8";
155
+ TypeTagVariants2[TypeTagVariants2["U64"] = 2] = "U64";
156
+ TypeTagVariants2[TypeTagVariants2["U128"] = 3] = "U128";
157
+ TypeTagVariants2[TypeTagVariants2["Address"] = 4] = "Address";
158
+ TypeTagVariants2[TypeTagVariants2["Signer"] = 5] = "Signer";
159
+ TypeTagVariants2[TypeTagVariants2["Vector"] = 6] = "Vector";
160
+ TypeTagVariants2[TypeTagVariants2["Struct"] = 7] = "Struct";
161
+ TypeTagVariants2[TypeTagVariants2["U16"] = 8] = "U16";
162
+ TypeTagVariants2[TypeTagVariants2["U32"] = 9] = "U32";
163
+ TypeTagVariants2[TypeTagVariants2["U256"] = 10] = "U256";
164
+ return TypeTagVariants2;
165
+ })(TypeTagVariants || {});
166
+ var ScriptTransactionArgumentVariants = /* @__PURE__ */ ((ScriptTransactionArgumentVariants2) => {
167
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U8"] = 0] = "U8";
168
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U64"] = 1] = "U64";
169
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U128"] = 2] = "U128";
170
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["Address"] = 3] = "Address";
171
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U8Vector"] = 4] = "U8Vector";
172
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["Bool"] = 5] = "Bool";
173
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U16"] = 6] = "U16";
174
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U32"] = 7] = "U32";
175
+ ScriptTransactionArgumentVariants2[ScriptTransactionArgumentVariants2["U256"] = 8] = "U256";
176
+ return ScriptTransactionArgumentVariants2;
177
+ })(ScriptTransactionArgumentVariants || {});
178
+ var TransactionPayloadVariants = /* @__PURE__ */ ((TransactionPayloadVariants2) => {
179
+ TransactionPayloadVariants2[TransactionPayloadVariants2["Script"] = 0] = "Script";
180
+ TransactionPayloadVariants2[TransactionPayloadVariants2["EntryFunction"] = 2] = "EntryFunction";
181
+ TransactionPayloadVariants2[TransactionPayloadVariants2["Multisig"] = 3] = "Multisig";
182
+ return TransactionPayloadVariants2;
183
+ })(TransactionPayloadVariants || {});
184
+ var TransactionVariants = /* @__PURE__ */ ((TransactionVariants2) => {
185
+ TransactionVariants2[TransactionVariants2["MultiAgentTransaction"] = 0] = "MultiAgentTransaction";
186
+ TransactionVariants2[TransactionVariants2["FeePayerTransaction"] = 1] = "FeePayerTransaction";
187
+ return TransactionVariants2;
188
+ })(TransactionVariants || {});
189
+ var TransactionAuthenticatorVariant = /* @__PURE__ */ ((TransactionAuthenticatorVariant2) => {
190
+ TransactionAuthenticatorVariant2[TransactionAuthenticatorVariant2["Ed25519"] = 0] = "Ed25519";
191
+ TransactionAuthenticatorVariant2[TransactionAuthenticatorVariant2["MultiEd25519"] = 1] = "MultiEd25519";
192
+ TransactionAuthenticatorVariant2[TransactionAuthenticatorVariant2["MultiAgent"] = 2] = "MultiAgent";
193
+ TransactionAuthenticatorVariant2[TransactionAuthenticatorVariant2["FeePayer"] = 3] = "FeePayer";
194
+ TransactionAuthenticatorVariant2[TransactionAuthenticatorVariant2["Secp256k1Ecdsa"] = 4] = "Secp256k1Ecdsa";
195
+ return TransactionAuthenticatorVariant2;
196
+ })(TransactionAuthenticatorVariant || {});
197
+ var AccountAuthenticatorVariant = /* @__PURE__ */ ((AccountAuthenticatorVariant2) => {
198
+ AccountAuthenticatorVariant2[AccountAuthenticatorVariant2["Ed25519"] = 0] = "Ed25519";
199
+ AccountAuthenticatorVariant2[AccountAuthenticatorVariant2["MultiEd25519"] = 1] = "MultiEd25519";
200
+ AccountAuthenticatorVariant2[AccountAuthenticatorVariant2["Secp256k1"] = 2] = "Secp256k1";
201
+ return AccountAuthenticatorVariant2;
202
+ })(AccountAuthenticatorVariant || {});
203
+ var TransactionResponseType = /* @__PURE__ */ ((TransactionResponseType2) => {
204
+ TransactionResponseType2["Pending"] = "pending_transaction";
205
+ TransactionResponseType2["User"] = "user_transaction";
206
+ TransactionResponseType2["Genesis"] = "genesis_transaction";
207
+ TransactionResponseType2["BlockMetadata"] = "block_metadata_transaction";
208
+ TransactionResponseType2["StateCheckpoint"] = "state_checkpoint_transaction";
209
+ return TransactionResponseType2;
210
+ })(TransactionResponseType || {});
211
+ var MoveFunctionVisibility = /* @__PURE__ */ ((MoveFunctionVisibility2) => {
212
+ MoveFunctionVisibility2["PRIVATE"] = "private";
213
+ MoveFunctionVisibility2["PUBLIC"] = "public";
214
+ MoveFunctionVisibility2["FRIEND"] = "friend";
215
+ return MoveFunctionVisibility2;
216
+ })(MoveFunctionVisibility || {});
217
+ var MoveAbility = /* @__PURE__ */ ((MoveAbility2) => {
218
+ MoveAbility2["STORE"] = "store";
219
+ MoveAbility2["DROP"] = "drop";
220
+ MoveAbility2["KEY"] = "key";
221
+ MoveAbility2["COPY"] = "copy";
222
+ return MoveAbility2;
223
+ })(MoveAbility || {});
224
+ var RoleType = /* @__PURE__ */ ((RoleType2) => {
225
+ RoleType2["VALIDATOR"] = "validator";
226
+ RoleType2["FULL_NODE"] = "full_node";
227
+ return RoleType2;
228
+ })(RoleType || {});
229
+ var SigningScheme = /* @__PURE__ */ ((SigningScheme2) => {
230
+ SigningScheme2[SigningScheme2["Ed25519"] = 0] = "Ed25519";
231
+ SigningScheme2[SigningScheme2["MultiEd25519"] = 1] = "MultiEd25519";
232
+ SigningScheme2[SigningScheme2["Secp256k1Ecdsa"] = 2] = "Secp256k1Ecdsa";
233
+ return SigningScheme2;
234
+ })(SigningScheme || {});
235
+ var DeriveScheme = /* @__PURE__ */ ((DeriveScheme2) => {
236
+ DeriveScheme2[DeriveScheme2["DeriveAuid"] = 251] = "DeriveAuid";
237
+ DeriveScheme2[DeriveScheme2["DeriveObjectAddressFromObject"] = 252] = "DeriveObjectAddressFromObject";
238
+ DeriveScheme2[DeriveScheme2["DeriveObjectAddressFromGuid"] = 253] = "DeriveObjectAddressFromGuid";
239
+ DeriveScheme2[DeriveScheme2["DeriveObjectAddressFromSeed"] = 254] = "DeriveObjectAddressFromSeed";
240
+ DeriveScheme2[DeriveScheme2["DeriveResourceAccountAddress"] = 255] = "DeriveResourceAccountAddress";
241
+ return DeriveScheme2;
242
+ })(DeriveScheme || {});
243
+
244
+ // src/version.ts
245
+ var VERSION = "0.0.0";
246
+
247
+ // src/client/core.ts
248
+ var errors = {
249
+ 400: "Bad Request",
250
+ 401: "Unauthorized",
251
+ 403: "Forbidden",
252
+ 404: "Not Found",
253
+ 429: "Too Many Requests",
254
+ 500: "Internal Server Error",
255
+ 502: "Bad Gateway",
256
+ 503: "Service Unavailable"
257
+ };
258
+ async function request(url, method, body, contentType, params, overrides) {
259
+ const headers = {
260
+ ...overrides == null ? void 0 : overrides.HEADERS,
261
+ "x-aptos-client": `aptos-ts-sdk/${VERSION}`,
262
+ "content-type": contentType != null ? contentType : "application/json" /* JSON */
263
+ };
264
+ if (overrides == null ? void 0 : overrides.TOKEN) {
265
+ headers.Authorization = `Bearer ${overrides == null ? void 0 : overrides.TOKEN}`;
266
+ }
267
+ return (0, import_aptos_client.default)({
268
+ url,
269
+ method,
270
+ body,
271
+ params,
272
+ headers,
273
+ overrides
274
+ });
275
+ }
276
+ async function aptosRequest(options, aptosConfig) {
277
+ var _a;
278
+ const { url, path, method, body, contentType, params, overrides } = options;
279
+ const fullUrl = `${url}/${path != null ? path : ""}`;
280
+ const response = await request(fullUrl, method, body, contentType, params, overrides);
281
+ const result = {
282
+ status: response.status,
283
+ statusText: response.statusText,
284
+ data: response.data,
285
+ headers: response.headers,
286
+ config: response.config,
287
+ url: fullUrl
288
+ };
289
+ if (aptosConfig.isIndexerRequest(url)) {
290
+ if (result.data.errors) {
291
+ throw new AptosApiError(
292
+ options,
293
+ result,
294
+ (_a = response.data.errors[0].message) != null ? _a : `Unhandled Error ${response.status} : ${response.statusText}`
295
+ );
296
+ }
297
+ result.data = result.data.data;
298
+ }
299
+ if (result.status >= 200 && result.status < 300) {
300
+ return result;
301
+ }
302
+ const errorMessage = errors[result.status];
303
+ throw new AptosApiError(
304
+ options,
305
+ result,
306
+ errorMessage != null ? errorMessage : `Unhandled Error ${response.status} : ${response.statusText}`
307
+ );
308
+ }
309
+
310
+ // src/utils/apiEndpoints.ts
311
+ var NetworkToIndexerAPI = {
312
+ mainnet: "https://indexer.mainnet.aptoslabs.com/v1/graphql",
313
+ testnet: "https://indexer-testnet.staging.gcp.aptosdev.com/v1/graphql",
314
+ devnet: "https://indexer-devnet.staging.gcp.aptosdev.com/v1/graphql",
315
+ local: "http://127.0.0.1:8090/v1/graphql"
316
+ };
317
+ var NetworkToNodeAPI = {
318
+ mainnet: "https://fullnode.mainnet.aptoslabs.com/v1",
319
+ testnet: "https://fullnode.testnet.aptoslabs.com/v1",
320
+ devnet: "https://fullnode.devnet.aptoslabs.com/v1",
321
+ local: "http://127.0.0.1:8080/v1"
322
+ };
323
+ var NetworkToFaucetAPI = {
324
+ mainnet: "https://faucet.mainnet.aptoslabs.com",
325
+ testnet: "https://faucet.testnet.aptoslabs.com",
326
+ devnet: "https://faucet.devnet.aptoslabs.com",
327
+ local: "http://127.0.0.1:8081"
328
+ };
329
+ var Network = /* @__PURE__ */ ((Network2) => {
330
+ Network2["MAINNET"] = "mainnet";
331
+ Network2["TESTNET"] = "testnet";
332
+ Network2["DEVNET"] = "devnet";
333
+ Network2["LOCAL"] = "local";
334
+ Network2["CUSTOM"] = "custom";
335
+ return Network2;
336
+ })(Network || {});
337
+ var NetworkToChainId = {
338
+ mainnet: 1,
339
+ testnet: 2
340
+ };
341
+
342
+ // src/utils/const.ts
343
+ var DEFAULT_NETWORK = "devnet" /* DEVNET */;
344
+ var DEFAULT_MAX_GAS_AMOUNT = 2e5;
345
+ var DEFAULT_TXN_EXP_SEC_FROM_NOW = 20;
346
+ var DEFAULT_TXN_TIMEOUT_SEC = 20;
347
+ var APTOS_COIN = "0x1::aptos_coin::AptosCoin";
348
+ var RAW_TRANSACTION_SALT = "APTOS::RawTransaction";
349
+ var RAW_TRANSACTION_WITH_DATA_SALT = "APTOS::RawTransactionWithData";
350
+
351
+ // src/client/get.ts
352
+ async function get(options) {
353
+ const { aptosConfig, overrides, params, contentType, acceptType, path, originMethod, type } = options;
354
+ const url = aptosConfig.getRequestUrl(type);
355
+ return aptosRequest(
356
+ {
357
+ url,
358
+ method: "GET",
359
+ originMethod,
360
+ path,
361
+ contentType: contentType == null ? void 0 : contentType.valueOf(),
362
+ acceptType: acceptType == null ? void 0 : acceptType.valueOf(),
363
+ params,
364
+ overrides: {
365
+ ...aptosConfig,
366
+ ...overrides
367
+ }
368
+ },
369
+ aptosConfig
370
+ );
371
+ }
372
+ async function getAptosFullNode(options) {
373
+ return get({ ...options, type: 0 /* FULLNODE */ });
374
+ }
375
+ async function paginateWithCursor(options) {
376
+ const out = [];
377
+ let cursor;
378
+ const requestParams = options.params;
379
+ while (true) {
380
+ requestParams.start = cursor;
381
+ const response = await getAptosFullNode({
382
+ aptosConfig: options.aptosConfig,
383
+ originMethod: options.originMethod,
384
+ path: options.path,
385
+ params: requestParams,
386
+ overrides: options.overrides
387
+ });
388
+ cursor = response.headers["x-aptos-cursor"];
389
+ delete response.headers;
390
+ out.push(...response.data);
391
+ if (cursor === null || cursor === void 0) {
392
+ break;
393
+ }
394
+ }
395
+ return out;
396
+ }
397
+
398
+ // src/client/post.ts
399
+ async function post(options) {
400
+ const { type, originMethod, path, body, acceptType, contentType, params, aptosConfig, overrides } = options;
401
+ const url = aptosConfig.getRequestUrl(type);
402
+ return aptosRequest(
403
+ {
404
+ url,
405
+ method: "POST",
406
+ originMethod,
407
+ path,
408
+ body,
409
+ contentType: contentType == null ? void 0 : contentType.valueOf(),
410
+ acceptType: acceptType == null ? void 0 : acceptType.valueOf(),
411
+ params,
412
+ overrides: {
413
+ ...aptosConfig,
414
+ ...overrides
415
+ }
416
+ },
417
+ aptosConfig
418
+ );
419
+ }
420
+ async function postAptosFullNode(options) {
421
+ return post({ ...options, type: 0 /* FULLNODE */ });
422
+ }
423
+ async function postAptosIndexer(options) {
424
+ return post({ ...options, type: 1 /* INDEXER */ });
425
+ }
426
+ async function postAptosFaucet(options) {
427
+ return post({ ...options, type: 2 /* FAUCET */ });
428
+ }
429
+
430
+ // src/core/accountAddress.ts
431
+ var import_utils2 = require("@noble/hashes/utils");
432
+
433
+ // src/bcs/consts.ts
434
+ var MAX_U8_NUMBER = 2 ** 8 - 1;
435
+ var MAX_U16_NUMBER = 2 ** 16 - 1;
436
+ var MAX_U32_NUMBER = 2 ** 32 - 1;
437
+ var MAX_U64_BIG_INT = BigInt(2) ** BigInt(64) - BigInt(1);
438
+ var MAX_U128_BIG_INT = BigInt(2) ** BigInt(128) - BigInt(1);
439
+ var MAX_U256_BIG_INT = BigInt(2) ** BigInt(256) - BigInt(1);
440
+
441
+ // src/core/hex.ts
442
+ var import_utils = require("@noble/hashes/utils");
443
+
444
+ // src/core/common.ts
445
+ var ParsingError = class extends Error {
446
+ constructor(message, invalidReason) {
447
+ super(message);
448
+ this.invalidReason = invalidReason;
449
+ }
450
+ };
451
+
452
+ // src/core/hex.ts
453
+ var HexInvalidReason = /* @__PURE__ */ ((HexInvalidReason2) => {
454
+ HexInvalidReason2["TOO_SHORT"] = "too_short";
455
+ HexInvalidReason2["INVALID_LENGTH"] = "invalid_length";
456
+ HexInvalidReason2["INVALID_HEX_CHARS"] = "invalid_hex_chars";
457
+ return HexInvalidReason2;
458
+ })(HexInvalidReason || {});
459
+ var Hex = class {
460
+ constructor(data) {
461
+ this.data = data;
462
+ }
463
+ toUint8Array() {
464
+ return this.data;
465
+ }
466
+ toStringWithoutPrefix() {
467
+ return (0, import_utils.bytesToHex)(this.data);
468
+ }
469
+ toString() {
470
+ return `0x${this.toStringWithoutPrefix()}`;
471
+ }
472
+ static fromString(str) {
473
+ let input = str;
474
+ if (input.startsWith("0x")) {
475
+ input = input.slice(2);
476
+ }
477
+ if (input.length === 0) {
478
+ throw new ParsingError(
479
+ "Hex string is too short, must be at least 1 char long, excluding the optional leading 0x.",
480
+ "too_short" /* TOO_SHORT */
481
+ );
482
+ }
483
+ if (input.length % 2 !== 0) {
484
+ throw new ParsingError("Hex string must be an even number of hex characters.", "invalid_length" /* INVALID_LENGTH */);
485
+ }
486
+ try {
487
+ return new Hex((0, import_utils.hexToBytes)(input));
488
+ } catch (e) {
489
+ const error = e;
490
+ throw new ParsingError(
491
+ `Hex string contains invalid hex characters: ${error.message}`,
492
+ "invalid_hex_chars" /* INVALID_HEX_CHARS */
493
+ );
494
+ }
495
+ }
496
+ static fromHexInput(hexInput) {
497
+ if (hexInput instanceof Uint8Array)
498
+ return new Hex(hexInput);
499
+ return Hex.fromString(hexInput);
500
+ }
501
+ static isValid(str) {
502
+ try {
503
+ Hex.fromString(str);
504
+ return { valid: true };
505
+ } catch (e) {
506
+ const error = e;
507
+ return {
508
+ valid: false,
509
+ invalidReason: error.invalidReason,
510
+ invalidReasonMessage: error.message
511
+ };
512
+ }
513
+ }
514
+ equals(other) {
515
+ if (this.data.length !== other.data.length)
516
+ return false;
517
+ return this.data.every((value, index) => value === other.data[index]);
518
+ }
519
+ };
520
+
521
+ // src/bcs/serializer.ts
522
+ var Serializable = class {
523
+ bcsToBytes() {
524
+ const serializer = new Serializer();
525
+ this.serialize(serializer);
526
+ return serializer.toUint8Array();
527
+ }
528
+ bcsToHex() {
529
+ const bcsBytes = this.bcsToBytes();
530
+ return Hex.fromHexInput(bcsBytes);
531
+ }
532
+ };
533
+ var Serializer = class {
534
+ constructor(length = 64) {
535
+ if (length <= 0) {
536
+ throw new Error("Length needs to be greater than 0");
537
+ }
538
+ this.buffer = new ArrayBuffer(length);
539
+ this.offset = 0;
540
+ }
541
+ ensureBufferWillHandleSize(bytes) {
542
+ while (this.buffer.byteLength < this.offset + bytes) {
543
+ const newBuffer = new ArrayBuffer(this.buffer.byteLength * 2);
544
+ new Uint8Array(newBuffer).set(new Uint8Array(this.buffer));
545
+ this.buffer = newBuffer;
546
+ }
547
+ }
548
+ appendToBuffer(values) {
549
+ this.ensureBufferWillHandleSize(values.length);
550
+ new Uint8Array(this.buffer, this.offset).set(values);
551
+ this.offset += values.length;
552
+ }
553
+ serializeWithFunction(fn, bytesLength, value) {
554
+ this.ensureBufferWillHandleSize(bytesLength);
555
+ const dv = new DataView(this.buffer, this.offset);
556
+ fn.apply(dv, [0, value, true]);
557
+ this.offset += bytesLength;
558
+ }
559
+ serializeStr(value) {
560
+ const textEncoder = new TextEncoder();
561
+ this.serializeBytes(textEncoder.encode(value));
562
+ }
563
+ serializeBytes(value) {
564
+ this.serializeU32AsUleb128(value.length);
565
+ this.appendToBuffer(value);
566
+ }
567
+ serializeFixedBytes(value) {
568
+ this.appendToBuffer(value);
569
+ }
570
+ serializeBool(value) {
571
+ ensureBoolean(value);
572
+ const byteValue = value ? 1 : 0;
573
+ this.appendToBuffer(new Uint8Array([byteValue]));
574
+ }
575
+ serializeU8(value) {
576
+ this.appendToBuffer(new Uint8Array([value]));
577
+ }
578
+ serializeU16(value) {
579
+ this.serializeWithFunction(DataView.prototype.setUint16, 2, value);
580
+ }
581
+ serializeU32(value) {
582
+ this.serializeWithFunction(DataView.prototype.setUint32, 4, value);
583
+ }
584
+ serializeU64(value) {
585
+ const low = BigInt(value) & BigInt(MAX_U32_NUMBER);
586
+ const high = BigInt(value) >> BigInt(32);
587
+ this.serializeU32(Number(low));
588
+ this.serializeU32(Number(high));
589
+ }
590
+ serializeU128(value) {
591
+ const low = BigInt(value) & MAX_U64_BIG_INT;
592
+ const high = BigInt(value) >> BigInt(64);
593
+ this.serializeU64(low);
594
+ this.serializeU64(high);
595
+ }
596
+ serializeU256(value) {
597
+ const low = BigInt(value) & MAX_U128_BIG_INT;
598
+ const high = BigInt(value) >> BigInt(128);
599
+ this.serializeU128(low);
600
+ this.serializeU128(high);
601
+ }
602
+ serializeU32AsUleb128(val) {
603
+ let value = val;
604
+ const valueArray = [];
605
+ while (value >>> 7 !== 0) {
606
+ valueArray.push(value & 127 | 128);
607
+ value >>>= 7;
608
+ }
609
+ valueArray.push(value);
610
+ this.appendToBuffer(new Uint8Array(valueArray));
611
+ }
612
+ toUint8Array() {
613
+ return new Uint8Array(this.buffer).slice(0, this.offset);
614
+ }
615
+ serialize(value) {
616
+ value.serialize(this);
617
+ }
618
+ serializeVector(values) {
619
+ this.serializeU32AsUleb128(values.length);
620
+ values.forEach((item) => {
621
+ item.serialize(this);
622
+ });
623
+ }
624
+ };
625
+ __decorateClass([
626
+ checkNumberRange(0, MAX_U8_NUMBER)
627
+ ], Serializer.prototype, "serializeU8", 1);
628
+ __decorateClass([
629
+ checkNumberRange(0, MAX_U16_NUMBER)
630
+ ], Serializer.prototype, "serializeU16", 1);
631
+ __decorateClass([
632
+ checkNumberRange(0, MAX_U32_NUMBER)
633
+ ], Serializer.prototype, "serializeU32", 1);
634
+ __decorateClass([
635
+ checkNumberRange(BigInt(0), MAX_U64_BIG_INT)
636
+ ], Serializer.prototype, "serializeU64", 1);
637
+ __decorateClass([
638
+ checkNumberRange(BigInt(0), MAX_U128_BIG_INT)
639
+ ], Serializer.prototype, "serializeU128", 1);
640
+ __decorateClass([
641
+ checkNumberRange(BigInt(0), MAX_U256_BIG_INT)
642
+ ], Serializer.prototype, "serializeU256", 1);
643
+ __decorateClass([
644
+ checkNumberRange(0, MAX_U32_NUMBER)
645
+ ], Serializer.prototype, "serializeU32AsUleb128", 1);
646
+ function ensureBoolean(value) {
647
+ if (typeof value !== "boolean") {
648
+ throw new Error(`${value} is not a boolean value`);
649
+ }
650
+ }
651
+ var outOfRangeErrorMessage = (value, min, max) => `${value} is out of range: [${min}, ${max}]`;
652
+ function validateNumberInRange(value, minValue, maxValue) {
653
+ const valueBigInt = BigInt(value);
654
+ if (valueBigInt > BigInt(maxValue) || valueBigInt < BigInt(minValue)) {
655
+ throw new Error(outOfRangeErrorMessage(value, minValue, maxValue));
656
+ }
657
+ }
658
+ function checkNumberRange(minValue, maxValue) {
659
+ return (target, propertyKey, descriptor) => {
660
+ const childFunction = descriptor.value;
661
+ descriptor.value = function deco(value) {
662
+ validateNumberInRange(value, minValue, maxValue);
663
+ return childFunction.apply(this, [value]);
664
+ };
665
+ return descriptor;
666
+ };
667
+ }
668
+
669
+ // src/core/accountAddress.ts
670
+ var AddressInvalidReason = /* @__PURE__ */ ((AddressInvalidReason2) => {
671
+ AddressInvalidReason2["INCORRECT_NUMBER_OF_BYTES"] = "incorrect_number_of_bytes";
672
+ AddressInvalidReason2["INVALID_HEX_CHARS"] = "invalid_hex_chars";
673
+ AddressInvalidReason2["TOO_SHORT"] = "too_short";
674
+ AddressInvalidReason2["TOO_LONG"] = "too_long";
675
+ AddressInvalidReason2["LEADING_ZERO_X_REQUIRED"] = "leading_zero_x_required";
676
+ AddressInvalidReason2["LONG_FORM_REQUIRED_UNLESS_SPECIAL"] = "long_form_required_unless_special";
677
+ AddressInvalidReason2["INVALID_PADDING_ZEROES"] = "INVALID_PADDING_ZEROES";
678
+ return AddressInvalidReason2;
679
+ })(AddressInvalidReason || {});
680
+ var _AccountAddress = class extends Serializable {
681
+ constructor(args) {
682
+ super();
683
+ if (args.data.length !== _AccountAddress.LENGTH) {
684
+ throw new ParsingError(
685
+ "AccountAddress data should be exactly 32 bytes long",
686
+ "incorrect_number_of_bytes" /* INCORRECT_NUMBER_OF_BYTES */
687
+ );
688
+ }
689
+ this.data = args.data;
690
+ }
691
+ isSpecial() {
692
+ return this.data.slice(0, this.data.length - 1).every((byte) => byte === 0) && this.data[this.data.length - 1] < 16;
693
+ }
694
+ toString() {
695
+ return `0x${this.toStringWithoutPrefix()}`;
696
+ }
697
+ toStringWithoutPrefix() {
698
+ let hex = (0, import_utils2.bytesToHex)(this.data);
699
+ if (this.isSpecial()) {
700
+ hex = hex[hex.length - 1];
701
+ }
702
+ return hex;
703
+ }
704
+ toStringLong() {
705
+ return `0x${this.toStringLongWithoutPrefix()}`;
706
+ }
707
+ toStringLongWithoutPrefix() {
708
+ return (0, import_utils2.bytesToHex)(this.data);
709
+ }
710
+ toUint8Array() {
711
+ return this.data;
712
+ }
713
+ serialize(serializer) {
714
+ serializer.serializeFixedBytes(this.data);
715
+ }
716
+ serializeForEntryFunction(serializer) {
717
+ const bcsBytes = this.bcsToBytes();
718
+ serializer.serializeBytes(bcsBytes);
719
+ }
720
+ serializeForScriptFunction(serializer) {
721
+ serializer.serializeU32AsUleb128(3 /* Address */);
722
+ serializer.serialize(this);
723
+ }
724
+ static deserialize(deserializer) {
725
+ const bytes = deserializer.deserializeFixedBytes(_AccountAddress.LENGTH);
726
+ return new _AccountAddress({ data: bytes });
727
+ }
728
+ static fromString(input) {
729
+ if (!input.startsWith("0x")) {
730
+ throw new ParsingError("Hex string must start with a leading 0x.", "leading_zero_x_required" /* LEADING_ZERO_X_REQUIRED */);
731
+ }
732
+ const address = _AccountAddress.fromStringRelaxed(input);
733
+ if (input.length !== _AccountAddress.LONG_STRING_LENGTH + 2) {
734
+ if (!address.isSpecial()) {
735
+ throw new ParsingError(
736
+ `The given hex string ${address} is not a special address, it must be represented as 0x + 64 chars.`,
737
+ "long_form_required_unless_special" /* LONG_FORM_REQUIRED_UNLESS_SPECIAL */
738
+ );
739
+ } else if (input.length !== 3) {
740
+ throw new ParsingError(
741
+ `The given hex string ${input} is a special address not in LONG form, it must be 0x0 to 0xf without padding zeroes.`,
742
+ "INVALID_PADDING_ZEROES" /* INVALID_PADDING_ZEROES */
743
+ );
744
+ }
745
+ }
746
+ return address;
747
+ }
748
+ static fromStringRelaxed(input) {
749
+ let parsedInput = input;
750
+ if (input.startsWith("0x")) {
751
+ parsedInput = input.slice(2);
752
+ }
753
+ if (parsedInput.length === 0) {
754
+ throw new ParsingError(
755
+ "Hex string is too short, must be 1 to 64 chars long, excluding the leading 0x.",
756
+ "too_short" /* TOO_SHORT */
757
+ );
758
+ }
759
+ if (parsedInput.length > 64) {
760
+ throw new ParsingError(
761
+ "Hex string is too long, must be 1 to 64 chars long, excluding the leading 0x.",
762
+ "too_long" /* TOO_LONG */
763
+ );
764
+ }
765
+ let addressBytes;
766
+ try {
767
+ addressBytes = (0, import_utils2.hexToBytes)(parsedInput.padStart(64, "0"));
768
+ } catch (e) {
769
+ const error = e;
770
+ throw new ParsingError(`Hex characters are invalid: ${error.message}`, "invalid_hex_chars" /* INVALID_HEX_CHARS */);
771
+ }
772
+ return new _AccountAddress({ data: addressBytes });
773
+ }
774
+ static fromHexInput(input) {
775
+ if (input instanceof Uint8Array) {
776
+ return new _AccountAddress({ data: input });
777
+ }
778
+ return _AccountAddress.fromString(input);
779
+ }
780
+ static fromHexInputRelaxed(hexInput) {
781
+ if (hexInput instanceof Uint8Array) {
782
+ return new _AccountAddress({ data: hexInput });
783
+ }
784
+ return _AccountAddress.fromStringRelaxed(hexInput);
785
+ }
786
+ static isValid(args) {
787
+ try {
788
+ if (args.relaxed) {
789
+ _AccountAddress.fromStringRelaxed(args.input);
790
+ } else {
791
+ _AccountAddress.fromString(args.input);
792
+ }
793
+ return { valid: true };
794
+ } catch (e) {
795
+ const error = e;
796
+ return {
797
+ valid: false,
798
+ invalidReason: error.invalidReason,
799
+ invalidReasonMessage: error.message
800
+ };
801
+ }
802
+ }
803
+ equals(other) {
804
+ if (this.data.length !== other.data.length)
805
+ return false;
806
+ return this.data.every((value, index) => value === other.data[index]);
807
+ }
808
+ };
809
+ var AccountAddress = _AccountAddress;
810
+ AccountAddress.LENGTH = 32;
811
+ AccountAddress.LONG_STRING_LENGTH = 64;
812
+ AccountAddress.ONE = _AccountAddress.fromString("0x1");
813
+ AccountAddress.TWO = _AccountAddress.fromString("0x2");
814
+ AccountAddress.THREE = _AccountAddress.fromString("0x3");
815
+ AccountAddress.FOUR = _AccountAddress.fromString("0x4");
816
+
817
+ // src/core/authenticationKey.ts
818
+ var import_sha32 = require("@noble/hashes/sha3");
819
+
820
+ // src/core/crypto/ed25519.ts
821
+ var import_tweetnacl = __toESM(require("tweetnacl"));
822
+
823
+ // src/bcs/deserializer.ts
824
+ var Deserializer = class {
825
+ constructor(data) {
826
+ this.buffer = new ArrayBuffer(data.length);
827
+ new Uint8Array(this.buffer).set(data, 0);
828
+ this.offset = 0;
829
+ }
830
+ read(length) {
831
+ if (this.offset + length > this.buffer.byteLength) {
832
+ throw new Error("Reached to the end of buffer");
833
+ }
834
+ const bytes = this.buffer.slice(this.offset, this.offset + length);
835
+ this.offset += length;
836
+ return bytes;
837
+ }
838
+ deserializeStr() {
839
+ const value = this.deserializeBytes();
840
+ const textDecoder = new TextDecoder();
841
+ return textDecoder.decode(value);
842
+ }
843
+ deserializeBytes() {
844
+ const len = this.deserializeUleb128AsU32();
845
+ return new Uint8Array(this.read(len));
846
+ }
847
+ deserializeFixedBytes(len) {
848
+ return new Uint8Array(this.read(len));
849
+ }
850
+ deserializeBool() {
851
+ const bool = new Uint8Array(this.read(1))[0];
852
+ if (bool !== 1 && bool !== 0) {
853
+ throw new Error("Invalid boolean value");
854
+ }
855
+ return bool === 1;
856
+ }
857
+ deserializeU8() {
858
+ return new DataView(this.read(1)).getUint8(0);
859
+ }
860
+ deserializeU16() {
861
+ return new DataView(this.read(2)).getUint16(0, true);
862
+ }
863
+ deserializeU32() {
864
+ return new DataView(this.read(4)).getUint32(0, true);
865
+ }
866
+ deserializeU64() {
867
+ const low = this.deserializeU32();
868
+ const high = this.deserializeU32();
869
+ return BigInt(BigInt(high) << BigInt(32) | BigInt(low));
870
+ }
871
+ deserializeU128() {
872
+ const low = this.deserializeU64();
873
+ const high = this.deserializeU64();
874
+ return BigInt(high << BigInt(64) | low);
875
+ }
876
+ deserializeU256() {
877
+ const low = this.deserializeU128();
878
+ const high = this.deserializeU128();
879
+ return BigInt(high << BigInt(128) | low);
880
+ }
881
+ deserializeUleb128AsU32() {
882
+ let value = BigInt(0);
883
+ let shift = 0;
884
+ while (value < MAX_U32_NUMBER) {
885
+ const byte = this.deserializeU8();
886
+ value |= BigInt(byte & 127) << BigInt(shift);
887
+ if ((byte & 128) === 0) {
888
+ break;
889
+ }
890
+ shift += 7;
891
+ }
892
+ if (value > MAX_U32_NUMBER) {
893
+ throw new Error("Overflow while parsing uleb128-encoded uint32 value");
894
+ }
895
+ return Number(value);
896
+ }
897
+ deserialize(cls) {
898
+ return cls.deserialize(this);
899
+ }
900
+ deserializeVector(cls) {
901
+ const length = this.deserializeUleb128AsU32();
902
+ const vector = new Array();
903
+ for (let i = 0; i < length; i += 1) {
904
+ vector.push(this.deserialize(cls));
905
+ }
906
+ return vector;
907
+ }
908
+ };
909
+
910
+ // src/bcs/serializable/fixedBytes.ts
911
+ var FixedBytes = class extends Serializable {
912
+ constructor(value) {
913
+ super();
914
+ this.value = Hex.fromHexInput(value).toUint8Array();
915
+ }
916
+ serialize(serializer) {
917
+ serializer.serializeFixedBytes(this.value);
918
+ }
919
+ serializeForEntryFunction(serializer) {
920
+ serializer.serialize(this);
921
+ }
922
+ serializeForScriptFunction(serializer) {
923
+ serializer.serialize(this);
924
+ }
925
+ static deserialize(deserializer, length) {
926
+ const bytes = deserializer.deserializeFixedBytes(length);
927
+ return new FixedBytes(bytes);
928
+ }
929
+ };
930
+
931
+ // src/bcs/serializable/entryFunctionBytes.ts
932
+ var EntryFunctionBytes = class extends Serializable {
933
+ constructor(value) {
934
+ super();
935
+ this.value = new FixedBytes(value);
936
+ }
937
+ serialize(serializer) {
938
+ serializer.serialize(this.value);
939
+ }
940
+ serializeForEntryFunction(serializer) {
941
+ serializer.serializeU32AsUleb128(this.value.value.length);
942
+ serializer.serialize(this);
943
+ }
944
+ static deserialize(deserializer, length) {
945
+ const fixedBytes = FixedBytes.deserialize(deserializer, length);
946
+ return new EntryFunctionBytes(fixedBytes.value);
947
+ }
948
+ };
949
+
950
+ // src/bcs/serializable/movePrimitives.ts
951
+ var Bool = class extends Serializable {
952
+ constructor(value) {
953
+ super();
954
+ ensureBoolean(value);
955
+ this.value = value;
956
+ }
957
+ serialize(serializer) {
958
+ serializer.serializeBool(this.value);
959
+ }
960
+ serializeForEntryFunction(serializer) {
961
+ const bcsBytes = this.bcsToBytes();
962
+ serializer.serializeBytes(bcsBytes);
963
+ }
964
+ serializeForScriptFunction(serializer) {
965
+ serializer.serializeU32AsUleb128(5 /* Bool */);
966
+ serializer.serialize(this);
967
+ }
968
+ static deserialize(deserializer) {
969
+ return new Bool(deserializer.deserializeBool());
970
+ }
971
+ };
972
+ var U8 = class extends Serializable {
973
+ constructor(value) {
974
+ super();
975
+ validateNumberInRange(value, 0, MAX_U8_NUMBER);
976
+ this.value = value;
977
+ }
978
+ serialize(serializer) {
979
+ serializer.serializeU8(this.value);
980
+ }
981
+ serializeForEntryFunction(serializer) {
982
+ const bcsBytes = this.bcsToBytes();
983
+ serializer.serializeBytes(bcsBytes);
984
+ }
985
+ serializeForScriptFunction(serializer) {
986
+ serializer.serializeU32AsUleb128(0 /* U8 */);
987
+ serializer.serialize(this);
988
+ }
989
+ static deserialize(deserializer) {
990
+ return new U8(deserializer.deserializeU8());
991
+ }
992
+ };
993
+ var U16 = class extends Serializable {
994
+ constructor(value) {
995
+ super();
996
+ validateNumberInRange(value, 0, MAX_U16_NUMBER);
997
+ this.value = value;
998
+ }
999
+ serialize(serializer) {
1000
+ serializer.serializeU16(this.value);
1001
+ }
1002
+ serializeForEntryFunction(serializer) {
1003
+ const bcsBytes = this.bcsToBytes();
1004
+ serializer.serializeBytes(bcsBytes);
1005
+ }
1006
+ serializeForScriptFunction(serializer) {
1007
+ serializer.serializeU32AsUleb128(6 /* U16 */);
1008
+ serializer.serialize(this);
1009
+ }
1010
+ static deserialize(deserializer) {
1011
+ return new U16(deserializer.deserializeU16());
1012
+ }
1013
+ };
1014
+ var U32 = class extends Serializable {
1015
+ constructor(value) {
1016
+ super();
1017
+ validateNumberInRange(value, 0, MAX_U32_NUMBER);
1018
+ this.value = value;
1019
+ }
1020
+ serialize(serializer) {
1021
+ serializer.serializeU32(this.value);
1022
+ }
1023
+ serializeForEntryFunction(serializer) {
1024
+ const bcsBytes = this.bcsToBytes();
1025
+ serializer.serializeBytes(bcsBytes);
1026
+ }
1027
+ serializeForScriptFunction(serializer) {
1028
+ serializer.serializeU32AsUleb128(7 /* U32 */);
1029
+ serializer.serialize(this);
1030
+ }
1031
+ static deserialize(deserializer) {
1032
+ return new U32(deserializer.deserializeU32());
1033
+ }
1034
+ };
1035
+ var U64 = class extends Serializable {
1036
+ constructor(value) {
1037
+ super();
1038
+ validateNumberInRange(value, BigInt(0), MAX_U64_BIG_INT);
1039
+ this.value = BigInt(value);
1040
+ }
1041
+ serialize(serializer) {
1042
+ serializer.serializeU64(this.value);
1043
+ }
1044
+ serializeForEntryFunction(serializer) {
1045
+ const bcsBytes = this.bcsToBytes();
1046
+ serializer.serializeBytes(bcsBytes);
1047
+ }
1048
+ serializeForScriptFunction(serializer) {
1049
+ serializer.serializeU32AsUleb128(1 /* U64 */);
1050
+ serializer.serialize(this);
1051
+ }
1052
+ static deserialize(deserializer) {
1053
+ return new U64(deserializer.deserializeU64());
1054
+ }
1055
+ };
1056
+ var U128 = class extends Serializable {
1057
+ constructor(value) {
1058
+ super();
1059
+ validateNumberInRange(value, BigInt(0), MAX_U128_BIG_INT);
1060
+ this.value = BigInt(value);
1061
+ }
1062
+ serialize(serializer) {
1063
+ serializer.serializeU128(this.value);
1064
+ }
1065
+ serializeForEntryFunction(serializer) {
1066
+ const bcsBytes = this.bcsToBytes();
1067
+ serializer.serializeBytes(bcsBytes);
1068
+ }
1069
+ serializeForScriptFunction(serializer) {
1070
+ serializer.serializeU32AsUleb128(2 /* U128 */);
1071
+ serializer.serialize(this);
1072
+ }
1073
+ static deserialize(deserializer) {
1074
+ return new U128(deserializer.deserializeU128());
1075
+ }
1076
+ };
1077
+ var U256 = class extends Serializable {
1078
+ constructor(value) {
1079
+ super();
1080
+ validateNumberInRange(value, BigInt(0), MAX_U256_BIG_INT);
1081
+ this.value = BigInt(value);
1082
+ }
1083
+ serialize(serializer) {
1084
+ serializer.serializeU256(this.value);
1085
+ }
1086
+ serializeForEntryFunction(serializer) {
1087
+ const bcsBytes = this.bcsToBytes();
1088
+ serializer.serializeBytes(bcsBytes);
1089
+ }
1090
+ serializeForScriptFunction(serializer) {
1091
+ serializer.serializeU32AsUleb128(8 /* U256 */);
1092
+ serializer.serialize(this);
1093
+ }
1094
+ static deserialize(deserializer) {
1095
+ return new U256(deserializer.deserializeU256());
1096
+ }
1097
+ };
1098
+
1099
+ // src/bcs/serializable/moveStructs.ts
1100
+ var MoveVector = class extends Serializable {
1101
+ constructor(values) {
1102
+ super();
1103
+ this.values = values;
1104
+ }
1105
+ serializeForEntryFunction(serializer) {
1106
+ const bcsBytes = this.bcsToBytes();
1107
+ serializer.serializeBytes(bcsBytes);
1108
+ }
1109
+ serializeForScriptFunction(serializer) {
1110
+ const isU8 = this.values[0] instanceof U8;
1111
+ if (!isU8) {
1112
+ throw new Error("Script function arguments only accept u8 vectors");
1113
+ }
1114
+ serializer.serializeU32AsUleb128(4 /* U8Vector */);
1115
+ serializer.serialize(this);
1116
+ }
1117
+ static U8(values) {
1118
+ let numbers;
1119
+ if (Array.isArray(values) && typeof values[0] === "number") {
1120
+ numbers = values;
1121
+ } else if (typeof values === "string") {
1122
+ const hex = Hex.fromHexInput(values);
1123
+ numbers = Array.from(hex.toUint8Array());
1124
+ } else if (values instanceof Uint8Array) {
1125
+ numbers = Array.from(values);
1126
+ } else {
1127
+ throw new Error("Invalid input type");
1128
+ }
1129
+ return new MoveVector(numbers.map((v) => new U8(v)));
1130
+ }
1131
+ static U16(values) {
1132
+ return new MoveVector(values.map((v) => new U16(v)));
1133
+ }
1134
+ static U32(values) {
1135
+ return new MoveVector(values.map((v) => new U32(v)));
1136
+ }
1137
+ static U64(values) {
1138
+ return new MoveVector(values.map((v) => new U64(v)));
1139
+ }
1140
+ static U128(values) {
1141
+ return new MoveVector(values.map((v) => new U128(v)));
1142
+ }
1143
+ static U256(values) {
1144
+ return new MoveVector(values.map((v) => new U256(v)));
1145
+ }
1146
+ static Bool(values) {
1147
+ return new MoveVector(values.map((v) => new Bool(v)));
1148
+ }
1149
+ static MoveString(values) {
1150
+ return new MoveVector(values.map((v) => new MoveString(v)));
1151
+ }
1152
+ serialize(serializer) {
1153
+ serializer.serializeVector(this.values);
1154
+ }
1155
+ static deserialize(deserializer, cls) {
1156
+ const length = deserializer.deserializeUleb128AsU32();
1157
+ const values = new Array();
1158
+ for (let i = 0; i < length; i += 1) {
1159
+ values.push(cls.deserialize(deserializer));
1160
+ }
1161
+ return new MoveVector(values);
1162
+ }
1163
+ };
1164
+ var MoveString = class extends Serializable {
1165
+ constructor(value) {
1166
+ super();
1167
+ this.value = value;
1168
+ }
1169
+ serialize(serializer) {
1170
+ serializer.serializeStr(this.value);
1171
+ }
1172
+ serializeForEntryFunction(serializer) {
1173
+ const bcsBytes = this.bcsToBytes();
1174
+ serializer.serializeBytes(bcsBytes);
1175
+ }
1176
+ serializeForScriptFunction(serializer) {
1177
+ const vectorU8 = MoveVector.U8(this.bcsToBytes());
1178
+ vectorU8.serializeForScriptFunction(serializer);
1179
+ }
1180
+ static deserialize(deserializer) {
1181
+ return new MoveString(deserializer.deserializeStr());
1182
+ }
1183
+ };
1184
+ var MoveOption = class extends Serializable {
1185
+ constructor(value) {
1186
+ super();
1187
+ if (typeof value !== "undefined" && value !== null) {
1188
+ this.vec = new MoveVector([value]);
1189
+ } else {
1190
+ this.vec = new MoveVector([]);
1191
+ }
1192
+ [this.value] = this.vec.values;
1193
+ }
1194
+ serializeForEntryFunction(serializer) {
1195
+ const bcsBytes = this.bcsToBytes();
1196
+ serializer.serializeBytes(bcsBytes);
1197
+ }
1198
+ unwrap() {
1199
+ if (!this.isSome()) {
1200
+ throw new Error("Called unwrap on a MoveOption with no value");
1201
+ } else {
1202
+ return this.vec.values[0];
1203
+ }
1204
+ }
1205
+ isSome() {
1206
+ return this.vec.values.length === 1;
1207
+ }
1208
+ serialize(serializer) {
1209
+ this.vec.serialize(serializer);
1210
+ }
1211
+ static U8(value) {
1212
+ return new MoveOption(value !== null && value !== void 0 ? new U8(value) : void 0);
1213
+ }
1214
+ static U16(value) {
1215
+ return new MoveOption(value !== null && value !== void 0 ? new U16(value) : void 0);
1216
+ }
1217
+ static U32(value) {
1218
+ return new MoveOption(value !== null && value !== void 0 ? new U32(value) : void 0);
1219
+ }
1220
+ static U64(value) {
1221
+ return new MoveOption(value !== null && value !== void 0 ? new U64(value) : void 0);
1222
+ }
1223
+ static U128(value) {
1224
+ return new MoveOption(value !== null && value !== void 0 ? new U128(value) : void 0);
1225
+ }
1226
+ static U256(value) {
1227
+ return new MoveOption(value !== null && value !== void 0 ? new U256(value) : void 0);
1228
+ }
1229
+ static Bool(value) {
1230
+ return new MoveOption(value !== null && value !== void 0 ? new Bool(value) : void 0);
1231
+ }
1232
+ static MoveString(value) {
1233
+ return new MoveOption(value !== null && value !== void 0 ? new MoveString(value) : void 0);
1234
+ }
1235
+ static deserialize(deserializer, cls) {
1236
+ const vector = MoveVector.deserialize(deserializer, cls);
1237
+ return new MoveOption(vector.values[0]);
1238
+ }
1239
+ };
1240
+ var MoveObject = class extends Serializable {
1241
+ constructor(value) {
1242
+ super();
1243
+ if (value instanceof AccountAddress) {
1244
+ this.value = value;
1245
+ } else {
1246
+ this.value = AccountAddress.fromHexInputRelaxed(value);
1247
+ }
1248
+ }
1249
+ serialize(serializer) {
1250
+ serializer.serialize(this.value);
1251
+ }
1252
+ serializeForEntryFunction(serializer) {
1253
+ this.value.serializeForEntryFunction(serializer);
1254
+ }
1255
+ serializeForScriptFunction(serializer) {
1256
+ this.value.serializeForScriptFunction(serializer);
1257
+ }
1258
+ static deserialize(deserializer) {
1259
+ const address = deserializer.deserialize(AccountAddress);
1260
+ return new MoveObject(address);
1261
+ }
1262
+ };
1263
+
1264
+ // src/core/crypto/asymmetricCrypto.ts
1265
+ var PublicKey = class extends Serializable {
1266
+ };
1267
+ var PrivateKey = class extends Serializable {
1268
+ };
1269
+ var Signature = class extends Serializable {
1270
+ };
1271
+
1272
+ // src/core/crypto/ed25519.ts
1273
+ var _Ed25519PublicKey = class extends PublicKey {
1274
+ constructor(hexInput) {
1275
+ super();
1276
+ const hex = Hex.fromHexInput(hexInput);
1277
+ if (hex.toUint8Array().length !== _Ed25519PublicKey.LENGTH) {
1278
+ throw new Error(`PublicKey length should be ${_Ed25519PublicKey.LENGTH}`);
1279
+ }
1280
+ this.key = hex;
1281
+ }
1282
+ toUint8Array() {
1283
+ return this.key.toUint8Array();
1284
+ }
1285
+ toString() {
1286
+ return this.key.toString();
1287
+ }
1288
+ verifySignature(args) {
1289
+ const { message, signature } = args;
1290
+ const rawMessage = Hex.fromHexInput(message).toUint8Array();
1291
+ const rawSignature = Hex.fromHexInput(signature.toUint8Array()).toUint8Array();
1292
+ return import_tweetnacl.default.sign.detached.verify(rawMessage, rawSignature, this.key.toUint8Array());
1293
+ }
1294
+ serialize(serializer) {
1295
+ serializer.serializeBytes(this.key.toUint8Array());
1296
+ }
1297
+ static deserialize(deserializer) {
1298
+ const bytes = deserializer.deserializeBytes();
1299
+ return new _Ed25519PublicKey(bytes);
1300
+ }
1301
+ };
1302
+ var Ed25519PublicKey = _Ed25519PublicKey;
1303
+ Ed25519PublicKey.LENGTH = 32;
1304
+ var _Ed25519PrivateKey = class extends PrivateKey {
1305
+ constructor(hexInput) {
1306
+ super();
1307
+ const privateKeyHex = Hex.fromHexInput(hexInput);
1308
+ if (privateKeyHex.toUint8Array().length !== _Ed25519PrivateKey.LENGTH) {
1309
+ throw new Error(`PrivateKey length should be ${_Ed25519PrivateKey.LENGTH}`);
1310
+ }
1311
+ this.signingKeyPair = import_tweetnacl.default.sign.keyPair.fromSeed(privateKeyHex.toUint8Array().slice(0, _Ed25519PrivateKey.LENGTH));
1312
+ }
1313
+ toUint8Array() {
1314
+ return this.signingKeyPair.secretKey.slice(0, _Ed25519PrivateKey.LENGTH);
1315
+ }
1316
+ toString() {
1317
+ return Hex.fromHexInput(this.toUint8Array()).toString();
1318
+ }
1319
+ sign(message) {
1320
+ const hex = Hex.fromHexInput(message);
1321
+ const signature = import_tweetnacl.default.sign.detached(hex.toUint8Array(), this.signingKeyPair.secretKey);
1322
+ return new Ed25519Signature(signature);
1323
+ }
1324
+ serialize(serializer) {
1325
+ serializer.serializeBytes(this.toUint8Array());
1326
+ }
1327
+ static deserialize(deserializer) {
1328
+ const bytes = deserializer.deserializeBytes();
1329
+ return new _Ed25519PrivateKey(bytes);
1330
+ }
1331
+ static generate() {
1332
+ const keyPair = import_tweetnacl.default.sign.keyPair();
1333
+ return new _Ed25519PrivateKey(keyPair.secretKey.slice(0, _Ed25519PrivateKey.LENGTH));
1334
+ }
1335
+ publicKey() {
1336
+ const bytes = this.signingKeyPair.publicKey;
1337
+ return new Ed25519PublicKey(bytes);
1338
+ }
1339
+ };
1340
+ var Ed25519PrivateKey = _Ed25519PrivateKey;
1341
+ Ed25519PrivateKey.LENGTH = 32;
1342
+ var _Ed25519Signature = class extends Signature {
1343
+ constructor(hexInput) {
1344
+ super();
1345
+ const hex = Hex.fromHexInput(hexInput);
1346
+ if (hex.toUint8Array().length !== _Ed25519Signature.LENGTH) {
1347
+ throw new Error(`Signature length should be ${_Ed25519Signature.LENGTH}`);
1348
+ }
1349
+ this.data = hex;
1350
+ }
1351
+ toUint8Array() {
1352
+ return this.data.toUint8Array();
1353
+ }
1354
+ toString() {
1355
+ return this.data.toString();
1356
+ }
1357
+ serialize(serializer) {
1358
+ serializer.serializeBytes(this.data.toUint8Array());
1359
+ }
1360
+ static deserialize(deserializer) {
1361
+ const bytes = deserializer.deserializeBytes();
1362
+ return new _Ed25519Signature(bytes);
1363
+ }
1364
+ };
1365
+ var Ed25519Signature = _Ed25519Signature;
1366
+ Ed25519Signature.LENGTH = 64;
1367
+
1368
+ // src/core/crypto/multiEd25519.ts
1369
+ var _MultiEd25519PublicKey = class extends PublicKey {
1370
+ constructor(args) {
1371
+ super();
1372
+ const { publicKeys, threshold } = args;
1373
+ if (publicKeys.length > _MultiEd25519PublicKey.MAX_KEYS || publicKeys.length < _MultiEd25519PublicKey.MIN_KEYS) {
1374
+ throw new Error(
1375
+ `Must have between ${_MultiEd25519PublicKey.MIN_KEYS} and ${_MultiEd25519PublicKey.MAX_KEYS} public keys, inclusive`
1376
+ );
1377
+ }
1378
+ if (threshold < _MultiEd25519PublicKey.MIN_THRESHOLD || threshold > publicKeys.length) {
1379
+ throw new Error(
1380
+ `Threshold must be between ${_MultiEd25519PublicKey.MIN_THRESHOLD} and ${publicKeys.length}, inclusive`
1381
+ );
1382
+ }
1383
+ this.publicKeys = publicKeys;
1384
+ this.threshold = threshold;
1385
+ }
1386
+ toUint8Array() {
1387
+ const bytes = new Uint8Array(this.publicKeys.length * Ed25519PublicKey.LENGTH + 1);
1388
+ this.publicKeys.forEach((k, i) => {
1389
+ bytes.set(k.toUint8Array(), i * Ed25519PublicKey.LENGTH);
1390
+ });
1391
+ bytes[this.publicKeys.length * Ed25519PublicKey.LENGTH] = this.threshold;
1392
+ return bytes;
1393
+ }
1394
+ toString() {
1395
+ return Hex.fromHexInput(this.toUint8Array()).toString();
1396
+ }
1397
+ verifySignature(args) {
1398
+ throw new Error("TODO - Method not implemented.");
1399
+ }
1400
+ serialize(serializer) {
1401
+ serializer.serializeBytes(this.toUint8Array());
1402
+ }
1403
+ static deserialize(deserializer) {
1404
+ const bytes = deserializer.deserializeBytes();
1405
+ const threshold = bytes[bytes.length - 1];
1406
+ const keys = [];
1407
+ for (let i = 0; i < bytes.length - 1; i += Ed25519PublicKey.LENGTH) {
1408
+ const begin = i;
1409
+ keys.push(new Ed25519PublicKey(bytes.subarray(begin, begin + Ed25519PublicKey.LENGTH)));
1410
+ }
1411
+ return new _MultiEd25519PublicKey({ publicKeys: keys, threshold });
1412
+ }
1413
+ };
1414
+ var MultiEd25519PublicKey = _MultiEd25519PublicKey;
1415
+ MultiEd25519PublicKey.MAX_KEYS = 32;
1416
+ MultiEd25519PublicKey.MIN_KEYS = 2;
1417
+ MultiEd25519PublicKey.MIN_THRESHOLD = 1;
1418
+ var _MultiEd25519Signature = class extends Signature {
1419
+ constructor(args) {
1420
+ super();
1421
+ const { signatures, bitmap } = args;
1422
+ if (bitmap.length !== _MultiEd25519Signature.BITMAP_LEN) {
1423
+ throw new Error(`"bitmap" length should be ${_MultiEd25519Signature.BITMAP_LEN}`);
1424
+ }
1425
+ if (signatures.length > _MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED) {
1426
+ throw new Error(
1427
+ `The number of signatures cannot be greater than ${_MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED}`
1428
+ );
1429
+ }
1430
+ this.signatures = signatures;
1431
+ this.bitmap = bitmap;
1432
+ }
1433
+ toUint8Array() {
1434
+ const bytes = new Uint8Array(this.signatures.length * Ed25519Signature.LENGTH + _MultiEd25519Signature.BITMAP_LEN);
1435
+ this.signatures.forEach((k, i) => {
1436
+ bytes.set(k.toUint8Array(), i * Ed25519Signature.LENGTH);
1437
+ });
1438
+ bytes.set(this.bitmap, this.signatures.length * Ed25519Signature.LENGTH);
1439
+ return bytes;
1440
+ }
1441
+ toString() {
1442
+ return Hex.fromHexInput(this.toUint8Array()).toString();
1443
+ }
1444
+ static createBitmap(args) {
1445
+ const { bits } = args;
1446
+ const firstBitInByte = 128;
1447
+ const bitmap = new Uint8Array([0, 0, 0, 0]);
1448
+ const dupCheckSet = /* @__PURE__ */ new Set();
1449
+ bits.forEach((bit) => {
1450
+ if (bit >= _MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED) {
1451
+ throw new Error(`Cannot have a signature larger than ${_MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED - 1}.`);
1452
+ }
1453
+ if (dupCheckSet.has(bit)) {
1454
+ throw new Error("Duplicate bits detected.");
1455
+ }
1456
+ dupCheckSet.add(bit);
1457
+ const byteOffset = Math.floor(bit / 8);
1458
+ let byte = bitmap[byteOffset];
1459
+ byte |= firstBitInByte >> bit % 8;
1460
+ bitmap[byteOffset] = byte;
1461
+ });
1462
+ return bitmap;
1463
+ }
1464
+ serialize(serializer) {
1465
+ serializer.serializeBytes(this.toUint8Array());
1466
+ }
1467
+ static deserialize(deserializer) {
1468
+ const bytes = deserializer.deserializeBytes();
1469
+ const bitmap = bytes.subarray(bytes.length - 4);
1470
+ const signatures = [];
1471
+ for (let i = 0; i < bytes.length - bitmap.length; i += Ed25519Signature.LENGTH) {
1472
+ const begin = i;
1473
+ signatures.push(new Ed25519Signature(bytes.subarray(begin, begin + Ed25519Signature.LENGTH)));
1474
+ }
1475
+ return new _MultiEd25519Signature({ signatures, bitmap });
1476
+ }
1477
+ };
1478
+ var MultiEd25519Signature = _MultiEd25519Signature;
1479
+ MultiEd25519Signature.MAX_SIGNATURES_SUPPORTED = 32;
1480
+ MultiEd25519Signature.BITMAP_LEN = 4;
1481
+
1482
+ // src/core/crypto/secp256k1.ts
1483
+ var import_sha3 = require("@noble/hashes/sha3");
1484
+ var import_secp256k1 = require("@noble/curves/secp256k1");
1485
+ var _Secp256k1PublicKey = class extends PublicKey {
1486
+ constructor(hexInput) {
1487
+ super();
1488
+ const hex = Hex.fromHexInput(hexInput);
1489
+ if (hex.toUint8Array().length !== _Secp256k1PublicKey.LENGTH) {
1490
+ throw new Error(`PublicKey length should be ${_Secp256k1PublicKey.LENGTH}`);
1491
+ }
1492
+ this.key = hex;
1493
+ }
1494
+ toUint8Array() {
1495
+ return this.key.toUint8Array();
1496
+ }
1497
+ toString() {
1498
+ return this.key.toString();
1499
+ }
1500
+ verifySignature(args) {
1501
+ const { message, signature } = args;
1502
+ const msgHex = Hex.fromHexInput(message).toUint8Array();
1503
+ const sha3Message = (0, import_sha3.sha3_256)(msgHex);
1504
+ const rawSignature = signature.toUint8Array();
1505
+ return import_secp256k1.secp256k1.verify(rawSignature, sha3Message, this.toUint8Array());
1506
+ }
1507
+ serialize(serializer) {
1508
+ serializer.serializeBytes(this.key.toUint8Array());
1509
+ }
1510
+ static deserialize(deserializer) {
1511
+ const bytes = deserializer.deserializeBytes();
1512
+ return new _Secp256k1PublicKey(bytes);
1513
+ }
1514
+ };
1515
+ var Secp256k1PublicKey = _Secp256k1PublicKey;
1516
+ Secp256k1PublicKey.LENGTH = 65;
1517
+ var _Secp256k1PrivateKey = class extends PrivateKey {
1518
+ constructor(hexInput) {
1519
+ super();
1520
+ const privateKeyHex = Hex.fromHexInput(hexInput);
1521
+ if (privateKeyHex.toUint8Array().length !== _Secp256k1PrivateKey.LENGTH) {
1522
+ throw new Error(`PrivateKey length should be ${_Secp256k1PrivateKey.LENGTH}`);
1523
+ }
1524
+ this.key = privateKeyHex;
1525
+ }
1526
+ toUint8Array() {
1527
+ return this.key.toUint8Array();
1528
+ }
1529
+ toString() {
1530
+ return this.key.toString();
1531
+ }
1532
+ sign(message) {
1533
+ const msgHex = Hex.fromHexInput(message);
1534
+ const sha3Message = (0, import_sha3.sha3_256)(msgHex.toUint8Array());
1535
+ const signature = import_secp256k1.secp256k1.sign(sha3Message, this.key.toUint8Array());
1536
+ return new Secp256k1Signature(signature.toCompactRawBytes());
1537
+ }
1538
+ serialize(serializer) {
1539
+ serializer.serializeBytes(this.toUint8Array());
1540
+ }
1541
+ static deserialize(deserializer) {
1542
+ const bytes = deserializer.deserializeBytes();
1543
+ return new _Secp256k1PrivateKey(bytes);
1544
+ }
1545
+ static generate() {
1546
+ const hexInput = import_secp256k1.secp256k1.utils.randomPrivateKey();
1547
+ return new _Secp256k1PrivateKey(hexInput);
1548
+ }
1549
+ publicKey() {
1550
+ const bytes = import_secp256k1.secp256k1.getPublicKey(this.key.toUint8Array(), false);
1551
+ return new Secp256k1PublicKey(bytes);
1552
+ }
1553
+ };
1554
+ var Secp256k1PrivateKey = _Secp256k1PrivateKey;
1555
+ Secp256k1PrivateKey.LENGTH = 32;
1556
+ var _Secp256k1Signature = class extends Signature {
1557
+ constructor(hexInput) {
1558
+ super();
1559
+ const hex = Hex.fromHexInput(hexInput);
1560
+ if (hex.toUint8Array().length !== _Secp256k1Signature.LENGTH) {
1561
+ throw new Error(`Signature length should be ${_Secp256k1Signature.LENGTH}`);
1562
+ }
1563
+ this.data = hex;
1564
+ }
1565
+ toUint8Array() {
1566
+ return this.data.toUint8Array();
1567
+ }
1568
+ toString() {
1569
+ return this.data.toString();
1570
+ }
1571
+ serialize(serializer) {
1572
+ serializer.serializeBytes(this.data.toUint8Array());
1573
+ }
1574
+ static deserialize(deserializer) {
1575
+ const hex = deserializer.deserializeBytes();
1576
+ return new _Secp256k1Signature(hex);
1577
+ }
1578
+ };
1579
+ var Secp256k1Signature = _Secp256k1Signature;
1580
+ Secp256k1Signature.LENGTH = 64;
1581
+
1582
+ // src/core/authenticationKey.ts
1583
+ var _AuthenticationKey = class {
1584
+ constructor(args) {
1585
+ const { data } = args;
1586
+ const hex = Hex.fromHexInput(data);
1587
+ if (hex.toUint8Array().length !== _AuthenticationKey.LENGTH) {
1588
+ throw new Error(`Authentication Key length should be ${_AuthenticationKey.LENGTH}`);
1589
+ }
1590
+ this.data = hex;
1591
+ }
1592
+ toString() {
1593
+ return this.data.toString();
1594
+ }
1595
+ toUint8Array() {
1596
+ return this.data.toUint8Array();
1597
+ }
1598
+ static fromBytesAndScheme(args) {
1599
+ const { bytes, scheme } = args;
1600
+ const inputBytes = Hex.fromHexInput(bytes).toUint8Array();
1601
+ const authKeyBytes = new Uint8Array(inputBytes.length + 1);
1602
+ authKeyBytes.set(inputBytes);
1603
+ authKeyBytes.set([scheme], inputBytes.length);
1604
+ const hash = import_sha32.sha3_256.create();
1605
+ hash.update(authKeyBytes);
1606
+ return new _AuthenticationKey({ data: hash.digest() });
1607
+ }
1608
+ static fromPublicKey(args) {
1609
+ const { publicKey } = args;
1610
+ let scheme;
1611
+ if (publicKey instanceof Ed25519PublicKey) {
1612
+ scheme = 0 /* Ed25519 */.valueOf();
1613
+ } else if (publicKey instanceof MultiEd25519PublicKey) {
1614
+ scheme = 1 /* MultiEd25519 */.valueOf();
1615
+ } else if (publicKey instanceof Secp256k1PublicKey) {
1616
+ scheme = 2 /* Secp256k1Ecdsa */.valueOf();
1617
+ } else {
1618
+ throw new Error("No supported authentication scheme for public key");
1619
+ }
1620
+ const pubKeyBytes = publicKey.toUint8Array();
1621
+ return _AuthenticationKey.fromBytesAndScheme({ bytes: pubKeyBytes, scheme });
1622
+ }
1623
+ derivedAddress() {
1624
+ return new AccountAddress({ data: this.data.toUint8Array() });
1625
+ }
1626
+ };
1627
+ var AuthenticationKey = _AuthenticationKey;
1628
+ AuthenticationKey.LENGTH = 32;
1629
+
1630
+ // src/utils/hdKey.ts
1631
+ var import_hmac = require("@noble/hashes/hmac");
1632
+ var import_sha512 = require("@noble/hashes/sha512");
1633
+ var bip39 = __toESM(require("@scure/bip39"));
1634
+ var APTOS_PATH_REGEX = /^m\/44'\/637'\/[0-9]+'\/[0-9]+'\/[0-9]+'?$/;
1635
+ var KeyType = /* @__PURE__ */ ((KeyType2) => {
1636
+ KeyType2["ED25519"] = "ed25519 seed";
1637
+ return KeyType2;
1638
+ })(KeyType || {});
1639
+ var HARDENED_OFFSET = 2147483648;
1640
+ var deriveKey = (hashSeed, data) => {
1641
+ const digest = import_hmac.hmac.create(import_sha512.sha512, hashSeed).update(data).digest();
1642
+ return {
1643
+ key: digest.slice(0, 32),
1644
+ chainCode: digest.slice(32)
1645
+ };
1646
+ };
1647
+ var CKDPriv = ({ key, chainCode }, index) => {
1648
+ const buffer = new ArrayBuffer(4);
1649
+ new DataView(buffer).setUint32(0, index);
1650
+ const indexBytes = new Uint8Array(buffer);
1651
+ const zero = new Uint8Array([0]);
1652
+ const data = new Uint8Array([...zero, ...key, ...indexBytes]);
1653
+ return deriveKey(chainCode, data);
1654
+ };
1655
+ var removeApostrophes = (val) => val.replace("'", "");
1656
+ var splitPath = (path) => path.split("/").slice(1).map(removeApostrophes);
1657
+ var isValidPath = (path) => {
1658
+ if (!APTOS_PATH_REGEX.test(path)) {
1659
+ return false;
1660
+ }
1661
+ return !splitPath(path).some(Number.isNaN);
1662
+ };
1663
+ var mnemonicToSeed = (mnemonic) => {
1664
+ const normalizedMnemonic = mnemonic.trim().split(/\s+/).map((part) => part.toLowerCase()).join(" ");
1665
+ return bip39.mnemonicToSeedSync(normalizedMnemonic);
1666
+ };
1667
+ var derivePrivateKeyFromMnemonic = (keyType, path, seedPhrase, offset = HARDENED_OFFSET) => {
1668
+ if (!isValidPath(path)) {
1669
+ throw new Error("Invalid derivation path");
1670
+ }
1671
+ const { key, chainCode } = deriveKey(keyType, mnemonicToSeed(seedPhrase));
1672
+ const segments = splitPath(path).map((el) => parseInt(el, 10));
1673
+ return segments.reduce((parentKeys, segment) => CKDPriv(parentKeys, segment + offset), { key, chainCode });
1674
+ };
1675
+
1676
+ // src/core/account.ts
1677
+ var Account = class {
1678
+ constructor(args) {
1679
+ const { privateKey, address } = args;
1680
+ this.publicKey = privateKey.publicKey();
1681
+ if (this.publicKey instanceof Ed25519PublicKey) {
1682
+ this.signingScheme = 0 /* Ed25519 */;
1683
+ } else if (this.publicKey instanceof MultiEd25519PublicKey) {
1684
+ this.signingScheme = 1 /* MultiEd25519 */;
1685
+ } else if (this.publicKey instanceof Secp256k1PublicKey) {
1686
+ this.signingScheme = 2 /* Secp256k1Ecdsa */;
1687
+ } else {
1688
+ throw new Error("Can not create new Account, unsupported public key type");
1689
+ }
1690
+ this.privateKey = privateKey;
1691
+ this.accountAddress = address;
1692
+ }
1693
+ static generate(scheme) {
1694
+ let privateKey;
1695
+ switch (scheme) {
1696
+ case 2 /* Secp256k1Ecdsa */:
1697
+ privateKey = Secp256k1PrivateKey.generate();
1698
+ break;
1699
+ default:
1700
+ privateKey = Ed25519PrivateKey.generate();
1701
+ }
1702
+ const address = new AccountAddress({
1703
+ data: Account.authKey({
1704
+ publicKey: privateKey.publicKey()
1705
+ }).toUint8Array()
1706
+ });
1707
+ return new Account({ privateKey, address });
1708
+ }
1709
+ static fromPrivateKey(privateKey) {
1710
+ const publicKey = privateKey.publicKey();
1711
+ const authKey = Account.authKey({ publicKey });
1712
+ const address = new AccountAddress({ data: authKey.toUint8Array() });
1713
+ return Account.fromPrivateKeyAndAddress({ privateKey, address });
1714
+ }
1715
+ static fromPrivateKeyAndAddress(args) {
1716
+ return new Account(args);
1717
+ }
1718
+ static fromDerivationPath(args) {
1719
+ const { path, mnemonic } = args;
1720
+ const { key } = derivePrivateKeyFromMnemonic("ed25519 seed" /* ED25519 */, path, mnemonic);
1721
+ const privateKey = new Ed25519PrivateKey(key);
1722
+ return Account.fromPrivateKey(privateKey);
1723
+ }
1724
+ static authKey(args) {
1725
+ const { publicKey } = args;
1726
+ const authKey = AuthenticationKey.fromPublicKey({ publicKey });
1727
+ return authKey.data;
1728
+ }
1729
+ sign(data) {
1730
+ return this.privateKey.sign(data);
1731
+ }
1732
+ verifySignature(args) {
1733
+ const { message, signature } = args;
1734
+ const rawMessage = Hex.fromHexInput(message).toUint8Array();
1735
+ return this.publicKey.verifySignature({ message: rawMessage, signature });
1736
+ }
1737
+ };
1738
+
1739
+ // src/types/generated/queries.ts
1740
+ var CurrentTokenOwnershipFieldsFragmentDoc = `
1741
+ fragment CurrentTokenOwnershipFields on current_token_ownerships_v2 {
1742
+ token_standard
1743
+ token_properties_mutated_v1
1744
+ token_data_id
1745
+ table_type_v1
1746
+ storage_id
1747
+ property_version_v1
1748
+ owner_address
1749
+ last_transaction_version
1750
+ last_transaction_timestamp
1751
+ is_soulbound_v2
1752
+ is_fungible_v2
1753
+ amount
1754
+ current_token_data {
1755
+ collection_id
1756
+ description
1757
+ is_fungible_v2
1758
+ largest_property_version_v1
1759
+ last_transaction_timestamp
1760
+ last_transaction_version
1761
+ maximum
1762
+ supply
1763
+ token_data_id
1764
+ token_name
1765
+ token_properties
1766
+ token_standard
1767
+ token_uri
1768
+ current_collection {
1769
+ collection_id
1770
+ collection_name
1771
+ creator_address
1772
+ current_supply
1773
+ description
1774
+ last_transaction_timestamp
1775
+ last_transaction_version
1776
+ max_supply
1777
+ mutable_description
1778
+ mutable_uri
1779
+ table_handle_v1
1780
+ token_standard
1781
+ total_minted_v2
1782
+ uri
1783
+ }
1784
+ }
1785
+ }
1786
+ `;
1787
+ var TokenActivitiesFieldsFragmentDoc = `
1788
+ fragment TokenActivitiesFields on token_activities_v2 {
1789
+ after_value
1790
+ before_value
1791
+ entry_function_id_str
1792
+ event_account_address
1793
+ event_index
1794
+ from_address
1795
+ is_fungible_v2
1796
+ property_version_v1
1797
+ to_address
1798
+ token_amount
1799
+ token_data_id
1800
+ token_standard
1801
+ transaction_timestamp
1802
+ transaction_version
1803
+ type
1804
+ }
1805
+ `;
1806
+ var GetAccountCoinsCount = `
1807
+ query getAccountCoinsCount($address: String) {
1808
+ current_fungible_asset_balances_aggregate(
1809
+ where: {owner_address: {_eq: $address}}
1810
+ ) {
1811
+ aggregate {
1812
+ count
1813
+ }
1814
+ }
1815
+ }
1816
+ `;
1817
+ var GetAccountCoinsData = `
1818
+ query getAccountCoinsData($where_condition: current_fungible_asset_balances_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_fungible_asset_balances_order_by!]) {
1819
+ current_fungible_asset_balances(
1820
+ where: $where_condition
1821
+ offset: $offset
1822
+ limit: $limit
1823
+ order_by: $order_by
1824
+ ) {
1825
+ amount
1826
+ asset_type
1827
+ is_frozen
1828
+ is_primary
1829
+ last_transaction_timestamp
1830
+ last_transaction_version
1831
+ owner_address
1832
+ storage_id
1833
+ token_standard
1834
+ metadata {
1835
+ token_standard
1836
+ symbol
1837
+ supply_aggregator_table_key_v1
1838
+ supply_aggregator_table_handle_v1
1839
+ project_uri
1840
+ name
1841
+ last_transaction_version
1842
+ last_transaction_timestamp
1843
+ icon_uri
1844
+ decimals
1845
+ creator_address
1846
+ asset_type
1847
+ }
1848
+ }
1849
+ }
1850
+ `;
1851
+ var GetAccountCollectionsWithOwnedTokens = `
1852
+ query getAccountCollectionsWithOwnedTokens($where_condition: current_collection_ownership_v2_view_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_collection_ownership_v2_view_order_by!]) {
1853
+ current_collection_ownership_v2_view(
1854
+ where: $where_condition
1855
+ offset: $offset
1856
+ limit: $limit
1857
+ order_by: $order_by
1858
+ ) {
1859
+ current_collection {
1860
+ collection_id
1861
+ collection_name
1862
+ creator_address
1863
+ current_supply
1864
+ description
1865
+ last_transaction_timestamp
1866
+ last_transaction_version
1867
+ mutable_description
1868
+ max_supply
1869
+ mutable_uri
1870
+ table_handle_v1
1871
+ token_standard
1872
+ total_minted_v2
1873
+ uri
1874
+ }
1875
+ collection_id
1876
+ collection_name
1877
+ collection_uri
1878
+ creator_address
1879
+ distinct_tokens
1880
+ last_transaction_version
1881
+ owner_address
1882
+ single_token_uri
1883
+ }
1884
+ }
1885
+ `;
1886
+ var GetAccountOwnedObjects = `
1887
+ query getAccountOwnedObjects($where_condition: current_objects_bool_exp, $offset: Int, $limit: Int, $order_by: [current_objects_order_by!]) {
1888
+ current_objects(
1889
+ where: $where_condition
1890
+ offset: $offset
1891
+ limit: $limit
1892
+ order_by: $order_by
1893
+ ) {
1894
+ allow_ungated_transfer
1895
+ state_key_hash
1896
+ owner_address
1897
+ object_address
1898
+ last_transaction_version
1899
+ last_guid_creation_num
1900
+ is_deleted
1901
+ }
1902
+ }
1903
+ `;
1904
+ var GetAccountOwnedTokens = `
1905
+ query getAccountOwnedTokens($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {
1906
+ current_token_ownerships_v2(
1907
+ where: $where_condition
1908
+ offset: $offset
1909
+ limit: $limit
1910
+ order_by: $order_by
1911
+ ) {
1912
+ ...CurrentTokenOwnershipFields
1913
+ }
1914
+ }
1915
+ ${CurrentTokenOwnershipFieldsFragmentDoc}`;
1916
+ var GetAccountOwnedTokensByTokenData = `
1917
+ query getAccountOwnedTokensByTokenData($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {
1918
+ current_token_ownerships_v2(
1919
+ where: $where_condition
1920
+ offset: $offset
1921
+ limit: $limit
1922
+ order_by: $order_by
1923
+ ) {
1924
+ ...CurrentTokenOwnershipFields
1925
+ }
1926
+ }
1927
+ ${CurrentTokenOwnershipFieldsFragmentDoc}`;
1928
+ var GetAccountOwnedTokensFromCollection = `
1929
+ query getAccountOwnedTokensFromCollection($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {
1930
+ current_token_ownerships_v2(
1931
+ where: $where_condition
1932
+ offset: $offset
1933
+ limit: $limit
1934
+ order_by: $order_by
1935
+ ) {
1936
+ ...CurrentTokenOwnershipFields
1937
+ }
1938
+ }
1939
+ ${CurrentTokenOwnershipFieldsFragmentDoc}`;
1940
+ var GetAccountTokensCount = `
1941
+ query getAccountTokensCount($where_condition: current_token_ownerships_v2_bool_exp, $offset: Int, $limit: Int) {
1942
+ current_token_ownerships_v2_aggregate(
1943
+ where: $where_condition
1944
+ offset: $offset
1945
+ limit: $limit
1946
+ ) {
1947
+ aggregate {
1948
+ count
1949
+ }
1950
+ }
1951
+ }
1952
+ `;
1953
+ var GetAccountTransactionsCount = `
1954
+ query getAccountTransactionsCount($address: String) {
1955
+ account_transactions_aggregate(where: {account_address: {_eq: $address}}) {
1956
+ aggregate {
1957
+ count
1958
+ }
1959
+ }
1960
+ }
1961
+ `;
1962
+ var GetChainTopUserTransactions = `
1963
+ query getChainTopUserTransactions($limit: Int) {
1964
+ user_transactions(limit: $limit, order_by: {version: desc}) {
1965
+ version
1966
+ }
1967
+ }
1968
+ `;
1969
+ var GetCollectionData = `
1970
+ query getCollectionData($where_condition: current_collections_v2_bool_exp!) {
1971
+ current_collections_v2(where: $where_condition) {
1972
+ collection_id
1973
+ collection_name
1974
+ creator_address
1975
+ current_supply
1976
+ description
1977
+ last_transaction_timestamp
1978
+ last_transaction_version
1979
+ max_supply
1980
+ mutable_description
1981
+ mutable_uri
1982
+ table_handle_v1
1983
+ token_standard
1984
+ total_minted_v2
1985
+ uri
1986
+ }
1987
+ }
1988
+ `;
1989
+ var GetCurrentFungibleAssetBalances = `
1990
+ query getCurrentFungibleAssetBalances($where_condition: current_fungible_asset_balances_bool_exp, $offset: Int, $limit: Int) {
1991
+ current_fungible_asset_balances(
1992
+ where: $where_condition
1993
+ offset: $offset
1994
+ limit: $limit
1995
+ ) {
1996
+ amount
1997
+ asset_type
1998
+ is_frozen
1999
+ is_primary
2000
+ last_transaction_timestamp
2001
+ last_transaction_version
2002
+ owner_address
2003
+ storage_id
2004
+ token_standard
2005
+ }
2006
+ }
2007
+ `;
2008
+ var GetDelegatedStakingActivities = `
2009
+ query getDelegatedStakingActivities($delegatorAddress: String, $poolAddress: String) {
2010
+ delegated_staking_activities(
2011
+ where: {delegator_address: {_eq: $delegatorAddress}, pool_address: {_eq: $poolAddress}}
2012
+ ) {
2013
+ amount
2014
+ delegator_address
2015
+ event_index
2016
+ event_type
2017
+ pool_address
2018
+ transaction_version
2019
+ }
2020
+ }
2021
+ `;
2022
+ var GetEvents = `
2023
+ query getEvents($where_condition: events_bool_exp, $offset: Int, $limit: Int, $order_by: [events_order_by!]) {
2024
+ events(
2025
+ where: $where_condition
2026
+ offset: $offset
2027
+ limit: $limit
2028
+ order_by: $order_by
2029
+ ) {
2030
+ account_address
2031
+ creation_number
2032
+ data
2033
+ event_index
2034
+ sequence_number
2035
+ transaction_block_height
2036
+ transaction_version
2037
+ type
2038
+ }
2039
+ }
2040
+ `;
2041
+ var GetFungibleAssetActivities = `
2042
+ query getFungibleAssetActivities($where_condition: fungible_asset_activities_bool_exp, $offset: Int, $limit: Int) {
2043
+ fungible_asset_activities(
2044
+ where: $where_condition
2045
+ offset: $offset
2046
+ limit: $limit
2047
+ ) {
2048
+ amount
2049
+ asset_type
2050
+ block_height
2051
+ entry_function_id_str
2052
+ event_index
2053
+ gas_fee_payer_address
2054
+ is_frozen
2055
+ is_gas_fee
2056
+ is_transaction_success
2057
+ owner_address
2058
+ storage_id
2059
+ storage_refund_amount
2060
+ token_standard
2061
+ transaction_timestamp
2062
+ transaction_version
2063
+ type
2064
+ }
2065
+ }
2066
+ `;
2067
+ var GetFungibleAssetMetadata = `
2068
+ query getFungibleAssetMetadata($where_condition: fungible_asset_metadata_bool_exp, $offset: Int, $limit: Int) {
2069
+ fungible_asset_metadata(where: $where_condition, offset: $offset, limit: $limit) {
2070
+ icon_uri
2071
+ project_uri
2072
+ supply_aggregator_table_handle_v1
2073
+ supply_aggregator_table_key_v1
2074
+ creator_address
2075
+ asset_type
2076
+ decimals
2077
+ last_transaction_timestamp
2078
+ last_transaction_version
2079
+ name
2080
+ symbol
2081
+ token_standard
2082
+ }
2083
+ }
2084
+ `;
2085
+ var GetNumberOfDelegators = `
2086
+ query getNumberOfDelegators($where_condition: num_active_delegator_per_pool_bool_exp!, $order_by: [num_active_delegator_per_pool_order_by!]) {
2087
+ num_active_delegator_per_pool(where: $where_condition, order_by: $order_by) {
2088
+ num_active_delegator
2089
+ pool_address
2090
+ }
2091
+ }
2092
+ `;
2093
+ var GetProcessorStatus = `
2094
+ query getProcessorStatus {
2095
+ processor_status {
2096
+ last_success_version
2097
+ processor
2098
+ last_updated
2099
+ }
2100
+ }
2101
+ `;
2102
+ var GetTokenActivity = `
2103
+ query getTokenActivity($where_condition: token_activities_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [token_activities_v2_order_by!]) {
2104
+ token_activities_v2(
2105
+ where: $where_condition
2106
+ order_by: $order_by
2107
+ offset: $offset
2108
+ limit: $limit
2109
+ ) {
2110
+ ...TokenActivitiesFields
2111
+ }
2112
+ }
2113
+ ${TokenActivitiesFieldsFragmentDoc}`;
2114
+ var GetCurrentTokenOwnership = `
2115
+ query getCurrentTokenOwnership($where_condition: current_token_ownerships_v2_bool_exp!, $offset: Int, $limit: Int, $order_by: [current_token_ownerships_v2_order_by!]) {
2116
+ current_token_ownerships_v2(
2117
+ where: $where_condition
2118
+ offset: $offset
2119
+ limit: $limit
2120
+ order_by: $order_by
2121
+ ) {
2122
+ ...CurrentTokenOwnershipFields
2123
+ }
2124
+ }
2125
+ ${CurrentTokenOwnershipFieldsFragmentDoc}`;
2126
+ var GetTokenData = `
2127
+ query getTokenData($where_condition: current_token_datas_v2_bool_exp, $offset: Int, $limit: Int, $order_by: [current_token_datas_v2_order_by!]) {
2128
+ current_token_datas_v2(
2129
+ where: $where_condition
2130
+ offset: $offset
2131
+ limit: $limit
2132
+ order_by: $order_by
2133
+ ) {
2134
+ collection_id
2135
+ description
2136
+ is_fungible_v2
2137
+ largest_property_version_v1
2138
+ last_transaction_timestamp
2139
+ last_transaction_version
2140
+ maximum
2141
+ supply
2142
+ token_data_id
2143
+ token_name
2144
+ token_properties
2145
+ token_standard
2146
+ token_uri
2147
+ current_collection {
2148
+ collection_id
2149
+ collection_name
2150
+ creator_address
2151
+ current_supply
2152
+ description
2153
+ last_transaction_timestamp
2154
+ last_transaction_version
2155
+ max_supply
2156
+ mutable_description
2157
+ mutable_uri
2158
+ table_handle_v1
2159
+ token_standard
2160
+ total_minted_v2
2161
+ uri
2162
+ }
2163
+ }
2164
+ }
2165
+ `;
2166
+
2167
+ // src/internal/general.ts
2168
+ async function getLedgerInfo(args) {
2169
+ const { aptosConfig } = args;
2170
+ const { data } = await getAptosFullNode({
2171
+ aptosConfig,
2172
+ originMethod: "getLedgerInfo",
2173
+ path: ""
2174
+ });
2175
+ return data;
2176
+ }
2177
+ async function getBlockByVersion(args) {
2178
+ const { aptosConfig, ledgerVersion, options } = args;
2179
+ const { data } = await getAptosFullNode({
2180
+ aptosConfig,
2181
+ originMethod: "getBlockByVersion",
2182
+ path: `blocks/by_version/${ledgerVersion}`,
2183
+ params: { with_transactions: options == null ? void 0 : options.withTransactions }
2184
+ });
2185
+ return data;
2186
+ }
2187
+ async function getBlockByHeight(args) {
2188
+ const { aptosConfig, blockHeight, options } = args;
2189
+ const { data } = await getAptosFullNode({
2190
+ aptosConfig,
2191
+ originMethod: "getBlockByHeight",
2192
+ path: `blocks/by_height/${blockHeight}`,
2193
+ params: { with_transactions: options == null ? void 0 : options.withTransactions }
2194
+ });
2195
+ return data;
2196
+ }
2197
+ async function getTableItem(args) {
2198
+ const { aptosConfig, handle, data, options } = args;
2199
+ const response = await postAptosFullNode({
2200
+ aptosConfig,
2201
+ originMethod: "getTableItem",
2202
+ path: `tables/${handle}/item`,
2203
+ params: { ledger_version: options == null ? void 0 : options.ledgerVersion },
2204
+ body: data
2205
+ });
2206
+ return response.data;
2207
+ }
2208
+ async function view(args) {
2209
+ var _a, _b;
2210
+ const { aptosConfig, payload, options } = args;
2211
+ const { data } = await postAptosFullNode({
2212
+ aptosConfig,
2213
+ originMethod: "view",
2214
+ path: "view",
2215
+ params: { ledger_version: options == null ? void 0 : options.ledgerVersion },
2216
+ body: {
2217
+ function: payload.function,
2218
+ type_arguments: (_a = payload.typeArguments) != null ? _a : [],
2219
+ arguments: (_b = payload.arguments) != null ? _b : []
2220
+ }
2221
+ });
2222
+ return data;
2223
+ }
2224
+ async function getChainTopUserTransactions(args) {
2225
+ const { aptosConfig, limit } = args;
2226
+ const graphqlQuery = {
2227
+ query: GetChainTopUserTransactions,
2228
+ variables: { limit }
2229
+ };
2230
+ const data = await queryIndexer({
2231
+ aptosConfig,
2232
+ query: graphqlQuery,
2233
+ originMethod: "getChainTopUserTransactions"
2234
+ });
2235
+ return data.user_transactions;
2236
+ }
2237
+ async function queryIndexer(args) {
2238
+ const { aptosConfig, query, originMethod } = args;
2239
+ const { data } = await postAptosIndexer({
2240
+ aptosConfig,
2241
+ originMethod: originMethod != null ? originMethod : "queryIndexer",
2242
+ path: "",
2243
+ body: query,
2244
+ overrides: { WITH_CREDENTIALS: false }
2245
+ });
2246
+ return data;
2247
+ }
2248
+ async function getProcessorStatuses(args) {
2249
+ const { aptosConfig } = args;
2250
+ const graphqlQuery = {
2251
+ query: GetProcessorStatus
2252
+ };
2253
+ const data = await queryIndexer({
2254
+ aptosConfig,
2255
+ query: graphqlQuery,
2256
+ originMethod: "getProcessorStatuses"
2257
+ });
2258
+ return data.processor_status;
2259
+ }
2260
+ async function getIndexerLastSuccessVersion(args) {
2261
+ const response = await getProcessorStatuses({ aptosConfig: args.aptosConfig });
2262
+ return response[0].last_success_version;
2263
+ }
2264
+
2265
+ // src/utils/memoize.ts
2266
+ var cache = /* @__PURE__ */ new Map();
2267
+ function memoizeAsync(func, key, ttlMs) {
2268
+ return async (...args) => {
2269
+ if (cache.has(key)) {
2270
+ const { value, timestamp } = cache.get(key);
2271
+ if (ttlMs === void 0 || Date.now() - timestamp <= ttlMs) {
2272
+ return value;
2273
+ }
2274
+ }
2275
+ const result = await func(...args);
2276
+ cache.set(key, { value: result, timestamp: Date.now() });
2277
+ return result;
2278
+ };
2279
+ }
2280
+
2281
+ // src/internal/account.ts
2282
+ async function getInfo(args) {
2283
+ const { aptosConfig, accountAddress } = args;
2284
+ const { data } = await getAptosFullNode({
2285
+ aptosConfig,
2286
+ originMethod: "getInfo",
2287
+ path: `accounts/${AccountAddress.fromHexInput(accountAddress).toString()}`
2288
+ });
2289
+ return data;
2290
+ }
2291
+ async function getModules(args) {
2292
+ var _a;
2293
+ const { aptosConfig, accountAddress, options } = args;
2294
+ return paginateWithCursor({
2295
+ aptosConfig,
2296
+ originMethod: "getModules",
2297
+ path: `accounts/${AccountAddress.fromHexInput(accountAddress).toString()}/modules`,
2298
+ params: {
2299
+ ledger_version: options == null ? void 0 : options.ledgerVersion,
2300
+ start: options == null ? void 0 : options.offset,
2301
+ limit: (_a = options == null ? void 0 : options.limit) != null ? _a : 1e3
2302
+ }
2303
+ });
2304
+ }
2305
+ async function getModule(args) {
2306
+ var _a;
2307
+ if (((_a = args.options) == null ? void 0 : _a.ledgerVersion) !== void 0) {
2308
+ return getModuleInner(args);
2309
+ }
2310
+ return memoizeAsync(
2311
+ async () => getModuleInner(args),
2312
+ `module-${args.accountAddress}-${args.moduleName}`,
2313
+ 1e3 * 60 * 5
2314
+ )();
2315
+ }
2316
+ async function getModuleInner(args) {
2317
+ const { aptosConfig, accountAddress, moduleName, options } = args;
2318
+ const { data } = await getAptosFullNode({
2319
+ aptosConfig,
2320
+ originMethod: "getModule",
2321
+ path: `accounts/${AccountAddress.fromHexInput(accountAddress).toString()}/module/${moduleName}`,
2322
+ params: { ledger_version: options == null ? void 0 : options.ledgerVersion }
2323
+ });
2324
+ return data;
2325
+ }
2326
+ async function getTransactions(args) {
2327
+ const { aptosConfig, accountAddress, options } = args;
2328
+ return paginateWithCursor({
2329
+ aptosConfig,
2330
+ originMethod: "getTransactions",
2331
+ path: `accounts/${AccountAddress.fromHexInput(accountAddress).toString()}/transactions`,
2332
+ params: { start: options == null ? void 0 : options.offset, limit: options == null ? void 0 : options.limit }
2333
+ });
2334
+ }
2335
+ async function getResources(args) {
2336
+ var _a;
2337
+ const { aptosConfig, accountAddress, options } = args;
2338
+ return paginateWithCursor({
2339
+ aptosConfig,
2340
+ originMethod: "getResources",
2341
+ path: `accounts/${AccountAddress.fromHexInput(accountAddress).toString()}/resources`,
2342
+ params: {
2343
+ ledger_version: options == null ? void 0 : options.ledgerVersion,
2344
+ start: options == null ? void 0 : options.offset,
2345
+ limit: (_a = options == null ? void 0 : options.limit) != null ? _a : 999
2346
+ }
2347
+ });
2348
+ }
2349
+ async function getResource(args) {
2350
+ const { aptosConfig, accountAddress, resourceType, options } = args;
2351
+ const { data } = await getAptosFullNode({
2352
+ aptosConfig,
2353
+ originMethod: "getResource",
2354
+ path: `accounts/${AccountAddress.fromHexInput(accountAddress).toString()}/resource/${resourceType}`,
2355
+ params: { ledger_version: options == null ? void 0 : options.ledgerVersion }
2356
+ });
2357
+ return data;
2358
+ }
2359
+ async function lookupOriginalAccountAddress(args) {
2360
+ const { aptosConfig, authenticationKey, options } = args;
2361
+ const resource = await getResource({
2362
+ aptosConfig,
2363
+ accountAddress: "0x1",
2364
+ resourceType: "0x1::account::OriginatingAddress",
2365
+ options
2366
+ });
2367
+ const {
2368
+ address_map: { handle }
2369
+ } = resource.data;
2370
+ try {
2371
+ const originalAddress = await getTableItem({
2372
+ aptosConfig,
2373
+ handle,
2374
+ data: {
2375
+ key: Hex.fromHexInput(authenticationKey).toString(),
2376
+ key_type: "address",
2377
+ value_type: "address"
2378
+ },
2379
+ options
2380
+ });
2381
+ return AccountAddress.fromHexInput(originalAddress);
2382
+ } catch (err) {
2383
+ if (err instanceof AptosApiError && err.data.error_code === "table_item_not_found") {
2384
+ return AccountAddress.fromHexInput(authenticationKey);
2385
+ }
2386
+ throw err;
2387
+ }
2388
+ }
2389
+ async function getAccountTokensCount(args) {
2390
+ const { aptosConfig, accountAddress } = args;
2391
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2392
+ const whereCondition = {
2393
+ owner_address: { _eq: address },
2394
+ amount: { _gt: "0" }
2395
+ };
2396
+ const graphqlQuery = {
2397
+ query: GetAccountTokensCount,
2398
+ variables: { where_condition: whereCondition }
2399
+ };
2400
+ const data = await queryIndexer({
2401
+ aptosConfig,
2402
+ query: graphqlQuery,
2403
+ originMethod: "getAccountTokensCount"
2404
+ });
2405
+ if (!data.current_token_ownerships_v2_aggregate.aggregate) {
2406
+ throw Error("Failed to get the count of account tokens");
2407
+ }
2408
+ return data.current_token_ownerships_v2_aggregate.aggregate.count;
2409
+ }
2410
+ async function getAccountOwnedTokens(args) {
2411
+ var _a, _b;
2412
+ const { aptosConfig, accountAddress, options } = args;
2413
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2414
+ const whereCondition = {
2415
+ owner_address: { _eq: address },
2416
+ amount: { _gt: 0 }
2417
+ };
2418
+ if (options == null ? void 0 : options.tokenStandard) {
2419
+ whereCondition.token_standard = { _eq: options == null ? void 0 : options.tokenStandard };
2420
+ }
2421
+ const graphqlQuery = {
2422
+ query: GetAccountOwnedTokens,
2423
+ variables: {
2424
+ where_condition: whereCondition,
2425
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
2426
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
2427
+ order_by: options == null ? void 0 : options.orderBy
2428
+ }
2429
+ };
2430
+ const data = await queryIndexer({
2431
+ aptosConfig,
2432
+ query: graphqlQuery,
2433
+ originMethod: "getAccountOwnedTokens"
2434
+ });
2435
+ return data.current_token_ownerships_v2;
2436
+ }
2437
+ async function getAccountOwnedTokensFromCollectionAddress(args) {
2438
+ var _a, _b;
2439
+ const { aptosConfig, accountAddress, collectionAddress, options } = args;
2440
+ const ownerAddress = AccountAddress.fromHexInput(accountAddress).toString();
2441
+ const collAddress = Hex.fromHexInput(collectionAddress).toString();
2442
+ const whereCondition = {
2443
+ owner_address: { _eq: ownerAddress },
2444
+ current_token_data: { collection_id: { _eq: collAddress } },
2445
+ amount: { _gt: 0 }
2446
+ };
2447
+ if (options == null ? void 0 : options.tokenStandard) {
2448
+ whereCondition.token_standard = { _eq: options == null ? void 0 : options.tokenStandard };
2449
+ }
2450
+ const graphqlQuery = {
2451
+ query: GetAccountOwnedTokensFromCollection,
2452
+ variables: {
2453
+ where_condition: whereCondition,
2454
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
2455
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
2456
+ order_by: options == null ? void 0 : options.orderBy
2457
+ }
2458
+ };
2459
+ const data = await queryIndexer({
2460
+ aptosConfig,
2461
+ query: graphqlQuery,
2462
+ originMethod: "getAccountOwnedTokensFromCollectionAddress"
2463
+ });
2464
+ return data.current_token_ownerships_v2;
2465
+ }
2466
+ async function getAccountCollectionsWithOwnedTokens(args) {
2467
+ var _a, _b;
2468
+ const { aptosConfig, accountAddress, options } = args;
2469
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2470
+ const whereCondition = {
2471
+ owner_address: { _eq: address },
2472
+ amount: { _gt: 0 }
2473
+ };
2474
+ if (options == null ? void 0 : options.tokenStandard) {
2475
+ whereCondition.current_collection = {
2476
+ token_standard: { _eq: options == null ? void 0 : options.tokenStandard }
2477
+ };
2478
+ }
2479
+ const graphqlQuery = {
2480
+ query: GetAccountCollectionsWithOwnedTokens,
2481
+ variables: {
2482
+ where_condition: whereCondition,
2483
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
2484
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
2485
+ order_by: options == null ? void 0 : options.orderBy
2486
+ }
2487
+ };
2488
+ const data = await queryIndexer({
2489
+ aptosConfig,
2490
+ query: graphqlQuery,
2491
+ originMethod: "getAccountCollectionsWithOwnedTokens"
2492
+ });
2493
+ return data.current_collection_ownership_v2_view;
2494
+ }
2495
+ async function getAccountTransactionsCount(args) {
2496
+ const { aptosConfig, accountAddress } = args;
2497
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2498
+ const graphqlQuery = {
2499
+ query: GetAccountTransactionsCount,
2500
+ variables: { address }
2501
+ };
2502
+ const data = await queryIndexer({
2503
+ aptosConfig,
2504
+ query: graphqlQuery,
2505
+ originMethod: "getAccountTransactionsCount"
2506
+ });
2507
+ if (!data.account_transactions_aggregate.aggregate) {
2508
+ throw Error("Failed to get the count of account transactions");
2509
+ }
2510
+ return data.account_transactions_aggregate.aggregate.count;
2511
+ }
2512
+ async function getAccountCoinsData(args) {
2513
+ var _a, _b;
2514
+ const { aptosConfig, accountAddress, options } = args;
2515
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2516
+ const whereCondition = {
2517
+ owner_address: { _eq: address }
2518
+ };
2519
+ const graphqlQuery = {
2520
+ query: GetAccountCoinsData,
2521
+ variables: {
2522
+ where_condition: whereCondition,
2523
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
2524
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
2525
+ order_by: options == null ? void 0 : options.orderBy
2526
+ }
2527
+ };
2528
+ const data = await queryIndexer({
2529
+ aptosConfig,
2530
+ query: graphqlQuery,
2531
+ originMethod: "getAccountCoinsData"
2532
+ });
2533
+ return data.current_fungible_asset_balances;
2534
+ }
2535
+ async function getAccountCoinsCount(args) {
2536
+ const { aptosConfig, accountAddress } = args;
2537
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2538
+ const graphqlQuery = {
2539
+ query: GetAccountCoinsCount,
2540
+ variables: { address }
2541
+ };
2542
+ const data = await queryIndexer({
2543
+ aptosConfig,
2544
+ query: graphqlQuery,
2545
+ originMethod: "getAccountCoinsCount"
2546
+ });
2547
+ if (!data.current_fungible_asset_balances_aggregate.aggregate) {
2548
+ throw Error("Failed to get the count of account coins");
2549
+ }
2550
+ return data.current_fungible_asset_balances_aggregate.aggregate.count;
2551
+ }
2552
+ async function getAccountOwnedObjects(args) {
2553
+ var _a, _b;
2554
+ const { aptosConfig, accountAddress, options } = args;
2555
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
2556
+ const whereCondition = {
2557
+ owner_address: { _eq: address }
2558
+ };
2559
+ const graphqlQuery = {
2560
+ query: GetAccountOwnedObjects,
2561
+ variables: {
2562
+ where_condition: whereCondition,
2563
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
2564
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
2565
+ order_by: options == null ? void 0 : options.orderBy
2566
+ }
2567
+ };
2568
+ const data = await queryIndexer({
2569
+ aptosConfig,
2570
+ query: graphqlQuery,
2571
+ originMethod: "getAccountOwnedObjects"
2572
+ });
2573
+ return data.current_objects;
2574
+ }
2575
+
2576
+ // src/api/account.ts
2577
+ var Account2 = class {
2578
+ constructor(config) {
2579
+ this.config = config;
2580
+ }
2581
+ async getAccountInfo(args) {
2582
+ return getInfo({ aptosConfig: this.config, ...args });
2583
+ }
2584
+ async getAccountModules(args) {
2585
+ return getModules({ aptosConfig: this.config, ...args });
2586
+ }
2587
+ async getAccountModule(args) {
2588
+ return getModule({ aptosConfig: this.config, ...args });
2589
+ }
2590
+ async getAccountTransactions(args) {
2591
+ return getTransactions({
2592
+ aptosConfig: this.config,
2593
+ ...args
2594
+ });
2595
+ }
2596
+ async getAccountResources(args) {
2597
+ return getResources({ aptosConfig: this.config, ...args });
2598
+ }
2599
+ async getAccountResource(args) {
2600
+ return getResource({ aptosConfig: this.config, ...args });
2601
+ }
2602
+ async lookupOriginalAccountAddress(args) {
2603
+ return lookupOriginalAccountAddress({ aptosConfig: this.config, ...args });
2604
+ }
2605
+ async getAccountTokensCount(args) {
2606
+ return getAccountTokensCount({
2607
+ aptosConfig: this.config,
2608
+ ...args
2609
+ });
2610
+ }
2611
+ async getAccountOwnedTokens(args) {
2612
+ return getAccountOwnedTokens({
2613
+ aptosConfig: this.config,
2614
+ ...args
2615
+ });
2616
+ }
2617
+ async getAccountOwnedTokensFromCollectionAddress(args) {
2618
+ return getAccountOwnedTokensFromCollectionAddress({
2619
+ aptosConfig: this.config,
2620
+ ...args
2621
+ });
2622
+ }
2623
+ async getAccountCollectionsWithOwnedTokens(args) {
2624
+ return getAccountCollectionsWithOwnedTokens({
2625
+ aptosConfig: this.config,
2626
+ ...args
2627
+ });
2628
+ }
2629
+ async getAccountTransactionsCount(args) {
2630
+ return getAccountTransactionsCount({
2631
+ aptosConfig: this.config,
2632
+ ...args
2633
+ });
2634
+ }
2635
+ async getAccountCoinsData(args) {
2636
+ return getAccountCoinsData({
2637
+ aptosConfig: this.config,
2638
+ ...args
2639
+ });
2640
+ }
2641
+ async getAccountCoinsCount(args) {
2642
+ return getAccountCoinsCount({ aptosConfig: this.config, ...args });
2643
+ }
2644
+ async getAccountOwnedObjects(args) {
2645
+ return getAccountOwnedObjects({
2646
+ aptosConfig: this.config,
2647
+ ...args
2648
+ });
2649
+ }
2650
+ };
2651
+
2652
+ // src/api/aptosConfig.ts
2653
+ var AptosConfig = class {
2654
+ constructor(settings) {
2655
+ var _a, _b;
2656
+ this.network = (_a = settings == null ? void 0 : settings.network) != null ? _a : DEFAULT_NETWORK;
2657
+ this.fullnode = settings == null ? void 0 : settings.fullnode;
2658
+ this.faucet = settings == null ? void 0 : settings.faucet;
2659
+ this.indexer = settings == null ? void 0 : settings.indexer;
2660
+ this.clientConfig = (_b = settings == null ? void 0 : settings.clientConfig) != null ? _b : {};
2661
+ }
2662
+ getRequestUrl(apiType) {
2663
+ switch (apiType) {
2664
+ case 0 /* FULLNODE */:
2665
+ if (this.fullnode !== void 0)
2666
+ return this.fullnode;
2667
+ if (this.network === "custom" /* CUSTOM */)
2668
+ throw new Error("Please provide a custom full node url");
2669
+ return NetworkToNodeAPI[this.network];
2670
+ case 2 /* FAUCET */:
2671
+ if (this.faucet !== void 0)
2672
+ return this.faucet;
2673
+ if (this.network === "custom" /* CUSTOM */)
2674
+ throw new Error("Please provide a custom faucet url");
2675
+ return NetworkToFaucetAPI[this.network];
2676
+ case 1 /* INDEXER */:
2677
+ if (this.indexer !== void 0)
2678
+ return this.indexer;
2679
+ if (this.network === "custom" /* CUSTOM */)
2680
+ throw new Error("Please provide a custom indexer url");
2681
+ return NetworkToIndexerAPI[this.network];
2682
+ default:
2683
+ throw Error(`apiType ${apiType} is not supported`);
2684
+ }
2685
+ }
2686
+ isIndexerRequest(url) {
2687
+ return NetworkToIndexerAPI[this.network] === url;
2688
+ }
2689
+ };
2690
+
2691
+ // src/transactions/instances/identifier.ts
2692
+ var Identifier = class extends Serializable {
2693
+ constructor(identifier) {
2694
+ super();
2695
+ this.identifier = identifier;
2696
+ }
2697
+ serialize(serializer) {
2698
+ serializer.serializeStr(this.identifier);
2699
+ }
2700
+ static deserialize(deserializer) {
2701
+ const identifier = deserializer.deserializeStr();
2702
+ return new Identifier(identifier);
2703
+ }
2704
+ };
2705
+
2706
+ // src/transactions/typeTag/typeTag.ts
2707
+ var TypeTag = class extends Serializable {
2708
+ static deserialize(deserializer) {
2709
+ const index = deserializer.deserializeUleb128AsU32();
2710
+ switch (index) {
2711
+ case 0 /* Bool */:
2712
+ return TypeTagBool.load(deserializer);
2713
+ case 1 /* U8 */:
2714
+ return TypeTagU8.load(deserializer);
2715
+ case 2 /* U64 */:
2716
+ return TypeTagU64.load(deserializer);
2717
+ case 3 /* U128 */:
2718
+ return TypeTagU128.load(deserializer);
2719
+ case 4 /* Address */:
2720
+ return TypeTagAddress.load(deserializer);
2721
+ case 5 /* Signer */:
2722
+ return TypeTagSigner.load(deserializer);
2723
+ case 6 /* Vector */:
2724
+ return TypeTagVector.load(deserializer);
2725
+ case 7 /* Struct */:
2726
+ return TypeTagStruct.load(deserializer);
2727
+ case 8 /* U16 */:
2728
+ return TypeTagU16.load(deserializer);
2729
+ case 9 /* U32 */:
2730
+ return TypeTagU32.load(deserializer);
2731
+ case 10 /* U256 */:
2732
+ return TypeTagU256.load(deserializer);
2733
+ default:
2734
+ throw new Error(`Unknown variant index for TypeTag: ${index}`);
2735
+ }
2736
+ }
2737
+ };
2738
+ var TypeTagBool = class extends TypeTag {
2739
+ serialize(serializer) {
2740
+ serializer.serializeU32AsUleb128(0 /* Bool */);
2741
+ }
2742
+ static load(_deserializer) {
2743
+ return new TypeTagBool();
2744
+ }
2745
+ };
2746
+ var TypeTagU8 = class extends TypeTag {
2747
+ serialize(serializer) {
2748
+ serializer.serializeU32AsUleb128(1 /* U8 */);
2749
+ }
2750
+ static load(_deserializer) {
2751
+ return new TypeTagU8();
2752
+ }
2753
+ };
2754
+ var TypeTagU16 = class extends TypeTag {
2755
+ serialize(serializer) {
2756
+ serializer.serializeU32AsUleb128(8 /* U16 */);
2757
+ }
2758
+ static load(_deserializer) {
2759
+ return new TypeTagU16();
2760
+ }
2761
+ };
2762
+ var TypeTagU32 = class extends TypeTag {
2763
+ serialize(serializer) {
2764
+ serializer.serializeU32AsUleb128(9 /* U32 */);
2765
+ }
2766
+ static load(_deserializer) {
2767
+ return new TypeTagU32();
2768
+ }
2769
+ };
2770
+ var TypeTagU64 = class extends TypeTag {
2771
+ serialize(serializer) {
2772
+ serializer.serializeU32AsUleb128(2 /* U64 */);
2773
+ }
2774
+ static load(_deserializer) {
2775
+ return new TypeTagU64();
2776
+ }
2777
+ };
2778
+ var TypeTagU128 = class extends TypeTag {
2779
+ serialize(serializer) {
2780
+ serializer.serializeU32AsUleb128(3 /* U128 */);
2781
+ }
2782
+ static load(_deserializer) {
2783
+ return new TypeTagU128();
2784
+ }
2785
+ };
2786
+ var TypeTagU256 = class extends TypeTag {
2787
+ serialize(serializer) {
2788
+ serializer.serializeU32AsUleb128(10 /* U256 */);
2789
+ }
2790
+ static load(_deserializer) {
2791
+ return new TypeTagU256();
2792
+ }
2793
+ };
2794
+ var TypeTagAddress = class extends TypeTag {
2795
+ serialize(serializer) {
2796
+ serializer.serializeU32AsUleb128(4 /* Address */);
2797
+ }
2798
+ static load(_deserializer) {
2799
+ return new TypeTagAddress();
2800
+ }
2801
+ };
2802
+ var TypeTagSigner = class extends TypeTag {
2803
+ serialize(serializer) {
2804
+ serializer.serializeU32AsUleb128(5 /* Signer */);
2805
+ }
2806
+ static load(_deserializer) {
2807
+ return new TypeTagSigner();
2808
+ }
2809
+ };
2810
+ var TypeTagVector = class extends TypeTag {
2811
+ constructor(value) {
2812
+ super();
2813
+ this.value = value;
2814
+ }
2815
+ serialize(serializer) {
2816
+ serializer.serializeU32AsUleb128(6 /* Vector */);
2817
+ this.value.serialize(serializer);
2818
+ }
2819
+ static load(deserializer) {
2820
+ const value = TypeTag.deserialize(deserializer);
2821
+ return new TypeTagVector(value);
2822
+ }
2823
+ };
2824
+ var TypeTagStruct = class extends TypeTag {
2825
+ constructor(value) {
2826
+ super();
2827
+ this.value = value;
2828
+ }
2829
+ serialize(serializer) {
2830
+ serializer.serializeU32AsUleb128(7 /* Struct */);
2831
+ this.value.serialize(serializer);
2832
+ }
2833
+ static load(deserializer) {
2834
+ const value = StructTag.deserialize(deserializer);
2835
+ return new TypeTagStruct(value);
2836
+ }
2837
+ isStringTypeTag() {
2838
+ return this.value.module_name.identifier === "string" && this.value.name.identifier === "String" && this.value.address.toString() === AccountAddress.ONE.toString();
2839
+ }
2840
+ };
2841
+ var StructTag = class extends Serializable {
2842
+ constructor(address, module_name, name, type_args) {
2843
+ super();
2844
+ this.address = address;
2845
+ this.module_name = module_name;
2846
+ this.name = name;
2847
+ this.type_args = type_args;
2848
+ }
2849
+ static fromString(structTag) {
2850
+ const typeTagStruct = new TypeTagParser(structTag).parseTypeTag();
2851
+ return new StructTag(
2852
+ typeTagStruct.value.address,
2853
+ typeTagStruct.value.module_name,
2854
+ typeTagStruct.value.name,
2855
+ typeTagStruct.value.type_args
2856
+ );
2857
+ }
2858
+ serialize(serializer) {
2859
+ serializer.serialize(this.address);
2860
+ serializer.serialize(this.module_name);
2861
+ serializer.serialize(this.name);
2862
+ serializer.serializeVector(this.type_args);
2863
+ }
2864
+ static deserialize(deserializer) {
2865
+ const address = AccountAddress.deserialize(deserializer);
2866
+ const moduleName = Identifier.deserialize(deserializer);
2867
+ const name = Identifier.deserialize(deserializer);
2868
+ const typeArgs = deserializer.deserializeVector(TypeTag);
2869
+ return new StructTag(address, moduleName, name, typeArgs);
2870
+ }
2871
+ };
2872
+ var stringStructTag = () => new StructTag(AccountAddress.ONE, new Identifier("string"), new Identifier("String"), []);
2873
+ function optionStructTag(typeArg) {
2874
+ return new StructTag(AccountAddress.ONE, new Identifier("option"), new Identifier("Option"), [typeArg]);
2875
+ }
2876
+ function objectStructTag(typeArg) {
2877
+ return new StructTag(AccountAddress.ONE, new Identifier("object"), new Identifier("Object"), [typeArg]);
2878
+ }
2879
+ var TypeTagParser = class {
2880
+ constructor(tagStr, typeTags) {
2881
+ this.typeTags = [];
2882
+ this.tokens = tokenize(tagStr);
2883
+ this.typeTags = typeTags || [];
2884
+ }
2885
+ consume(targetToken) {
2886
+ const token = this.tokens.shift();
2887
+ if (!token || token[1] !== targetToken) {
2888
+ bail("Invalid type tag.");
2889
+ }
2890
+ }
2891
+ consumeWholeGeneric() {
2892
+ this.consume("<");
2893
+ while (this.tokens[0][1] !== ">") {
2894
+ if (this.tokens[0][1] === "<") {
2895
+ this.consumeWholeGeneric();
2896
+ } else {
2897
+ this.tokens.shift();
2898
+ }
2899
+ }
2900
+ this.consume(">");
2901
+ }
2902
+ parseCommaList(endToken, allowTrailingComma) {
2903
+ const res = [];
2904
+ if (this.tokens.length <= 0) {
2905
+ bail("Invalid type tag.");
2906
+ }
2907
+ while (this.tokens[0][1] !== endToken) {
2908
+ res.push(this.parseTypeTag());
2909
+ if (this.tokens.length > 0 && this.tokens[0][1] === endToken) {
2910
+ break;
2911
+ }
2912
+ this.consume(",");
2913
+ if (this.tokens.length > 0 && this.tokens[0][1] === endToken && allowTrailingComma) {
2914
+ break;
2915
+ }
2916
+ if (this.tokens.length <= 0) {
2917
+ bail("Invalid type tag.");
2918
+ }
2919
+ }
2920
+ return res;
2921
+ }
2922
+ parseTypeTag() {
2923
+ if (this.tokens.length === 0) {
2924
+ bail("Invalid type tag.");
2925
+ }
2926
+ const [tokenTy, tokenVal] = this.tokens.shift();
2927
+ if (tokenVal === "u8") {
2928
+ return new TypeTagU8();
2929
+ }
2930
+ if (tokenVal === "u16") {
2931
+ return new TypeTagU16();
2932
+ }
2933
+ if (tokenVal === "u32") {
2934
+ return new TypeTagU32();
2935
+ }
2936
+ if (tokenVal === "u64") {
2937
+ return new TypeTagU64();
2938
+ }
2939
+ if (tokenVal === "u128") {
2940
+ return new TypeTagU128();
2941
+ }
2942
+ if (tokenVal === "u256") {
2943
+ return new TypeTagU256();
2944
+ }
2945
+ if (tokenVal === "bool") {
2946
+ return new TypeTagBool();
2947
+ }
2948
+ if (tokenVal === "address") {
2949
+ return new TypeTagAddress();
2950
+ }
2951
+ if (tokenVal === "vector") {
2952
+ this.consume("<");
2953
+ const res = this.parseTypeTag();
2954
+ this.consume(">");
2955
+ return new TypeTagVector(res);
2956
+ }
2957
+ if (tokenVal === "string") {
2958
+ return new TypeTagStruct(stringStructTag());
2959
+ }
2960
+ if (tokenTy === "IDENT" && (tokenVal.startsWith("0x") || tokenVal.startsWith("0X"))) {
2961
+ const address = AccountAddress.fromHexInput(tokenVal);
2962
+ this.consume("::");
2963
+ const [moduleTokenTy, module2] = this.tokens.shift();
2964
+ if (moduleTokenTy !== "IDENT") {
2965
+ bail("Invalid type tag.");
2966
+ }
2967
+ this.consume("::");
2968
+ const [nameTokenTy, name] = this.tokens.shift();
2969
+ if (nameTokenTy !== "IDENT") {
2970
+ bail("Invalid type tag.");
2971
+ }
2972
+ if (AccountAddress.ONE.toString() === address.toString() && module2 === "object" && name === "Object") {
2973
+ this.consumeWholeGeneric();
2974
+ return new TypeTagAddress();
2975
+ }
2976
+ let tyTags = [];
2977
+ if (this.tokens.length > 0 && this.tokens[0][1] === "<") {
2978
+ this.consume("<");
2979
+ tyTags = this.parseCommaList(">", true);
2980
+ this.consume(">");
2981
+ }
2982
+ const structTag = new StructTag(address, new Identifier(module2), new Identifier(name), tyTags);
2983
+ return new TypeTagStruct(structTag);
2984
+ }
2985
+ if (tokenTy === "GENERIC") {
2986
+ if (this.typeTags.length === 0) {
2987
+ bail("Can't convert generic type since no typeTags were specified.");
2988
+ }
2989
+ const idx = parseInt(tokenVal.substring(1), 10);
2990
+ return new TypeTagParser(this.typeTags[idx]).parseTypeTag();
2991
+ }
2992
+ throw new Error("Invalid type tag.");
2993
+ }
2994
+ };
2995
+ var TypeTagParserError = class extends Error {
2996
+ constructor(message) {
2997
+ super(message);
2998
+ this.name = "TypeTagParserError";
2999
+ }
3000
+ };
3001
+ function tokenize(tagStr) {
3002
+ let pos = 0;
3003
+ const tokens = [];
3004
+ while (pos < tagStr.length) {
3005
+ const [token, size] = nextToken(tagStr, pos);
3006
+ if (token[0] !== "SPACE") {
3007
+ tokens.push(token);
3008
+ }
3009
+ pos += size;
3010
+ }
3011
+ return tokens;
3012
+ }
3013
+ function bail(message) {
3014
+ throw new TypeTagParserError(message);
3015
+ }
3016
+ function isWhiteSpace(c) {
3017
+ return !!c.match(/\s/);
3018
+ }
3019
+ function isValidAlphabetic(c) {
3020
+ return !!c.match(/[_A-Za-z0-9]/g);
3021
+ }
3022
+ function isGeneric(c) {
3023
+ return !!c.match(/T\d+/g);
3024
+ }
3025
+ function nextToken(tagStr, pos) {
3026
+ const c = tagStr[pos];
3027
+ if (c === ":") {
3028
+ if (tagStr.slice(pos, pos + 2) === "::") {
3029
+ return [["COLON", "::"], 2];
3030
+ }
3031
+ bail("Unrecognized token.");
3032
+ } else if (c === "<") {
3033
+ return [["LT", "<"], 1];
3034
+ } else if (c === ">") {
3035
+ return [["GT", ">"], 1];
3036
+ } else if (c === ",") {
3037
+ return [["COMMA", ","], 1];
3038
+ } else if (isWhiteSpace(c)) {
3039
+ let res = "";
3040
+ for (let i = pos; i < tagStr.length; i += 1) {
3041
+ const char = tagStr[i];
3042
+ if (isWhiteSpace(char)) {
3043
+ res = `${res}${char}`;
3044
+ } else {
3045
+ break;
3046
+ }
3047
+ }
3048
+ return [["SPACE", res], res.length];
3049
+ } else if (isValidAlphabetic(c)) {
3050
+ let res = "";
3051
+ for (let i = pos; i < tagStr.length; i += 1) {
3052
+ const char = tagStr[i];
3053
+ if (isValidAlphabetic(char)) {
3054
+ res = `${res}${char}`;
3055
+ } else {
3056
+ break;
3057
+ }
3058
+ }
3059
+ if (isGeneric(res)) {
3060
+ return [["GENERIC", res], res.length];
3061
+ }
3062
+ return [["IDENT", res], res.length];
3063
+ }
3064
+ throw new Error("Unrecognized token.");
3065
+ }
3066
+
3067
+ // src/transactions/transaction_builder/transaction_builder.ts
3068
+ var import_sha33 = require("@noble/hashes/sha3");
3069
+
3070
+ // src/utils/helpers.ts
3071
+ async function sleep(timeMs) {
3072
+ return new Promise((resolve) => {
3073
+ setTimeout(resolve, timeMs);
3074
+ });
3075
+ }
3076
+
3077
+ // src/internal/transaction.ts
3078
+ async function getTransactions2(args) {
3079
+ const { aptosConfig, options } = args;
3080
+ return paginateWithCursor({
3081
+ aptosConfig,
3082
+ originMethod: "getTransactions",
3083
+ path: "transactions",
3084
+ params: { start: options == null ? void 0 : options.offset, limit: options == null ? void 0 : options.limit }
3085
+ });
3086
+ }
3087
+ async function getGasPriceEstimation(args) {
3088
+ const { aptosConfig } = args;
3089
+ return memoizeAsync(
3090
+ async () => {
3091
+ const { data } = await getAptosFullNode({
3092
+ aptosConfig,
3093
+ originMethod: "getGasPriceEstimation",
3094
+ path: "estimate_gas_price"
3095
+ });
3096
+ return data;
3097
+ },
3098
+ `gas-price-${aptosConfig.network}`,
3099
+ 1e3 * 60 * 5
3100
+ )();
3101
+ }
3102
+ async function getTransactionByVersion(args) {
3103
+ const { aptosConfig, ledgerVersion } = args;
3104
+ const { data } = await getAptosFullNode({
3105
+ aptosConfig,
3106
+ originMethod: "getTransactionByVersion",
3107
+ path: `transactions/by_version/${ledgerVersion}`
3108
+ });
3109
+ return data;
3110
+ }
3111
+ async function getTransactionByHash(args) {
3112
+ const { aptosConfig, transactionHash } = args;
3113
+ const { data } = await getAptosFullNode({
3114
+ aptosConfig,
3115
+ path: `transactions/by_hash/${transactionHash}`,
3116
+ originMethod: "getTransactionByHash"
3117
+ });
3118
+ return data;
3119
+ }
3120
+ async function isTransactionPending(args) {
3121
+ const { aptosConfig, transactionHash } = args;
3122
+ try {
3123
+ const transaction = await getTransactionByHash({ aptosConfig, transactionHash });
3124
+ return transaction.type === "pending_transaction" /* Pending */;
3125
+ } catch (e) {
3126
+ if ((e == null ? void 0 : e.status) === 404) {
3127
+ return true;
3128
+ }
3129
+ throw e;
3130
+ }
3131
+ }
3132
+ async function waitForTransaction(args) {
3133
+ var _a, _b, _c;
3134
+ const { aptosConfig, transactionHash, options } = args;
3135
+ const timeoutSecs = (_a = options == null ? void 0 : options.timeoutSecs) != null ? _a : DEFAULT_TXN_TIMEOUT_SEC;
3136
+ const checkSuccess = (_b = options == null ? void 0 : options.checkSuccess) != null ? _b : true;
3137
+ const indexerVersionCheck = (_c = options == null ? void 0 : options.indexerVersionCheck) != null ? _c : true;
3138
+ let isPending = true;
3139
+ let timeElapsed = 0;
3140
+ let lastTxn;
3141
+ let lastError;
3142
+ let backoffIntervalMs = 200;
3143
+ const backoffMultiplier = 1.5;
3144
+ while (isPending) {
3145
+ if (timeElapsed >= timeoutSecs) {
3146
+ break;
3147
+ }
3148
+ try {
3149
+ lastTxn = await getTransactionByHash({ aptosConfig, transactionHash });
3150
+ isPending = lastTxn.type === "pending_transaction" /* Pending */;
3151
+ if (!isPending) {
3152
+ break;
3153
+ }
3154
+ } catch (e) {
3155
+ const isAptosApiError = e instanceof AptosApiError;
3156
+ if (!isAptosApiError) {
3157
+ throw e;
3158
+ }
3159
+ lastError = e;
3160
+ const isRequestError = e.status !== 404 && e.status >= 400 && e.status < 500;
3161
+ if (isRequestError) {
3162
+ throw e;
3163
+ }
3164
+ }
3165
+ await sleep(backoffIntervalMs);
3166
+ timeElapsed += backoffIntervalMs / 1e3;
3167
+ backoffIntervalMs *= backoffMultiplier;
3168
+ }
3169
+ if (lastTxn === void 0) {
3170
+ if (lastError) {
3171
+ throw lastError;
3172
+ } else {
3173
+ throw new WaitForTransactionError(
3174
+ `Fetching transaction ${transactionHash} failed and timed out after ${timeoutSecs} seconds`,
3175
+ lastTxn
3176
+ );
3177
+ }
3178
+ }
3179
+ if (lastTxn.type === "pending_transaction" /* Pending */) {
3180
+ throw new WaitForTransactionError(
3181
+ `Transaction ${transactionHash} timed out in pending state after ${timeoutSecs} seconds`,
3182
+ lastTxn
3183
+ );
3184
+ }
3185
+ if (!checkSuccess) {
3186
+ return lastTxn;
3187
+ }
3188
+ if (!lastTxn.success) {
3189
+ throw new FailedTransactionError(
3190
+ `Transaction ${transactionHash} failed with an error: ${lastTxn.vm_status}`,
3191
+ lastTxn
3192
+ );
3193
+ }
3194
+ if (indexerVersionCheck) {
3195
+ try {
3196
+ await waitForLastSuccessIndexerVersionSync({ aptosConfig, ledgerVersion: Number(lastTxn.version) });
3197
+ } catch (_e) {
3198
+ throw new WaitForTransactionError(
3199
+ `Transaction ${transactionHash} committed, but timed out waiting for indexer to sync with ledger version ${lastTxn.version}.You can disable this check by setting \`indexerVersionCheck\` to false in the \`extraArgs\` parameter.`,
3200
+ lastTxn
3201
+ );
3202
+ }
3203
+ }
3204
+ return lastTxn;
3205
+ }
3206
+ async function waitForLastSuccessIndexerVersionSync(args) {
3207
+ const { aptosConfig, ledgerVersion } = args;
3208
+ const timeoutMilliseconds = 3e3;
3209
+ const startTime = new Date().getTime();
3210
+ let indexerVersion = -1;
3211
+ while (indexerVersion < ledgerVersion) {
3212
+ if (new Date().getTime() - startTime > timeoutMilliseconds) {
3213
+ throw new Error("waitForLastSuccessIndexerVersionSync timeout");
3214
+ }
3215
+ indexerVersion = await getIndexerLastSuccessVersion({ aptosConfig });
3216
+ if (indexerVersion >= ledgerVersion) {
3217
+ break;
3218
+ }
3219
+ await sleep(200);
3220
+ }
3221
+ }
3222
+ var WaitForTransactionError = class extends Error {
3223
+ constructor(message, lastSubmittedTransaction) {
3224
+ super(message);
3225
+ this.lastSubmittedTransaction = lastSubmittedTransaction;
3226
+ }
3227
+ };
3228
+ var FailedTransactionError = class extends Error {
3229
+ constructor(message, transaction) {
3230
+ super(message);
3231
+ this.transaction = transaction;
3232
+ }
3233
+ };
3234
+
3235
+ // src/transactions/authenticator/account.ts
3236
+ var AccountAuthenticator = class extends Serializable {
3237
+ static deserialize(deserializer) {
3238
+ const index = deserializer.deserializeUleb128AsU32();
3239
+ switch (index) {
3240
+ case 0 /* Ed25519 */:
3241
+ return AccountAuthenticatorEd25519.load(deserializer);
3242
+ case 1 /* MultiEd25519 */:
3243
+ return AccountAuthenticatorMultiEd25519.load(deserializer);
3244
+ case 2 /* Secp256k1 */:
3245
+ return AccountAuthenticatorSecp256k1.load(deserializer);
3246
+ default:
3247
+ throw new Error(`Unknown variant index for AccountAuthenticator: ${index}`);
3248
+ }
3249
+ }
3250
+ };
3251
+ var AccountAuthenticatorEd25519 = class extends AccountAuthenticator {
3252
+ constructor(public_key, signature) {
3253
+ super();
3254
+ this.public_key = public_key;
3255
+ this.signature = signature;
3256
+ }
3257
+ serialize(serializer) {
3258
+ serializer.serializeU32AsUleb128(0 /* Ed25519 */);
3259
+ this.public_key.serialize(serializer);
3260
+ this.signature.serialize(serializer);
3261
+ }
3262
+ static load(deserializer) {
3263
+ const public_key = Ed25519PublicKey.deserialize(deserializer);
3264
+ const signature = Ed25519Signature.deserialize(deserializer);
3265
+ return new AccountAuthenticatorEd25519(public_key, signature);
3266
+ }
3267
+ };
3268
+ var AccountAuthenticatorMultiEd25519 = class extends AccountAuthenticator {
3269
+ constructor(public_key, signature) {
3270
+ super();
3271
+ this.public_key = public_key;
3272
+ this.signature = signature;
3273
+ }
3274
+ serialize(serializer) {
3275
+ serializer.serializeU32AsUleb128(1 /* MultiEd25519 */);
3276
+ this.public_key.serialize(serializer);
3277
+ this.signature.serialize(serializer);
3278
+ }
3279
+ static load(deserializer) {
3280
+ const public_key = MultiEd25519PublicKey.deserialize(deserializer);
3281
+ const signature = MultiEd25519Signature.deserialize(deserializer);
3282
+ return new AccountAuthenticatorMultiEd25519(public_key, signature);
3283
+ }
3284
+ };
3285
+ var AccountAuthenticatorSecp256k1 = class extends AccountAuthenticator {
3286
+ constructor(public_key, signature) {
3287
+ super();
3288
+ this.public_key = public_key;
3289
+ this.signature = signature;
3290
+ }
3291
+ serialize(serializer) {
3292
+ serializer.serializeU32AsUleb128(2 /* Secp256k1 */);
3293
+ this.public_key.serialize(serializer);
3294
+ this.signature.serialize(serializer);
3295
+ }
3296
+ static load(deserializer) {
3297
+ const public_key = Secp256k1PublicKey.deserialize(deserializer);
3298
+ const signature = Secp256k1Signature.deserialize(deserializer);
3299
+ return new AccountAuthenticatorSecp256k1(public_key, signature);
3300
+ }
3301
+ };
3302
+
3303
+ // src/transactions/authenticator/transaction.ts
3304
+ var TransactionAuthenticator = class {
3305
+ static deserialize(deserializer) {
3306
+ const index = deserializer.deserializeUleb128AsU32();
3307
+ switch (index) {
3308
+ case 0 /* Ed25519 */:
3309
+ return TransactionAuthenticatorEd25519.load(deserializer);
3310
+ case 1 /* MultiEd25519 */:
3311
+ return TransactionAuthenticatorMultiEd25519.load(deserializer);
3312
+ case 2 /* MultiAgent */:
3313
+ return TransactionAuthenticatorMultiAgent.load(deserializer);
3314
+ case 3 /* FeePayer */:
3315
+ return TransactionAuthenticatorFeePayer.load(deserializer);
3316
+ case 4 /* Secp256k1Ecdsa */:
3317
+ return TransactionAuthenticatorSecp256k1.load(deserializer);
3318
+ default:
3319
+ throw new Error(`Unknown variant index for TransactionAuthenticator: ${index}`);
3320
+ }
3321
+ }
3322
+ };
3323
+ var TransactionAuthenticatorEd25519 = class extends TransactionAuthenticator {
3324
+ constructor(public_key, signature) {
3325
+ super();
3326
+ this.public_key = public_key;
3327
+ this.signature = signature;
3328
+ }
3329
+ serialize(serializer) {
3330
+ serializer.serializeU32AsUleb128(0 /* Ed25519 */);
3331
+ this.public_key.serialize(serializer);
3332
+ this.signature.serialize(serializer);
3333
+ }
3334
+ static load(deserializer) {
3335
+ const public_key = Ed25519PublicKey.deserialize(deserializer);
3336
+ const signature = Ed25519Signature.deserialize(deserializer);
3337
+ return new TransactionAuthenticatorEd25519(public_key, signature);
3338
+ }
3339
+ };
3340
+ var TransactionAuthenticatorMultiEd25519 = class extends TransactionAuthenticator {
3341
+ constructor(public_key, signature) {
3342
+ super();
3343
+ this.public_key = public_key;
3344
+ this.signature = signature;
3345
+ }
3346
+ serialize(serializer) {
3347
+ serializer.serializeU32AsUleb128(1 /* MultiEd25519 */);
3348
+ this.public_key.serialize(serializer);
3349
+ this.signature.serialize(serializer);
3350
+ }
3351
+ static load(deserializer) {
3352
+ const public_key = MultiEd25519PublicKey.deserialize(deserializer);
3353
+ const signature = MultiEd25519Signature.deserialize(deserializer);
3354
+ return new TransactionAuthenticatorMultiEd25519(public_key, signature);
3355
+ }
3356
+ };
3357
+ var TransactionAuthenticatorMultiAgent = class extends TransactionAuthenticator {
3358
+ constructor(sender, secondary_signer_addresses, secondary_signers) {
3359
+ super();
3360
+ this.sender = sender;
3361
+ this.secondary_signer_addresses = secondary_signer_addresses;
3362
+ this.secondary_signers = secondary_signers;
3363
+ }
3364
+ serialize(serializer) {
3365
+ serializer.serializeU32AsUleb128(2 /* MultiAgent */);
3366
+ this.sender.serialize(serializer);
3367
+ serializer.serializeVector(this.secondary_signer_addresses);
3368
+ serializer.serializeVector(this.secondary_signers);
3369
+ }
3370
+ static load(deserializer) {
3371
+ const sender = AccountAuthenticator.deserialize(deserializer);
3372
+ const secondary_signer_addresses = deserializer.deserializeVector(AccountAddress);
3373
+ const secondary_signers = deserializer.deserializeVector(AccountAuthenticator);
3374
+ return new TransactionAuthenticatorMultiAgent(sender, secondary_signer_addresses, secondary_signers);
3375
+ }
3376
+ };
3377
+ var TransactionAuthenticatorFeePayer = class extends TransactionAuthenticator {
3378
+ constructor(sender, secondary_signer_addresses, secondary_signers, fee_payer) {
3379
+ super();
3380
+ this.sender = sender;
3381
+ this.secondary_signer_addresses = secondary_signer_addresses;
3382
+ this.secondary_signers = secondary_signers;
3383
+ this.fee_payer = fee_payer;
3384
+ }
3385
+ serialize(serializer) {
3386
+ serializer.serializeU32AsUleb128(3 /* FeePayer */);
3387
+ this.sender.serialize(serializer);
3388
+ serializer.serializeVector(this.secondary_signer_addresses);
3389
+ serializer.serializeVector(this.secondary_signers);
3390
+ this.fee_payer.address.serialize(serializer);
3391
+ this.fee_payer.authenticator.serialize(serializer);
3392
+ }
3393
+ static load(deserializer) {
3394
+ const sender = AccountAuthenticator.deserialize(deserializer);
3395
+ const secondary_signer_addresses = deserializer.deserializeVector(AccountAddress);
3396
+ const secondary_signers = deserializer.deserializeVector(AccountAuthenticator);
3397
+ const address = AccountAddress.deserialize(deserializer);
3398
+ const authenticator = AccountAuthenticator.deserialize(deserializer);
3399
+ const fee_payer = { address, authenticator };
3400
+ return new TransactionAuthenticatorFeePayer(sender, secondary_signer_addresses, secondary_signers, fee_payer);
3401
+ }
3402
+ };
3403
+ var TransactionAuthenticatorSecp256k1 = class extends TransactionAuthenticator {
3404
+ constructor(public_key, signature) {
3405
+ super();
3406
+ this.public_key = public_key;
3407
+ this.signature = signature;
3408
+ }
3409
+ serialize(serializer) {
3410
+ serializer.serializeU32AsUleb128(4 /* Secp256k1Ecdsa */);
3411
+ this.public_key.serialize(serializer);
3412
+ this.signature.serialize(serializer);
3413
+ }
3414
+ static load(deserializer) {
3415
+ const public_key = Secp256k1PublicKey.deserialize(deserializer);
3416
+ const signature = Secp256k1Signature.deserialize(deserializer);
3417
+ return new TransactionAuthenticatorSecp256k1(public_key, signature);
3418
+ }
3419
+ };
3420
+
3421
+ // src/transactions/instances/chainId.ts
3422
+ var ChainId = class extends Serializable {
3423
+ constructor(chainId) {
3424
+ super();
3425
+ this.chainId = chainId;
3426
+ }
3427
+ serialize(serializer) {
3428
+ serializer.serializeU8(this.chainId);
3429
+ }
3430
+ static deserialize(deserializer) {
3431
+ const chainId = deserializer.deserializeU8();
3432
+ return new ChainId(chainId);
3433
+ }
3434
+ };
3435
+
3436
+ // src/transactions/instances/moduleId.ts
3437
+ var ModuleId = class extends Serializable {
3438
+ constructor(address, name) {
3439
+ super();
3440
+ this.address = address;
3441
+ this.name = name;
3442
+ }
3443
+ static fromStr(moduleId) {
3444
+ const parts = moduleId.split("::");
3445
+ if (parts.length !== 2) {
3446
+ throw new Error("Invalid module id.");
3447
+ }
3448
+ return new ModuleId(AccountAddress.fromString(parts[0]), new Identifier(parts[1]));
3449
+ }
3450
+ serialize(serializer) {
3451
+ this.address.serialize(serializer);
3452
+ this.name.serialize(serializer);
3453
+ }
3454
+ static deserialize(deserializer) {
3455
+ const address = AccountAddress.deserialize(deserializer);
3456
+ const name = Identifier.deserialize(deserializer);
3457
+ return new ModuleId(address, name);
3458
+ }
3459
+ };
3460
+
3461
+ // src/transactions/instances/transactionPayload.ts
3462
+ function deserializeFromScriptArgument(deserializer) {
3463
+ const index = deserializer.deserializeUleb128AsU32();
3464
+ switch (index) {
3465
+ case 0 /* U8 */:
3466
+ return U8.deserialize(deserializer);
3467
+ case 1 /* U64 */:
3468
+ return U64.deserialize(deserializer);
3469
+ case 2 /* U128 */:
3470
+ return U128.deserialize(deserializer);
3471
+ case 3 /* Address */:
3472
+ return AccountAddress.deserialize(deserializer);
3473
+ case 4 /* U8Vector */:
3474
+ return MoveVector.deserialize(deserializer, U8);
3475
+ case 5 /* Bool */:
3476
+ return Bool.deserialize(deserializer);
3477
+ case 6 /* U16 */:
3478
+ return U16.deserialize(deserializer);
3479
+ case 7 /* U32 */:
3480
+ return U32.deserialize(deserializer);
3481
+ case 8 /* U256 */:
3482
+ return U256.deserialize(deserializer);
3483
+ default:
3484
+ throw new Error(`Unknown variant index for ScriptTransactionArgument: ${index}`);
3485
+ }
3486
+ }
3487
+ var TransactionPayload = class extends Serializable {
3488
+ static deserialize(deserializer) {
3489
+ const index = deserializer.deserializeUleb128AsU32();
3490
+ switch (index) {
3491
+ case 0 /* Script */:
3492
+ return TransactionPayloadScript.load(deserializer);
3493
+ case 2 /* EntryFunction */:
3494
+ return TransactionPayloadEntryFunction.load(deserializer);
3495
+ case 3 /* Multisig */:
3496
+ return TransactionPayloadMultisig.load(deserializer);
3497
+ default:
3498
+ throw new Error(`Unknown variant index for TransactionPayload: ${index}`);
3499
+ }
3500
+ }
3501
+ };
3502
+ var TransactionPayloadScript = class extends TransactionPayload {
3503
+ constructor(script) {
3504
+ super();
3505
+ this.script = script;
3506
+ }
3507
+ serialize(serializer) {
3508
+ serializer.serializeU32AsUleb128(0 /* Script */);
3509
+ this.script.serialize(serializer);
3510
+ }
3511
+ static load(deserializer) {
3512
+ const script = Script.deserialize(deserializer);
3513
+ return new TransactionPayloadScript(script);
3514
+ }
3515
+ };
3516
+ var TransactionPayloadEntryFunction = class extends TransactionPayload {
3517
+ constructor(entryFunction) {
3518
+ super();
3519
+ this.entryFunction = entryFunction;
3520
+ }
3521
+ serialize(serializer) {
3522
+ serializer.serializeU32AsUleb128(2 /* EntryFunction */);
3523
+ this.entryFunction.serialize(serializer);
3524
+ }
3525
+ static load(deserializer) {
3526
+ const entryFunction = EntryFunction.deserialize(deserializer);
3527
+ return new TransactionPayloadEntryFunction(entryFunction);
3528
+ }
3529
+ };
3530
+ var TransactionPayloadMultisig = class extends TransactionPayload {
3531
+ constructor(multiSig) {
3532
+ super();
3533
+ this.multiSig = multiSig;
3534
+ }
3535
+ serialize(serializer) {
3536
+ serializer.serializeU32AsUleb128(3 /* Multisig */);
3537
+ this.multiSig.serialize(serializer);
3538
+ }
3539
+ static load(deserializer) {
3540
+ const multiSig = MultiSig.deserialize(deserializer);
3541
+ return new TransactionPayloadMultisig(multiSig);
3542
+ }
3543
+ };
3544
+ var EntryFunction = class {
3545
+ constructor(module_name, function_name, type_args, args) {
3546
+ this.module_name = module_name;
3547
+ this.function_name = function_name;
3548
+ this.type_args = type_args;
3549
+ this.args = args;
3550
+ }
3551
+ static build(module_id, function_name, type_args, args) {
3552
+ return new EntryFunction(ModuleId.fromStr(module_id), new Identifier(function_name), type_args, args);
3553
+ }
3554
+ serialize(serializer) {
3555
+ this.module_name.serialize(serializer);
3556
+ this.function_name.serialize(serializer);
3557
+ serializer.serializeVector(this.type_args);
3558
+ serializer.serializeU32AsUleb128(this.args.length);
3559
+ this.args.forEach((item) => {
3560
+ item.serializeForEntryFunction(serializer);
3561
+ });
3562
+ }
3563
+ static deserialize(deserializer) {
3564
+ const module_name = ModuleId.deserialize(deserializer);
3565
+ const function_name = Identifier.deserialize(deserializer);
3566
+ const type_args = deserializer.deserializeVector(TypeTag);
3567
+ const length = deserializer.deserializeUleb128AsU32();
3568
+ const args = new Array();
3569
+ for (let i = 0; i < length; i += 1) {
3570
+ const fixedBytesLength = deserializer.deserializeUleb128AsU32();
3571
+ const fixedBytes = EntryFunctionBytes.deserialize(deserializer, fixedBytesLength);
3572
+ args.push(fixedBytes);
3573
+ }
3574
+ return new EntryFunction(module_name, function_name, type_args, args);
3575
+ }
3576
+ };
3577
+ var Script = class {
3578
+ constructor(bytecode, type_args, args) {
3579
+ this.bytecode = bytecode;
3580
+ this.type_args = type_args;
3581
+ this.args = args;
3582
+ }
3583
+ serialize(serializer) {
3584
+ serializer.serializeBytes(this.bytecode);
3585
+ serializer.serializeVector(this.type_args);
3586
+ serializer.serializeU32AsUleb128(this.args.length);
3587
+ this.args.forEach((item) => {
3588
+ item.serializeForScriptFunction(serializer);
3589
+ });
3590
+ }
3591
+ static deserialize(deserializer) {
3592
+ const bytecode = deserializer.deserializeBytes();
3593
+ const type_args = deserializer.deserializeVector(TypeTag);
3594
+ const length = deserializer.deserializeUleb128AsU32();
3595
+ const args = new Array();
3596
+ for (let i = 0; i < length; i += 1) {
3597
+ const scriptArgument = deserializeFromScriptArgument(deserializer);
3598
+ args.push(scriptArgument);
3599
+ }
3600
+ return new Script(bytecode, type_args, args);
3601
+ }
3602
+ };
3603
+ var MultiSig = class {
3604
+ constructor(multisig_address, transaction_payload) {
3605
+ this.multisig_address = multisig_address;
3606
+ this.transaction_payload = transaction_payload;
3607
+ }
3608
+ serialize(serializer) {
3609
+ this.multisig_address.serialize(serializer);
3610
+ if (this.transaction_payload === void 0) {
3611
+ serializer.serializeBool(false);
3612
+ } else {
3613
+ serializer.serializeBool(true);
3614
+ this.transaction_payload.serialize(serializer);
3615
+ }
3616
+ }
3617
+ static deserialize(deserializer) {
3618
+ const multisig_address = AccountAddress.deserialize(deserializer);
3619
+ const payloadPresent = deserializer.deserializeBool();
3620
+ let transaction_payload;
3621
+ if (payloadPresent) {
3622
+ transaction_payload = MultiSigTransactionPayload.deserialize(deserializer);
3623
+ }
3624
+ return new MultiSig(multisig_address, transaction_payload);
3625
+ }
3626
+ };
3627
+ var MultiSigTransactionPayload = class {
3628
+ constructor(transaction_payload) {
3629
+ this.transaction_payload = transaction_payload;
3630
+ }
3631
+ serialize(serializer) {
3632
+ serializer.serializeU32AsUleb128(0);
3633
+ this.transaction_payload.serialize(serializer);
3634
+ }
3635
+ static deserialize(deserializer) {
3636
+ deserializer.deserializeUleb128AsU32();
3637
+ return new MultiSigTransactionPayload(EntryFunction.deserialize(deserializer));
3638
+ }
3639
+ };
3640
+
3641
+ // src/transactions/instances/rawTransaction.ts
3642
+ var RawTransaction = class extends Serializable {
3643
+ constructor(sender, sequence_number, payload, max_gas_amount, gas_unit_price, expiration_timestamp_secs, chain_id) {
3644
+ super();
3645
+ this.sender = sender;
3646
+ this.sequence_number = sequence_number;
3647
+ this.payload = payload;
3648
+ this.max_gas_amount = max_gas_amount;
3649
+ this.gas_unit_price = gas_unit_price;
3650
+ this.expiration_timestamp_secs = expiration_timestamp_secs;
3651
+ this.chain_id = chain_id;
3652
+ }
3653
+ serialize(serializer) {
3654
+ this.sender.serialize(serializer);
3655
+ serializer.serializeU64(this.sequence_number);
3656
+ this.payload.serialize(serializer);
3657
+ serializer.serializeU64(this.max_gas_amount);
3658
+ serializer.serializeU64(this.gas_unit_price);
3659
+ serializer.serializeU64(this.expiration_timestamp_secs);
3660
+ this.chain_id.serialize(serializer);
3661
+ }
3662
+ static deserialize(deserializer) {
3663
+ const sender = AccountAddress.deserialize(deserializer);
3664
+ const sequence_number = deserializer.deserializeU64();
3665
+ const payload = TransactionPayload.deserialize(deserializer);
3666
+ const max_gas_amount = deserializer.deserializeU64();
3667
+ const gas_unit_price = deserializer.deserializeU64();
3668
+ const expiration_timestamp_secs = deserializer.deserializeU64();
3669
+ const chain_id = ChainId.deserialize(deserializer);
3670
+ return new RawTransaction(
3671
+ sender,
3672
+ sequence_number,
3673
+ payload,
3674
+ max_gas_amount,
3675
+ gas_unit_price,
3676
+ expiration_timestamp_secs,
3677
+ chain_id
3678
+ );
3679
+ }
3680
+ };
3681
+ var RawTransactionWithData = class extends Serializable {
3682
+ static deserialize(deserializer) {
3683
+ const index = deserializer.deserializeUleb128AsU32();
3684
+ switch (index) {
3685
+ case 0 /* MultiAgentTransaction */:
3686
+ return MultiAgentRawTransaction.load(deserializer);
3687
+ case 1 /* FeePayerTransaction */:
3688
+ return FeePayerRawTransaction.load(deserializer);
3689
+ default:
3690
+ throw new Error(`Unknown variant index for RawTransactionWithData: ${index}`);
3691
+ }
3692
+ }
3693
+ };
3694
+ var MultiAgentRawTransaction = class extends RawTransactionWithData {
3695
+ constructor(raw_txn, secondary_signer_addresses) {
3696
+ super();
3697
+ this.raw_txn = raw_txn;
3698
+ this.secondary_signer_addresses = secondary_signer_addresses;
3699
+ }
3700
+ serialize(serializer) {
3701
+ serializer.serializeU32AsUleb128(0 /* MultiAgentTransaction */);
3702
+ this.raw_txn.serialize(serializer);
3703
+ serializer.serializeVector(this.secondary_signer_addresses);
3704
+ }
3705
+ static load(deserializer) {
3706
+ const rawTxn = RawTransaction.deserialize(deserializer);
3707
+ const secondarySignerAddresses = deserializer.deserializeVector(AccountAddress);
3708
+ return new MultiAgentRawTransaction(rawTxn, secondarySignerAddresses);
3709
+ }
3710
+ };
3711
+ var FeePayerRawTransaction = class extends RawTransactionWithData {
3712
+ constructor(raw_txn, secondary_signer_addresses, fee_payer_address) {
3713
+ super();
3714
+ this.raw_txn = raw_txn;
3715
+ this.secondary_signer_addresses = secondary_signer_addresses;
3716
+ this.fee_payer_address = fee_payer_address;
3717
+ }
3718
+ serialize(serializer) {
3719
+ serializer.serializeU32AsUleb128(1 /* FeePayerTransaction */);
3720
+ this.raw_txn.serialize(serializer);
3721
+ serializer.serializeVector(this.secondary_signer_addresses);
3722
+ this.fee_payer_address.serialize(serializer);
3723
+ }
3724
+ static load(deserializer) {
3725
+ const rawTxn = RawTransaction.deserialize(deserializer);
3726
+ const secondarySignerAddresses = deserializer.deserializeVector(AccountAddress);
3727
+ const feePayerAddress = AccountAddress.deserialize(deserializer);
3728
+ return new FeePayerRawTransaction(rawTxn, secondarySignerAddresses, feePayerAddress);
3729
+ }
3730
+ };
3731
+
3732
+ // src/transactions/instances/signedTransaction.ts
3733
+ var SignedTransaction = class extends Serializable {
3734
+ constructor(raw_txn, authenticator) {
3735
+ super();
3736
+ this.raw_txn = raw_txn;
3737
+ this.authenticator = authenticator;
3738
+ }
3739
+ serialize(serializer) {
3740
+ this.raw_txn.serialize(serializer);
3741
+ this.authenticator.serialize(serializer);
3742
+ }
3743
+ static deserialize(deserializer) {
3744
+ const raw_txn = RawTransaction.deserialize(deserializer);
3745
+ const authenticator = TransactionAuthenticator.deserialize(deserializer);
3746
+ return new SignedTransaction(raw_txn, authenticator);
3747
+ }
3748
+ };
3749
+
3750
+ // src/transactions/transaction_builder/transaction_builder.ts
3751
+ function generateTransactionPayload(args) {
3752
+ var _a, _b, _c;
3753
+ if ("bytecode" in args) {
3754
+ return new TransactionPayloadScript(
3755
+ new Script(Hex.fromHexInput(args.bytecode).toUint8Array(), (_a = args.typeArguments) != null ? _a : [], args.arguments)
3756
+ );
3757
+ }
3758
+ if ("multisigAddress" in args) {
3759
+ const funcNameParts2 = args.function.split("::");
3760
+ return new TransactionPayloadMultisig(
3761
+ new MultiSig(
3762
+ args.multisigAddress,
3763
+ new MultiSigTransactionPayload(
3764
+ EntryFunction.build(
3765
+ `${funcNameParts2[0]}::${funcNameParts2[1]}`,
3766
+ funcNameParts2[2],
3767
+ (_b = args.typeArguments) != null ? _b : [],
3768
+ args.arguments
3769
+ )
3770
+ )
3771
+ )
3772
+ );
3773
+ }
3774
+ const funcNameParts = args.function.split("::");
3775
+ return new TransactionPayloadEntryFunction(
3776
+ EntryFunction.build(
3777
+ `${funcNameParts[0]}::${funcNameParts[1]}`,
3778
+ funcNameParts[2],
3779
+ (_c = args.typeArguments) != null ? _c : [],
3780
+ args.arguments
3781
+ )
3782
+ );
3783
+ }
3784
+ async function generateRawTransaction(args) {
3785
+ const { aptosConfig, sender, payload, options } = args;
3786
+ const getSequenceNumber = (options == null ? void 0 : options.accountSequenceNumber) ? Promise.resolve({ sequence_number: options.accountSequenceNumber }) : getInfo({ aptosConfig, accountAddress: sender });
3787
+ const getChainId = NetworkToChainId[aptosConfig.network] ? Promise.resolve({ chain_id: NetworkToChainId[aptosConfig.network] }) : getLedgerInfo({ aptosConfig });
3788
+ const getGasUnitPrice = (options == null ? void 0 : options.gasUnitPrice) ? Promise.resolve({ gas_estimate: options.gasUnitPrice }) : getGasPriceEstimation({ aptosConfig });
3789
+ const [{ sequence_number: sequenceNumber }, { chain_id: chainId }, { gas_estimate: gasEstimate }] = await Promise.all(
3790
+ [getSequenceNumber, getChainId, getGasUnitPrice]
3791
+ );
3792
+ const { maxGasAmount, gasUnitPrice, expireTimestamp } = {
3793
+ maxGasAmount: BigInt(DEFAULT_MAX_GAS_AMOUNT),
3794
+ gasUnitPrice: BigInt(gasEstimate),
3795
+ expireTimestamp: BigInt(Math.floor(Date.now() / 1e3) + DEFAULT_TXN_EXP_SEC_FROM_NOW),
3796
+ ...options
3797
+ };
3798
+ return new RawTransaction(
3799
+ AccountAddress.fromHexInput(sender),
3800
+ BigInt(sequenceNumber),
3801
+ payload,
3802
+ BigInt(maxGasAmount),
3803
+ BigInt(gasUnitPrice),
3804
+ BigInt(expireTimestamp),
3805
+ new ChainId(chainId)
3806
+ );
3807
+ }
3808
+ async function buildTransaction(args) {
3809
+ const { aptosConfig, sender, payload, options, secondarySignerAddresses, feePayerAddress } = args;
3810
+ const rawTxn = await generateRawTransaction({
3811
+ aptosConfig,
3812
+ sender,
3813
+ payload,
3814
+ options
3815
+ });
3816
+ if (feePayerAddress) {
3817
+ const signers = secondarySignerAddresses ? secondarySignerAddresses.map((signer) => AccountAddress.fromHexInput(signer)) : [];
3818
+ return {
3819
+ rawTransaction: rawTxn.bcsToBytes(),
3820
+ secondarySignerAddresses: signers,
3821
+ feePayerAddress: AccountAddress.fromHexInput(feePayerAddress)
3822
+ };
3823
+ }
3824
+ if (secondarySignerAddresses) {
3825
+ const signers = secondarySignerAddresses.map(
3826
+ (signer) => AccountAddress.fromHexInput(signer)
3827
+ );
3828
+ return {
3829
+ rawTransaction: rawTxn.bcsToBytes(),
3830
+ secondarySignerAddresses: signers
3831
+ };
3832
+ }
3833
+ return { rawTransaction: rawTxn.bcsToBytes() };
3834
+ }
3835
+ function generateSignedTransactionForSimulation(args) {
3836
+ var _a, _b;
3837
+ const { signerPublicKey, transaction, secondarySignersPublicKeys, feePayerPublicKey } = args;
3838
+ const deserializer = new Deserializer(transaction.rawTransaction);
3839
+ const deserializedTransaction = RawTransaction.deserialize(deserializer);
3840
+ const accountAuthenticator = getAuthenticatorForSimulation(signerPublicKey);
3841
+ if (transaction.feePayerAddress) {
3842
+ const transactionToSign = new FeePayerRawTransaction(
3843
+ deserializedTransaction,
3844
+ (_a = transaction.secondarySignerAddresses) != null ? _a : [],
3845
+ transaction.feePayerAddress
3846
+ );
3847
+ let secondaryAccountAuthenticators = [];
3848
+ if (secondarySignersPublicKeys) {
3849
+ secondaryAccountAuthenticators = secondarySignersPublicKeys.map(
3850
+ (publicKey) => getAuthenticatorForSimulation(publicKey)
3851
+ );
3852
+ }
3853
+ const feePayerAuthenticator = getAuthenticatorForSimulation(feePayerPublicKey);
3854
+ const transactionAuthenticator2 = new TransactionAuthenticatorFeePayer(
3855
+ accountAuthenticator,
3856
+ (_b = transaction.secondarySignerAddresses) != null ? _b : [],
3857
+ secondaryAccountAuthenticators,
3858
+ {
3859
+ address: transaction.feePayerAddress,
3860
+ authenticator: feePayerAuthenticator
3861
+ }
3862
+ );
3863
+ return new SignedTransaction(transactionToSign.raw_txn, transactionAuthenticator2).bcsToBytes();
3864
+ }
3865
+ if (transaction.secondarySignerAddresses) {
3866
+ const transactionToSign = new MultiAgentRawTransaction(
3867
+ deserializedTransaction,
3868
+ transaction.secondarySignerAddresses
3869
+ );
3870
+ let secondaryAccountAuthenticators = [];
3871
+ secondaryAccountAuthenticators = secondarySignersPublicKeys.map(
3872
+ (publicKey) => getAuthenticatorForSimulation(publicKey)
3873
+ );
3874
+ const transactionAuthenticator2 = new TransactionAuthenticatorMultiAgent(
3875
+ accountAuthenticator,
3876
+ transaction.secondarySignerAddresses,
3877
+ secondaryAccountAuthenticators
3878
+ );
3879
+ return new SignedTransaction(transactionToSign.raw_txn, transactionAuthenticator2).bcsToBytes();
3880
+ }
3881
+ let transactionAuthenticator;
3882
+ if (accountAuthenticator instanceof AccountAuthenticatorEd25519) {
3883
+ transactionAuthenticator = new TransactionAuthenticatorEd25519(
3884
+ accountAuthenticator.public_key,
3885
+ accountAuthenticator.signature
3886
+ );
3887
+ } else if (accountAuthenticator instanceof AccountAuthenticatorSecp256k1) {
3888
+ transactionAuthenticator = new TransactionAuthenticatorSecp256k1(
3889
+ accountAuthenticator.public_key,
3890
+ accountAuthenticator.signature
3891
+ );
3892
+ } else {
3893
+ throw new Error("Invalid public key");
3894
+ }
3895
+ return new SignedTransaction(deserializedTransaction, transactionAuthenticator).bcsToBytes();
3896
+ }
3897
+ function getAuthenticatorForSimulation(publicKey) {
3898
+ if (publicKey instanceof Ed25519PublicKey) {
3899
+ return new AccountAuthenticatorEd25519(
3900
+ new Ed25519PublicKey(publicKey.toUint8Array()),
3901
+ new Ed25519Signature(new Uint8Array(64))
3902
+ );
3903
+ }
3904
+ return new AccountAuthenticatorSecp256k1(
3905
+ new Secp256k1PublicKey(publicKey.toUint8Array()),
3906
+ new Secp256k1Signature(new Uint8Array(64))
3907
+ );
3908
+ }
3909
+ function sign(args) {
3910
+ const { signer, transaction } = args;
3911
+ const transactionToSign = deriveTransactionType(transaction);
3912
+ const message = getSigningMessage(transactionToSign);
3913
+ const signerSignature = signer.sign(message);
3914
+ switch (signer.signingScheme) {
3915
+ case 0 /* Ed25519 */:
3916
+ return new AccountAuthenticatorEd25519(
3917
+ new Ed25519PublicKey(signer.publicKey.toUint8Array()),
3918
+ new Ed25519Signature(signerSignature.toUint8Array())
3919
+ );
3920
+ case 2 /* Secp256k1Ecdsa */:
3921
+ return new AccountAuthenticatorSecp256k1(
3922
+ new Secp256k1PublicKey(signer.publicKey.toUint8Array()),
3923
+ new Secp256k1Signature(signerSignature.toUint8Array())
3924
+ );
3925
+ default:
3926
+ throw new Error(`Cannot sign transaction, signing scheme ${signer.signingScheme} not supported`);
3927
+ }
3928
+ }
3929
+ function generateSignedTransaction(args) {
3930
+ const { transaction, senderAuthenticator, secondarySignerAuthenticators } = args;
3931
+ const transactionToSubmit = deriveTransactionType(transaction);
3932
+ if (secondarySignerAuthenticators) {
3933
+ return generateMultiSignersSignedTransaction(
3934
+ transactionToSubmit,
3935
+ senderAuthenticator,
3936
+ secondarySignerAuthenticators
3937
+ );
3938
+ }
3939
+ const deserializer = new Deserializer(senderAuthenticator.bcsToBytes());
3940
+ const accountAuthenticator = AccountAuthenticator.deserialize(deserializer);
3941
+ if (accountAuthenticator instanceof AccountAuthenticatorEd25519) {
3942
+ const transactionAuthenticator = new TransactionAuthenticatorEd25519(
3943
+ accountAuthenticator.public_key,
3944
+ accountAuthenticator.signature
3945
+ );
3946
+ return new SignedTransaction(transactionToSubmit, transactionAuthenticator).bcsToBytes();
3947
+ }
3948
+ if (accountAuthenticator instanceof AccountAuthenticatorSecp256k1) {
3949
+ const transactionAuthenticator = new TransactionAuthenticatorSecp256k1(
3950
+ accountAuthenticator.public_key,
3951
+ accountAuthenticator.signature
3952
+ );
3953
+ return new SignedTransaction(transactionToSubmit, transactionAuthenticator).bcsToBytes();
3954
+ }
3955
+ throw new Error(
3956
+ `Cannot generate a signed transaction, ${accountAuthenticator} is not a supported account authentication scheme`
3957
+ );
3958
+ }
3959
+ function deriveTransactionType(transaction) {
3960
+ var _a;
3961
+ const deserializer = new Deserializer(transaction.rawTransaction);
3962
+ const deserializedTransaction = RawTransaction.deserialize(deserializer);
3963
+ if (transaction.feePayerAddress) {
3964
+ return new FeePayerRawTransaction(
3965
+ deserializedTransaction,
3966
+ (_a = transaction.secondarySignerAddresses) != null ? _a : [],
3967
+ transaction.feePayerAddress
3968
+ );
3969
+ }
3970
+ if (transaction.secondarySignerAddresses) {
3971
+ return new MultiAgentRawTransaction(deserializedTransaction, transaction.secondarySignerAddresses);
3972
+ }
3973
+ return deserializedTransaction;
3974
+ }
3975
+ function generateMultiSignersSignedTransaction(transaction, senderAuthenticator, secondarySignerAuthenticators) {
3976
+ if (transaction instanceof FeePayerRawTransaction) {
3977
+ if (!secondarySignerAuthenticators.feePayerAuthenticator) {
3978
+ throw new Error("Must provide a feePayerAuthenticator argument to generate a signed fee payer transaction");
3979
+ }
3980
+ const { feePayerAuthenticator, additionalSignersAuthenticators } = secondarySignerAuthenticators;
3981
+ const txAuthenticatorFeePayer = new TransactionAuthenticatorFeePayer(
3982
+ senderAuthenticator,
3983
+ transaction.secondary_signer_addresses,
3984
+ additionalSignersAuthenticators != null ? additionalSignersAuthenticators : [],
3985
+ {
3986
+ address: transaction.fee_payer_address,
3987
+ authenticator: feePayerAuthenticator
3988
+ }
3989
+ );
3990
+ return new SignedTransaction(transaction.raw_txn, txAuthenticatorFeePayer).bcsToBytes();
3991
+ }
3992
+ if (transaction instanceof MultiAgentRawTransaction) {
3993
+ if (!secondarySignerAuthenticators.additionalSignersAuthenticators) {
3994
+ throw new Error(
3995
+ "Must provide a additionalSignersAuthenticators argument to generate a signed multi agent transaction"
3996
+ );
3997
+ }
3998
+ const { additionalSignersAuthenticators } = secondarySignerAuthenticators;
3999
+ const multiAgentAuthenticator = new TransactionAuthenticatorMultiAgent(
4000
+ senderAuthenticator,
4001
+ transaction.secondary_signer_addresses,
4002
+ additionalSignersAuthenticators != null ? additionalSignersAuthenticators : []
4003
+ );
4004
+ return new SignedTransaction(transaction.raw_txn, multiAgentAuthenticator).bcsToBytes();
4005
+ }
4006
+ throw new Error(
4007
+ `Cannot prepare multi signers transaction to submission, ${typeof transaction} transaction is not supported`
4008
+ );
4009
+ }
4010
+ function getSigningMessage(rawTxn) {
4011
+ const hash = import_sha33.sha3_256.create();
4012
+ if (rawTxn instanceof RawTransaction) {
4013
+ hash.update(RAW_TRANSACTION_SALT);
4014
+ } else if (rawTxn instanceof MultiAgentRawTransaction) {
4015
+ hash.update(RAW_TRANSACTION_WITH_DATA_SALT);
4016
+ } else if (rawTxn instanceof FeePayerRawTransaction) {
4017
+ hash.update(RAW_TRANSACTION_WITH_DATA_SALT);
4018
+ } else {
4019
+ throw new Error(`Unknown transaction type to sign on: ${rawTxn}`);
4020
+ }
4021
+ const prefix = hash.digest();
4022
+ const body = rawTxn.bcsToBytes();
4023
+ const mergedArray = new Uint8Array(prefix.length + body.length);
4024
+ mergedArray.set(prefix);
4025
+ mergedArray.set(body, prefix.length);
4026
+ return mergedArray;
4027
+ }
4028
+
4029
+ // src/internal/transactionSubmission.ts
4030
+ async function generateTransaction(args) {
4031
+ const { aptosConfig, sender, data, options, secondarySignerAddresses, feePayerAddress } = args;
4032
+ const payload = await generateTransactionPayload(data);
4033
+ return buildTransaction({
4034
+ aptosConfig,
4035
+ sender,
4036
+ payload,
4037
+ options,
4038
+ secondarySignerAddresses,
4039
+ feePayerAddress
4040
+ });
4041
+ }
4042
+ function signTransaction(args) {
4043
+ const accountAuthenticator = sign({ ...args });
4044
+ return accountAuthenticator;
4045
+ }
4046
+ async function simulateTransaction(args) {
4047
+ var _a, _b, _c, _d, _e, _f;
4048
+ const { aptosConfig, transaction, signerPublicKey, secondarySignersPublicKeys, feePayerPublicKey, options } = args;
4049
+ const signedTransaction = generateSignedTransactionForSimulation({
4050
+ transaction,
4051
+ signerPublicKey,
4052
+ secondarySignersPublicKeys,
4053
+ feePayerPublicKey,
4054
+ options
4055
+ });
4056
+ const { data } = await postAptosFullNode({
4057
+ aptosConfig,
4058
+ body: signedTransaction,
4059
+ path: "transactions/simulate",
4060
+ params: {
4061
+ estimate_gas_unit_price: (_b = (_a = args.options) == null ? void 0 : _a.estimateGasUnitPrice) != null ? _b : false,
4062
+ estimate_max_gas_amount: (_d = (_c = args.options) == null ? void 0 : _c.estimateMaxGasAmount) != null ? _d : false,
4063
+ estimate_prioritized_gas_unit_price: (_f = (_e = args.options) == null ? void 0 : _e.estimatePrioritizedGasUnitPrice) != null ? _f : false
4064
+ },
4065
+ originMethod: "simulateTransaction",
4066
+ contentType: "application/x.aptos.signed_transaction+bcs" /* BCS_SIGNED_TRANSACTION */
4067
+ });
4068
+ return data;
4069
+ }
4070
+ async function submitTransaction(args) {
4071
+ const { aptosConfig } = args;
4072
+ const signedTransaction = generateSignedTransaction({ ...args });
4073
+ const { data } = await postAptosFullNode({
4074
+ aptosConfig,
4075
+ body: signedTransaction,
4076
+ path: "transactions",
4077
+ originMethod: "submitTransaction",
4078
+ contentType: "application/x.aptos.signed_transaction+bcs" /* BCS_SIGNED_TRANSACTION */
4079
+ });
4080
+ return data;
4081
+ }
4082
+
4083
+ // src/internal/coin.ts
4084
+ async function transferCoinTransaction(args) {
4085
+ const { aptosConfig, sender, recipient, amount, coinType, options } = args;
4086
+ const coinStructType = coinType != null ? coinType : APTOS_COIN;
4087
+ const transaction = await generateTransaction({
4088
+ aptosConfig,
4089
+ sender: sender.accountAddress.toString(),
4090
+ data: {
4091
+ function: "0x1::aptos_account::transfer_coins",
4092
+ typeArguments: [new TypeTagStruct(StructTag.fromString(coinStructType))],
4093
+ arguments: [AccountAddress.fromHexInput(recipient), new U64(amount)]
4094
+ },
4095
+ options
4096
+ });
4097
+ return transaction;
4098
+ }
4099
+
4100
+ // src/api/coin.ts
4101
+ var Coin = class {
4102
+ constructor(config) {
4103
+ this.config = config;
4104
+ }
4105
+ async transferCoinTransaction(args) {
4106
+ return transferCoinTransaction({ aptosConfig: this.config, ...args });
4107
+ }
4108
+ };
4109
+
4110
+ // src/internal/digitalAsset.ts
4111
+ async function mintTokenTransaction(args) {
4112
+ const { aptosConfig, options, creator } = args;
4113
+ const transaction = await generateTransaction({
4114
+ aptosConfig,
4115
+ sender: creator.accountAddress.toString(),
4116
+ data: {
4117
+ function: "0x4::aptos_token::mint",
4118
+ arguments: [
4119
+ new MoveString(args.collection),
4120
+ new MoveString(args.description),
4121
+ new MoveString(args.name),
4122
+ new MoveString(args.uri),
4123
+ MoveVector.MoveString([]),
4124
+ MoveVector.MoveString([]),
4125
+ new MoveVector([])
4126
+ ]
4127
+ },
4128
+ options
4129
+ });
4130
+ return transaction;
4131
+ }
4132
+ async function getTokenData(args) {
4133
+ const { aptosConfig, tokenAddress } = args;
4134
+ const whereCondition = {
4135
+ token_data_id: { _eq: Hex.fromHexInput(tokenAddress).toString() }
4136
+ };
4137
+ const graphqlQuery = {
4138
+ query: GetTokenData,
4139
+ variables: {
4140
+ where_condition: whereCondition
4141
+ }
4142
+ };
4143
+ const data = await queryIndexer({
4144
+ aptosConfig,
4145
+ query: graphqlQuery,
4146
+ originMethod: "getTokenData"
4147
+ });
4148
+ return data.current_token_datas_v2[0];
4149
+ }
4150
+ async function getCurrentTokenOwnership(args) {
4151
+ const { aptosConfig, tokenAddress } = args;
4152
+ const whereCondition = {
4153
+ token_data_id: { _eq: Hex.fromHexInput(tokenAddress).toString() }
4154
+ };
4155
+ const graphqlQuery = {
4156
+ query: GetCurrentTokenOwnership,
4157
+ variables: {
4158
+ where_condition: whereCondition
4159
+ }
4160
+ };
4161
+ const data = await queryIndexer({
4162
+ aptosConfig,
4163
+ query: graphqlQuery,
4164
+ originMethod: "getCurrentTokenOwnership"
4165
+ });
4166
+ return data.current_token_ownerships_v2[0];
4167
+ }
4168
+ async function getOwnedTokens(args) {
4169
+ var _a, _b;
4170
+ const { aptosConfig, ownerAddress, options } = args;
4171
+ const whereCondition = {
4172
+ owner_address: { _eq: Hex.fromHexInput(ownerAddress).toString() }
4173
+ };
4174
+ const graphqlQuery = {
4175
+ query: GetCurrentTokenOwnership,
4176
+ variables: {
4177
+ where_condition: whereCondition,
4178
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
4179
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
4180
+ order_by: options == null ? void 0 : options.orderBy
4181
+ }
4182
+ };
4183
+ const data = await queryIndexer({
4184
+ aptosConfig,
4185
+ query: graphqlQuery,
4186
+ originMethod: "getOwnedTokens"
4187
+ });
4188
+ return data.current_token_ownerships_v2;
4189
+ }
4190
+ async function getTokenActivity(args) {
4191
+ var _a, _b;
4192
+ const { aptosConfig, tokenAddress, options } = args;
4193
+ const whereCondition = {
4194
+ token_data_id: { _eq: Hex.fromHexInput(tokenAddress).toString() }
4195
+ };
4196
+ const graphqlQuery = {
4197
+ query: GetTokenActivity,
4198
+ variables: {
4199
+ where_condition: whereCondition,
4200
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
4201
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
4202
+ order_by: options == null ? void 0 : options.orderBy
4203
+ }
4204
+ };
4205
+ const data = await queryIndexer({
4206
+ aptosConfig,
4207
+ query: graphqlQuery,
4208
+ originMethod: "getTokenActivity"
4209
+ });
4210
+ return data.token_activities_v2;
4211
+ }
4212
+ async function createCollectionTransaction(args) {
4213
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
4214
+ const { aptosConfig, options, creator } = args;
4215
+ const transaction = await generateTransaction({
4216
+ aptosConfig,
4217
+ sender: creator.accountAddress.toString(),
4218
+ data: {
4219
+ function: "0x4::aptos_token::create_collection",
4220
+ arguments: [
4221
+ new MoveString(args.description),
4222
+ new U64((_a = args.maxSupply) != null ? _a : MAX_U64_BIG_INT),
4223
+ new MoveString(args.name),
4224
+ new MoveString(args.uri),
4225
+ new Bool((_b = args.mutableDescription) != null ? _b : true),
4226
+ new Bool((_c = args.mutableRoyalty) != null ? _c : true),
4227
+ new Bool((_d = args.mutableURI) != null ? _d : true),
4228
+ new Bool((_e = args.mutableTokenDescription) != null ? _e : true),
4229
+ new Bool((_f = args.mutableTokenName) != null ? _f : true),
4230
+ new Bool((_g = args.mutableTokenProperties) != null ? _g : true),
4231
+ new Bool((_h = args.mutableTokenURI) != null ? _h : true),
4232
+ new Bool((_i = args.tokensBurnableByCreator) != null ? _i : true),
4233
+ new Bool((_j = args.tokensFreezableByCreator) != null ? _j : true),
4234
+ new U64((_k = args.royaltyNumerator) != null ? _k : 0),
4235
+ new U64((_l = args.royaltyDenominator) != null ? _l : 1)
4236
+ ]
4237
+ },
4238
+ options
4239
+ });
4240
+ return transaction;
4241
+ }
4242
+ async function getCollectionData(args) {
4243
+ var _a;
4244
+ const { aptosConfig, creatorAddress, collectionName, options } = args;
4245
+ const address = Hex.fromHexInput(creatorAddress).toString();
4246
+ const whereCondition = {
4247
+ collection_name: { _eq: collectionName },
4248
+ creator_address: { _eq: address }
4249
+ };
4250
+ if (options == null ? void 0 : options.tokenStandard) {
4251
+ whereCondition.token_standard = { _eq: (_a = options == null ? void 0 : options.tokenStandard) != null ? _a : "v2" };
4252
+ }
4253
+ const graphqlQuery = {
4254
+ query: GetCollectionData,
4255
+ variables: {
4256
+ where_condition: whereCondition
4257
+ }
4258
+ };
4259
+ const data = await queryIndexer({
4260
+ aptosConfig,
4261
+ query: graphqlQuery,
4262
+ originMethod: "getCollectionData"
4263
+ });
4264
+ if (data.current_collections_v2.length === 0) {
4265
+ throw Error("Collection not found");
4266
+ }
4267
+ return data.current_collections_v2[0];
4268
+ }
4269
+ async function getCollectionId(args) {
4270
+ return (await getCollectionData(args)).collection_id;
4271
+ }
4272
+
4273
+ // src/api/digitalAsset.ts
4274
+ var DigitalAsset = class {
4275
+ constructor(config) {
4276
+ this.config = config;
4277
+ }
4278
+ async createCollectionTransaction(args) {
4279
+ return createCollectionTransaction({ aptosConfig: this.config, ...args });
4280
+ }
4281
+ async getCollectionData(args) {
4282
+ return getCollectionData({ aptosConfig: this.config, ...args });
4283
+ }
4284
+ async getCollectionId(args) {
4285
+ return getCollectionId({ aptosConfig: this.config, ...args });
4286
+ }
4287
+ async mintTokenTransaction(args) {
4288
+ return mintTokenTransaction({ aptosConfig: this.config, ...args });
4289
+ }
4290
+ async getTokenData(args) {
4291
+ return getTokenData({ aptosConfig: this.config, ...args });
4292
+ }
4293
+ async getCurrentTokenOwnership(args) {
4294
+ return getCurrentTokenOwnership({ aptosConfig: this.config, ...args });
4295
+ }
4296
+ async getOwnedTokens(args) {
4297
+ return getOwnedTokens({ aptosConfig: this.config, ...args });
4298
+ }
4299
+ async getTokenActivity(args) {
4300
+ return getTokenActivity({ aptosConfig: this.config, ...args });
4301
+ }
4302
+ };
4303
+
4304
+ // src/internal/event.ts
4305
+ async function getAccountEventsByCreationNumber(args) {
4306
+ const { accountAddress, aptosConfig, creationNumber } = args;
4307
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
4308
+ const whereCondition = {
4309
+ account_address: { _eq: address },
4310
+ creation_number: { _eq: creationNumber }
4311
+ };
4312
+ return getEvents({ aptosConfig, options: { where: whereCondition } });
4313
+ }
4314
+ async function getAccountEventsByEventType(args) {
4315
+ const { accountAddress, aptosConfig, eventType, options } = args;
4316
+ const address = AccountAddress.fromHexInput(accountAddress).toString();
4317
+ const whereCondition = {
4318
+ account_address: { _eq: address },
4319
+ type: { _eq: eventType }
4320
+ };
4321
+ const customOptions = {
4322
+ where: whereCondition,
4323
+ pagination: options == null ? void 0 : options.pagination,
4324
+ orderBy: options == null ? void 0 : options.orderBy
4325
+ };
4326
+ return getEvents({ aptosConfig, options: customOptions });
4327
+ }
4328
+ async function getEvents(args) {
4329
+ var _a, _b;
4330
+ const { aptosConfig, options } = args;
4331
+ const graphqlQuery = {
4332
+ query: GetEvents,
4333
+ variables: {
4334
+ where_condition: options == null ? void 0 : options.where,
4335
+ offset: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.offset,
4336
+ limit: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.limit,
4337
+ order_by: options == null ? void 0 : options.orderBy
4338
+ }
4339
+ };
4340
+ const data = await queryIndexer({
4341
+ aptosConfig,
4342
+ query: graphqlQuery,
4343
+ originMethod: "getEvents"
4344
+ });
4345
+ return data.events;
4346
+ }
4347
+
4348
+ // src/api/event.ts
4349
+ var Event = class {
4350
+ constructor(config) {
4351
+ this.config = config;
4352
+ }
4353
+ async getAccountEventsByCreationNumber(args) {
4354
+ return getAccountEventsByCreationNumber({ aptosConfig: this.config, ...args });
4355
+ }
4356
+ async getAccountEventsByEventType(args) {
4357
+ return getAccountEventsByEventType({ aptosConfig: this.config, ...args });
4358
+ }
4359
+ async getEvents(args) {
4360
+ return getEvents({ aptosConfig: this.config, ...args });
4361
+ }
4362
+ };
4363
+
4364
+ // src/internal/faucet.ts
4365
+ async function fundAccount(args) {
4366
+ var _a;
4367
+ const { aptosConfig, accountAddress, amount } = args;
4368
+ const timeoutSecs = (_a = args.timeoutSecs) != null ? _a : DEFAULT_TXN_TIMEOUT_SEC;
4369
+ const { data } = await postAptosFaucet({
4370
+ aptosConfig,
4371
+ path: "fund",
4372
+ body: {
4373
+ address: AccountAddress.fromHexInput(accountAddress).toString(),
4374
+ amount
4375
+ },
4376
+ originMethod: "fundAccount"
4377
+ });
4378
+ const txnHash = data.txn_hashes[0];
4379
+ await waitForTransaction({ aptosConfig, transactionHash: txnHash, options: { timeoutSecs } });
4380
+ return txnHash;
4381
+ }
4382
+
4383
+ // src/api/faucet.ts
4384
+ var Faucet = class {
4385
+ constructor(config) {
4386
+ this.config = config;
4387
+ }
4388
+ async fundAccount(args) {
4389
+ return fundAccount({ aptosConfig: this.config, ...args });
4390
+ }
4391
+ };
4392
+
4393
+ // src/internal/fungibleAsset.ts
4394
+ async function getFungibleAssetMetadata(args) {
4395
+ var _a, _b;
4396
+ const { aptosConfig, options } = args;
4397
+ const graphqlQuery = {
4398
+ query: GetFungibleAssetMetadata,
4399
+ variables: {
4400
+ where_condition: options == null ? void 0 : options.where,
4401
+ limit: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.limit,
4402
+ offset: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.offset
4403
+ }
4404
+ };
4405
+ const data = await queryIndexer({
4406
+ aptosConfig,
4407
+ query: graphqlQuery,
4408
+ originMethod: "getFungibleAssetMetadata"
4409
+ });
4410
+ return data.fungible_asset_metadata;
4411
+ }
4412
+ async function getFungibleAssetActivities(args) {
4413
+ var _a, _b;
4414
+ const { aptosConfig, options } = args;
4415
+ const graphqlQuery = {
4416
+ query: GetFungibleAssetActivities,
4417
+ variables: {
4418
+ where_condition: options == null ? void 0 : options.where,
4419
+ limit: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.limit,
4420
+ offset: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.offset
4421
+ }
4422
+ };
4423
+ const data = await queryIndexer({
4424
+ aptosConfig,
4425
+ query: graphqlQuery,
4426
+ originMethod: "getFungibleAssetActivities"
4427
+ });
4428
+ return data.fungible_asset_activities;
4429
+ }
4430
+ async function getCurrentFungibleAssetBalances(args) {
4431
+ var _a, _b;
4432
+ const { aptosConfig, options } = args;
4433
+ const graphqlQuery = {
4434
+ query: GetCurrentFungibleAssetBalances,
4435
+ variables: {
4436
+ where_condition: options == null ? void 0 : options.where,
4437
+ limit: (_a = options == null ? void 0 : options.pagination) == null ? void 0 : _a.limit,
4438
+ offset: (_b = options == null ? void 0 : options.pagination) == null ? void 0 : _b.offset
4439
+ }
4440
+ };
4441
+ const data = await queryIndexer({
4442
+ aptosConfig,
4443
+ query: graphqlQuery,
4444
+ originMethod: "getCurrentFungibleAssetBalances"
4445
+ });
4446
+ return data.current_fungible_asset_balances;
4447
+ }
4448
+
4449
+ // src/api/fungibleAsset.ts
4450
+ var FungibleAsset = class {
4451
+ constructor(config) {
4452
+ this.config = config;
4453
+ }
4454
+ async getFungibleAssetMetadata(args) {
4455
+ return getFungibleAssetMetadata({ aptosConfig: this.config, ...args });
4456
+ }
4457
+ async getFungibleAssetActivities(args) {
4458
+ return getFungibleAssetActivities({ aptosConfig: this.config, ...args });
4459
+ }
4460
+ async getCurrentFungibleAssetBalances(args) {
4461
+ return getCurrentFungibleAssetBalances({ aptosConfig: this.config, ...args });
4462
+ }
4463
+ };
4464
+
4465
+ // src/api/general.ts
4466
+ var General = class {
4467
+ constructor(config) {
4468
+ this.config = config;
4469
+ }
4470
+ async getLedgerInfo() {
4471
+ return getLedgerInfo({ aptosConfig: this.config });
4472
+ }
4473
+ async getChainId() {
4474
+ const result = await this.getLedgerInfo();
4475
+ return result.chain_id;
4476
+ }
4477
+ async getBlockByVersion(args) {
4478
+ return getBlockByVersion({
4479
+ aptosConfig: this.config,
4480
+ ...args
4481
+ });
4482
+ }
4483
+ async getBlockByHeight(args) {
4484
+ return getBlockByHeight({ aptosConfig: this.config, ...args });
4485
+ }
4486
+ async getTableItem(args) {
4487
+ return getTableItem({ aptosConfig: this.config, ...args });
4488
+ }
4489
+ async view(args) {
4490
+ return view({ aptosConfig: this.config, ...args });
4491
+ }
4492
+ async getChainTopUserTransactions(args) {
4493
+ return getChainTopUserTransactions({
4494
+ aptosConfig: this.config,
4495
+ ...args
4496
+ });
4497
+ }
4498
+ async queryIndexer(args) {
4499
+ return queryIndexer({
4500
+ aptosConfig: this.config,
4501
+ ...args
4502
+ });
4503
+ }
4504
+ async getIndexerLastSuccessVersion() {
4505
+ return getIndexerLastSuccessVersion({ aptosConfig: this.config });
4506
+ }
4507
+ };
4508
+
4509
+ // src/internal/staking.ts
4510
+ async function getNumberOfDelegators(args) {
4511
+ const { aptosConfig, poolAddress } = args;
4512
+ const address = Hex.fromHexInput(poolAddress).toString();
4513
+ const query = {
4514
+ query: GetNumberOfDelegators,
4515
+ variables: { where_condition: { pool_address: { _eq: address } } }
4516
+ };
4517
+ const data = await queryIndexer({ aptosConfig, query });
4518
+ if (data.num_active_delegator_per_pool.length === 0) {
4519
+ throw Error("Delegator pool not found");
4520
+ }
4521
+ return data.num_active_delegator_per_pool[0].num_active_delegator;
4522
+ }
4523
+ async function getNumberOfDelegatorsForAllPools(args) {
4524
+ const { aptosConfig, options } = args;
4525
+ const query = {
4526
+ query: GetNumberOfDelegators,
4527
+ variables: { where_condition: {}, order_by: options == null ? void 0 : options.orderBy }
4528
+ };
4529
+ const data = await queryIndexer({
4530
+ aptosConfig,
4531
+ query
4532
+ });
4533
+ return data.num_active_delegator_per_pool;
4534
+ }
4535
+ async function getDelegatedStakingActivities(args) {
4536
+ const { aptosConfig, delegatorAddress, poolAddress } = args;
4537
+ const query = {
4538
+ query: GetDelegatedStakingActivities,
4539
+ variables: {
4540
+ delegatorAddress: Hex.fromHexInput(delegatorAddress).toString(),
4541
+ poolAddress: Hex.fromHexInput(poolAddress).toString()
4542
+ }
4543
+ };
4544
+ const data = await queryIndexer({ aptosConfig, query });
4545
+ return data.delegated_staking_activities;
4546
+ }
4547
+
4548
+ // src/api/staking.ts
4549
+ var Staking = class {
4550
+ constructor(config) {
4551
+ this.config = config;
4552
+ }
4553
+ async getNumberOfDelegators(args) {
4554
+ return getNumberOfDelegators({ aptosConfig: this.config, ...args });
4555
+ }
4556
+ async getNumberOfDelegatorsForAllPools(args) {
4557
+ return getNumberOfDelegatorsForAllPools({ aptosConfig: this.config, ...args });
4558
+ }
4559
+ async getDelegatedStakingActivities(args) {
4560
+ return getDelegatedStakingActivities({ aptosConfig: this.config, ...args });
4561
+ }
4562
+ };
4563
+
4564
+ // src/api/transaction.ts
4565
+ var Transaction = class {
4566
+ constructor(config) {
4567
+ this.config = config;
4568
+ }
4569
+ async getTransactions(args) {
4570
+ return getTransactions2({
4571
+ aptosConfig: this.config,
4572
+ ...args
4573
+ });
4574
+ }
4575
+ async getTransactionByVersion(args) {
4576
+ return getTransactionByVersion({
4577
+ aptosConfig: this.config,
4578
+ ...args
4579
+ });
4580
+ }
4581
+ async getTransactionByHash(args) {
4582
+ return getTransactionByHash({
4583
+ aptosConfig: this.config,
4584
+ ...args
4585
+ });
4586
+ }
4587
+ async isPendingTransaction(args) {
4588
+ return isTransactionPending({
4589
+ aptosConfig: this.config,
4590
+ ...args
4591
+ });
4592
+ }
4593
+ async waitForTransaction(args) {
4594
+ return waitForTransaction({
4595
+ aptosConfig: this.config,
4596
+ ...args
4597
+ });
4598
+ }
4599
+ async getGasPriceEstimation() {
4600
+ return getGasPriceEstimation({
4601
+ aptosConfig: this.config
4602
+ });
4603
+ }
4604
+ };
4605
+
4606
+ // src/api/transactionSubmission.ts
4607
+ var TransactionSubmission = class {
4608
+ constructor(config) {
4609
+ this.config = config;
4610
+ }
4611
+ async generateTransaction(args) {
4612
+ return generateTransaction({ aptosConfig: this.config, ...args });
4613
+ }
4614
+ signTransaction(args) {
4615
+ return signTransaction({ ...args });
4616
+ }
4617
+ async simulateTransaction(args) {
4618
+ return simulateTransaction({ aptosConfig: this.config, ...args });
4619
+ }
4620
+ async submitTransaction(args) {
4621
+ return submitTransaction({ aptosConfig: this.config, ...args });
4622
+ }
4623
+ async signAndSubmitTransaction(args) {
4624
+ const { signer, transaction } = args;
4625
+ const authenticator = signTransaction({ signer, transaction });
4626
+ return submitTransaction({
4627
+ aptosConfig: this.config,
4628
+ transaction,
4629
+ senderAuthenticator: authenticator
4630
+ });
4631
+ }
4632
+ };
4633
+
4634
+ // src/api/aptos.ts
4635
+ var Aptos = class {
4636
+ constructor(settings) {
4637
+ this.config = new AptosConfig(settings);
4638
+ this.account = new Account2(this.config);
4639
+ this.coin = new Coin(this.config);
4640
+ this.digitalAsset = new DigitalAsset(this.config);
4641
+ this.event = new Event(this.config);
4642
+ this.faucet = new Faucet(this.config);
4643
+ this.fungibleAsset = new FungibleAsset(this.config);
4644
+ this.general = new General(this.config);
4645
+ this.staking = new Staking(this.config);
4646
+ this.transaction = new Transaction(this.config);
4647
+ this.transactionSubmission = new TransactionSubmission(this.config);
4648
+ }
4649
+ };
4650
+ function applyMixin(targetClass, baseClass, baseClassProp) {
4651
+ Object.getOwnPropertyNames(baseClass.prototype).forEach((propertyName) => {
4652
+ const propertyDescriptor = Object.getOwnPropertyDescriptor(baseClass.prototype, propertyName);
4653
+ if (!propertyDescriptor)
4654
+ return;
4655
+ propertyDescriptor.value = function(...args) {
4656
+ return this[baseClassProp][propertyName](...args);
4657
+ };
4658
+ Object.defineProperty(targetClass.prototype, propertyName, propertyDescriptor);
4659
+ });
4660
+ }
4661
+ applyMixin(Aptos, Account2, "account");
4662
+ applyMixin(Aptos, Coin, "coin");
4663
+ applyMixin(Aptos, DigitalAsset, "digitalAsset");
4664
+ applyMixin(Aptos, Event, "event");
4665
+ applyMixin(Aptos, Faucet, "faucet");
4666
+ applyMixin(Aptos, FungibleAsset, "fungibleAsset");
4667
+ applyMixin(Aptos, General, "general");
4668
+ applyMixin(Aptos, Staking, "staking");
4669
+ applyMixin(Aptos, Transaction, "transaction");
4670
+ applyMixin(Aptos, TransactionSubmission, "transactionSubmission");
4671
+ // Annotate the CommonJS export names for ESM import in node:
4672
+ 0 && (module.exports = {
4673
+ APTOS_PATH_REGEX,
4674
+ Account,
4675
+ AccountAddress,
4676
+ AccountAuthenticatorVariant,
4677
+ AddressInvalidReason,
4678
+ Aptos,
4679
+ AptosApiError,
4680
+ AptosConfig,
4681
+ AuthenticationKey,
4682
+ Bool,
4683
+ DeriveScheme,
4684
+ Deserializer,
4685
+ Ed25519PrivateKey,
4686
+ Ed25519PublicKey,
4687
+ Ed25519Signature,
4688
+ EntryFunctionBytes,
4689
+ FixedBytes,
4690
+ Hex,
4691
+ HexInvalidReason,
4692
+ KeyType,
4693
+ MimeType,
4694
+ MoveAbility,
4695
+ MoveFunctionVisibility,
4696
+ MoveObject,
4697
+ MoveOption,
4698
+ MoveString,
4699
+ MoveVector,
4700
+ MultiEd25519PublicKey,
4701
+ MultiEd25519Signature,
4702
+ Network,
4703
+ NetworkToChainId,
4704
+ NetworkToFaucetAPI,
4705
+ NetworkToIndexerAPI,
4706
+ NetworkToNodeAPI,
4707
+ ParsingError,
4708
+ PrivateKey,
4709
+ PublicKey,
4710
+ RoleType,
4711
+ ScriptTransactionArgumentVariants,
4712
+ Secp256k1PrivateKey,
4713
+ Secp256k1PublicKey,
4714
+ Secp256k1Signature,
4715
+ Serializable,
4716
+ Serializer,
4717
+ Signature,
4718
+ SigningScheme,
4719
+ StructTag,
4720
+ TransactionAuthenticatorVariant,
4721
+ TransactionPayloadVariants,
4722
+ TransactionResponseType,
4723
+ TransactionVariants,
4724
+ TypeTag,
4725
+ TypeTagAddress,
4726
+ TypeTagBool,
4727
+ TypeTagParser,
4728
+ TypeTagParserError,
4729
+ TypeTagSigner,
4730
+ TypeTagStruct,
4731
+ TypeTagU128,
4732
+ TypeTagU16,
4733
+ TypeTagU256,
4734
+ TypeTagU32,
4735
+ TypeTagU64,
4736
+ TypeTagU8,
4737
+ TypeTagVariants,
4738
+ TypeTagVector,
4739
+ U128,
4740
+ U16,
4741
+ U256,
4742
+ U32,
4743
+ U64,
4744
+ U8,
4745
+ aptosRequest,
4746
+ derivePrivateKeyFromMnemonic,
4747
+ ensureBoolean,
4748
+ get,
4749
+ getAptosFullNode,
4750
+ isValidPath,
4751
+ objectStructTag,
4752
+ optionStructTag,
4753
+ outOfRangeErrorMessage,
4754
+ paginateWithCursor,
4755
+ post,
4756
+ postAptosFaucet,
4757
+ postAptosFullNode,
4758
+ postAptosIndexer,
4759
+ stringStructTag,
4760
+ validateNumberInRange
4761
+ });
4762
+ //# sourceMappingURL=index.js.map