@wallfree-dev/aptos 0.13.43-beta.11

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 (44) hide show
  1. package/.npm-cache/_logs/2026-01-11T13_30_26_409Z-debug-0.log +14 -0
  2. package/README.md +32 -0
  3. package/index.d.ts +6 -0
  4. package/index.js +32 -0
  5. package/index.js.map +1 -0
  6. package/package.json +63 -0
  7. package/v1/block-explorer/AptosBlockExplorer.d.ts +9 -0
  8. package/v1/block-explorer/AptosBlockExplorer.js +72 -0
  9. package/v1/block-explorer/AptosBlockExplorer.js.map +1 -0
  10. package/v1/module/AptosCoinTokens.d.ts +5 -0
  11. package/v1/module/AptosCoinTokens.js +49 -0
  12. package/v1/module/AptosCoinTokens.js.map +1 -0
  13. package/v1/module/AptosModule.d.ts +18 -0
  14. package/v1/module/AptosModule.js +131 -0
  15. package/v1/module/AptosModule.js.map +1 -0
  16. package/v1/protocol/AptosCoinTokenProtocol.d.ts +89 -0
  17. package/v1/protocol/AptosCoinTokenProtocol.js +860 -0
  18. package/v1/protocol/AptosCoinTokenProtocol.js.map +1 -0
  19. package/v1/protocol/AptosProtocol.d.ts +77 -0
  20. package/v1/protocol/AptosProtocol.js +912 -0
  21. package/v1/protocol/AptosProtocol.js.map +1 -0
  22. package/v1/serializer/v3/schemas/converter/transaction-converter.d.ts +14 -0
  23. package/v1/serializer/v3/schemas/converter/transaction-converter.js +34 -0
  24. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -0
  25. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-aptos.d.ts +6 -0
  26. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-aptos.js +3 -0
  27. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-aptos.js.map +1 -0
  28. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-aptos.d.ts +3 -0
  29. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-aptos.js +3 -0
  30. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-aptos.js.map +1 -0
  31. package/v1/serializer/v3/schemas/generated/transaction-sign-request-aptos.json +29 -0
  32. package/v1/serializer/v3/schemas/generated/transaction-sign-response-aptos.json +19 -0
  33. package/v1/serializer/v3/serializer-companion.d.ts +15 -0
  34. package/v1/serializer/v3/serializer-companion.js +160 -0
  35. package/v1/serializer/v3/serializer-companion.js.map +1 -0
  36. package/v1/serializer/v3/validators/transaction-validator.d.ts +7 -0
  37. package/v1/serializer/v3/validators/transaction-validator.js +84 -0
  38. package/v1/serializer/v3/validators/transaction-validator.js.map +1 -0
  39. package/v1/serializer/v3/validators/validators.d.ts +4 -0
  40. package/v1/serializer/v3/validators/validators.js +45 -0
  41. package/v1/serializer/v3/validators/validators.js.map +1 -0
  42. package/v1/types/protocol.d.ts +37 -0
  43. package/v1/types/protocol.js +3 -0
  44. package/v1/types/protocol.js.map +1 -0
@@ -0,0 +1,860 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
37
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
+ return new (P || (P = Promise))(function (resolve, reject) {
39
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
43
+ });
44
+ };
45
+ var __generator = (this && this.__generator) || function (thisArg, body) {
46
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
47
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48
+ function verb(n) { return function (v) { return step([n, v]); }; }
49
+ function step(op) {
50
+ if (f) throw new TypeError("Generator is already executing.");
51
+ while (_) try {
52
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
53
+ if (y = 0, t) op = [op[0] & 2, t.value];
54
+ switch (op[0]) {
55
+ case 0: case 1: t = op; break;
56
+ case 4: _.label++; return { value: op[1], done: false };
57
+ case 5: _.label++; y = op[1]; op = [0]; continue;
58
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
59
+ default:
60
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64
+ if (t[2]) _.ops.pop();
65
+ _.trys.pop(); continue;
66
+ }
67
+ op = body.call(thisArg, _);
68
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70
+ }
71
+ };
72
+ var __rest = (this && this.__rest) || function (s, e) {
73
+ var t = {};
74
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
75
+ t[p] = s[p];
76
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
77
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
78
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
79
+ t[p[i]] = s[p[i]];
80
+ }
81
+ return t;
82
+ };
83
+ Object.defineProperty(exports, "__esModule", { value: true });
84
+ exports.createAptosCoinTokenProtocol = exports.AptosCoinTokenProtocolImpl = void 0;
85
+ var module_kit_1 = require("@wallfree-dev/module-kit");
86
+ var nacl = __importStar(require("tweetnacl"));
87
+ var js_sha3_1 = require("js-sha3");
88
+ var AptosProtocol_1 = require("./AptosProtocol");
89
+ // Default gas settings for Aptos
90
+ var DEFAULT_MAX_GAS_AMOUNT = 2000;
91
+ var DEFAULT_GAS_UNIT_PRICE = 100;
92
+ // Implementation
93
+ var AptosCoinTokenProtocolImpl = /** @class */ (function () {
94
+ function AptosCoinTokenProtocolImpl(options) {
95
+ this.options = options;
96
+ this.units = options.units;
97
+ this.mainUnit = options.mainUnit;
98
+ this.contractAddress = options.contractAddress;
99
+ this.isCoinType = options.contractAddress.includes('::');
100
+ }
101
+ AptosCoinTokenProtocolImpl.prototype.fetchJson = function (endpoint, options) {
102
+ return __awaiter(this, void 0, void 0, function () {
103
+ var url, response, _a, _b, _c;
104
+ return __generator(this, function (_d) {
105
+ switch (_d.label) {
106
+ case 0:
107
+ url = "".concat(this.options.network.rpcUrl).concat(endpoint);
108
+ return [4 /*yield*/, fetch(url, __assign(__assign({}, options), { headers: __assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }))];
109
+ case 1:
110
+ response = _d.sent();
111
+ if (!!response.ok) return [3 /*break*/, 3];
112
+ _a = Error.bind;
113
+ _c = (_b = "HTTP ".concat(response.status, ": ")).concat;
114
+ return [4 /*yield*/, response.text()];
115
+ case 2: throw new (_a.apply(Error, [void 0, _c.apply(_b, [_d.sent()])]))();
116
+ case 3: return [2 /*return*/, response.json()];
117
+ }
118
+ });
119
+ });
120
+ };
121
+ // SubProtocol methods
122
+ AptosCoinTokenProtocolImpl.prototype.getType = function () {
123
+ return __awaiter(this, void 0, void 0, function () {
124
+ return __generator(this, function (_a) {
125
+ return [2 /*return*/, 'token'];
126
+ });
127
+ });
128
+ };
129
+ AptosCoinTokenProtocolImpl.prototype.mainProtocol = function () {
130
+ return __awaiter(this, void 0, void 0, function () {
131
+ return __generator(this, function (_a) {
132
+ return [2 /*return*/, this.options.mainIdentifier];
133
+ });
134
+ });
135
+ };
136
+ AptosCoinTokenProtocolImpl.prototype.getContractAddress = function () {
137
+ return __awaiter(this, void 0, void 0, function () {
138
+ return __generator(this, function (_a) {
139
+ return [2 /*return*/, this.contractAddress];
140
+ });
141
+ });
142
+ };
143
+ AptosCoinTokenProtocolImpl.prototype.getMetadata = function () {
144
+ return __awaiter(this, void 0, void 0, function () {
145
+ return __generator(this, function (_a) {
146
+ return [2 /*return*/, {
147
+ identifier: this.options.identifier,
148
+ name: this.options.name,
149
+ units: this.units,
150
+ mainUnit: this.mainUnit,
151
+ fee: {
152
+ defaults: {
153
+ low: (0, module_kit_1.newAmount)(0.0002, 'APT'),
154
+ medium: (0, module_kit_1.newAmount)(0.0002, 'APT'),
155
+ high: (0, module_kit_1.newAmount)(0.0004, 'APT')
156
+ },
157
+ units: AptosProtocol_1.APTOS_UNITS_METADATA,
158
+ mainUnit: 'APT'
159
+ },
160
+ account: {
161
+ standardDerivationPath: "m/44'/637'/0'/0'/0'",
162
+ address: {
163
+ isCaseSensitive: false,
164
+ placeholder: '0x...',
165
+ regex: '^0x[a-fA-F0-9]{64}$'
166
+ }
167
+ }
168
+ }];
169
+ });
170
+ });
171
+ };
172
+ AptosCoinTokenProtocolImpl.prototype.getPublicKeyBuffer = function (publicKey) {
173
+ if (publicKey.format === 'hex') {
174
+ return Buffer.from(publicKey.value, 'hex');
175
+ }
176
+ else if (publicKey.format === 'encoded') {
177
+ return Buffer.from(publicKey.value, 'hex');
178
+ }
179
+ return Buffer.from(publicKey.value, 'hex');
180
+ };
181
+ AptosCoinTokenProtocolImpl.prototype.getAddressFromPublicKey = function (publicKey) {
182
+ return __awaiter(this, void 0, void 0, function () {
183
+ var pubKeyBytes, dataToHash, hash;
184
+ return __generator(this, function (_a) {
185
+ pubKeyBytes = this.getPublicKeyBuffer(publicKey);
186
+ dataToHash = Buffer.concat([pubKeyBytes, Buffer.from([0x00])]);
187
+ hash = (0, js_sha3_1.sha3_256)(dataToHash);
188
+ return [2 /*return*/, '0x' + hash];
189
+ });
190
+ });
191
+ };
192
+ AptosCoinTokenProtocolImpl.prototype.getAddressesFromPublicKey = function (publicKey) {
193
+ return __awaiter(this, void 0, void 0, function () {
194
+ var address;
195
+ return __generator(this, function (_a) {
196
+ switch (_a.label) {
197
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
198
+ case 1:
199
+ address = _a.sent();
200
+ return [2 /*return*/, [{
201
+ address: address,
202
+ cursor: { hasNext: false }
203
+ }]];
204
+ }
205
+ });
206
+ });
207
+ };
208
+ AptosCoinTokenProtocolImpl.prototype.validateAddress = function (address) {
209
+ return __awaiter(this, void 0, void 0, function () {
210
+ return __generator(this, function (_a) {
211
+ try {
212
+ return [2 /*return*/, /^0x[a-fA-F0-9]{1,64}$/.test(address)];
213
+ }
214
+ catch (_b) {
215
+ return [2 /*return*/, false];
216
+ }
217
+ return [2 /*return*/];
218
+ });
219
+ });
220
+ };
221
+ AptosCoinTokenProtocolImpl.prototype.getBalanceOfAddress = function (address) {
222
+ var _a, _b, _c, _d, _e, _f, _g;
223
+ return __awaiter(this, void 0, void 0, function () {
224
+ var contractAddress, resource, balance_1, e_1, indexerUrl, graphqlQuery, response, _h, _j, _k, result, faBalances, balance;
225
+ return __generator(this, function (_l) {
226
+ switch (_l.label) {
227
+ case 0:
228
+ contractAddress = this.contractAddress;
229
+ if (!this.isCoinType) return [3 /*break*/, 4];
230
+ _l.label = 1;
231
+ case 1:
232
+ _l.trys.push([1, 3, , 4]);
233
+ return [4 /*yield*/, this.fetchJson("/accounts/".concat(address, "/resource/0x1::coin::CoinStore<").concat(contractAddress, ">"))];
234
+ case 2:
235
+ resource = _l.sent();
236
+ balance_1 = ((_b = (_a = resource === null || resource === void 0 ? void 0 : resource.data) === null || _a === void 0 ? void 0 : _a.coin) === null || _b === void 0 ? void 0 : _b.value) || '0';
237
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(balance_1, 'blockchain') }];
238
+ case 3:
239
+ e_1 = _l.sent();
240
+ if (((_c = e_1 === null || e_1 === void 0 ? void 0 : e_1.message) === null || _c === void 0 ? void 0 : _c.includes('404')) || ((_d = e_1 === null || e_1 === void 0 ? void 0 : e_1.message) === null || _d === void 0 ? void 0 : _d.includes('not found'))) {
241
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(0, 'blockchain') }];
242
+ }
243
+ throw e_1;
244
+ case 4:
245
+ indexerUrl = 'https://indexer.mainnet.aptoslabs.com/v1/graphql';
246
+ graphqlQuery = "{ current_fungible_asset_balances(where: {owner_address: {_eq: \"".concat(address, "\"}, asset_type: {_eq: \"").concat(contractAddress, "\"}}) { amount } }");
247
+ return [4 /*yield*/, fetch(indexerUrl, {
248
+ method: 'POST',
249
+ headers: { 'Content-Type': 'application/json' },
250
+ body: JSON.stringify({ query: graphqlQuery })
251
+ })];
252
+ case 5:
253
+ response = _l.sent();
254
+ if (!!response.ok) return [3 /*break*/, 7];
255
+ _h = Error.bind;
256
+ _k = (_j = "Indexer API failed: ".concat(response.status, ": ")).concat;
257
+ return [4 /*yield*/, response.text()];
258
+ case 6: throw new (_h.apply(Error, [void 0, _k.apply(_j, [_l.sent()])]))();
259
+ case 7: return [4 /*yield*/, response.json()];
260
+ case 8:
261
+ result = _l.sent();
262
+ faBalances = (_e = result === null || result === void 0 ? void 0 : result.data) === null || _e === void 0 ? void 0 : _e.current_fungible_asset_balances;
263
+ balance = String((_g = (_f = faBalances === null || faBalances === void 0 ? void 0 : faBalances[0]) === null || _f === void 0 ? void 0 : _f.amount) !== null && _g !== void 0 ? _g : '0');
264
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(balance, 'blockchain') }];
265
+ }
266
+ });
267
+ });
268
+ };
269
+ AptosCoinTokenProtocolImpl.prototype.getBalanceOfPublicKey = function (publicKey) {
270
+ return __awaiter(this, void 0, void 0, function () {
271
+ var address;
272
+ return __generator(this, function (_a) {
273
+ switch (_a.label) {
274
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
275
+ case 1:
276
+ address = _a.sent();
277
+ return [2 /*return*/, this.getBalanceOfAddress(address)];
278
+ }
279
+ });
280
+ });
281
+ };
282
+ AptosCoinTokenProtocolImpl.prototype.getDetailsFromTransaction = function (transaction, publicKey) {
283
+ return __awaiter(this, void 0, void 0, function () {
284
+ var txData, fromAddress, fee, toAddress, amount, functionName, args;
285
+ return __generator(this, function (_a) {
286
+ try {
287
+ txData = JSON.parse(transaction.serialized);
288
+ fromAddress = txData.sender || '';
289
+ fee = (0, module_kit_1.newAmount)((BigInt(txData.max_gas_amount || 0) * BigInt(txData.gas_unit_price || 0)).toString(), 'Octas');
290
+ toAddress = '';
291
+ amount = (0, module_kit_1.newAmount)(0, 'blockchain');
292
+ if (txData.payload) {
293
+ functionName = txData.payload.function || '';
294
+ args = txData.payload.arguments || [];
295
+ if (functionName.includes('coin::transfer') && args.length >= 2) {
296
+ toAddress = args[0];
297
+ amount = (0, module_kit_1.newAmount)(args[1], 'blockchain');
298
+ }
299
+ else if (functionName.includes('primary_fungible_store::transfer') && args.length >= 3) {
300
+ toAddress = args[1];
301
+ amount = (0, module_kit_1.newAmount)(args[2], 'blockchain');
302
+ }
303
+ }
304
+ return [2 /*return*/, [
305
+ {
306
+ from: [fromAddress],
307
+ to: toAddress ? [toAddress] : [],
308
+ amount: amount,
309
+ fee: fee,
310
+ isInbound: false,
311
+ network: this.options.network
312
+ }
313
+ ]];
314
+ }
315
+ catch (e) {
316
+ console.error('[aptos-coin][getDetailsFromTransaction] Failed:', e);
317
+ return [2 /*return*/, [{
318
+ from: [],
319
+ to: [],
320
+ amount: (0, module_kit_1.newAmount)(0, 'blockchain'),
321
+ fee: (0, module_kit_1.newAmount)(0, 'Octas'),
322
+ isInbound: false,
323
+ network: this.options.network
324
+ }]];
325
+ }
326
+ return [2 /*return*/];
327
+ });
328
+ });
329
+ };
330
+ AptosCoinTokenProtocolImpl.prototype.getTransactionDetailsFromSigned = function (signedTx) {
331
+ return __awaiter(this, void 0, void 0, function () {
332
+ return __generator(this, function (_a) {
333
+ return [2 /*return*/, this.getDetailsFromTransaction(signedTx.transaction, null)];
334
+ });
335
+ });
336
+ };
337
+ AptosCoinTokenProtocolImpl.prototype.verifyMessageWithPublicKey = function (message, signature, publicKey) {
338
+ return __awaiter(this, void 0, void 0, function () {
339
+ var messageBytes, signatureBytes, pubKeyBytes;
340
+ return __generator(this, function (_a) {
341
+ try {
342
+ messageBytes = Buffer.from(message);
343
+ signatureBytes = Buffer.from(signature.value, signature.format === 'hex' ? 'hex' : undefined);
344
+ pubKeyBytes = this.getPublicKeyBuffer(publicKey);
345
+ return [2 /*return*/, nacl.sign.detached.verify(messageBytes, signatureBytes, pubKeyBytes)];
346
+ }
347
+ catch (e) {
348
+ return [2 /*return*/, false];
349
+ }
350
+ return [2 /*return*/];
351
+ });
352
+ });
353
+ };
354
+ AptosCoinTokenProtocolImpl.prototype.encryptAsymmetricWithPublicKey = function (payload, publicKey) {
355
+ return __awaiter(this, void 0, void 0, function () {
356
+ return __generator(this, function (_a) {
357
+ throw new Error('Not implemented');
358
+ });
359
+ });
360
+ };
361
+ AptosCoinTokenProtocolImpl.prototype.getCryptoConfiguration = function () {
362
+ return __awaiter(this, void 0, void 0, function () {
363
+ return __generator(this, function (_a) {
364
+ return [2 /*return*/, { algorithm: 'ed25519' }];
365
+ });
366
+ });
367
+ };
368
+ AptosCoinTokenProtocolImpl.prototype.getKeyPairFromDerivative = function (derivative) {
369
+ return __awaiter(this, void 0, void 0, function () {
370
+ var secretKeyBuffer, publicKeyBuffer;
371
+ return __generator(this, function (_a) {
372
+ secretKeyBuffer = Buffer.from(derivative.secretKey, 'hex');
373
+ publicKeyBuffer = Buffer.from(derivative.publicKey, 'hex');
374
+ return [2 /*return*/, {
375
+ publicKey: {
376
+ value: publicKeyBuffer.toString('hex'),
377
+ format: 'hex',
378
+ type: 'pub'
379
+ },
380
+ secretKey: {
381
+ value: secretKeyBuffer.toString('hex'),
382
+ format: 'hex',
383
+ type: 'priv'
384
+ }
385
+ }];
386
+ });
387
+ });
388
+ };
389
+ AptosCoinTokenProtocolImpl.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
390
+ return __awaiter(this, void 0, void 0, function () {
391
+ var txData, keyHex, secretKeyBytes, signingKey, publicKeyBytes, keyPair, signatureBytes, _signingMessage, unsignedTxData, signedTxData;
392
+ return __generator(this, function (_a) {
393
+ txData = JSON.parse(transaction.serialized);
394
+ keyHex = secretKey.value;
395
+ secretKeyBytes = Buffer.from(keyHex, secretKey.format === 'hex' ? 'hex' : undefined);
396
+ if (secretKeyBytes.length === 64) {
397
+ signingKey = secretKeyBytes;
398
+ publicKeyBytes = secretKeyBytes.slice(32);
399
+ }
400
+ else if (secretKeyBytes.length === 32) {
401
+ keyPair = nacl.sign.keyPair.fromSeed(secretKeyBytes);
402
+ signingKey = keyPair.secretKey;
403
+ publicKeyBytes = keyPair.publicKey;
404
+ }
405
+ else {
406
+ throw new Error('Invalid secret key length');
407
+ }
408
+ signatureBytes = nacl.sign.detached(Buffer.from(txData.signing_message, 'hex'), signingKey);
409
+ _signingMessage = txData.signing_message, unsignedTxData = __rest(txData, ["signing_message"]);
410
+ signedTxData = __assign(__assign({}, unsignedTxData), { signature: {
411
+ type: 'ed25519_signature',
412
+ public_key: '0x' + Buffer.from(publicKeyBytes).toString('hex'),
413
+ signature: '0x' + Buffer.from(signatureBytes).toString('hex')
414
+ } });
415
+ return [2 /*return*/, {
416
+ serialized: JSON.stringify(signedTxData),
417
+ type: 'signed'
418
+ }];
419
+ });
420
+ });
421
+ };
422
+ AptosCoinTokenProtocolImpl.prototype.signMessageWithKeyPair = function (message, keyPair) {
423
+ return __awaiter(this, void 0, void 0, function () {
424
+ var messageBytes, secretKeyBytes, signingKey, signature;
425
+ return __generator(this, function (_a) {
426
+ messageBytes = Buffer.from(message);
427
+ secretKeyBytes = Buffer.from(keyPair.secretKey.value, keyPair.secretKey.format === 'hex' ? 'hex' : undefined);
428
+ if (secretKeyBytes.length === 64) {
429
+ signingKey = secretKeyBytes;
430
+ }
431
+ else if (secretKeyBytes.length === 32) {
432
+ signingKey = nacl.sign.keyPair.fromSeed(secretKeyBytes).secretKey;
433
+ }
434
+ else {
435
+ throw new Error('Invalid secret key length');
436
+ }
437
+ signature = nacl.sign.detached(messageBytes, signingKey);
438
+ return [2 /*return*/, (0, module_kit_1.newSignature)(Buffer.from(signature).toString('hex'), 'hex')];
439
+ });
440
+ });
441
+ };
442
+ AptosCoinTokenProtocolImpl.prototype.decryptAsymmetricWithKeyPair = function (payload, keyPair) {
443
+ return __awaiter(this, void 0, void 0, function () {
444
+ return __generator(this, function (_a) {
445
+ throw new Error('Not implemented');
446
+ });
447
+ });
448
+ };
449
+ AptosCoinTokenProtocolImpl.prototype.encryptAESWithSecretKey = function (payload, secretKey) {
450
+ return __awaiter(this, void 0, void 0, function () {
451
+ return __generator(this, function (_a) {
452
+ throw new Error('Not implemented');
453
+ });
454
+ });
455
+ };
456
+ AptosCoinTokenProtocolImpl.prototype.decryptAESWithSecretKey = function (payload, secretKey) {
457
+ return __awaiter(this, void 0, void 0, function () {
458
+ return __generator(this, function (_a) {
459
+ throw new Error('Not implemented');
460
+ });
461
+ });
462
+ };
463
+ AptosCoinTokenProtocolImpl.prototype.getNetwork = function () {
464
+ return __awaiter(this, void 0, void 0, function () {
465
+ return __generator(this, function (_a) {
466
+ return [2 /*return*/, this.options.network];
467
+ });
468
+ });
469
+ };
470
+ AptosCoinTokenProtocolImpl.prototype.getTransactionsForAddress = function (address, limit, cursor) {
471
+ var _a, _b;
472
+ return __awaiter(this, void 0, void 0, function () {
473
+ var effectiveLimit, offset, indexerUrl, versionsQuery, versionsResponse, versionsResult, versionActivities, versions, graphqlQuery, response, result, activities, txMap, _i, activities_1, activity, version, txs_1, hasNext, newCursor, e_2;
474
+ var _this = this;
475
+ return __generator(this, function (_c) {
476
+ switch (_c.label) {
477
+ case 0:
478
+ _c.trys.push([0, 5, , 6]);
479
+ effectiveLimit = limit || AptosCoinTokenProtocolImpl.DEFAULT_TX_LIMIT;
480
+ offset = (cursor === null || cursor === void 0 ? void 0 : cursor.offset) || 0;
481
+ indexerUrl = 'https://indexer.mainnet.aptoslabs.com/v1/graphql';
482
+ versionsQuery = "{\n fungible_asset_activities(\n where: {\n owner_address: { _eq: \"".concat(address, "\" },\n asset_type: { _eq: \"").concat(this.contractAddress, "\" }\n },\n order_by: { transaction_version: desc },\n limit: ").concat(effectiveLimit, ",\n offset: ").concat(offset, "\n ) {\n transaction_version\n }\n }");
483
+ return [4 /*yield*/, fetch(indexerUrl, {
484
+ method: 'POST',
485
+ headers: { 'Content-Type': 'application/json' },
486
+ body: JSON.stringify({ query: versionsQuery })
487
+ })];
488
+ case 1:
489
+ versionsResponse = _c.sent();
490
+ if (!versionsResponse.ok) {
491
+ throw new Error("Indexer API failed: ".concat(versionsResponse.status));
492
+ }
493
+ return [4 /*yield*/, versionsResponse.json()];
494
+ case 2:
495
+ versionsResult = _c.sent();
496
+ versionActivities = ((_a = versionsResult === null || versionsResult === void 0 ? void 0 : versionsResult.data) === null || _a === void 0 ? void 0 : _a.fungible_asset_activities) || [];
497
+ versions = Array.from(new Set(versionActivities.map(function (a) { return a.transaction_version; })));
498
+ if (versions.length === 0) {
499
+ return [2 /*return*/, { transactions: [], cursor: { hasNext: false } }];
500
+ }
501
+ graphqlQuery = "{\n fungible_asset_activities(\n where: {\n transaction_version: { _in: [".concat(versions.join(','), "] },\n asset_type: { _eq: \"").concat(this.contractAddress, "\" }\n },\n order_by: { transaction_version: desc }\n ) {\n transaction_version\n type\n amount\n owner_address\n transaction_timestamp\n is_transaction_success\n }\n }");
502
+ return [4 /*yield*/, fetch(indexerUrl, {
503
+ method: 'POST',
504
+ headers: { 'Content-Type': 'application/json' },
505
+ body: JSON.stringify({ query: graphqlQuery })
506
+ })];
507
+ case 3:
508
+ response = _c.sent();
509
+ if (!response.ok) {
510
+ throw new Error("Indexer API failed: ".concat(response.status));
511
+ }
512
+ return [4 /*yield*/, response.json()];
513
+ case 4:
514
+ result = _c.sent();
515
+ activities = ((_b = result === null || result === void 0 ? void 0 : result.data) === null || _b === void 0 ? void 0 : _b.fungible_asset_activities) || [];
516
+ txMap = new Map();
517
+ for (_i = 0, activities_1 = activities; _i < activities_1.length; _i++) {
518
+ activity = activities_1[_i];
519
+ version = activity.transaction_version.toString();
520
+ if (!txMap.has(version)) {
521
+ txMap.set(version, {
522
+ version: version,
523
+ timestamp: activity.transaction_timestamp,
524
+ success: activity.is_transaction_success,
525
+ activities: []
526
+ });
527
+ }
528
+ txMap.get(version).activities.push(activity);
529
+ }
530
+ txs_1 = [];
531
+ txMap.forEach(function (txData, version) {
532
+ try {
533
+ var acts = txData.activities;
534
+ var amount = (0, module_kit_1.newAmount)(0, 'blockchain');
535
+ var isInbound = false;
536
+ var fromAddress = '';
537
+ var toAddress = '';
538
+ for (var _i = 0, acts_1 = acts; _i < acts_1.length; _i++) {
539
+ var act = acts_1[_i];
540
+ var actType = (act.type || '').toLowerCase();
541
+ var ownerAddr = act.owner_address || '';
542
+ // Handle various FA activity type formats
543
+ if (actType.includes('deposit') || actType.includes('creditstore')) {
544
+ // Deposit recipient
545
+ toAddress = ownerAddr;
546
+ if (ownerAddr.toLowerCase() === address.toLowerCase()) {
547
+ amount = (0, module_kit_1.newAmount)(act.amount || '0', 'blockchain');
548
+ isInbound = true;
549
+ }
550
+ }
551
+ else if (actType.includes('withdraw') || actType.includes('debitstore')) {
552
+ // Withdraw sender
553
+ fromAddress = ownerAddr;
554
+ if (ownerAddr.toLowerCase() === address.toLowerCase()) {
555
+ amount = (0, module_kit_1.newAmount)(act.amount || '0', 'blockchain');
556
+ isInbound = false;
557
+ }
558
+ }
559
+ }
560
+ // If we couldn't determine amount from our address activities, use any available amount
561
+ if (amount.value === '0') {
562
+ for (var _a = 0, acts_2 = acts; _a < acts_2.length; _a++) {
563
+ var act = acts_2[_a];
564
+ if (act.amount) {
565
+ amount = (0, module_kit_1.newAmount)(act.amount, 'blockchain');
566
+ break;
567
+ }
568
+ }
569
+ }
570
+ var timestamp = txData.timestamp
571
+ ? Math.floor(new Date(txData.timestamp).getTime() / 1000)
572
+ : Math.floor(Date.now() / 1000);
573
+ txs_1.push({
574
+ hash: version,
575
+ timestamp: timestamp,
576
+ status: txData.success ? 'applied' : 'failed',
577
+ amount: amount,
578
+ fee: (0, module_kit_1.newAmount)(0, 'Octas'),
579
+ from: fromAddress ? [fromAddress] : [],
580
+ to: toAddress ? [toAddress] : [],
581
+ isInbound: isInbound,
582
+ network: _this.options.network
583
+ });
584
+ }
585
+ catch (e) {
586
+ console.warn('[aptos-token][getTransactionsForAddress] Failed to parse activity');
587
+ }
588
+ });
589
+ hasNext = versionActivities.length === effectiveLimit;
590
+ newCursor = {
591
+ hasNext: hasNext,
592
+ offset: offset + versionActivities.length
593
+ };
594
+ return [2 /*return*/, {
595
+ transactions: txs_1,
596
+ cursor: newCursor
597
+ }];
598
+ case 5:
599
+ e_2 = _c.sent();
600
+ console.error('[aptos-token][getTransactionsForAddress] Failed:', e_2);
601
+ return [2 /*return*/, {
602
+ transactions: [],
603
+ cursor: { hasNext: false }
604
+ }];
605
+ case 6: return [2 /*return*/];
606
+ }
607
+ });
608
+ });
609
+ };
610
+ AptosCoinTokenProtocolImpl.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
611
+ return __awaiter(this, void 0, void 0, function () {
612
+ var address;
613
+ return __generator(this, function (_a) {
614
+ switch (_a.label) {
615
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
616
+ case 1:
617
+ address = _a.sent();
618
+ return [2 /*return*/, this.getTransactionsForAddress(address, limit, cursor)];
619
+ }
620
+ });
621
+ });
622
+ };
623
+ AptosCoinTokenProtocolImpl.prototype.getTransactionStatus = function (transactionIds) {
624
+ return __awaiter(this, void 0, void 0, function () {
625
+ var result, _i, transactionIds_1, txHash, tx, _a;
626
+ return __generator(this, function (_b) {
627
+ switch (_b.label) {
628
+ case 0:
629
+ result = {};
630
+ _i = 0, transactionIds_1 = transactionIds;
631
+ _b.label = 1;
632
+ case 1:
633
+ if (!(_i < transactionIds_1.length)) return [3 /*break*/, 6];
634
+ txHash = transactionIds_1[_i];
635
+ _b.label = 2;
636
+ case 2:
637
+ _b.trys.push([2, 4, , 5]);
638
+ return [4 /*yield*/, this.fetchJson("/transactions/by_hash/".concat(txHash))];
639
+ case 3:
640
+ tx = _b.sent();
641
+ result[txHash] = { status: tx.success ? 'applied' : 'failed' };
642
+ return [3 /*break*/, 5];
643
+ case 4:
644
+ _a = _b.sent();
645
+ result[txHash] = { status: 'unknown' };
646
+ return [3 /*break*/, 5];
647
+ case 5:
648
+ _i++;
649
+ return [3 /*break*/, 1];
650
+ case 6: return [2 /*return*/, result];
651
+ }
652
+ });
653
+ });
654
+ };
655
+ AptosCoinTokenProtocolImpl.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
656
+ return __awaiter(this, void 0, void 0, function () {
657
+ var balance;
658
+ return __generator(this, function (_a) {
659
+ switch (_a.label) {
660
+ case 0: return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
661
+ case 1:
662
+ balance = _a.sent();
663
+ return [2 /*return*/, balance.total];
664
+ }
665
+ });
666
+ });
667
+ };
668
+ AptosCoinTokenProtocolImpl.prototype.getTransactionFeeWithPublicKey = function (publicKey, details, configuration) {
669
+ return __awaiter(this, void 0, void 0, function () {
670
+ var gasEstimate, gasPrice, estimatedGas, fee, _a, defaultFee;
671
+ return __generator(this, function (_b) {
672
+ switch (_b.label) {
673
+ case 0:
674
+ _b.trys.push([0, 2, , 3]);
675
+ return [4 /*yield*/, this.fetchJson('/estimate_gas_price')];
676
+ case 1:
677
+ gasEstimate = _b.sent();
678
+ gasPrice = parseInt(gasEstimate.gas_estimate || '100');
679
+ estimatedGas = DEFAULT_MAX_GAS_AMOUNT;
680
+ fee = (estimatedGas * gasPrice).toString();
681
+ return [2 /*return*/, {
682
+ low: (0, module_kit_1.newAmount)(fee, 'Octas'),
683
+ medium: (0, module_kit_1.newAmount)(fee, 'Octas'),
684
+ high: (0, module_kit_1.newAmount)((estimatedGas * gasPrice * 2).toString(), 'Octas')
685
+ }];
686
+ case 2:
687
+ _a = _b.sent();
688
+ defaultFee = (DEFAULT_MAX_GAS_AMOUNT * DEFAULT_GAS_UNIT_PRICE).toString();
689
+ return [2 /*return*/, {
690
+ low: (0, module_kit_1.newAmount)(defaultFee, 'Octas'),
691
+ medium: (0, module_kit_1.newAmount)(defaultFee, 'Octas'),
692
+ high: (0, module_kit_1.newAmount)((DEFAULT_MAX_GAS_AMOUNT * DEFAULT_GAS_UNIT_PRICE * 2).toString(), 'Octas')
693
+ }];
694
+ case 3: return [2 /*return*/];
695
+ }
696
+ });
697
+ });
698
+ };
699
+ AptosCoinTokenProtocolImpl.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
700
+ var _a, _b;
701
+ return __awaiter(this, void 0, void 0, function () {
702
+ var fromAddress, sequenceNumber, accountInfo, e_3, gasUnitPrice, gasEstimate, _c, ledgerInfo, currentTimestamp, expirationTimestamp, detail, amountValue, payload, txPayload, encodingRequest, encodingText, signingMessage;
703
+ return __generator(this, function (_d) {
704
+ switch (_d.label) {
705
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)
706
+ // Get account info for sequence number
707
+ ];
708
+ case 1:
709
+ fromAddress = _d.sent();
710
+ sequenceNumber = '0';
711
+ _d.label = 2;
712
+ case 2:
713
+ _d.trys.push([2, 4, , 5]);
714
+ return [4 /*yield*/, this.fetchJson("/accounts/".concat(fromAddress))];
715
+ case 3:
716
+ accountInfo = _d.sent();
717
+ sequenceNumber = accountInfo.sequence_number || '0';
718
+ return [3 /*break*/, 5];
719
+ case 4:
720
+ e_3 = _d.sent();
721
+ if (!((_a = e_3 === null || e_3 === void 0 ? void 0 : e_3.message) === null || _a === void 0 ? void 0 : _a.includes('404')) && !((_b = e_3 === null || e_3 === void 0 ? void 0 : e_3.message) === null || _b === void 0 ? void 0 : _b.includes('not found'))) {
722
+ throw e_3;
723
+ }
724
+ return [3 /*break*/, 5];
725
+ case 5:
726
+ gasUnitPrice = DEFAULT_GAS_UNIT_PRICE;
727
+ _d.label = 6;
728
+ case 6:
729
+ _d.trys.push([6, 8, , 9]);
730
+ return [4 /*yield*/, this.fetchJson('/estimate_gas_price')];
731
+ case 7:
732
+ gasEstimate = _d.sent();
733
+ gasUnitPrice = parseInt(gasEstimate.gas_estimate || '100');
734
+ return [3 /*break*/, 9];
735
+ case 8:
736
+ _c = _d.sent();
737
+ return [3 /*break*/, 9];
738
+ case 9: return [4 /*yield*/, this.fetchJson('/')];
739
+ case 10:
740
+ ledgerInfo = _d.sent();
741
+ currentTimestamp = parseInt(ledgerInfo.ledger_timestamp || '0') / 1000000;
742
+ expirationTimestamp = Math.floor(currentTimestamp) + 600;
743
+ detail = details[0];
744
+ amountValue = (0, module_kit_1.newAmount)(detail.amount).blockchain(this.units).value;
745
+ payload = this.isCoinType
746
+ ? {
747
+ type: 'entry_function_payload',
748
+ function: '0x1::coin::transfer',
749
+ type_arguments: [this.contractAddress],
750
+ arguments: [detail.to, amountValue]
751
+ }
752
+ : {
753
+ type: 'entry_function_payload',
754
+ function: '0x1::primary_fungible_store::transfer',
755
+ type_arguments: ['0x1::fungible_asset::Metadata'],
756
+ arguments: [this.contractAddress, detail.to, amountValue]
757
+ };
758
+ txPayload = {
759
+ sender: fromAddress,
760
+ sequence_number: sequenceNumber,
761
+ max_gas_amount: DEFAULT_MAX_GAS_AMOUNT.toString(),
762
+ gas_unit_price: gasUnitPrice.toString(),
763
+ expiration_timestamp_secs: expirationTimestamp.toString(),
764
+ payload: payload
765
+ };
766
+ return [4 /*yield*/, fetch("".concat(this.options.network.rpcUrl, "/transactions/encode_submission"), {
767
+ method: 'POST',
768
+ headers: { 'Content-Type': 'application/json' },
769
+ body: JSON.stringify(txPayload)
770
+ })];
771
+ case 11:
772
+ encodingRequest = _d.sent();
773
+ return [4 /*yield*/, encodingRequest.text()];
774
+ case 12:
775
+ encodingText = _d.sent();
776
+ if (!encodingRequest.ok) {
777
+ throw new Error("Encode submission failed: ".concat(encodingRequest.status, ": ").concat(encodingText));
778
+ }
779
+ signingMessage = encodingText;
780
+ try {
781
+ signingMessage = JSON.parse(encodingText);
782
+ }
783
+ catch (_e) {
784
+ // ignore
785
+ }
786
+ if (typeof signingMessage !== 'string') {
787
+ throw new Error("Encode submission failed: unexpected response: ".concat(encodingText));
788
+ }
789
+ return [2 /*return*/, {
790
+ serialized: JSON.stringify(__assign(__assign({}, txPayload), { signing_message: signingMessage.replace(/^0x/, '') })),
791
+ type: 'unsigned'
792
+ }];
793
+ }
794
+ });
795
+ });
796
+ };
797
+ AptosCoinTokenProtocolImpl.prototype.broadcastTransaction = function (transaction) {
798
+ return __awaiter(this, void 0, void 0, function () {
799
+ var signedTxData, _signingMessage, txToSubmit, response, _a, _b, result, i, txStatus, _c;
800
+ return __generator(this, function (_d) {
801
+ switch (_d.label) {
802
+ case 0:
803
+ signedTxData = JSON.parse(transaction.serialized);
804
+ _signingMessage = signedTxData.signing_message, txToSubmit = __rest(signedTxData, ["signing_message"]);
805
+ return [4 /*yield*/, fetch("".concat(this.options.network.rpcUrl, "/transactions"), {
806
+ method: 'POST',
807
+ headers: { 'Content-Type': 'application/json' },
808
+ body: JSON.stringify(txToSubmit)
809
+ })];
810
+ case 1:
811
+ response = _d.sent();
812
+ if (!!response.ok) return [3 /*break*/, 3];
813
+ _a = Error.bind;
814
+ _b = "Broadcast failed: ".concat;
815
+ return [4 /*yield*/, response.text()];
816
+ case 2: throw new (_a.apply(Error, [void 0, _b.apply("Broadcast failed: ", [_d.sent()])]))();
817
+ case 3: return [4 /*yield*/, response.json()
818
+ // Wait for confirmation
819
+ ];
820
+ case 4:
821
+ result = _d.sent();
822
+ i = 0;
823
+ _d.label = 5;
824
+ case 5:
825
+ if (!(i < 30)) return [3 /*break*/, 12];
826
+ _d.label = 6;
827
+ case 6:
828
+ _d.trys.push([6, 8, , 9]);
829
+ return [4 /*yield*/, this.fetchJson("/transactions/by_hash/".concat(result.hash))];
830
+ case 7:
831
+ txStatus = _d.sent();
832
+ if (txStatus.type === 'user_transaction') {
833
+ return [3 /*break*/, 12];
834
+ }
835
+ return [3 /*break*/, 9];
836
+ case 8:
837
+ _c = _d.sent();
838
+ return [3 /*break*/, 9];
839
+ case 9: return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 1000); })];
840
+ case 10:
841
+ _d.sent();
842
+ _d.label = 11;
843
+ case 11:
844
+ i++;
845
+ return [3 /*break*/, 5];
846
+ case 12: return [2 /*return*/, result.hash];
847
+ }
848
+ });
849
+ });
850
+ };
851
+ AptosCoinTokenProtocolImpl.DEFAULT_TX_LIMIT = 10;
852
+ return AptosCoinTokenProtocolImpl;
853
+ }());
854
+ exports.AptosCoinTokenProtocolImpl = AptosCoinTokenProtocolImpl;
855
+ // Factory function
856
+ function createAptosCoinTokenProtocol(options) {
857
+ return new AptosCoinTokenProtocolImpl(options);
858
+ }
859
+ exports.createAptosCoinTokenProtocol = createAptosCoinTokenProtocol;
860
+ //# sourceMappingURL=AptosCoinTokenProtocol.js.map