@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,912 @@
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.createAptosProtocol = exports.AptosProtocol = exports.APTOS_UNITS_METADATA = void 0;
85
+ var module_kit_1 = require("@wallfree-dev/module-kit");
86
+ var nacl = __importStar(require("tweetnacl"));
87
+ var bignumber_1 = require("@wallfree-dev/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber");
88
+ var js_sha3_1 = require("js-sha3");
89
+ exports.APTOS_UNITS_METADATA = {
90
+ APT: {
91
+ symbol: { value: 'APT', market: 'apt' },
92
+ decimals: 8
93
+ },
94
+ Octas: {
95
+ symbol: { value: 'Octas' },
96
+ decimals: 0
97
+ }
98
+ };
99
+ // Default gas settings for Aptos
100
+ var DEFAULT_MAX_GAS_AMOUNT = 2000;
101
+ var DEFAULT_GAS_UNIT_PRICE = 100;
102
+ var AptosProtocol = /** @class */ (function () {
103
+ function AptosProtocol(options) {
104
+ this.options = options;
105
+ }
106
+ AptosProtocol.prototype.fetchJson = function (endpoint, options) {
107
+ return __awaiter(this, void 0, void 0, function () {
108
+ var url, response, _a, _b, _c;
109
+ return __generator(this, function (_d) {
110
+ switch (_d.label) {
111
+ case 0:
112
+ url = "".concat(this.options.network.rpcUrl).concat(endpoint);
113
+ return [4 /*yield*/, fetch(url, __assign(__assign({}, options), { headers: __assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }))];
114
+ case 1:
115
+ response = _d.sent();
116
+ if (!!response.ok) return [3 /*break*/, 3];
117
+ _a = Error.bind;
118
+ _c = (_b = "HTTP ".concat(response.status, ": ")).concat;
119
+ return [4 /*yield*/, response.text()];
120
+ case 2: throw new (_a.apply(Error, [void 0, _c.apply(_b, [_d.sent()])]))();
121
+ case 3: return [2 /*return*/, response.json()];
122
+ }
123
+ });
124
+ });
125
+ };
126
+ AptosProtocol.prototype.getMetadata = function () {
127
+ return __awaiter(this, void 0, void 0, function () {
128
+ return __generator(this, function (_a) {
129
+ return [2 /*return*/, {
130
+ identifier: 'aptos',
131
+ name: 'Aptos',
132
+ units: exports.APTOS_UNITS_METADATA,
133
+ mainUnit: 'APT',
134
+ fee: {
135
+ defaults: {
136
+ low: (0, module_kit_1.newAmount)(0.0002, 'APT'),
137
+ medium: (0, module_kit_1.newAmount)(0.0002, 'APT'),
138
+ high: (0, module_kit_1.newAmount)(0.0004, 'APT')
139
+ },
140
+ units: exports.APTOS_UNITS_METADATA,
141
+ mainUnit: 'APT'
142
+ },
143
+ account: {
144
+ standardDerivationPath: "m/44'/637'/0'/0'/0'",
145
+ address: {
146
+ isCaseSensitive: false,
147
+ placeholder: '0x...',
148
+ regex: '^0x[a-fA-F0-9]{64}$'
149
+ }
150
+ },
151
+ transaction: {
152
+ arbitraryData: {
153
+ inner: { name: 'data' }
154
+ }
155
+ }
156
+ }];
157
+ });
158
+ });
159
+ };
160
+ AptosProtocol.prototype.getPublicKeyBuffer = function (publicKey) {
161
+ if (publicKey.format === 'hex') {
162
+ return Buffer.from(publicKey.value, 'hex');
163
+ }
164
+ else if (publicKey.format === 'encoded') {
165
+ return Buffer.from(publicKey.value, 'hex');
166
+ }
167
+ return Buffer.from(publicKey.value, 'hex');
168
+ };
169
+ AptosProtocol.prototype.getAddressFromPublicKey = function (publicKey) {
170
+ return __awaiter(this, void 0, void 0, function () {
171
+ var pubKeyBytes, dataToHash, hash;
172
+ return __generator(this, function (_a) {
173
+ pubKeyBytes = this.getPublicKeyBuffer(publicKey);
174
+ dataToHash = Buffer.concat([pubKeyBytes, Buffer.from([0x00])]);
175
+ hash = (0, js_sha3_1.sha3_256)(dataToHash);
176
+ return [2 /*return*/, '0x' + hash];
177
+ });
178
+ });
179
+ };
180
+ AptosProtocol.prototype.getAddressesFromPublicKey = function (publicKey) {
181
+ return __awaiter(this, void 0, void 0, function () {
182
+ var address;
183
+ return __generator(this, function (_a) {
184
+ switch (_a.label) {
185
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
186
+ case 1:
187
+ address = _a.sent();
188
+ return [2 /*return*/, [{
189
+ address: address,
190
+ cursor: { hasNext: false }
191
+ }]];
192
+ }
193
+ });
194
+ });
195
+ };
196
+ AptosProtocol.prototype.validateAddress = function (address) {
197
+ return __awaiter(this, void 0, void 0, function () {
198
+ return __generator(this, function (_a) {
199
+ try {
200
+ // Check if it's a valid hex address (0x followed by 1-64 hex characters)
201
+ return [2 /*return*/, /^0x[a-fA-F0-9]{1,64}$/.test(address)];
202
+ }
203
+ catch (_b) {
204
+ return [2 /*return*/, false];
205
+ }
206
+ return [2 /*return*/];
207
+ });
208
+ });
209
+ };
210
+ AptosProtocol.prototype.getBalanceOfAddress = function (address) {
211
+ var _a, _b, _c;
212
+ return __awaiter(this, void 0, void 0, function () {
213
+ var indexerUrl, query, response, result, balances, balance, e_1, resources, balance, e_2;
214
+ return __generator(this, function (_d) {
215
+ switch (_d.label) {
216
+ case 0:
217
+ _d.trys.push([0, 4, , 5]);
218
+ indexerUrl = 'https://indexer.mainnet.aptoslabs.com/v1/graphql';
219
+ query = {
220
+ query: "\n query GetAccountCoins {\n current_fungible_asset_balances(\n where: {owner_address: {_eq: \"".concat(address, "\"}, asset_type: {_eq: \"0x1::aptos_coin::AptosCoin\"}}\n ) {\n amount\n }\n }\n ")
221
+ };
222
+ return [4 /*yield*/, fetch(indexerUrl, {
223
+ method: 'POST',
224
+ headers: { 'Content-Type': 'application/json' },
225
+ body: JSON.stringify(query)
226
+ })];
227
+ case 1:
228
+ response = _d.sent();
229
+ if (!response.ok) return [3 /*break*/, 3];
230
+ return [4 /*yield*/, response.json()];
231
+ case 2:
232
+ result = _d.sent();
233
+ balances = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.current_fungible_asset_balances;
234
+ if (balances && balances.length > 0) {
235
+ balance = balances[0].amount || '0';
236
+ return [2 /*return*/, {
237
+ total: (0, module_kit_1.newAmount)(balance, 'Octas')
238
+ }];
239
+ }
240
+ _d.label = 3;
241
+ case 3: return [3 /*break*/, 5];
242
+ case 4:
243
+ e_1 = _d.sent();
244
+ return [3 /*break*/, 5];
245
+ case 5:
246
+ _d.trys.push([5, 7, , 8]);
247
+ return [4 /*yield*/, this.fetchJson("/accounts/".concat(address, "/resource/0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>"))];
248
+ case 6:
249
+ resources = _d.sent();
250
+ balance = ((_c = (_b = resources === null || resources === void 0 ? void 0 : resources.data) === null || _b === void 0 ? void 0 : _b.coin) === null || _c === void 0 ? void 0 : _c.value) || '0';
251
+ return [2 /*return*/, {
252
+ total: (0, module_kit_1.newAmount)(balance, 'Octas')
253
+ }];
254
+ case 7:
255
+ e_2 = _d.sent();
256
+ // Account might not exist yet or has no balance
257
+ return [2 /*return*/, { total: (0, module_kit_1.newAmount)(0, 'Octas') }];
258
+ case 8: return [2 /*return*/];
259
+ }
260
+ });
261
+ });
262
+ };
263
+ AptosProtocol.prototype.getBalanceOfPublicKey = function (publicKey) {
264
+ return __awaiter(this, void 0, void 0, function () {
265
+ var address;
266
+ return __generator(this, function (_a) {
267
+ switch (_a.label) {
268
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
269
+ case 1:
270
+ address = _a.sent();
271
+ return [2 /*return*/, this.getBalanceOfAddress(address)];
272
+ }
273
+ });
274
+ });
275
+ };
276
+ AptosProtocol.prototype.getDetailsFromTransaction = function (transaction, publicKey) {
277
+ return __awaiter(this, void 0, void 0, function () {
278
+ var txData, fromAddress, fee, toAddress, amount, args, fallbackTx;
279
+ return __generator(this, function (_a) {
280
+ try {
281
+ txData = JSON.parse(transaction.serialized);
282
+ fromAddress = txData.sender || '';
283
+ fee = (0, module_kit_1.newAmount)((BigInt(txData.max_gas_amount || 0) * BigInt(txData.gas_unit_price || 0)).toString(), 'Octas');
284
+ toAddress = '';
285
+ amount = (0, module_kit_1.newAmount)(0, 'Octas');
286
+ // Parse payload
287
+ if (txData.payload) {
288
+ args = txData.payload.arguments || [];
289
+ if (args.length >= 2) {
290
+ toAddress = args[0];
291
+ amount = (0, module_kit_1.newAmount)(args[1], 'Octas');
292
+ }
293
+ }
294
+ return [2 /*return*/, [
295
+ {
296
+ from: [fromAddress],
297
+ to: toAddress ? [toAddress] : [],
298
+ amount: amount,
299
+ fee: fee,
300
+ isInbound: false,
301
+ network: this.options.network
302
+ }
303
+ ]];
304
+ }
305
+ catch (e) {
306
+ console.error('[aptos][getDetailsFromTransaction] Failed to parse transaction:', e);
307
+ fallbackTx = {
308
+ from: [],
309
+ to: [],
310
+ amount: (0, module_kit_1.newAmount)(0, 'Octas'),
311
+ fee: (0, module_kit_1.newAmount)(0, 'Octas'),
312
+ isInbound: false,
313
+ network: this.options.network
314
+ };
315
+ return [2 /*return*/, [fallbackTx]];
316
+ }
317
+ return [2 /*return*/];
318
+ });
319
+ });
320
+ };
321
+ AptosProtocol.prototype.getTransactionDetailsFromSigned = function (signedTx) {
322
+ return __awaiter(this, void 0, void 0, function () {
323
+ return __generator(this, function (_a) {
324
+ return [2 /*return*/, this.getDetailsFromTransaction(signedTx.transaction, null)];
325
+ });
326
+ });
327
+ };
328
+ AptosProtocol.prototype.verifyMessageWithPublicKey = function (message, signature, publicKey) {
329
+ return __awaiter(this, void 0, void 0, function () {
330
+ var messageBytes, signatureBytes, pubKeyBytes;
331
+ return __generator(this, function (_a) {
332
+ try {
333
+ messageBytes = Buffer.from(message);
334
+ signatureBytes = Buffer.from(signature.value, signature.format === 'hex' ? 'hex' : undefined);
335
+ pubKeyBytes = this.getPublicKeyBuffer(publicKey);
336
+ return [2 /*return*/, nacl.sign.detached.verify(messageBytes, signatureBytes, pubKeyBytes)];
337
+ }
338
+ catch (e) {
339
+ return [2 /*return*/, false];
340
+ }
341
+ return [2 /*return*/];
342
+ });
343
+ });
344
+ };
345
+ AptosProtocol.prototype.encryptAsymmetricWithPublicKey = function (payload, publicKey) {
346
+ return __awaiter(this, void 0, void 0, function () {
347
+ return __generator(this, function (_a) {
348
+ throw new Error('Not implemented');
349
+ });
350
+ });
351
+ };
352
+ AptosProtocol.prototype.getCryptoConfiguration = function () {
353
+ return __awaiter(this, void 0, void 0, function () {
354
+ return __generator(this, function (_a) {
355
+ return [2 /*return*/, { algorithm: 'ed25519' }];
356
+ });
357
+ });
358
+ };
359
+ AptosProtocol.prototype.getKeyPairFromDerivative = function (derivative) {
360
+ return __awaiter(this, void 0, void 0, function () {
361
+ var secretKeyBuffer, publicKeyBuffer;
362
+ return __generator(this, function (_a) {
363
+ secretKeyBuffer = Buffer.from(derivative.secretKey, 'hex');
364
+ publicKeyBuffer = Buffer.from(derivative.publicKey, 'hex');
365
+ return [2 /*return*/, {
366
+ publicKey: {
367
+ value: publicKeyBuffer.toString('hex'),
368
+ format: 'hex',
369
+ type: 'pub'
370
+ },
371
+ secretKey: {
372
+ value: secretKeyBuffer.toString('hex'),
373
+ format: 'hex',
374
+ type: 'priv'
375
+ }
376
+ }];
377
+ });
378
+ });
379
+ };
380
+ AptosProtocol.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
381
+ return __awaiter(this, void 0, void 0, function () {
382
+ var txData, keyHex, secretKeyBytes, signingKey, publicKeyBytes, keyPair, signatureBytes, _signingMessage, unsignedTxData, signedTxData;
383
+ return __generator(this, function (_a) {
384
+ txData = JSON.parse(transaction.serialized);
385
+ keyHex = secretKey.value;
386
+ secretKeyBytes = Buffer.from(keyHex, secretKey.format === 'hex' ? 'hex' : undefined);
387
+ if (secretKeyBytes.length === 64) {
388
+ signingKey = secretKeyBytes;
389
+ publicKeyBytes = secretKeyBytes.slice(32);
390
+ }
391
+ else if (secretKeyBytes.length === 32) {
392
+ keyPair = nacl.sign.keyPair.fromSeed(secretKeyBytes);
393
+ signingKey = keyPair.secretKey;
394
+ publicKeyBytes = keyPair.publicKey;
395
+ }
396
+ else {
397
+ throw new Error('Invalid secret key length');
398
+ }
399
+ signatureBytes = nacl.sign.detached(Buffer.from(txData.signing_message, 'hex'), signingKey);
400
+ _signingMessage = txData.signing_message, unsignedTxData = __rest(txData, ["signing_message"]);
401
+ signedTxData = __assign(__assign({}, unsignedTxData), { signature: {
402
+ type: 'ed25519_signature',
403
+ public_key: '0x' + Buffer.from(publicKeyBytes).toString('hex'),
404
+ signature: '0x' + Buffer.from(signatureBytes).toString('hex')
405
+ } });
406
+ return [2 /*return*/, {
407
+ serialized: JSON.stringify(signedTxData),
408
+ type: 'signed'
409
+ }];
410
+ });
411
+ });
412
+ };
413
+ AptosProtocol.prototype.signMessageWithKeyPair = function (message, keyPair) {
414
+ return __awaiter(this, void 0, void 0, function () {
415
+ var messageBytes, secretKeyBytes, signingKey, signature;
416
+ return __generator(this, function (_a) {
417
+ messageBytes = Buffer.from(message);
418
+ secretKeyBytes = Buffer.from(keyPair.secretKey.value, keyPair.secretKey.format === 'hex' ? 'hex' : undefined);
419
+ if (secretKeyBytes.length === 64) {
420
+ signingKey = secretKeyBytes;
421
+ }
422
+ else if (secretKeyBytes.length === 32) {
423
+ signingKey = nacl.sign.keyPair.fromSeed(secretKeyBytes).secretKey;
424
+ }
425
+ else {
426
+ throw new Error('Invalid secret key length');
427
+ }
428
+ signature = nacl.sign.detached(messageBytes, signingKey);
429
+ return [2 /*return*/, (0, module_kit_1.newSignature)(Buffer.from(signature).toString('hex'), 'hex')];
430
+ });
431
+ });
432
+ };
433
+ AptosProtocol.prototype.decryptAsymmetricWithKeyPair = function (payload, keyPair) {
434
+ return __awaiter(this, void 0, void 0, function () {
435
+ return __generator(this, function (_a) {
436
+ throw new Error('Not implemented');
437
+ });
438
+ });
439
+ };
440
+ AptosProtocol.prototype.encryptAESWithSecretKey = function (payload, secretKey) {
441
+ return __awaiter(this, void 0, void 0, function () {
442
+ return __generator(this, function (_a) {
443
+ throw new Error('Not implemented');
444
+ });
445
+ });
446
+ };
447
+ AptosProtocol.prototype.decryptAESWithSecretKey = function (payload, secretKey) {
448
+ return __awaiter(this, void 0, void 0, function () {
449
+ return __generator(this, function (_a) {
450
+ throw new Error('Not implemented');
451
+ });
452
+ });
453
+ };
454
+ AptosProtocol.prototype.getNetwork = function () {
455
+ return __awaiter(this, void 0, void 0, function () {
456
+ return __generator(this, function (_a) {
457
+ return [2 /*return*/, this.options.network];
458
+ });
459
+ });
460
+ };
461
+ AptosProtocol.prototype.getTransactionsForAddress = function (address, limit, cursor) {
462
+ var _a, _b;
463
+ return __awaiter(this, void 0, void 0, function () {
464
+ var effectiveLimit, offset, indexerUrl, versionsQuery, versionsResponse, versionsResult, versionActivities, versions, graphqlQuery, response, result, activities, txMap, _i, activities_1, activity, version, txs_1, hasNext, newCursor, e_3;
465
+ var _this = this;
466
+ return __generator(this, function (_c) {
467
+ switch (_c.label) {
468
+ case 0:
469
+ _c.trys.push([0, 5, , 6]);
470
+ effectiveLimit = limit || AptosProtocol.DEFAULT_TX_LIMIT;
471
+ offset = (cursor === null || cursor === void 0 ? void 0 : cursor.offset) || 0;
472
+ indexerUrl = 'https://indexer.mainnet.aptoslabs.com/v1/graphql';
473
+ versionsQuery = "{\n fungible_asset_activities(\n where: {\n owner_address: { _eq: \"".concat(address, "\" },\n asset_type: { _in: [\"0xa\", \"0x000000000000000000000000000000000000000000000000000000000000000a\", \"0x1::aptos_coin::AptosCoin\"] }\n },\n order_by: { transaction_version: desc },\n limit: ").concat(effectiveLimit, ",\n offset: ").concat(offset, "\n ) {\n transaction_version\n }\n }");
474
+ return [4 /*yield*/, fetch(indexerUrl, {
475
+ method: 'POST',
476
+ headers: { 'Content-Type': 'application/json' },
477
+ body: JSON.stringify({ query: versionsQuery })
478
+ })];
479
+ case 1:
480
+ versionsResponse = _c.sent();
481
+ if (!versionsResponse.ok) {
482
+ throw new Error("Indexer API failed: ".concat(versionsResponse.status));
483
+ }
484
+ return [4 /*yield*/, versionsResponse.json()];
485
+ case 2:
486
+ versionsResult = _c.sent();
487
+ versionActivities = ((_a = versionsResult === null || versionsResult === void 0 ? void 0 : versionsResult.data) === null || _a === void 0 ? void 0 : _a.fungible_asset_activities) || [];
488
+ versions = Array.from(new Set(versionActivities.map(function (a) { return a.transaction_version; })));
489
+ if (versions.length === 0) {
490
+ return [2 /*return*/, { transactions: [], cursor: { hasNext: false } }];
491
+ }
492
+ graphqlQuery = "{\n fungible_asset_activities(\n where: {\n transaction_version: { _in: [".concat(versions.join(','), "] },\n asset_type: { _in: [\"0xa\", \"0x000000000000000000000000000000000000000000000000000000000000000a\", \"0x1::aptos_coin::AptosCoin\"] }\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 }");
493
+ return [4 /*yield*/, fetch(indexerUrl, {
494
+ method: 'POST',
495
+ headers: { 'Content-Type': 'application/json' },
496
+ body: JSON.stringify({ query: graphqlQuery })
497
+ })];
498
+ case 3:
499
+ response = _c.sent();
500
+ if (!response.ok) {
501
+ throw new Error("Indexer API failed: ".concat(response.status));
502
+ }
503
+ return [4 /*yield*/, response.json()];
504
+ case 4:
505
+ result = _c.sent();
506
+ activities = ((_b = result === null || result === void 0 ? void 0 : result.data) === null || _b === void 0 ? void 0 : _b.fungible_asset_activities) || [];
507
+ txMap = new Map();
508
+ for (_i = 0, activities_1 = activities; _i < activities_1.length; _i++) {
509
+ activity = activities_1[_i];
510
+ version = activity.transaction_version.toString();
511
+ if (!txMap.has(version)) {
512
+ txMap.set(version, {
513
+ version: version,
514
+ timestamp: activity.transaction_timestamp,
515
+ success: activity.is_transaction_success,
516
+ activities: []
517
+ });
518
+ }
519
+ txMap.get(version).activities.push(activity);
520
+ }
521
+ txs_1 = [];
522
+ txMap.forEach(function (txData, version) {
523
+ try {
524
+ var acts = txData.activities;
525
+ var amount = (0, module_kit_1.newAmount)(0, 'Octas');
526
+ var isInbound = false;
527
+ var fee = (0, module_kit_1.newAmount)(0, 'Octas');
528
+ // Collect all withdraw addresses (senders) and deposit addresses (recipients)
529
+ var withdrawAddresses = [];
530
+ var depositAddresses = [];
531
+ var gasFeePayerAddress = '';
532
+ for (var _i = 0, acts_1 = acts; _i < acts_1.length; _i++) {
533
+ var act = acts_1[_i];
534
+ var actType = (act.type || '').toLowerCase();
535
+ var ownerAddr = act.owner_address || '';
536
+ if (actType.includes('gasfee')) {
537
+ fee = (0, module_kit_1.newAmount)(act.amount || '0', 'Octas');
538
+ gasFeePayerAddress = ownerAddr;
539
+ }
540
+ else if (actType.includes('deposit')) {
541
+ // Deposit recipient
542
+ if (ownerAddr && !depositAddresses.includes(ownerAddr)) {
543
+ depositAddresses.push(ownerAddr);
544
+ }
545
+ if (ownerAddr.toLowerCase() === address.toLowerCase()) {
546
+ amount = (0, module_kit_1.newAmount)(act.amount || '0', 'Octas');
547
+ isInbound = true;
548
+ }
549
+ }
550
+ else if (actType.includes('withdraw')) {
551
+ // Withdraw sender
552
+ if (ownerAddr && !withdrawAddresses.includes(ownerAddr)) {
553
+ withdrawAddresses.push(ownerAddr);
554
+ }
555
+ if (ownerAddr.toLowerCase() === address.toLowerCase()) {
556
+ amount = (0, module_kit_1.newAmount)(act.amount || '0', 'Octas');
557
+ isInbound = false;
558
+ }
559
+ }
560
+ }
561
+ // Determine from and to addresses based on transaction direction
562
+ var fromAddresses = [];
563
+ var toAddresses = [];
564
+ if (isInbound) {
565
+ // Inbound: from = senders (not current user), to = current user
566
+ fromAddresses = withdrawAddresses.filter(function (addr) { return addr.toLowerCase() !== address.toLowerCase(); });
567
+ toAddresses = depositAddresses.filter(function (addr) { return addr.toLowerCase() === address.toLowerCase(); });
568
+ // If no external sender found, use gas fee payer as sender
569
+ if (fromAddresses.length === 0 && gasFeePayerAddress && gasFeePayerAddress.toLowerCase() !== address.toLowerCase()) {
570
+ fromAddresses = [gasFeePayerAddress];
571
+ }
572
+ }
573
+ else {
574
+ // Outbound: from = current user, to = recipients (not current user)
575
+ fromAddresses = withdrawAddresses.filter(function (addr) { return addr.toLowerCase() === address.toLowerCase(); });
576
+ toAddresses = depositAddresses.filter(function (addr) { return addr.toLowerCase() !== address.toLowerCase(); });
577
+ // If no external sender found for from, use current user if they paid gas
578
+ if (fromAddresses.length === 0 && gasFeePayerAddress && gasFeePayerAddress.toLowerCase() === address.toLowerCase()) {
579
+ fromAddresses = [gasFeePayerAddress];
580
+ }
581
+ }
582
+ // Fallback: if from is empty, use withdraw addresses; if to is empty, use deposit addresses
583
+ if (fromAddresses.length === 0 && withdrawAddresses.length > 0) {
584
+ fromAddresses = withdrawAddresses;
585
+ }
586
+ if (toAddresses.length === 0 && depositAddresses.length > 0) {
587
+ toAddresses = depositAddresses;
588
+ }
589
+ // If we couldn't determine amount from our address activities, use any available amount
590
+ if (amount.value === '0') {
591
+ for (var _a = 0, acts_2 = acts; _a < acts_2.length; _a++) {
592
+ var act = acts_2[_a];
593
+ var actType = (act.type || '').toLowerCase();
594
+ if (!actType.includes('gasfee') && act.amount) {
595
+ amount = (0, module_kit_1.newAmount)(act.amount, 'Octas');
596
+ break;
597
+ }
598
+ }
599
+ }
600
+ var timestamp = txData.timestamp
601
+ ? Math.floor(new Date(txData.timestamp).getTime() / 1000)
602
+ : Math.floor(Date.now() / 1000);
603
+ txs_1.push({
604
+ hash: version,
605
+ timestamp: timestamp,
606
+ status: txData.success ? 'applied' : 'failed',
607
+ amount: amount,
608
+ fee: fee,
609
+ from: fromAddresses,
610
+ to: toAddresses,
611
+ isInbound: isInbound,
612
+ network: _this.options.network
613
+ });
614
+ }
615
+ catch (e) {
616
+ console.warn('[aptos][getTransactionsForAddress] Failed to parse activity');
617
+ }
618
+ });
619
+ // Sort by version descending
620
+ txs_1.sort(function (a, b) { return parseInt(b.hash) - parseInt(a.hash); });
621
+ hasNext = versionActivities.length === effectiveLimit;
622
+ newCursor = {
623
+ hasNext: hasNext,
624
+ offset: offset + versionActivities.length
625
+ };
626
+ return [2 /*return*/, {
627
+ transactions: txs_1,
628
+ cursor: newCursor
629
+ }];
630
+ case 5:
631
+ e_3 = _c.sent();
632
+ console.error('[aptos][getTransactionsForAddress] Failed:', e_3);
633
+ return [2 /*return*/, {
634
+ transactions: [],
635
+ cursor: { hasNext: false }
636
+ }];
637
+ case 6: return [2 /*return*/];
638
+ }
639
+ });
640
+ });
641
+ };
642
+ AptosProtocol.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
643
+ return __awaiter(this, void 0, void 0, function () {
644
+ var address;
645
+ return __generator(this, function (_a) {
646
+ switch (_a.label) {
647
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
648
+ case 1:
649
+ address = _a.sent();
650
+ return [2 /*return*/, this.getTransactionsForAddress(address, limit, cursor)];
651
+ }
652
+ });
653
+ });
654
+ };
655
+ AptosProtocol.prototype.getTransactionStatus = function (transactionIds) {
656
+ return __awaiter(this, void 0, void 0, function () {
657
+ var result, _i, transactionIds_1, txHash, tx, _a;
658
+ return __generator(this, function (_b) {
659
+ switch (_b.label) {
660
+ case 0:
661
+ result = {};
662
+ _i = 0, transactionIds_1 = transactionIds;
663
+ _b.label = 1;
664
+ case 1:
665
+ if (!(_i < transactionIds_1.length)) return [3 /*break*/, 6];
666
+ txHash = transactionIds_1[_i];
667
+ _b.label = 2;
668
+ case 2:
669
+ _b.trys.push([2, 4, , 5]);
670
+ return [4 /*yield*/, this.fetchJson("/transactions/by_hash/".concat(txHash))];
671
+ case 3:
672
+ tx = _b.sent();
673
+ result[txHash] = { status: tx.success ? 'applied' : 'failed' };
674
+ return [3 /*break*/, 5];
675
+ case 4:
676
+ _a = _b.sent();
677
+ result[txHash] = { status: 'unknown' };
678
+ return [3 /*break*/, 5];
679
+ case 5:
680
+ _i++;
681
+ return [3 /*break*/, 1];
682
+ case 6: return [2 /*return*/, result];
683
+ }
684
+ });
685
+ });
686
+ };
687
+ AptosProtocol.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
688
+ return __awaiter(this, void 0, void 0, function () {
689
+ var balance, fee, feeOctas, maxAmount, maxString;
690
+ return __generator(this, function (_a) {
691
+ switch (_a.label) {
692
+ case 0: return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
693
+ case 1:
694
+ balance = _a.sent();
695
+ return [4 /*yield*/, this.getTransactionFeeWithPublicKey(publicKey, [{ to: to === null || to === void 0 ? void 0 : to[0], amount: (0, module_kit_1.newAmount)(0, 'Octas') }])];
696
+ case 2:
697
+ fee = _a.sent();
698
+ feeOctas = fee && fee.medium && fee.medium.value !== undefined ? new bignumber_1.BigNumber(fee.medium.value) : new bignumber_1.BigNumber(20000);
699
+ maxAmount = new bignumber_1.BigNumber(balance.total.value).minus(feeOctas);
700
+ maxString = maxAmount.gt(0) ? maxAmount.toFixed(0) : '0';
701
+ return [2 /*return*/, (0, module_kit_1.newAmount)(maxString, 'Octas')];
702
+ }
703
+ });
704
+ });
705
+ };
706
+ AptosProtocol.prototype.getTransactionFeeWithPublicKey = function (publicKey, details, configuration) {
707
+ return __awaiter(this, void 0, void 0, function () {
708
+ var gasEstimate, gasPrice, estimatedGas, fee, _a, defaultFee;
709
+ return __generator(this, function (_b) {
710
+ switch (_b.label) {
711
+ case 0:
712
+ _b.trys.push([0, 2, , 3]);
713
+ return [4 /*yield*/, this.fetchJson('/estimate_gas_price')];
714
+ case 1:
715
+ gasEstimate = _b.sent();
716
+ gasPrice = parseInt(gasEstimate.gas_estimate || '100');
717
+ estimatedGas = DEFAULT_MAX_GAS_AMOUNT;
718
+ fee = (estimatedGas * gasPrice).toString();
719
+ return [2 /*return*/, {
720
+ low: (0, module_kit_1.newAmount)(fee, 'Octas'),
721
+ medium: (0, module_kit_1.newAmount)(fee, 'Octas'),
722
+ high: (0, module_kit_1.newAmount)((estimatedGas * gasPrice * 2).toString(), 'Octas')
723
+ }];
724
+ case 2:
725
+ _a = _b.sent();
726
+ defaultFee = (DEFAULT_MAX_GAS_AMOUNT * DEFAULT_GAS_UNIT_PRICE).toString();
727
+ return [2 /*return*/, {
728
+ low: (0, module_kit_1.newAmount)(defaultFee, 'Octas'),
729
+ medium: (0, module_kit_1.newAmount)(defaultFee, 'Octas'),
730
+ high: (0, module_kit_1.newAmount)((DEFAULT_MAX_GAS_AMOUNT * DEFAULT_GAS_UNIT_PRICE * 2).toString(), 'Octas')
731
+ }];
732
+ case 3: return [2 /*return*/];
733
+ }
734
+ });
735
+ });
736
+ };
737
+ AptosProtocol.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
738
+ var _a, _b;
739
+ return __awaiter(this, void 0, void 0, function () {
740
+ var fromAddress, sequenceNumber, accountInfo, e_4, gasUnitPrice, gasEstimate, _c, ledgerInfo, currentTimestamp, expirationTimestamp, detail, amountOctas, txPayload, encodingRequest, encodingText, signingMessage;
741
+ return __generator(this, function (_d) {
742
+ switch (_d.label) {
743
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)
744
+ // Get account info for sequence number
745
+ ];
746
+ case 1:
747
+ fromAddress = _d.sent();
748
+ sequenceNumber = '0';
749
+ _d.label = 2;
750
+ case 2:
751
+ _d.trys.push([2, 4, , 5]);
752
+ return [4 /*yield*/, this.fetchJson("/accounts/".concat(fromAddress))];
753
+ case 3:
754
+ accountInfo = _d.sent();
755
+ sequenceNumber = accountInfo.sequence_number || '0';
756
+ return [3 /*break*/, 5];
757
+ case 4:
758
+ e_4 = _d.sent();
759
+ // Account might not exist yet, use 0
760
+ if (!((_a = e_4 === null || e_4 === void 0 ? void 0 : e_4.message) === null || _a === void 0 ? void 0 : _a.includes('404')) && !((_b = e_4 === null || e_4 === void 0 ? void 0 : e_4.message) === null || _b === void 0 ? void 0 : _b.includes('not found'))) {
761
+ throw e_4;
762
+ }
763
+ return [3 /*break*/, 5];
764
+ case 5:
765
+ gasUnitPrice = DEFAULT_GAS_UNIT_PRICE;
766
+ _d.label = 6;
767
+ case 6:
768
+ _d.trys.push([6, 8, , 9]);
769
+ return [4 /*yield*/, this.fetchJson('/estimate_gas_price')];
770
+ case 7:
771
+ gasEstimate = _d.sent();
772
+ gasUnitPrice = parseInt(gasEstimate.gas_estimate || '100');
773
+ return [3 /*break*/, 9];
774
+ case 8:
775
+ _c = _d.sent();
776
+ return [3 /*break*/, 9];
777
+ case 9: return [4 /*yield*/, this.fetchJson('/')];
778
+ case 10:
779
+ ledgerInfo = _d.sent();
780
+ currentTimestamp = parseInt(ledgerInfo.ledger_timestamp || '0') / 1000000;
781
+ expirationTimestamp = Math.floor(currentTimestamp) + 600 // 10 minutes expiry
782
+ ;
783
+ detail = details[0];
784
+ amountOctas = (0, module_kit_1.newAmount)(detail.amount).blockchain(exports.APTOS_UNITS_METADATA).value;
785
+ txPayload = {
786
+ sender: fromAddress,
787
+ sequence_number: sequenceNumber,
788
+ max_gas_amount: DEFAULT_MAX_GAS_AMOUNT.toString(),
789
+ gas_unit_price: gasUnitPrice.toString(),
790
+ expiration_timestamp_secs: expirationTimestamp.toString(),
791
+ payload: {
792
+ type: 'entry_function_payload',
793
+ function: '0x1::aptos_account::transfer',
794
+ type_arguments: [],
795
+ arguments: [detail.to, amountOctas]
796
+ }
797
+ };
798
+ return [4 /*yield*/, fetch("".concat(this.options.network.rpcUrl, "/transactions/encode_submission"), {
799
+ method: 'POST',
800
+ headers: { 'Content-Type': 'application/json' },
801
+ body: JSON.stringify(txPayload)
802
+ })];
803
+ case 11:
804
+ encodingRequest = _d.sent();
805
+ return [4 /*yield*/, encodingRequest.text()];
806
+ case 12:
807
+ encodingText = _d.sent();
808
+ if (!encodingRequest.ok) {
809
+ throw new Error("Encode submission failed: ".concat(encodingRequest.status, ": ").concat(encodingText));
810
+ }
811
+ signingMessage = encodingText;
812
+ try {
813
+ signingMessage = JSON.parse(encodingText);
814
+ }
815
+ catch (_e) {
816
+ // ignore
817
+ }
818
+ if (typeof signingMessage !== 'string') {
819
+ throw new Error("Encode submission failed: unexpected response: ".concat(encodingText));
820
+ }
821
+ // signingMessage is hex string of the message to sign
822
+ return [2 /*return*/, {
823
+ serialized: JSON.stringify(__assign(__assign({}, txPayload), { signing_message: signingMessage.replace(/^0x/, '') })),
824
+ type: 'unsigned'
825
+ }];
826
+ }
827
+ });
828
+ });
829
+ };
830
+ AptosProtocol.prototype.broadcastTransaction = function (transaction) {
831
+ return __awaiter(this, void 0, void 0, function () {
832
+ var signedTxData, _signingMessage, txToSubmit, response, _a, _b, result, i, txStatus, _c;
833
+ return __generator(this, function (_d) {
834
+ switch (_d.label) {
835
+ case 0:
836
+ signedTxData = JSON.parse(transaction.serialized);
837
+ _signingMessage = signedTxData.signing_message, txToSubmit = __rest(signedTxData
838
+ // Submit to Aptos REST API
839
+ , ["signing_message"]);
840
+ return [4 /*yield*/, fetch("".concat(this.options.network.rpcUrl, "/transactions"), {
841
+ method: 'POST',
842
+ headers: { 'Content-Type': 'application/json' },
843
+ body: JSON.stringify(txToSubmit)
844
+ })];
845
+ case 1:
846
+ response = _d.sent();
847
+ if (!!response.ok) return [3 /*break*/, 3];
848
+ _a = Error.bind;
849
+ _b = "Broadcast failed: ".concat;
850
+ return [4 /*yield*/, response.text()];
851
+ case 2: throw new (_a.apply(Error, [void 0, _b.apply("Broadcast failed: ", [_d.sent()])]))();
852
+ case 3: return [4 /*yield*/, response.json()
853
+ // Wait for transaction to be confirmed
854
+ ];
855
+ case 4:
856
+ result = _d.sent();
857
+ i = 0;
858
+ _d.label = 5;
859
+ case 5:
860
+ if (!(i < 30)) return [3 /*break*/, 12];
861
+ _d.label = 6;
862
+ case 6:
863
+ _d.trys.push([6, 8, , 9]);
864
+ return [4 /*yield*/, this.fetchJson("/transactions/by_hash/".concat(result.hash))];
865
+ case 7:
866
+ txStatus = _d.sent();
867
+ if (txStatus.type === 'user_transaction') {
868
+ return [3 /*break*/, 12];
869
+ }
870
+ return [3 /*break*/, 9];
871
+ case 8:
872
+ _c = _d.sent();
873
+ return [3 /*break*/, 9];
874
+ case 9: return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 1000); })];
875
+ case 10:
876
+ _d.sent();
877
+ _d.label = 11;
878
+ case 11:
879
+ i++;
880
+ return [3 /*break*/, 5];
881
+ case 12: return [2 /*return*/, result.hash];
882
+ }
883
+ });
884
+ });
885
+ };
886
+ AptosProtocol.prototype.getTokenBalancesOfPublicKey = function (publicKey, tokens) {
887
+ return __awaiter(this, void 0, void 0, function () {
888
+ return __generator(this, function (_a) {
889
+ return [2 /*return*/, {}];
890
+ });
891
+ });
892
+ };
893
+ AptosProtocol.DEFAULT_TX_LIMIT = 10;
894
+ return AptosProtocol;
895
+ }());
896
+ exports.AptosProtocol = AptosProtocol;
897
+ function createAptosProtocol(options) {
898
+ if (options === void 0) { options = {}; }
899
+ var defaultNetwork = {
900
+ name: 'Aptos Mainnet',
901
+ type: 'mainnet',
902
+ rpcUrl: 'https://fullnode.mainnet.aptoslabs.com/v1',
903
+ blockExplorerUrl: 'https://explorer.aptoslabs.com',
904
+ chainId: 1,
905
+ blockExplorerApi: ''
906
+ };
907
+ return new AptosProtocol({
908
+ network: __assign(__assign({}, defaultNetwork), options.network)
909
+ });
910
+ }
911
+ exports.createAptosProtocol = createAptosProtocol;
912
+ //# sourceMappingURL=AptosProtocol.js.map