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