@vleap/warps-adapter-fastset 0.1.0-alpha.13 → 0.1.0-alpha.15

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.
package/dist/index.js ADDED
@@ -0,0 +1,1057 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Address: () => Address,
34
+ Amount: () => Amount,
35
+ BcsTransaction: () => BcsTransaction,
36
+ Bytes32: () => Bytes32,
37
+ Claim: () => Claim,
38
+ ClaimType: () => ClaimType,
39
+ FastsetClient: () => FastsetClient,
40
+ NativeTokenSet: () => NativeTokenSet,
41
+ Nonce: () => Nonce,
42
+ PublicKey: () => PublicKey,
43
+ Transaction: () => Transaction,
44
+ Transfer: () => Transfer,
45
+ TransferClaim: () => TransferClaim,
46
+ UserData: () => UserData,
47
+ Wallet: () => Wallet,
48
+ WarpFastsetConstants: () => WarpFastsetConstants,
49
+ WarpFastsetDataLoader: () => WarpFastsetDataLoader,
50
+ WarpFastsetExecutor: () => WarpFastsetExecutor,
51
+ WarpFastsetExplorer: () => WarpFastsetExplorer,
52
+ WarpFastsetResults: () => WarpFastsetResults,
53
+ WarpFastsetSerializer: () => WarpFastsetSerializer,
54
+ getFastsetAdapter: () => getFastsetAdapter
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+
58
+ // src/constants.ts
59
+ var WarpFastsetConstants = {
60
+ // Placeholder for future FastSet-specific constants
61
+ };
62
+
63
+ // src/main.ts
64
+ var import_warps4 = require("@vleap/warps");
65
+
66
+ // src/sdk/FastsetClient.ts
67
+ var import_ed255192 = require("@noble/ed25519");
68
+
69
+ // src/sdk/TransactionSigner.ts
70
+ var import_ed25519 = require("@noble/ed25519");
71
+
72
+ // src/sdk/types.ts
73
+ var import_bcs = require("@mysten/bcs");
74
+ BigInt.prototype.toJSON = function() {
75
+ return Number(this);
76
+ };
77
+ var Bytes32 = import_bcs.bcs.fixedArray(32, import_bcs.bcs.u8());
78
+ var PublicKey = Bytes32;
79
+ var Address = import_bcs.bcs.enum("Address", {
80
+ External: PublicKey,
81
+ FastSet: PublicKey
82
+ });
83
+ var Amount = import_bcs.bcs.u256().transform({
84
+ input: (val) => hexToDecimal(val.toString()),
85
+ output: (value) => value
86
+ });
87
+ var UserData = import_bcs.bcs.option(Bytes32);
88
+ var Nonce = import_bcs.bcs.u64();
89
+ var Transfer = import_bcs.bcs.struct("Transfer", {
90
+ recipient: Address,
91
+ amount: Amount,
92
+ user_data: UserData
93
+ });
94
+ var ClaimType = import_bcs.bcs.enum("ClaimType", {
95
+ Transfer
96
+ });
97
+ var BcsTransaction = import_bcs.bcs.struct("Transaction", {
98
+ sender: PublicKey,
99
+ nonce: Nonce,
100
+ timestamp_nanos: import_bcs.bcs.u128(),
101
+ claim: ClaimType
102
+ });
103
+ function hexToDecimal(hex) {
104
+ return BigInt(`0x${hex}`).toString();
105
+ }
106
+
107
+ // src/sdk/TransactionSigner.ts
108
+ var TransactionSigner = class {
109
+ static async signTransaction(transaction, privateKey) {
110
+ const msg = BcsTransaction.serialize(transaction);
111
+ const msgBytes = msg.toBytes();
112
+ const prefix = new TextEncoder().encode("Transaction::");
113
+ const dataToSign = new Uint8Array(prefix.length + msgBytes.length);
114
+ dataToSign.set(prefix, 0);
115
+ dataToSign.set(msgBytes, prefix.length);
116
+ return (0, import_ed25519.sign)(dataToSign, privateKey);
117
+ }
118
+ };
119
+
120
+ // src/sdk/Wallet.ts
121
+ var bech32 = __toESM(require("bech32"), 1);
122
+
123
+ // src/sdk/Claim.ts
124
+ var Claim = class {
125
+ static fromTransaction(transaction) {
126
+ const claimType = Object.keys(transaction.claim)[0];
127
+ const claimData = transaction.claim[claimType];
128
+ switch (claimType) {
129
+ case "Transfer":
130
+ return TransferClaim.fromData(claimData);
131
+ default:
132
+ throw new Error(`Unknown claim type: ${claimType}`);
133
+ }
134
+ }
135
+ };
136
+ var TransferClaim = class _TransferClaim extends Claim {
137
+ constructor(recipient, amount, userData) {
138
+ super();
139
+ this.type = "Transfer";
140
+ this.data = { recipient, amount, userData };
141
+ }
142
+ toTransactionData() {
143
+ return {
144
+ Transfer: {
145
+ recipient: { FastSet: this.data.recipient },
146
+ amount: this.data.amount,
147
+ user_data: this.data.userData ?? null
148
+ }
149
+ };
150
+ }
151
+ static fromData(data) {
152
+ const recipient = data.recipient.FastSet || data.recipient.External;
153
+ return new _TransferClaim(recipient, data.amount, data.user_data);
154
+ }
155
+ getRecipient() {
156
+ return this.data.recipient;
157
+ }
158
+ getAmount() {
159
+ return this.data.amount;
160
+ }
161
+ getUserData() {
162
+ return this.data.userData;
163
+ }
164
+ };
165
+
166
+ // src/sdk/ed25519-setup.ts
167
+ var ed = __toESM(require("@noble/ed25519"), 1);
168
+ var import_sha512 = require("@noble/hashes/sha512");
169
+ if (ed.etc) {
170
+ ed.etc.sha512Sync = (...m) => (0, import_sha512.sha512)(ed.etc.concatBytes(...m));
171
+ }
172
+
173
+ // src/sdk/Transaction.ts
174
+ var Transaction = class _Transaction {
175
+ constructor(sender, nonce, claim, options = {}) {
176
+ this.sender = sender;
177
+ this.nonce = nonce;
178
+ this.claim = claim;
179
+ this.timestamp = options.timestamp ?? BigInt(Date.now()) * 1000000n;
180
+ }
181
+ toTransaction() {
182
+ return {
183
+ sender: this.sender,
184
+ nonce: this.nonce,
185
+ timestamp_nanos: this.timestamp,
186
+ claim: this.claim.toTransactionData()
187
+ };
188
+ }
189
+ getSender() {
190
+ return this.sender;
191
+ }
192
+ getNonce() {
193
+ return this.nonce;
194
+ }
195
+ getClaim() {
196
+ return this.claim;
197
+ }
198
+ getTimestamp() {
199
+ return this.timestamp;
200
+ }
201
+ static fromTransaction(transaction) {
202
+ const claim = Claim.fromTransaction(transaction);
203
+ return new _Transaction(transaction.sender, transaction.nonce, claim, { timestamp: transaction.timestamp_nanos });
204
+ }
205
+ };
206
+
207
+ // src/sdk/Wallet.ts
208
+ var Wallet = class _Wallet {
209
+ constructor(privateKeyHex) {
210
+ const cleanPrivateKey = privateKeyHex.replace(/^0x/, "");
211
+ this.privateKey = Buffer.from(cleanPrivateKey, "hex");
212
+ this.publicKey = ed.getPublicKey(this.privateKey);
213
+ this.publicKeyHex = Buffer.from(this.publicKey).toString("hex");
214
+ }
215
+ toBech32() {
216
+ const words = bech32.bech32m.toWords(this.publicKey);
217
+ return bech32.bech32m.encode("set", words);
218
+ }
219
+ getWalletInfo() {
220
+ return {
221
+ publicKeyHex: this.publicKeyHex,
222
+ address: this.toBech32()
223
+ };
224
+ }
225
+ createTransferClaim(recipientAddress, amount, assetType) {
226
+ const recipientBytes = _Wallet.decodeBech32Address(recipientAddress);
227
+ const assetTypeBytes = new TextEncoder().encode(assetType);
228
+ const userData = new Uint8Array(32);
229
+ userData.set(assetTypeBytes.slice(0, 32));
230
+ return new TransferClaim(recipientBytes, amount.toString(), userData);
231
+ }
232
+ createTransaction(nonce, claim) {
233
+ return new Transaction(this.publicKey, nonce, claim);
234
+ }
235
+ async signTransaction(transaction) {
236
+ const transactionData = transaction.toTransaction();
237
+ return await TransactionSigner.signTransaction(transactionData, this.privateKey);
238
+ }
239
+ static decodeBech32Address(address) {
240
+ try {
241
+ const decoded = bech32.bech32m.decode(address);
242
+ return new Uint8Array(bech32.bech32m.fromWords(decoded.words));
243
+ } catch (error) {
244
+ const decoded = bech32.bech32.decode(address);
245
+ return new Uint8Array(bech32.bech32.fromWords(decoded.words));
246
+ }
247
+ }
248
+ static encodeBech32Address(publicKey) {
249
+ const words = bech32.bech32m.toWords(publicKey);
250
+ return bech32.bech32m.encode("set", words);
251
+ }
252
+ static fromPrivateKey(privateKeyHex) {
253
+ return new _Wallet(privateKeyHex);
254
+ }
255
+ static generateNew() {
256
+ const privateKey = ed.utils.randomPrivateKey();
257
+ const privateKeyHex = Buffer.from(privateKey).toString("hex");
258
+ return new _Wallet(privateKeyHex);
259
+ }
260
+ static async fromPrivateKeyFile(filePath) {
261
+ const fs = await import("fs/promises");
262
+ const privateKeyHex = (await fs.readFile(filePath, "utf8")).trim();
263
+ return new _Wallet(privateKeyHex);
264
+ }
265
+ };
266
+
267
+ // src/sdk/FastsetClient.ts
268
+ BigInt.prototype.toJSON = function() {
269
+ return Number(this);
270
+ };
271
+ var FastsetClient = class {
272
+ constructor(config) {
273
+ this.config = config;
274
+ }
275
+ async getAccountInfo(address) {
276
+ try {
277
+ const addressBytes = Wallet.decodeBech32Address(address);
278
+ const response = await this.requestValidator("set_getAccountInfo", {
279
+ address: Array.from(addressBytes)
280
+ });
281
+ if (response.error) {
282
+ return null;
283
+ }
284
+ return response.result;
285
+ } catch (error) {
286
+ return null;
287
+ }
288
+ }
289
+ async getNextNonce(senderAddress) {
290
+ const accountInfo = await this.getAccountInfo(senderAddress);
291
+ return accountInfo?.next_nonce ?? 0;
292
+ }
293
+ async fundFromFaucet(recipientAddress, amount) {
294
+ const recipientBytes = Wallet.decodeBech32Address(recipientAddress);
295
+ const response = await this.requestProxy("faucetDrip", {
296
+ recipient: Array.from(recipientBytes),
297
+ amount
298
+ });
299
+ if (response.error) {
300
+ throw new Error(`Faucet request failed: ${response.error.message}`);
301
+ }
302
+ return response.result;
303
+ }
304
+ async submitTransaction(request) {
305
+ const response = await this.requestValidator("set_submitTransaction", {
306
+ transaction: request.transaction,
307
+ signature: Array.from(request.signature)
308
+ });
309
+ if (response.error) {
310
+ throw new Error(`Transaction submission failed: ${response.error.message}`);
311
+ }
312
+ const result = response.result;
313
+ return {
314
+ transaction_hash: new Uint8Array(result.transaction_hash),
315
+ validator: new Uint8Array(result.validator),
316
+ signature: new Uint8Array(result.signature)
317
+ };
318
+ }
319
+ async submitCertificate(request) {
320
+ const response = await this.requestValidator("set_submitTransactionCertificate", {
321
+ transaction: request.transaction,
322
+ signature: Array.from(request.signature),
323
+ validator_signatures: request.validator_signatures.map(([validator, signature]) => [Array.from(validator), Array.from(signature)])
324
+ });
325
+ if (response.error) {
326
+ throw new Error(`Certificate submission failed: ${response.error.message}`);
327
+ }
328
+ }
329
+ async executeTransfer(senderPrivateKey, recipient, amount, userData) {
330
+ const senderPublicKey = await (0, import_ed255192.getPublicKey)(senderPrivateKey);
331
+ const senderAddress = Wallet.encodeBech32Address(senderPublicKey);
332
+ const nonce = await this.getNextNonce(senderAddress);
333
+ const recipientBytes = Wallet.decodeBech32Address(recipient);
334
+ const transaction = {
335
+ sender: senderPublicKey,
336
+ nonce,
337
+ timestamp_nanos: BigInt(Date.now()) * 1000000n,
338
+ claim: {
339
+ Transfer: {
340
+ recipient: { FastSet: recipientBytes },
341
+ amount,
342
+ user_data: userData ?? null
343
+ }
344
+ }
345
+ };
346
+ const signature = await this.signTransaction(transaction, senderPrivateKey);
347
+ const submitResponse = await this.submitTransaction({
348
+ transaction,
349
+ signature
350
+ });
351
+ await this.submitCertificate({
352
+ transaction,
353
+ signature,
354
+ validator_signatures: [[submitResponse.validator, submitResponse.signature]]
355
+ });
356
+ return submitResponse.transaction_hash;
357
+ }
358
+ async submitClaim(senderPrivateKey, claim) {
359
+ const senderPublicKey = await (0, import_ed255192.getPublicKey)(senderPrivateKey);
360
+ const senderAddress = Wallet.encodeBech32Address(senderPublicKey);
361
+ const nonce = await this.getNextNonce(senderAddress);
362
+ const transaction = {
363
+ sender: senderPublicKey,
364
+ nonce,
365
+ timestamp_nanos: BigInt(Date.now()) * 1000000n,
366
+ claim
367
+ };
368
+ const signature = await this.signTransaction(transaction, senderPrivateKey);
369
+ const submitResponse = await this.submitTransaction({
370
+ transaction,
371
+ signature
372
+ });
373
+ await this.submitCertificate({
374
+ transaction,
375
+ signature,
376
+ validator_signatures: [[submitResponse.validator, submitResponse.signature]]
377
+ });
378
+ return submitResponse.transaction_hash;
379
+ }
380
+ async signTransaction(transaction, privateKey) {
381
+ return await TransactionSigner.signTransaction(transaction, privateKey);
382
+ }
383
+ async getTransactionStatus(txHash) {
384
+ try {
385
+ const response = await this.requestValidator("set_getTransactionStatus", {
386
+ hash: txHash
387
+ });
388
+ if (response.error) {
389
+ return null;
390
+ }
391
+ return response.result;
392
+ } catch (error) {
393
+ return null;
394
+ }
395
+ }
396
+ async getTransactionInfo(txHash) {
397
+ try {
398
+ const response = await this.requestValidator("set_getTransactionInfo", {
399
+ hash: txHash
400
+ });
401
+ if (response.error) {
402
+ return null;
403
+ }
404
+ return response.result;
405
+ } catch (error) {
406
+ return null;
407
+ }
408
+ }
409
+ async getNetworkInfo() {
410
+ try {
411
+ const response = await this.requestValidator("set_getNetworkInfo", {});
412
+ if (response.error) {
413
+ return null;
414
+ }
415
+ return response.result;
416
+ } catch (error) {
417
+ return null;
418
+ }
419
+ }
420
+ async requestValidator(method, params) {
421
+ return this.request(this.config.validatorUrl, method, params);
422
+ }
423
+ async requestProxy(method, params) {
424
+ return this.request(this.config.proxyUrl, method, params);
425
+ }
426
+ async request(url, method, params) {
427
+ const request = {
428
+ jsonrpc: "2.0",
429
+ id: 1,
430
+ method,
431
+ params
432
+ };
433
+ const response = await fetch(url, {
434
+ method: "POST",
435
+ headers: { "Content-Type": "application/json" },
436
+ body: JSON.stringify(request, this.jsonReplacer)
437
+ });
438
+ if (!response.ok) {
439
+ throw new Error(`HTTP request failed: ${response.statusText}`);
440
+ }
441
+ return response.json();
442
+ }
443
+ jsonReplacer(key, value) {
444
+ if (value instanceof Uint8Array) {
445
+ return Array.from(value);
446
+ }
447
+ return value;
448
+ }
449
+ };
450
+
451
+ // src/WarpFastsetDataLoader.ts
452
+ var WarpFastsetDataLoader = class {
453
+ constructor(config, chain) {
454
+ this.config = config;
455
+ this.chain = chain;
456
+ const validatorUrl = this.chain.defaultApiUrl;
457
+ const proxyUrl = this.chain.defaultApiUrl;
458
+ this.client = new FastsetClient({
459
+ validatorUrl,
460
+ proxyUrl
461
+ });
462
+ }
463
+ async getAccount(address) {
464
+ try {
465
+ const accountInfo = await this.client.getAccountInfo(address);
466
+ if (!accountInfo) {
467
+ return {
468
+ chain: this.chain.name,
469
+ address,
470
+ balance: BigInt(0)
471
+ };
472
+ }
473
+ return {
474
+ chain: this.chain.name,
475
+ address,
476
+ balance: BigInt(parseInt(accountInfo.balance, 16))
477
+ };
478
+ } catch (error) {
479
+ return {
480
+ chain: this.chain.name,
481
+ address,
482
+ balance: BigInt(0)
483
+ };
484
+ }
485
+ }
486
+ async getAccountAssets(address) {
487
+ try {
488
+ const account = await this.getAccount(address);
489
+ if (account.balance > 0) {
490
+ return [
491
+ {
492
+ chain: this.chain.name,
493
+ identifier: this.chain.nativeToken?.identifier || "SET",
494
+ name: this.chain.nativeToken?.name || "SET",
495
+ decimals: this.chain.nativeToken?.decimals || 6,
496
+ amount: account.balance,
497
+ logoUrl: this.chain.nativeToken?.logoUrl
498
+ }
499
+ ];
500
+ }
501
+ return [];
502
+ } catch (error) {
503
+ return [];
504
+ }
505
+ }
506
+ async getAccountActions(address, options) {
507
+ return [];
508
+ }
509
+ async getAccountInfo(address) {
510
+ try {
511
+ const accountInfo = await this.client.getAccountInfo(address);
512
+ if (!accountInfo) {
513
+ return null;
514
+ }
515
+ const balanceDecimal = parseInt(accountInfo.balance, 16);
516
+ return {
517
+ address,
518
+ balance: accountInfo.balance,
519
+ balanceDecimal,
520
+ nextNonce: accountInfo.next_nonce,
521
+ sequenceNumber: accountInfo.sequence_number
522
+ };
523
+ } catch (error) {
524
+ console.error("Error getting account info:", error);
525
+ return null;
526
+ }
527
+ }
528
+ async getTransactionInfo(txHash) {
529
+ try {
530
+ return {
531
+ hash: txHash,
532
+ hashHex: txHash.startsWith("0x") ? txHash.slice(2) : txHash,
533
+ status: "submitted",
534
+ details: {
535
+ hash: txHash,
536
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
537
+ }
538
+ };
539
+ } catch (error) {
540
+ console.error("Error getting transaction info:", error);
541
+ return null;
542
+ }
543
+ }
544
+ async checkTransferStatus(fromAddress, toAddress, amount) {
545
+ try {
546
+ const fromAccount = await this.getAccountInfo(fromAddress);
547
+ const toAccount = await this.getAccountInfo(toAddress);
548
+ if (!fromAccount || !toAccount) {
549
+ return false;
550
+ }
551
+ const transferAmount = parseInt(amount);
552
+ const fromBalance = fromAccount.balanceDecimal;
553
+ return fromBalance < transferAmount;
554
+ } catch (error) {
555
+ console.error("Error checking transfer status:", error);
556
+ return false;
557
+ }
558
+ }
559
+ async getAccountBalance(address) {
560
+ const accountInfo = await this.getAccountInfo(address);
561
+ if (!accountInfo) {
562
+ return null;
563
+ }
564
+ return {
565
+ balance: accountInfo.balance,
566
+ balanceDecimal: accountInfo.balanceDecimal
567
+ };
568
+ }
569
+ };
570
+
571
+ // src/WarpFastsetExecutor.ts
572
+ var import_warps2 = require("@vleap/warps");
573
+
574
+ // src/WarpFastsetSerializer.ts
575
+ var import_warps = require("@vleap/warps");
576
+ var WarpFastsetSerializer = class {
577
+ constructor() {
578
+ this.coreSerializer = new import_warps.WarpSerializer();
579
+ }
580
+ typedToString(value) {
581
+ if (typeof value === "string") {
582
+ return `string:${value}`;
583
+ }
584
+ if (typeof value === "number") {
585
+ return `number:${value}`;
586
+ }
587
+ if (typeof value === "boolean") {
588
+ return `boolean:${value}`;
589
+ }
590
+ if (typeof value === "bigint") {
591
+ return `biguint:${value.toString()}`;
592
+ }
593
+ if (Array.isArray(value)) {
594
+ const items = value.map((item) => this.typedToString(item)).join(",");
595
+ return `array:${items}`;
596
+ }
597
+ if (value === null) {
598
+ return "null:null";
599
+ }
600
+ if (value === void 0) {
601
+ return "undefined:undefined";
602
+ }
603
+ return `string:${String(value)}`;
604
+ }
605
+ typedToNative(value) {
606
+ if (typeof value === "string") {
607
+ return ["string", value];
608
+ }
609
+ if (typeof value === "number") {
610
+ return ["number", value];
611
+ }
612
+ if (typeof value === "boolean") {
613
+ return ["boolean", value];
614
+ }
615
+ if (typeof value === "bigint") {
616
+ return ["biguint", value.toString()];
617
+ }
618
+ return ["string", String(value)];
619
+ }
620
+ nativeToTyped(type, value) {
621
+ switch (type) {
622
+ case "string":
623
+ return String(value);
624
+ case "number":
625
+ return Number(value);
626
+ case "boolean":
627
+ return Boolean(value);
628
+ case "biguint":
629
+ return BigInt(value);
630
+ case "address":
631
+ return String(value);
632
+ case "hex":
633
+ return String(value);
634
+ default:
635
+ return String(value);
636
+ }
637
+ }
638
+ nativeToType(type) {
639
+ switch (type) {
640
+ case "string":
641
+ return "string";
642
+ case "number":
643
+ return "number";
644
+ case "boolean":
645
+ return "boolean";
646
+ case "biguint":
647
+ return "biguint";
648
+ case "address":
649
+ return "address";
650
+ case "hex":
651
+ return "hex";
652
+ default:
653
+ return "string";
654
+ }
655
+ }
656
+ stringToTyped(value) {
657
+ const colonIndex = value.indexOf(":");
658
+ if (colonIndex === -1) {
659
+ return value;
660
+ }
661
+ const type = value.substring(0, colonIndex);
662
+ const stringValue = value.substring(colonIndex + 1);
663
+ switch (type) {
664
+ case "string":
665
+ return stringValue;
666
+ case "number":
667
+ return Number(stringValue);
668
+ case "boolean":
669
+ return stringValue === "true";
670
+ case "biguint":
671
+ return BigInt(stringValue);
672
+ case "array":
673
+ return stringValue.split(",").map((item) => this.stringToTyped(item));
674
+ case "null":
675
+ return null;
676
+ case "undefined":
677
+ return void 0;
678
+ default:
679
+ return stringValue;
680
+ }
681
+ }
682
+ };
683
+
684
+ // src/WarpFastsetExecutor.ts
685
+ var WarpFastsetExecutor = class {
686
+ constructor(config, chain) {
687
+ this.config = config;
688
+ this.chain = chain;
689
+ this.serializer = new WarpFastsetSerializer();
690
+ const validatorUrl = (0, import_warps2.getProviderUrl)(this.config, chain.name, this.config.env, this.chain.defaultApiUrl);
691
+ const proxyUrl = (0, import_warps2.getProviderUrl)(this.config, chain.name, this.config.env, this.chain.defaultApiUrl);
692
+ this.fastsetClient = new FastsetClient({
693
+ validatorUrl,
694
+ proxyUrl
695
+ });
696
+ }
697
+ async createTransaction(executable) {
698
+ const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
699
+ switch (action.type) {
700
+ case "transfer":
701
+ return this.createTransferTransaction(executable);
702
+ case "contract":
703
+ return this.createContractCallTransaction(executable);
704
+ case "query":
705
+ throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeQuery instead");
706
+ case "collect":
707
+ throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeCollect instead");
708
+ default:
709
+ throw new Error(`WarpFastsetExecutor: Invalid action type (${action.type})`);
710
+ }
711
+ }
712
+ async createTransferTransaction(executable) {
713
+ const userWallet = this.config.user?.wallets?.[executable.chain.name];
714
+ if (!userWallet) throw new Error("WarpFastsetExecutor: createTransfer - user address not set");
715
+ if (!this.isValidFastsetAddress(executable.destination)) {
716
+ throw new Error(`WarpFastsetExecutor: Invalid destination address: ${executable.destination}`);
717
+ }
718
+ if (executable.value < 0) {
719
+ throw new Error(`WarpFastsetExecutor: Transfer value cannot be negative: ${executable.value}`);
720
+ }
721
+ const recipientAddress = this.fromBase64(executable.destination);
722
+ const amount = this.normalizeAmount(executable.value.toString());
723
+ const userData = executable.data ? this.fromBase64(this.serializer.stringToTyped(executable.data)) : void 0;
724
+ return {
725
+ type: "fastset-transfer",
726
+ recipient: recipientAddress,
727
+ amount,
728
+ userData,
729
+ chain: executable.chain
730
+ };
731
+ }
732
+ async createContractCallTransaction(executable) {
733
+ const userWallet = this.config.user?.wallets?.[executable.chain.name];
734
+ if (!userWallet) throw new Error("WarpFastsetExecutor: createContractCall - user address not set");
735
+ const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
736
+ if (!action || !("func" in action) || !action.func) {
737
+ throw new Error("WarpFastsetExecutor: Contract action must have a function name");
738
+ }
739
+ if (!this.isValidFastsetAddress(executable.destination)) {
740
+ throw new Error(`WarpFastsetExecutor: Invalid contract address: ${executable.destination}`);
741
+ }
742
+ if (executable.value < 0) {
743
+ throw new Error(`WarpFastsetExecutor: Contract call value cannot be negative: ${executable.value}`);
744
+ }
745
+ try {
746
+ const contractAddress = this.fromBase64(executable.destination);
747
+ const encodedData = this.encodeFunctionData(action.func, executable.args);
748
+ return {
749
+ type: "fastset-contract-call",
750
+ contract: contractAddress,
751
+ function: action.func,
752
+ data: encodedData,
753
+ value: executable.value,
754
+ chain: executable.chain
755
+ };
756
+ } catch (error) {
757
+ throw new Error(`WarpFastsetExecutor: Failed to encode function data for ${action.func}: ${error}`);
758
+ }
759
+ }
760
+ async executeQuery(executable) {
761
+ const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
762
+ if (action.type !== "query") {
763
+ throw new Error(`WarpFastsetExecutor: Invalid action type for executeQuery: ${action.type}`);
764
+ }
765
+ if (!action.func) {
766
+ throw new Error("WarpFastsetExecutor: Query action must have a function name");
767
+ }
768
+ if (!this.isValidFastsetAddress(executable.destination)) {
769
+ throw new Error(`WarpFastsetExecutor: Invalid contract address for query: ${executable.destination}`);
770
+ }
771
+ try {
772
+ const contractAddress = this.fromBase64(executable.destination);
773
+ const result = await this.executeFastsetQuery(contractAddress, action.func, executable.args);
774
+ return {
775
+ success: true,
776
+ result,
777
+ chain: executable.chain
778
+ };
779
+ } catch (error) {
780
+ return {
781
+ success: false,
782
+ error: error instanceof Error ? error.message : String(error),
783
+ chain: executable.chain
784
+ };
785
+ }
786
+ }
787
+ async preprocessInput(chain, input, type, value) {
788
+ return value;
789
+ }
790
+ async signMessage(message, privateKey) {
791
+ throw new Error("Not implemented");
792
+ }
793
+ async executeTransfer(executable) {
794
+ const userWallet = this.config.user?.wallets?.[executable.chain.name];
795
+ if (!userWallet) throw new Error("WarpFastsetExecutor: executeTransfer - user wallet not set");
796
+ const transaction = await this.createTransferTransaction(executable);
797
+ return {
798
+ success: true,
799
+ transaction,
800
+ chain: executable.chain.name,
801
+ message: "Transaction created successfully. Use executeTransferWithKey to execute with private key."
802
+ };
803
+ }
804
+ async executeTransferWithKey(executable, privateKey) {
805
+ const userWallet = this.config.user?.wallets?.[executable.chain.name];
806
+ if (!userWallet) throw new Error("WarpFastsetExecutor: executeTransfer - user wallet not set");
807
+ const transaction = await this.createTransferTransaction(executable);
808
+ const privateKeyBytes = this.fromBase64(privateKey);
809
+ const transactionHash = await this.fastsetClient.executeTransfer(
810
+ privateKeyBytes,
811
+ transaction.recipient,
812
+ transaction.amount,
813
+ transaction.userData
814
+ );
815
+ return {
816
+ success: true,
817
+ transactionHash: Array.from(transactionHash),
818
+ chain: executable.chain.name
819
+ };
820
+ }
821
+ encodeFunctionData(functionName, args) {
822
+ return JSON.stringify({
823
+ function: functionName,
824
+ arguments: args
825
+ });
826
+ }
827
+ async executeFastsetQuery(contractAddress, functionName, args) {
828
+ const validatorUrl = (0, import_warps2.getProviderUrl)(this.config, this.chain.name, this.config.env, this.chain.defaultApiUrl);
829
+ const response = await fetch(`${validatorUrl}/query`, {
830
+ method: "POST",
831
+ headers: {
832
+ "Content-Type": "application/json"
833
+ },
834
+ body: JSON.stringify({
835
+ contract: Array.from(contractAddress),
836
+ function: functionName,
837
+ arguments: args
838
+ })
839
+ });
840
+ if (!response.ok) {
841
+ throw new Error(`Fastset query failed: ${response.statusText}`);
842
+ }
843
+ return response.json();
844
+ }
845
+ isValidFastsetAddress(address) {
846
+ if (typeof address !== "string" || address.length === 0) {
847
+ return false;
848
+ }
849
+ if (address.startsWith("fs") || address.startsWith("pi")) {
850
+ return true;
851
+ }
852
+ try {
853
+ const decoded = this.fromBase64(address);
854
+ return decoded.length === 32;
855
+ } catch {
856
+ return false;
857
+ }
858
+ }
859
+ fromBase64(base64) {
860
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
861
+ }
862
+ normalizeAmount(amount) {
863
+ return amount.startsWith("0x") ? amount.slice(2) : amount;
864
+ }
865
+ };
866
+
867
+ // src/WarpFastsetExplorer.ts
868
+ var WarpFastsetExplorer = class {
869
+ constructor(_chainInfo, _config) {
870
+ this._chainInfo = _chainInfo;
871
+ this._config = _config;
872
+ this.explorerUrl = "https://explorer.fastset.xyz";
873
+ }
874
+ getAccountUrl(address) {
875
+ return `${this.explorerUrl}/account/${address}`;
876
+ }
877
+ getTransactionUrl(hash) {
878
+ return `${this.explorerUrl}/transaction/${hash}`;
879
+ }
880
+ getAssetUrl(identifier) {
881
+ return `${this.explorerUrl}/asset/${identifier}`;
882
+ }
883
+ getContractUrl(address) {
884
+ return `${this.explorerUrl}/account/${address}`;
885
+ }
886
+ };
887
+
888
+ // src/WarpFastsetResults.ts
889
+ var import_warps3 = require("@vleap/warps");
890
+ var WarpFastsetResults = class {
891
+ constructor(config, chain) {
892
+ this.config = config;
893
+ this.chain = chain;
894
+ this.serializer = new WarpFastsetSerializer();
895
+ }
896
+ async getTransactionExecutionResults(warp, tx) {
897
+ const success = this.isTransactionSuccessful(tx);
898
+ const transactionHash = this.extractTransactionHash(tx);
899
+ const blockNumber = this.extractBlockNumber(tx);
900
+ const timestamp = this.extractTimestamp(tx);
901
+ return {
902
+ success,
903
+ warp,
904
+ action: 0,
905
+ user: this.config.user?.wallets?.[this.chain.name] || null,
906
+ txHash: transactionHash,
907
+ tx,
908
+ next: null,
909
+ values: [transactionHash, blockNumber, timestamp],
910
+ valuesRaw: [transactionHash, blockNumber, timestamp],
911
+ results: {},
912
+ messages: {}
913
+ };
914
+ }
915
+ async extractQueryResults(warp, typedValues, actionIndex, inputs) {
916
+ const values = typedValues.map((t) => this.serializer.typedToString(t));
917
+ const valuesRaw = typedValues.map((t) => this.serializer.typedToNative(t)[1]);
918
+ let results = {};
919
+ if (!warp.results) return { values, results };
920
+ const getNestedValue = (path) => {
921
+ const match = path.match(/^out\[(\d+)\]$/);
922
+ if (match) {
923
+ const index = parseInt(match[1]) - 1;
924
+ return valuesRaw[index];
925
+ }
926
+ const indices = path.split(".").slice(1).map((i) => parseInt(i) - 1);
927
+ if (indices.length === 0) return void 0;
928
+ let value = valuesRaw[indices[0]];
929
+ for (let i = 1; i < indices.length; i++) {
930
+ if (value === void 0 || value === null) return void 0;
931
+ value = value[indices[i]];
932
+ }
933
+ return value;
934
+ };
935
+ for (const [key, path] of Object.entries(warp.results)) {
936
+ if (path.startsWith(import_warps3.WarpConstants.Transform.Prefix)) continue;
937
+ const currentActionIndex = (0, import_warps3.parseResultsOutIndex)(path);
938
+ if (currentActionIndex !== null && currentActionIndex !== actionIndex) {
939
+ results[key] = null;
940
+ continue;
941
+ }
942
+ if (path.startsWith("out.") || path === "out" || path.startsWith("out[")) {
943
+ const value = getNestedValue(path);
944
+ results[key] = value || null;
945
+ } else {
946
+ results[key] = path;
947
+ }
948
+ }
949
+ return { values, results: await (0, import_warps3.evaluateResultsCommon)(warp, results, actionIndex, inputs, this.config.transform?.runner) };
950
+ }
951
+ isTransactionSuccessful(tx) {
952
+ if (!tx) return false;
953
+ if (tx.success === false) return false;
954
+ if (tx.success === true) return true;
955
+ if (tx.status === "success") return true;
956
+ if (tx.status === 1) return true;
957
+ if (tx.result && tx.result.success === true) return true;
958
+ return false;
959
+ }
960
+ extractTransactionHash(tx) {
961
+ if (!tx) return "";
962
+ return tx.transaction_hash || tx.transactionHash || tx.hash || tx.result && tx.result.transaction_hash || "";
963
+ }
964
+ extractBlockNumber(tx) {
965
+ if (!tx) return "0";
966
+ return tx.block_number?.toString() || tx.blockNumber?.toString() || tx.result && tx.result.block_number?.toString() || "0";
967
+ }
968
+ extractTimestamp(tx) {
969
+ if (!tx) return "0";
970
+ return tx.timestamp?.toString() || tx.timestamp_nanos?.toString() || tx.result && tx.result.timestamp?.toString() || Date.now().toString();
971
+ }
972
+ };
973
+
974
+ // src/main.ts
975
+ var NativeTokenSet = {
976
+ chain: import_warps4.WarpChainName.Fastset,
977
+ identifier: "SET",
978
+ name: "SET",
979
+ decimals: 6,
980
+ logoUrl: "https://vleap.ai/images/tokens/set.svg"
981
+ };
982
+ function createFastsetAdapter(chainName, chainPrefix, chainInfos) {
983
+ return (config, fallback) => {
984
+ const chainInfo = chainInfos[config.env];
985
+ if (!chainInfo) throw new Error(`FastsetAdapter: chain info not found for chain ${chainName}`);
986
+ if (!fallback) throw new Error("Fastset adapter requires a fallback adapter");
987
+ return {
988
+ chain: chainName,
989
+ chainInfo,
990
+ prefix: chainPrefix,
991
+ builder: () => fallback.builder(),
992
+ executor: new WarpFastsetExecutor(config, chainInfo),
993
+ results: new WarpFastsetResults(config, chainInfo),
994
+ serializer: new WarpFastsetSerializer(),
995
+ registry: fallback.registry,
996
+ explorer: new WarpFastsetExplorer(chainInfo, config),
997
+ abiBuilder: () => fallback.abiBuilder(),
998
+ brandBuilder: () => fallback.brandBuilder(),
999
+ dataLoader: new WarpFastsetDataLoader(config, chainInfo)
1000
+ };
1001
+ };
1002
+ }
1003
+ var getFastsetAdapter = createFastsetAdapter(import_warps4.WarpChainName.Fastset, "fastset", {
1004
+ mainnet: {
1005
+ name: import_warps4.WarpChainName.Fastset,
1006
+ displayName: "FastSet",
1007
+ chainId: "1",
1008
+ blockTime: 1e3,
1009
+ addressHrp: "set",
1010
+ defaultApiUrl: "https://rpc.fastset.xyz",
1011
+ nativeToken: NativeTokenSet
1012
+ },
1013
+ testnet: {
1014
+ name: import_warps4.WarpChainName.Fastset,
1015
+ displayName: "FastSet Testnet",
1016
+ chainId: "testnet",
1017
+ blockTime: 1e3,
1018
+ addressHrp: "set",
1019
+ defaultApiUrl: "https://rpc.fastset.xyz",
1020
+ nativeToken: NativeTokenSet
1021
+ },
1022
+ devnet: {
1023
+ name: import_warps4.WarpChainName.Fastset,
1024
+ displayName: "FastSet Devnet",
1025
+ chainId: "devnet",
1026
+ blockTime: 1e3,
1027
+ addressHrp: "set",
1028
+ defaultApiUrl: "https://rpc.fastset.xyz",
1029
+ nativeToken: NativeTokenSet
1030
+ }
1031
+ });
1032
+ // Annotate the CommonJS export names for ESM import in node:
1033
+ 0 && (module.exports = {
1034
+ Address,
1035
+ Amount,
1036
+ BcsTransaction,
1037
+ Bytes32,
1038
+ Claim,
1039
+ ClaimType,
1040
+ FastsetClient,
1041
+ NativeTokenSet,
1042
+ Nonce,
1043
+ PublicKey,
1044
+ Transaction,
1045
+ Transfer,
1046
+ TransferClaim,
1047
+ UserData,
1048
+ Wallet,
1049
+ WarpFastsetConstants,
1050
+ WarpFastsetDataLoader,
1051
+ WarpFastsetExecutor,
1052
+ WarpFastsetExplorer,
1053
+ WarpFastsetResults,
1054
+ WarpFastsetSerializer,
1055
+ getFastsetAdapter
1056
+ });
1057
+ //# sourceMappingURL=index.js.map