@vleap/warps-adapter-fastset 0.1.0-alpha.3 → 0.1.0-alpha.31

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 CHANGED
@@ -1,11 +1,14 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
9
  var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
10
+ for (var name2 in all)
11
+ __defProp(target, name2, { get: all[name2], enumerable: true });
9
12
  };
10
13
  var __copyProps = (to, from, except, desc) => {
11
14
  if (from && typeof from === "object" || typeof from === "function") {
@@ -15,486 +18,1700 @@ var __copyProps = (to, from, except, desc) => {
15
18
  }
16
19
  return to;
17
20
  };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
18
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
31
 
20
32
  // src/index.ts
21
33
  var index_exports = {};
22
34
  __export(index_exports, {
23
- Address: () => Address,
24
- Amount: () => Amount,
25
- Bytes32: () => Bytes32,
26
- ClaimType: () => ClaimType,
27
- FastsetClient: () => FastsetClient,
28
- Nonce: () => Nonce,
29
- PublicKey: () => PublicKey,
30
- Transaction: () => Transaction,
31
- Transfer: () => Transfer,
32
- UserData: () => UserData,
33
- WarpFastsetBuilder: () => WarpFastsetBuilder,
34
- WarpFastsetConstants: () => WarpFastsetConstants,
35
+ NativeTokenSet: () => NativeTokenSet,
35
36
  WarpFastsetExecutor: () => WarpFastsetExecutor,
36
- WarpFastsetExplorer: () => WarpFastsetExplorer,
37
- WarpFastsetResults: () => WarpFastsetResults,
38
- WarpFastsetSerializer: () => WarpFastsetSerializer,
39
- decimalToHex: () => decimalToHex,
40
- fromBase64: () => fromBase64,
41
- getFastsetAdapter: () => getFastsetAdapter,
42
- hexToDecimal: () => hexToDecimal2,
43
- isValidFastsetAddress: () => isValidFastsetAddress,
44
- normalizeAmount: () => normalizeAmount,
45
- toBase64String: () => toBase64String,
46
- toHexString: () => toHexString,
47
- validateAmount: () => validateAmount,
48
- validatePrivateKey: () => validatePrivateKey,
49
- validatePublicKey: () => validatePublicKey
37
+ WarpFastsetWallet: () => WarpFastsetWallet,
38
+ getFastsetAdapter: () => getFastsetAdapter
50
39
  });
51
40
  module.exports = __toCommonJS(index_exports);
52
41
 
53
- // src/constants.ts
54
- var WarpFastsetConstants = {
55
- Pi: {
56
- Identifier: "PI",
57
- DisplayName: "Pi",
58
- Decimals: 18
59
- },
60
- GasLimit: {
61
- Default: 21e3,
62
- ContractCall: 1e5,
63
- ContractDeploy: 5e5,
64
- Transfer: 21e3,
65
- Approve: 46e3,
66
- Swap: 2e5
67
- },
68
- GasPrice: {
69
- Default: "20000000000",
70
- // 20 gwei
71
- Low: "10000000000",
72
- // 10 gwei
73
- Medium: "20000000000",
74
- // 20 gwei
75
- High: "50000000000"
76
- // 50 gwei
77
- },
78
- Validation: {
79
- AddressLength: 42,
80
- HexPrefix: "0x",
81
- MinGasLimit: 21e3,
82
- MaxGasLimit: 3e7
83
- },
84
- Timeouts: {
85
- DefaultRpcTimeout: 3e4,
86
- // 30 seconds
87
- GasEstimationTimeout: 1e4,
88
- // 10 seconds
89
- QueryTimeout: 15e3
90
- // 15 seconds
42
+ // src/main.ts
43
+ var import_warps6 = require("@vleap/warps");
44
+
45
+ // src/helpers/encode.ts
46
+ var encoder = new TextEncoder();
47
+ var decoder = new TextDecoder();
48
+ function uint8ArrayToHex(uint8Array) {
49
+ return Buffer.from(uint8Array).toString("hex");
50
+ }
51
+ function hexToUint8Array(hex) {
52
+ return new Uint8Array(Buffer.from(hex, "hex"));
53
+ }
54
+ function stringToUint8Array(str) {
55
+ return new Uint8Array(Buffer.from(str, "utf8"));
56
+ }
57
+
58
+ // src/helpers/general.ts
59
+ var import_warps = require("@vleap/warps");
60
+
61
+ // src/sdk/FastsetClient.ts
62
+ var bech32 = __toESM(require("bech32"), 1);
63
+
64
+ // ../../node_modules/@scure/base/lib/esm/index.js
65
+ function isBytes(a) {
66
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
67
+ }
68
+ function isArrayOf(isString, arr) {
69
+ if (!Array.isArray(arr))
70
+ return false;
71
+ if (arr.length === 0)
72
+ return true;
73
+ if (isString) {
74
+ return arr.every((item) => typeof item === "string");
75
+ } else {
76
+ return arr.every((item) => Number.isSafeInteger(item));
77
+ }
78
+ }
79
+ function astr(label, input) {
80
+ if (typeof input !== "string")
81
+ throw new Error(`${label}: string expected`);
82
+ return true;
83
+ }
84
+ function anumber(n) {
85
+ if (!Number.isSafeInteger(n))
86
+ throw new Error(`invalid integer: ${n}`);
87
+ }
88
+ function aArr(input) {
89
+ if (!Array.isArray(input))
90
+ throw new Error("array expected");
91
+ }
92
+ function astrArr(label, input) {
93
+ if (!isArrayOf(true, input))
94
+ throw new Error(`${label}: array of strings expected`);
95
+ }
96
+ function anumArr(label, input) {
97
+ if (!isArrayOf(false, input))
98
+ throw new Error(`${label}: array of numbers expected`);
99
+ }
100
+ // @__NO_SIDE_EFFECTS__
101
+ function chain(...args) {
102
+ const id2 = (a) => a;
103
+ const wrap = (a, b) => (c) => a(b(c));
104
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id2);
105
+ const decode = args.map((x) => x.decode).reduce(wrap, id2);
106
+ return { encode, decode };
107
+ }
108
+ // @__NO_SIDE_EFFECTS__
109
+ function alphabet(letters) {
110
+ const lettersA = typeof letters === "string" ? letters.split("") : letters;
111
+ const len = lettersA.length;
112
+ astrArr("alphabet", lettersA);
113
+ const indexes = new Map(lettersA.map((l, i) => [l, i]));
114
+ return {
115
+ encode: (digits) => {
116
+ aArr(digits);
117
+ return digits.map((i) => {
118
+ if (!Number.isSafeInteger(i) || i < 0 || i >= len)
119
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
120
+ return lettersA[i];
121
+ });
122
+ },
123
+ decode: (input) => {
124
+ aArr(input);
125
+ return input.map((letter) => {
126
+ astr("alphabet.decode", letter);
127
+ const i = indexes.get(letter);
128
+ if (i === void 0)
129
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
130
+ return i;
131
+ });
132
+ }
133
+ };
134
+ }
135
+ // @__NO_SIDE_EFFECTS__
136
+ function join(separator = "") {
137
+ astr("join", separator);
138
+ return {
139
+ encode: (from) => {
140
+ astrArr("join.decode", from);
141
+ return from.join(separator);
142
+ },
143
+ decode: (to) => {
144
+ astr("join.decode", to);
145
+ return to.split(separator);
146
+ }
147
+ };
148
+ }
149
+ function convertRadix(data, from, to) {
150
+ if (from < 2)
151
+ throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
152
+ if (to < 2)
153
+ throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
154
+ aArr(data);
155
+ if (!data.length)
156
+ return [];
157
+ let pos = 0;
158
+ const res = [];
159
+ const digits = Array.from(data, (d) => {
160
+ anumber(d);
161
+ if (d < 0 || d >= from)
162
+ throw new Error(`invalid integer: ${d}`);
163
+ return d;
164
+ });
165
+ const dlen = digits.length;
166
+ while (true) {
167
+ let carry = 0;
168
+ let done = true;
169
+ for (let i = pos; i < dlen; i++) {
170
+ const digit = digits[i];
171
+ const fromCarry = from * carry;
172
+ const digitBase = fromCarry + digit;
173
+ if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) {
174
+ throw new Error("convertRadix: carry overflow");
175
+ }
176
+ const div = digitBase / to;
177
+ carry = digitBase % to;
178
+ const rounded = Math.floor(div);
179
+ digits[i] = rounded;
180
+ if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
181
+ throw new Error("convertRadix: carry overflow");
182
+ if (!done)
183
+ continue;
184
+ else if (!rounded)
185
+ pos = i;
186
+ else
187
+ done = false;
188
+ }
189
+ res.push(carry);
190
+ if (done)
191
+ break;
192
+ }
193
+ for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
194
+ res.push(0);
195
+ return res.reverse();
196
+ }
197
+ // @__NO_SIDE_EFFECTS__
198
+ function radix(num) {
199
+ anumber(num);
200
+ const _256 = 2 ** 8;
201
+ return {
202
+ encode: (bytes) => {
203
+ if (!isBytes(bytes))
204
+ throw new Error("radix.encode input should be Uint8Array");
205
+ return convertRadix(Array.from(bytes), _256, num);
206
+ },
207
+ decode: (digits) => {
208
+ anumArr("radix.decode", digits);
209
+ return Uint8Array.from(convertRadix(digits, num, _256));
210
+ }
211
+ };
212
+ }
213
+ var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join(""));
214
+ var base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
215
+
216
+ // ../../node_modules/@mysten/utils/dist/esm/b58.js
217
+ var toBase58 = (buffer) => base58.encode(buffer);
218
+ var fromBase58 = (str) => base58.decode(str);
219
+
220
+ // ../../node_modules/@mysten/utils/dist/esm/b64.js
221
+ function fromBase64(base64String) {
222
+ return Uint8Array.from(atob(base64String), (char) => char.charCodeAt(0));
223
+ }
224
+ var CHUNK_SIZE = 8192;
225
+ function toBase64(bytes) {
226
+ if (bytes.length < CHUNK_SIZE) {
227
+ return btoa(String.fromCharCode(...bytes));
228
+ }
229
+ let output = "";
230
+ for (var i = 0; i < bytes.length; i += CHUNK_SIZE) {
231
+ const chunk = bytes.slice(i, i + CHUNK_SIZE);
232
+ output += String.fromCharCode(...chunk);
233
+ }
234
+ return btoa(output);
235
+ }
236
+
237
+ // ../../node_modules/@mysten/utils/dist/esm/hex.js
238
+ function fromHex(hexStr) {
239
+ const normalized = hexStr.startsWith("0x") ? hexStr.slice(2) : hexStr;
240
+ const padded = normalized.length % 2 === 0 ? normalized : `0${normalized}`;
241
+ const intArr = padded.match(/[0-9a-fA-F]{2}/g)?.map((byte) => parseInt(byte, 16)) ?? [];
242
+ if (intArr.length !== padded.length / 2) {
243
+ throw new Error(`Invalid hex string ${hexStr}`);
244
+ }
245
+ return Uint8Array.from(intArr);
246
+ }
247
+ function toHex(bytes) {
248
+ return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
249
+ }
250
+
251
+ // ../../node_modules/@mysten/bcs/dist/esm/uleb.js
252
+ function ulebEncode(num) {
253
+ const arr = [];
254
+ let len = 0;
255
+ if (num === 0) {
256
+ return [0];
257
+ }
258
+ while (num > 0) {
259
+ arr[len] = num & 127;
260
+ if (num >>= 7) {
261
+ arr[len] |= 128;
262
+ }
263
+ len += 1;
264
+ }
265
+ return arr;
266
+ }
267
+ function ulebDecode(arr) {
268
+ let total = 0;
269
+ let shift = 0;
270
+ let len = 0;
271
+ while (true) {
272
+ const byte = arr[len];
273
+ len += 1;
274
+ total |= (byte & 127) << shift;
275
+ if ((byte & 128) === 0) {
276
+ break;
277
+ }
278
+ shift += 7;
279
+ }
280
+ return {
281
+ value: total,
282
+ length: len
283
+ };
284
+ }
285
+
286
+ // ../../node_modules/@mysten/bcs/dist/esm/reader.js
287
+ var BcsReader = class {
288
+ /**
289
+ * @param {Uint8Array} data Data to use as a buffer.
290
+ */
291
+ constructor(data) {
292
+ this.bytePosition = 0;
293
+ this.dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
294
+ }
295
+ /**
296
+ * Shift current cursor position by `bytes`.
297
+ *
298
+ * @param {Number} bytes Number of bytes to
299
+ * @returns {this} Self for possible chaining.
300
+ */
301
+ shift(bytes) {
302
+ this.bytePosition += bytes;
303
+ return this;
304
+ }
305
+ /**
306
+ * Read U8 value from the buffer and shift cursor by 1.
307
+ * @returns
308
+ */
309
+ read8() {
310
+ const value = this.dataView.getUint8(this.bytePosition);
311
+ this.shift(1);
312
+ return value;
313
+ }
314
+ /**
315
+ * Read U16 value from the buffer and shift cursor by 2.
316
+ * @returns
317
+ */
318
+ read16() {
319
+ const value = this.dataView.getUint16(this.bytePosition, true);
320
+ this.shift(2);
321
+ return value;
322
+ }
323
+ /**
324
+ * Read U32 value from the buffer and shift cursor by 4.
325
+ * @returns
326
+ */
327
+ read32() {
328
+ const value = this.dataView.getUint32(this.bytePosition, true);
329
+ this.shift(4);
330
+ return value;
331
+ }
332
+ /**
333
+ * Read U64 value from the buffer and shift cursor by 8.
334
+ * @returns
335
+ */
336
+ read64() {
337
+ const value1 = this.read32();
338
+ const value2 = this.read32();
339
+ const result = value2.toString(16) + value1.toString(16).padStart(8, "0");
340
+ return BigInt("0x" + result).toString(10);
341
+ }
342
+ /**
343
+ * Read U128 value from the buffer and shift cursor by 16.
344
+ */
345
+ read128() {
346
+ const value1 = BigInt(this.read64());
347
+ const value2 = BigInt(this.read64());
348
+ const result = value2.toString(16) + value1.toString(16).padStart(16, "0");
349
+ return BigInt("0x" + result).toString(10);
350
+ }
351
+ /**
352
+ * Read U128 value from the buffer and shift cursor by 32.
353
+ * @returns
354
+ */
355
+ read256() {
356
+ const value1 = BigInt(this.read128());
357
+ const value2 = BigInt(this.read128());
358
+ const result = value2.toString(16) + value1.toString(16).padStart(32, "0");
359
+ return BigInt("0x" + result).toString(10);
360
+ }
361
+ /**
362
+ * Read `num` number of bytes from the buffer and shift cursor by `num`.
363
+ * @param num Number of bytes to read.
364
+ */
365
+ readBytes(num) {
366
+ const start = this.bytePosition + this.dataView.byteOffset;
367
+ const value = new Uint8Array(this.dataView.buffer, start, num);
368
+ this.shift(num);
369
+ return value;
370
+ }
371
+ /**
372
+ * Read ULEB value - an integer of varying size. Used for enum indexes and
373
+ * vector lengths.
374
+ * @returns {Number} The ULEB value.
375
+ */
376
+ readULEB() {
377
+ const start = this.bytePosition + this.dataView.byteOffset;
378
+ const buffer = new Uint8Array(this.dataView.buffer, start);
379
+ const { value, length } = ulebDecode(buffer);
380
+ this.shift(length);
381
+ return value;
382
+ }
383
+ /**
384
+ * Read a BCS vector: read a length and then apply function `cb` X times
385
+ * where X is the length of the vector, defined as ULEB in BCS bytes.
386
+ * @param cb Callback to process elements of vector.
387
+ * @returns {Array<Any>} Array of the resulting values, returned by callback.
388
+ */
389
+ readVec(cb) {
390
+ const length = this.readULEB();
391
+ const result = [];
392
+ for (let i = 0; i < length; i++) {
393
+ result.push(cb(this, i, length));
394
+ }
395
+ return result;
91
396
  }
92
397
  };
93
398
 
94
- // src/WarpFastsetBuilder.ts
95
- var WarpFastsetBuilder = class {
96
- constructor(config) {
97
- this.config = config;
98
- this.warp = {};
99
- this.actions = [];
399
+ // ../../node_modules/@mysten/bcs/dist/esm/utils.js
400
+ function encodeStr(data, encoding) {
401
+ switch (encoding) {
402
+ case "base58":
403
+ return toBase58(data);
404
+ case "base64":
405
+ return toBase64(data);
406
+ case "hex":
407
+ return toHex(data);
408
+ default:
409
+ throw new Error("Unsupported encoding, supported values are: base64, hex");
100
410
  }
101
- async createFromRaw(encoded) {
102
- try {
103
- const parsed = JSON.parse(encoded);
104
- this.warp = parsed;
105
- this.actions = parsed.actions || [];
106
- return this.build();
107
- } catch (error) {
108
- throw new Error(`Failed to parse Fastset warp data: ${error}`);
411
+ }
412
+
413
+ // ../../node_modules/@mysten/bcs/dist/esm/writer.js
414
+ var BcsWriter = class {
415
+ constructor({
416
+ initialSize = 1024,
417
+ maxSize = Infinity,
418
+ allocateSize = 1024
419
+ } = {}) {
420
+ this.bytePosition = 0;
421
+ this.size = initialSize;
422
+ this.maxSize = maxSize;
423
+ this.allocateSize = allocateSize;
424
+ this.dataView = new DataView(new ArrayBuffer(initialSize));
425
+ }
426
+ ensureSizeOrGrow(bytes) {
427
+ const requiredSize = this.bytePosition + bytes;
428
+ if (requiredSize > this.size) {
429
+ const nextSize = Math.min(this.maxSize, this.size + this.allocateSize);
430
+ if (requiredSize > nextSize) {
431
+ throw new Error(
432
+ `Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${requiredSize}`
433
+ );
434
+ }
435
+ this.size = nextSize;
436
+ const nextBuffer = new ArrayBuffer(this.size);
437
+ new Uint8Array(nextBuffer).set(new Uint8Array(this.dataView.buffer));
438
+ this.dataView = new DataView(nextBuffer);
109
439
  }
110
440
  }
111
- setTitle(title) {
112
- this.warp.title = title;
441
+ /**
442
+ * Shift current cursor position by `bytes`.
443
+ *
444
+ * @param {Number} bytes Number of bytes to
445
+ * @returns {this} Self for possible chaining.
446
+ */
447
+ shift(bytes) {
448
+ this.bytePosition += bytes;
113
449
  return this;
114
450
  }
115
- setDescription(description) {
116
- this.warp.description = description;
451
+ /**
452
+ * Write a U8 value into a buffer and shift cursor position by 1.
453
+ * @param {Number} value Value to write.
454
+ * @returns {this}
455
+ */
456
+ write8(value) {
457
+ this.ensureSizeOrGrow(1);
458
+ this.dataView.setUint8(this.bytePosition, Number(value));
459
+ return this.shift(1);
460
+ }
461
+ /**
462
+ * Write a U16 value into a buffer and shift cursor position by 2.
463
+ * @param {Number} value Value to write.
464
+ * @returns {this}
465
+ */
466
+ write16(value) {
467
+ this.ensureSizeOrGrow(2);
468
+ this.dataView.setUint16(this.bytePosition, Number(value), true);
469
+ return this.shift(2);
470
+ }
471
+ /**
472
+ * Write a U32 value into a buffer and shift cursor position by 4.
473
+ * @param {Number} value Value to write.
474
+ * @returns {this}
475
+ */
476
+ write32(value) {
477
+ this.ensureSizeOrGrow(4);
478
+ this.dataView.setUint32(this.bytePosition, Number(value), true);
479
+ return this.shift(4);
480
+ }
481
+ /**
482
+ * Write a U64 value into a buffer and shift cursor position by 8.
483
+ * @param {bigint} value Value to write.
484
+ * @returns {this}
485
+ */
486
+ write64(value) {
487
+ toLittleEndian(BigInt(value), 8).forEach((el) => this.write8(el));
117
488
  return this;
118
489
  }
119
- setPreview(preview) {
120
- this.warp.preview = preview;
490
+ /**
491
+ * Write a U128 value into a buffer and shift cursor position by 16.
492
+ *
493
+ * @param {bigint} value Value to write.
494
+ * @returns {this}
495
+ */
496
+ write128(value) {
497
+ toLittleEndian(BigInt(value), 16).forEach((el) => this.write8(el));
121
498
  return this;
122
499
  }
123
- setActions(actions) {
124
- this.actions = actions;
500
+ /**
501
+ * Write a U256 value into a buffer and shift cursor position by 16.
502
+ *
503
+ * @param {bigint} value Value to write.
504
+ * @returns {this}
505
+ */
506
+ write256(value) {
507
+ toLittleEndian(BigInt(value), 32).forEach((el) => this.write8(el));
125
508
  return this;
126
509
  }
127
- addAction(action) {
128
- this.actions.push(action);
510
+ /**
511
+ * Write a ULEB value into a buffer and shift cursor position by number of bytes
512
+ * written.
513
+ * @param {Number} value Value to write.
514
+ * @returns {this}
515
+ */
516
+ writeULEB(value) {
517
+ ulebEncode(value).forEach((el) => this.write8(el));
129
518
  return this;
130
519
  }
131
- async build() {
132
- return {
133
- protocol: "warp",
134
- name: this.warp.name || "fastset-warp",
135
- title: this.warp.title || "",
136
- description: this.warp.description || null,
137
- preview: this.warp.preview || null,
138
- actions: this.actions,
139
- meta: {
140
- chain: "fastset",
141
- hash: this.generateHash(this.warp.title || ""),
142
- creator: this.config.user?.wallets?.fastset || "",
143
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
144
- }
145
- };
520
+ /**
521
+ * Write a vector into a buffer by first writing the vector length and then calling
522
+ * a callback on each passed value.
523
+ *
524
+ * @param {Array<Any>} vector Array of elements to write.
525
+ * @param {WriteVecCb} cb Callback to call on each element of the vector.
526
+ * @returns {this}
527
+ */
528
+ writeVec(vector2, cb) {
529
+ this.writeULEB(vector2.length);
530
+ Array.from(vector2).forEach((el, i) => cb(this, el, i, vector2.length));
531
+ return this;
146
532
  }
147
- createInscriptionTransaction(warp) {
148
- return {
149
- type: "fastset-inscription",
150
- data: JSON.stringify(warp)
151
- // TODO: Add Fastset-specific transaction fields
152
- };
533
+ /**
534
+ * Adds support for iterations over the object.
535
+ * @returns {Uint8Array}
536
+ */
537
+ *[Symbol.iterator]() {
538
+ for (let i = 0; i < this.bytePosition; i++) {
539
+ yield this.dataView.getUint8(i);
540
+ }
541
+ return this.toBytes();
542
+ }
543
+ /**
544
+ * Get underlying buffer taking only value bytes (in case initial buffer size was bigger).
545
+ * @returns {Uint8Array} Resulting bcs.
546
+ */
547
+ toBytes() {
548
+ return new Uint8Array(this.dataView.buffer.slice(0, this.bytePosition));
549
+ }
550
+ /**
551
+ * Represent data as 'hex' or 'base64'
552
+ * @param encoding Encoding to use: 'base64' or 'hex'
553
+ */
554
+ toString(encoding) {
555
+ return encodeStr(this.toBytes(), encoding);
153
556
  }
154
- async createFromTransaction(tx, validate = true) {
155
- try {
156
- const warpData = tx.data || tx.payload || tx.content;
157
- if (!warpData) {
158
- throw new Error("No warp data found in transaction");
557
+ };
558
+ function toLittleEndian(bigint, size) {
559
+ const result = new Uint8Array(size);
560
+ let i = 0;
561
+ while (bigint > 0) {
562
+ result[i] = Number(bigint % BigInt(256));
563
+ bigint = bigint / BigInt(256);
564
+ i += 1;
565
+ }
566
+ return result;
567
+ }
568
+
569
+ // ../../node_modules/@mysten/bcs/dist/esm/bcs-type.js
570
+ var __typeError = (msg) => {
571
+ throw TypeError(msg);
572
+ };
573
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
574
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
575
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
576
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
577
+ var _write;
578
+ var _serialize;
579
+ var _schema;
580
+ var _bytes;
581
+ var _BcsType = class _BcsType2 {
582
+ constructor(options) {
583
+ __privateAdd(this, _write);
584
+ __privateAdd(this, _serialize);
585
+ this.name = options.name;
586
+ this.read = options.read;
587
+ this.serializedSize = options.serializedSize ?? (() => null);
588
+ __privateSet(this, _write, options.write);
589
+ __privateSet(this, _serialize, options.serialize ?? ((value, options2) => {
590
+ const writer = new BcsWriter({
591
+ initialSize: this.serializedSize(value) ?? void 0,
592
+ ...options2
593
+ });
594
+ __privateGet(this, _write).call(this, value, writer);
595
+ return writer.toBytes();
596
+ }));
597
+ this.validate = options.validate ?? (() => {
598
+ });
599
+ }
600
+ write(value, writer) {
601
+ this.validate(value);
602
+ __privateGet(this, _write).call(this, value, writer);
603
+ }
604
+ serialize(value, options) {
605
+ this.validate(value);
606
+ return new SerializedBcs(this, __privateGet(this, _serialize).call(this, value, options));
607
+ }
608
+ parse(bytes) {
609
+ const reader = new BcsReader(bytes);
610
+ return this.read(reader);
611
+ }
612
+ fromHex(hex) {
613
+ return this.parse(fromHex(hex));
614
+ }
615
+ fromBase58(b64) {
616
+ return this.parse(fromBase58(b64));
617
+ }
618
+ fromBase64(b64) {
619
+ return this.parse(fromBase64(b64));
620
+ }
621
+ transform({
622
+ name: name2,
623
+ input,
624
+ output,
625
+ validate
626
+ }) {
627
+ return new _BcsType2({
628
+ name: name2 ?? this.name,
629
+ read: (reader) => output ? output(this.read(reader)) : this.read(reader),
630
+ write: (value, writer) => __privateGet(this, _write).call(this, input ? input(value) : value, writer),
631
+ serializedSize: (value) => this.serializedSize(input ? input(value) : value),
632
+ serialize: (value, options) => __privateGet(this, _serialize).call(this, input ? input(value) : value, options),
633
+ validate: (value) => {
634
+ validate?.(value);
635
+ this.validate(input ? input(value) : value);
159
636
  }
160
- const parsed = typeof warpData === "string" ? JSON.parse(warpData) : warpData;
161
- if (validate) {
162
- this.validateWarp(parsed);
637
+ });
638
+ }
639
+ };
640
+ _write = /* @__PURE__ */ new WeakMap();
641
+ _serialize = /* @__PURE__ */ new WeakMap();
642
+ var BcsType = _BcsType;
643
+ var SERIALIZED_BCS_BRAND = Symbol.for("@mysten/serialized-bcs");
644
+ var SerializedBcs = class {
645
+ constructor(schema, bytes) {
646
+ __privateAdd(this, _schema);
647
+ __privateAdd(this, _bytes);
648
+ __privateSet(this, _schema, schema);
649
+ __privateSet(this, _bytes, bytes);
650
+ }
651
+ // Used to brand SerializedBcs so that they can be identified, even between multiple copies
652
+ // of the @mysten/bcs package are installed
653
+ get [SERIALIZED_BCS_BRAND]() {
654
+ return true;
655
+ }
656
+ toBytes() {
657
+ return __privateGet(this, _bytes);
658
+ }
659
+ toHex() {
660
+ return toHex(__privateGet(this, _bytes));
661
+ }
662
+ toBase64() {
663
+ return toBase64(__privateGet(this, _bytes));
664
+ }
665
+ toBase58() {
666
+ return toBase58(__privateGet(this, _bytes));
667
+ }
668
+ parse() {
669
+ return __privateGet(this, _schema).parse(__privateGet(this, _bytes));
670
+ }
671
+ };
672
+ _schema = /* @__PURE__ */ new WeakMap();
673
+ _bytes = /* @__PURE__ */ new WeakMap();
674
+ function fixedSizeBcsType({
675
+ size,
676
+ ...options
677
+ }) {
678
+ return new BcsType({
679
+ ...options,
680
+ serializedSize: () => size
681
+ });
682
+ }
683
+ function uIntBcsType({
684
+ readMethod,
685
+ writeMethod,
686
+ ...options
687
+ }) {
688
+ return fixedSizeBcsType({
689
+ ...options,
690
+ read: (reader) => reader[readMethod](),
691
+ write: (value, writer) => writer[writeMethod](value),
692
+ validate: (value) => {
693
+ if (value < 0 || value > options.maxValue) {
694
+ throw new TypeError(
695
+ `Invalid ${options.name} value: ${value}. Expected value in range 0-${options.maxValue}`
696
+ );
163
697
  }
164
- return parsed;
165
- } catch (error) {
166
- throw new Error(`Failed to create warp from Fastset transaction: ${error}`);
698
+ options.validate?.(value);
167
699
  }
168
- }
169
- async createFromTransactionHash(hash, cache) {
170
- try {
171
- const tx = await this.fetchTransaction(hash);
172
- if (!tx) {
173
- return null;
700
+ });
701
+ }
702
+ function bigUIntBcsType({
703
+ readMethod,
704
+ writeMethod,
705
+ ...options
706
+ }) {
707
+ return fixedSizeBcsType({
708
+ ...options,
709
+ read: (reader) => reader[readMethod](),
710
+ write: (value, writer) => writer[writeMethod](BigInt(value)),
711
+ validate: (val) => {
712
+ const value = BigInt(val);
713
+ if (value < 0 || value > options.maxValue) {
714
+ throw new TypeError(
715
+ `Invalid ${options.name} value: ${value}. Expected value in range 0-${options.maxValue}`
716
+ );
174
717
  }
175
- return this.createFromTransaction(tx);
176
- } catch (error) {
177
- console.error(`Failed to create warp from Fastset transaction hash: ${error}`);
178
- return null;
718
+ options.validate?.(value);
179
719
  }
180
- }
181
- generateHash(data) {
182
- let hash = 0;
183
- for (let i = 0; i < data.length; i++) {
184
- const char = data.charCodeAt(i);
185
- hash = (hash << 5) - hash + char;
186
- hash = hash & hash;
720
+ });
721
+ }
722
+ function dynamicSizeBcsType({
723
+ serialize,
724
+ ...options
725
+ }) {
726
+ const type = new BcsType({
727
+ ...options,
728
+ serialize,
729
+ write: (value, writer) => {
730
+ for (const byte of type.serialize(value).toBytes()) {
731
+ writer.write8(byte);
732
+ }
187
733
  }
188
- return hash.toString(16);
189
- }
190
- validateWarp(warp) {
191
- if (!warp.title) {
192
- throw new Error("Warp must have a title");
734
+ });
735
+ return type;
736
+ }
737
+ function stringLikeBcsType({
738
+ toBytes: toBytes2,
739
+ fromBytes,
740
+ ...options
741
+ }) {
742
+ return new BcsType({
743
+ ...options,
744
+ read: (reader) => {
745
+ const length = reader.readULEB();
746
+ const bytes = reader.readBytes(length);
747
+ return fromBytes(bytes);
748
+ },
749
+ write: (hex, writer) => {
750
+ const bytes = toBytes2(hex);
751
+ writer.writeULEB(bytes.length);
752
+ for (let i = 0; i < bytes.length; i++) {
753
+ writer.write8(bytes[i]);
754
+ }
755
+ },
756
+ serialize: (value) => {
757
+ const bytes = toBytes2(value);
758
+ const size = ulebEncode(bytes.length);
759
+ const result = new Uint8Array(size.length + bytes.length);
760
+ result.set(size, 0);
761
+ result.set(bytes, size.length);
762
+ return result;
763
+ },
764
+ validate: (value) => {
765
+ if (typeof value !== "string") {
766
+ throw new TypeError(`Invalid ${options.name} value: ${value}. Expected string`);
767
+ }
768
+ options.validate?.(value);
193
769
  }
194
- if (!warp.actions || !Array.isArray(warp.actions)) {
195
- throw new Error("Warp must have actions array");
770
+ });
771
+ }
772
+ function lazyBcsType(cb) {
773
+ let lazyType = null;
774
+ function getType() {
775
+ if (!lazyType) {
776
+ lazyType = cb();
196
777
  }
778
+ return lazyType;
779
+ }
780
+ return new BcsType({
781
+ name: "lazy",
782
+ read: (data) => getType().read(data),
783
+ serializedSize: (value) => getType().serializedSize(value),
784
+ write: (value, writer) => getType().write(value, writer),
785
+ serialize: (value, options) => getType().serialize(value, options).toBytes()
786
+ });
787
+ }
788
+ var BcsStruct = class extends BcsType {
789
+ constructor({ name: name2, fields, ...options }) {
790
+ const canonicalOrder = Object.entries(fields);
791
+ super({
792
+ name: name2,
793
+ serializedSize: (values) => {
794
+ let total = 0;
795
+ for (const [field, type] of canonicalOrder) {
796
+ const size = type.serializedSize(values[field]);
797
+ if (size == null) {
798
+ return null;
799
+ }
800
+ total += size;
801
+ }
802
+ return total;
803
+ },
804
+ read: (reader) => {
805
+ const result = {};
806
+ for (const [field, type] of canonicalOrder) {
807
+ result[field] = type.read(reader);
808
+ }
809
+ return result;
810
+ },
811
+ write: (value, writer) => {
812
+ for (const [field, type] of canonicalOrder) {
813
+ type.write(value[field], writer);
814
+ }
815
+ },
816
+ ...options,
817
+ validate: (value) => {
818
+ options?.validate?.(value);
819
+ if (typeof value !== "object" || value == null) {
820
+ throw new TypeError(`Expected object, found ${typeof value}`);
821
+ }
822
+ }
823
+ });
197
824
  }
198
- async fetchTransaction(hash) {
199
- const response = await fetch(`${this.getApiUrl()}/transaction/${hash}`);
200
- if (!response.ok) {
201
- return null;
202
- }
203
- return response.json();
825
+ };
826
+ var BcsEnum = class extends BcsType {
827
+ constructor({ fields, ...options }) {
828
+ const canonicalOrder = Object.entries(fields);
829
+ super({
830
+ read: (reader) => {
831
+ const index = reader.readULEB();
832
+ const enumEntry = canonicalOrder[index];
833
+ if (!enumEntry) {
834
+ throw new TypeError(`Unknown value ${index} for enum ${name}`);
835
+ }
836
+ const [kind, type] = enumEntry;
837
+ return {
838
+ [kind]: type?.read(reader) ?? true,
839
+ $kind: kind
840
+ };
841
+ },
842
+ write: (value, writer) => {
843
+ const [name2, val] = Object.entries(value).filter(
844
+ ([name3]) => Object.hasOwn(fields, name3)
845
+ )[0];
846
+ for (let i = 0; i < canonicalOrder.length; i++) {
847
+ const [optionName, optionType] = canonicalOrder[i];
848
+ if (optionName === name2) {
849
+ writer.writeULEB(i);
850
+ optionType?.write(val, writer);
851
+ return;
852
+ }
853
+ }
854
+ },
855
+ ...options,
856
+ validate: (value) => {
857
+ options?.validate?.(value);
858
+ if (typeof value !== "object" || value == null) {
859
+ throw new TypeError(`Expected object, found ${typeof value}`);
860
+ }
861
+ const keys = Object.keys(value).filter(
862
+ (k) => value[k] !== void 0 && Object.hasOwn(fields, k)
863
+ );
864
+ if (keys.length !== 1) {
865
+ throw new TypeError(
866
+ `Expected object with one key, but found ${keys.length} for type ${name}}`
867
+ );
868
+ }
869
+ const [variant] = keys;
870
+ if (!Object.hasOwn(fields, variant)) {
871
+ throw new TypeError(`Invalid enum variant ${variant}`);
872
+ }
873
+ }
874
+ });
204
875
  }
205
- getApiUrl() {
206
- return "https://api.fastset.xyz";
876
+ };
877
+ var BcsTuple = class extends BcsType {
878
+ constructor({ fields, name: name2, ...options }) {
879
+ super({
880
+ name: name2 ?? `(${fields.map((t) => t.name).join(", ")})`,
881
+ serializedSize: (values) => {
882
+ let total = 0;
883
+ for (let i = 0; i < fields.length; i++) {
884
+ const size = fields[i].serializedSize(values[i]);
885
+ if (size == null) {
886
+ return null;
887
+ }
888
+ total += size;
889
+ }
890
+ return total;
891
+ },
892
+ read: (reader) => {
893
+ const result = [];
894
+ for (const field of fields) {
895
+ result.push(field.read(reader));
896
+ }
897
+ return result;
898
+ },
899
+ write: (value, writer) => {
900
+ for (let i = 0; i < fields.length; i++) {
901
+ fields[i].write(value[i], writer);
902
+ }
903
+ },
904
+ ...options,
905
+ validate: (value) => {
906
+ options?.validate?.(value);
907
+ if (!Array.isArray(value)) {
908
+ throw new TypeError(`Expected array, found ${typeof value}`);
909
+ }
910
+ if (value.length !== fields.length) {
911
+ throw new TypeError(`Expected array of length ${fields.length}, found ${value.length}`);
912
+ }
913
+ }
914
+ });
207
915
  }
208
916
  };
209
917
 
210
- // src/WarpFastsetExecutor.ts
211
- var import_warps2 = require("@vleap/warps");
212
-
213
- // src/config.ts
214
- var FASTSET_CHAIN_CONFIGS = {
215
- fastset: {
216
- mainnet: {
217
- apiUrl: "http://157.90.201.117:8765",
218
- proxyUrl: "http://136.243.61.168:44444",
219
- explorerUrl: "https://explorer.fastset.com",
220
- chainId: "1",
221
- registryAddress: "0x0000000000000000000000000000000000000000",
222
- nativeToken: "PI",
223
- blockTime: 12e3
918
+ // ../../node_modules/@mysten/bcs/dist/esm/bcs.js
919
+ function fixedArray(size, type, options) {
920
+ return new BcsType({
921
+ read: (reader) => {
922
+ const result = new Array(size);
923
+ for (let i = 0; i < size; i++) {
924
+ result[i] = type.read(reader);
925
+ }
926
+ return result;
224
927
  },
225
- testnet: {
226
- apiUrl: "http://157.90.201.117:8765",
227
- proxyUrl: "http://136.243.61.168:44444",
228
- explorerUrl: "https://testnet-explorer.fastset.com",
229
- chainId: "11155111",
230
- registryAddress: "0x0000000000000000000000000000000000000000",
231
- nativeToken: "PI",
232
- blockTime: 12e3
928
+ write: (value, writer) => {
929
+ for (const item of value) {
930
+ type.write(item, writer);
931
+ }
233
932
  },
234
- devnet: {
235
- apiUrl: "http://157.90.201.117:8765",
236
- proxyUrl: "http://136.243.61.168:44444",
237
- explorerUrl: "http://localhost:4000",
238
- chainId: "1337",
239
- registryAddress: "0x0000000000000000000000000000000000000000",
240
- nativeToken: "PI",
241
- blockTime: 12e3
933
+ ...options,
934
+ name: options?.name ?? `${type.name}[${size}]`,
935
+ validate: (value) => {
936
+ options?.validate?.(value);
937
+ if (!value || typeof value !== "object" || !("length" in value)) {
938
+ throw new TypeError(`Expected array, found ${typeof value}`);
939
+ }
940
+ if (value.length !== size) {
941
+ throw new TypeError(`Expected array of length ${size}, found ${value.length}`);
942
+ }
242
943
  }
944
+ });
945
+ }
946
+ function option(type) {
947
+ return bcs.enum(`Option<${type.name}>`, {
948
+ None: null,
949
+ Some: type
950
+ }).transform({
951
+ input: (value) => {
952
+ if (value == null) {
953
+ return { None: true };
954
+ }
955
+ return { Some: value };
956
+ },
957
+ output: (value) => {
958
+ if (value.$kind === "Some") {
959
+ return value.Some;
960
+ }
961
+ return null;
962
+ }
963
+ });
964
+ }
965
+ function vector(type, options) {
966
+ return new BcsType({
967
+ read: (reader) => {
968
+ const length = reader.readULEB();
969
+ const result = new Array(length);
970
+ for (let i = 0; i < length; i++) {
971
+ result[i] = type.read(reader);
972
+ }
973
+ return result;
974
+ },
975
+ write: (value, writer) => {
976
+ writer.writeULEB(value.length);
977
+ for (const item of value) {
978
+ type.write(item, writer);
979
+ }
980
+ },
981
+ ...options,
982
+ name: options?.name ?? `vector<${type.name}>`,
983
+ validate: (value) => {
984
+ options?.validate?.(value);
985
+ if (!value || typeof value !== "object" || !("length" in value)) {
986
+ throw new TypeError(`Expected array, found ${typeof value}`);
987
+ }
988
+ }
989
+ });
990
+ }
991
+ function map(keyType, valueType) {
992
+ return bcs.vector(bcs.tuple([keyType, valueType])).transform({
993
+ name: `Map<${keyType.name}, ${valueType.name}>`,
994
+ input: (value) => {
995
+ return [...value.entries()];
996
+ },
997
+ output: (value) => {
998
+ const result = /* @__PURE__ */ new Map();
999
+ for (const [key, val] of value) {
1000
+ result.set(key, val);
1001
+ }
1002
+ return result;
1003
+ }
1004
+ });
1005
+ }
1006
+ var bcs = {
1007
+ /**
1008
+ * Creates a BcsType that can be used to read and write an 8-bit unsigned integer.
1009
+ * @example
1010
+ * bcs.u8().serialize(255).toBytes() // Uint8Array [ 255 ]
1011
+ */
1012
+ u8(options) {
1013
+ return uIntBcsType({
1014
+ readMethod: "read8",
1015
+ writeMethod: "write8",
1016
+ size: 1,
1017
+ maxValue: 2 ** 8 - 1,
1018
+ ...options,
1019
+ name: options?.name ?? "u8"
1020
+ });
1021
+ },
1022
+ /**
1023
+ * Creates a BcsType that can be used to read and write a 16-bit unsigned integer.
1024
+ * @example
1025
+ * bcs.u16().serialize(65535).toBytes() // Uint8Array [ 255, 255 ]
1026
+ */
1027
+ u16(options) {
1028
+ return uIntBcsType({
1029
+ readMethod: "read16",
1030
+ writeMethod: "write16",
1031
+ size: 2,
1032
+ maxValue: 2 ** 16 - 1,
1033
+ ...options,
1034
+ name: options?.name ?? "u16"
1035
+ });
1036
+ },
1037
+ /**
1038
+ * Creates a BcsType that can be used to read and write a 32-bit unsigned integer.
1039
+ * @example
1040
+ * bcs.u32().serialize(4294967295).toBytes() // Uint8Array [ 255, 255, 255, 255 ]
1041
+ */
1042
+ u32(options) {
1043
+ return uIntBcsType({
1044
+ readMethod: "read32",
1045
+ writeMethod: "write32",
1046
+ size: 4,
1047
+ maxValue: 2 ** 32 - 1,
1048
+ ...options,
1049
+ name: options?.name ?? "u32"
1050
+ });
1051
+ },
1052
+ /**
1053
+ * Creates a BcsType that can be used to read and write a 64-bit unsigned integer.
1054
+ * @example
1055
+ * bcs.u64().serialize(1).toBytes() // Uint8Array [ 1, 0, 0, 0, 0, 0, 0, 0 ]
1056
+ */
1057
+ u64(options) {
1058
+ return bigUIntBcsType({
1059
+ readMethod: "read64",
1060
+ writeMethod: "write64",
1061
+ size: 8,
1062
+ maxValue: 2n ** 64n - 1n,
1063
+ ...options,
1064
+ name: options?.name ?? "u64"
1065
+ });
1066
+ },
1067
+ /**
1068
+ * Creates a BcsType that can be used to read and write a 128-bit unsigned integer.
1069
+ * @example
1070
+ * bcs.u128().serialize(1).toBytes() // Uint8Array [ 1, ..., 0 ]
1071
+ */
1072
+ u128(options) {
1073
+ return bigUIntBcsType({
1074
+ readMethod: "read128",
1075
+ writeMethod: "write128",
1076
+ size: 16,
1077
+ maxValue: 2n ** 128n - 1n,
1078
+ ...options,
1079
+ name: options?.name ?? "u128"
1080
+ });
1081
+ },
1082
+ /**
1083
+ * Creates a BcsType that can be used to read and write a 256-bit unsigned integer.
1084
+ * @example
1085
+ * bcs.u256().serialize(1).toBytes() // Uint8Array [ 1, ..., 0 ]
1086
+ */
1087
+ u256(options) {
1088
+ return bigUIntBcsType({
1089
+ readMethod: "read256",
1090
+ writeMethod: "write256",
1091
+ size: 32,
1092
+ maxValue: 2n ** 256n - 1n,
1093
+ ...options,
1094
+ name: options?.name ?? "u256"
1095
+ });
1096
+ },
1097
+ /**
1098
+ * Creates a BcsType that can be used to read and write boolean values.
1099
+ * @example
1100
+ * bcs.bool().serialize(true).toBytes() // Uint8Array [ 1 ]
1101
+ */
1102
+ bool(options) {
1103
+ return fixedSizeBcsType({
1104
+ size: 1,
1105
+ read: (reader) => reader.read8() === 1,
1106
+ write: (value, writer) => writer.write8(value ? 1 : 0),
1107
+ ...options,
1108
+ name: options?.name ?? "bool",
1109
+ validate: (value) => {
1110
+ options?.validate?.(value);
1111
+ if (typeof value !== "boolean") {
1112
+ throw new TypeError(`Expected boolean, found ${typeof value}`);
1113
+ }
1114
+ }
1115
+ });
1116
+ },
1117
+ /**
1118
+ * Creates a BcsType that can be used to read and write unsigned LEB encoded integers
1119
+ * @example
1120
+ *
1121
+ */
1122
+ uleb128(options) {
1123
+ return dynamicSizeBcsType({
1124
+ read: (reader) => reader.readULEB(),
1125
+ serialize: (value) => {
1126
+ return Uint8Array.from(ulebEncode(value));
1127
+ },
1128
+ ...options,
1129
+ name: options?.name ?? "uleb128"
1130
+ });
1131
+ },
1132
+ /**
1133
+ * Creates a BcsType representing a fixed length byte array
1134
+ * @param size The number of bytes this types represents
1135
+ * @example
1136
+ * bcs.bytes(3).serialize(new Uint8Array([1, 2, 3])).toBytes() // Uint8Array [1, 2, 3]
1137
+ */
1138
+ bytes(size, options) {
1139
+ return fixedSizeBcsType({
1140
+ size,
1141
+ read: (reader) => reader.readBytes(size),
1142
+ write: (value, writer) => {
1143
+ const array = new Uint8Array(value);
1144
+ for (let i = 0; i < size; i++) {
1145
+ writer.write8(array[i] ?? 0);
1146
+ }
1147
+ },
1148
+ ...options,
1149
+ name: options?.name ?? `bytes[${size}]`,
1150
+ validate: (value) => {
1151
+ options?.validate?.(value);
1152
+ if (!value || typeof value !== "object" || !("length" in value)) {
1153
+ throw new TypeError(`Expected array, found ${typeof value}`);
1154
+ }
1155
+ if (value.length !== size) {
1156
+ throw new TypeError(`Expected array of length ${size}, found ${value.length}`);
1157
+ }
1158
+ }
1159
+ });
1160
+ },
1161
+ /**
1162
+ * Creates a BcsType representing a variable length byte array
1163
+ *
1164
+ * @example
1165
+ * bcs.byteVector().serialize([1, 2, 3]).toBytes() // Uint8Array [3, 1, 2, 3]
1166
+ */
1167
+ byteVector(options) {
1168
+ return new BcsType({
1169
+ read: (reader) => {
1170
+ const length = reader.readULEB();
1171
+ return reader.readBytes(length);
1172
+ },
1173
+ write: (value, writer) => {
1174
+ const array = new Uint8Array(value);
1175
+ writer.writeULEB(array.length);
1176
+ for (let i = 0; i < array.length; i++) {
1177
+ writer.write8(array[i] ?? 0);
1178
+ }
1179
+ },
1180
+ ...options,
1181
+ name: options?.name ?? "vector<u8>",
1182
+ serializedSize: (value) => {
1183
+ const length = "length" in value ? value.length : null;
1184
+ return length == null ? null : ulebEncode(length).length + length;
1185
+ },
1186
+ validate: (value) => {
1187
+ options?.validate?.(value);
1188
+ if (!value || typeof value !== "object" || !("length" in value)) {
1189
+ throw new TypeError(`Expected array, found ${typeof value}`);
1190
+ }
1191
+ }
1192
+ });
1193
+ },
1194
+ /**
1195
+ * Creates a BcsType that can ser/de string values. Strings will be UTF-8 encoded
1196
+ * @example
1197
+ * bcs.string().serialize('a').toBytes() // Uint8Array [ 1, 97 ]
1198
+ */
1199
+ string(options) {
1200
+ return stringLikeBcsType({
1201
+ toBytes: (value) => new TextEncoder().encode(value),
1202
+ fromBytes: (bytes) => new TextDecoder().decode(bytes),
1203
+ ...options,
1204
+ name: options?.name ?? "string"
1205
+ });
1206
+ },
1207
+ /**
1208
+ * Creates a BcsType that represents a fixed length array of a given type
1209
+ * @param size The number of elements in the array
1210
+ * @param type The BcsType of each element in the array
1211
+ * @example
1212
+ * bcs.fixedArray(3, bcs.u8()).serialize([1, 2, 3]).toBytes() // Uint8Array [ 1, 2, 3 ]
1213
+ */
1214
+ fixedArray,
1215
+ /**
1216
+ * Creates a BcsType representing an optional value
1217
+ * @param type The BcsType of the optional value
1218
+ * @example
1219
+ * bcs.option(bcs.u8()).serialize(null).toBytes() // Uint8Array [ 0 ]
1220
+ * bcs.option(bcs.u8()).serialize(1).toBytes() // Uint8Array [ 1, 1 ]
1221
+ */
1222
+ option,
1223
+ /**
1224
+ * Creates a BcsType representing a variable length vector of a given type
1225
+ * @param type The BcsType of each element in the vector
1226
+ *
1227
+ * @example
1228
+ * bcs.vector(bcs.u8()).toBytes([1, 2, 3]) // Uint8Array [ 3, 1, 2, 3 ]
1229
+ */
1230
+ vector,
1231
+ /**
1232
+ * Creates a BcsType representing a tuple of a given set of types
1233
+ * @param types The BcsTypes for each element in the tuple
1234
+ *
1235
+ * @example
1236
+ * const tuple = bcs.tuple([bcs.u8(), bcs.string(), bcs.bool()])
1237
+ * tuple.serialize([1, 'a', true]).toBytes() // Uint8Array [ 1, 1, 97, 1 ]
1238
+ */
1239
+ tuple(fields, options) {
1240
+ return new BcsTuple({
1241
+ fields,
1242
+ ...options
1243
+ });
1244
+ },
1245
+ /**
1246
+ * Creates a BcsType representing a struct of a given set of fields
1247
+ * @param name The name of the struct
1248
+ * @param fields The fields of the struct. The order of the fields affects how data is serialized and deserialized
1249
+ *
1250
+ * @example
1251
+ * const struct = bcs.struct('MyStruct', {
1252
+ * a: bcs.u8(),
1253
+ * b: bcs.string(),
1254
+ * })
1255
+ * struct.serialize({ a: 1, b: 'a' }).toBytes() // Uint8Array [ 1, 1, 97 ]
1256
+ */
1257
+ struct(name2, fields, options) {
1258
+ return new BcsStruct({
1259
+ name: name2,
1260
+ fields,
1261
+ ...options
1262
+ });
1263
+ },
1264
+ /**
1265
+ * Creates a BcsType representing an enum of a given set of options
1266
+ * @param name The name of the enum
1267
+ * @param values The values of the enum. The order of the values affects how data is serialized and deserialized.
1268
+ * null can be used to represent a variant with no data.
1269
+ *
1270
+ * @example
1271
+ * const enum = bcs.enum('MyEnum', {
1272
+ * A: bcs.u8(),
1273
+ * B: bcs.string(),
1274
+ * C: null,
1275
+ * })
1276
+ * enum.serialize({ A: 1 }).toBytes() // Uint8Array [ 0, 1 ]
1277
+ * enum.serialize({ B: 'a' }).toBytes() // Uint8Array [ 1, 1, 97 ]
1278
+ * enum.serialize({ C: true }).toBytes() // Uint8Array [ 2 ]
1279
+ */
1280
+ enum(name2, fields, options) {
1281
+ return new BcsEnum({
1282
+ name: name2,
1283
+ fields,
1284
+ ...options
1285
+ });
1286
+ },
1287
+ /**
1288
+ * Creates a BcsType representing a map of a given key and value type
1289
+ * @param keyType The BcsType of the key
1290
+ * @param valueType The BcsType of the value
1291
+ * @example
1292
+ * const map = bcs.map(bcs.u8(), bcs.string())
1293
+ * map.serialize(new Map([[2, 'a']])).toBytes() // Uint8Array [ 1, 2, 1, 97 ]
1294
+ */
1295
+ map,
1296
+ /**
1297
+ * Creates a BcsType that wraps another BcsType which is lazily evaluated. This is useful for creating recursive types.
1298
+ * @param cb A callback that returns the BcsType
1299
+ */
1300
+ lazy(cb) {
1301
+ return lazyBcsType(cb);
243
1302
  }
244
1303
  };
245
- var DEFAULT_CHAIN = "fastset";
246
- var getFastsetChainConfig = (chain = DEFAULT_CHAIN, env) => {
247
- const chainConfigs = FASTSET_CHAIN_CONFIGS[chain];
248
- if (!chainConfigs) {
249
- throw new Error(`Unsupported Fastset chain: ${chain}`);
250
- }
251
- const config = chainConfigs[env];
252
- if (!config) {
253
- throw new Error(`Unsupported environment ${env} for chain ${chain}`);
254
- }
255
- return config;
256
- };
257
- var getFastsetApiUrl = (env, chain = DEFAULT_CHAIN) => {
258
- return getFastsetChainConfig(chain, env).apiUrl;
259
- };
260
- var getFastsetProxyUrl = (env, chain = DEFAULT_CHAIN) => {
261
- return getFastsetChainConfig(chain, env).proxyUrl;
262
- };
263
-
264
- // src/sdk/FastsetClient.ts
265
- var import_ed25519 = require("@noble/ed25519");
266
1304
 
267
1305
  // src/sdk/types.ts
268
- var import_bcs = require("@mysten/bcs");
269
1306
  BigInt.prototype.toJSON = function() {
270
1307
  return Number(this);
271
1308
  };
272
- var Bytes32 = import_bcs.bcs.fixedArray(32, import_bcs.bcs.u8());
1309
+ var Bytes32 = bcs.fixedArray(32, bcs.u8());
1310
+ var Bytes64 = bcs.fixedArray(64, bcs.u8());
273
1311
  var PublicKey = Bytes32;
274
- var Address = import_bcs.bcs.enum("Address", {
1312
+ var Signature = Bytes64;
1313
+ var Address = bcs.enum("Address", {
275
1314
  External: PublicKey,
276
1315
  FastSet: PublicKey
277
1316
  });
278
- var Amount = import_bcs.bcs.u256().transform({
1317
+ var Amount = bcs.u256().transform({
1318
+ // CAUTION: When we build a transaction object, we must use a hex encoded string because the
1319
+ // validator expects amounts to be in hex. However, bcs.u256() by default expects a decimal
1320
+ // string. Therefore, we must transform the input amount from hex to decimal here.
279
1321
  input: (val) => hexToDecimal(val.toString()),
280
1322
  output: (value) => value
281
1323
  });
282
- var UserData = import_bcs.bcs.option(Bytes32);
283
- var Nonce = import_bcs.bcs.u64();
284
- var Transfer = import_bcs.bcs.struct("Transfer", {
285
- recipient: Address,
1324
+ var Balance = bcs.string().transform({
1325
+ input: (val) => val,
1326
+ output: (value) => value
1327
+ });
1328
+ var UserData = bcs.option(Bytes32);
1329
+ var Nonce = bcs.u64();
1330
+ var Quorum = bcs.u64();
1331
+ var TokenId = Bytes32;
1332
+ var Transfer = bcs.struct("Transfer", {
1333
+ amount: Amount,
1334
+ user_data: UserData
1335
+ });
1336
+ var TokenTransfer = bcs.struct("TokenTransfer", {
1337
+ token_id: TokenId,
286
1338
  amount: Amount,
287
1339
  user_data: UserData
288
1340
  });
289
- var ClaimType = import_bcs.bcs.enum("ClaimType", {
290
- Transfer
1341
+ var TokenCreation = bcs.struct("TokenCreation", {
1342
+ token_name: bcs.string(),
1343
+ decimals: bcs.u8(),
1344
+ initial_amount: Amount,
1345
+ mints: bcs.vector(PublicKey),
1346
+ user_data: UserData
1347
+ });
1348
+ var AddressChange = bcs.enum("AddressChange", {
1349
+ Add: PublicKey,
1350
+ Remove: PublicKey
1351
+ });
1352
+ var TokenManagement = bcs.struct("TokenManagement", {
1353
+ token_id: TokenId,
1354
+ update_id: Nonce,
1355
+ new_admin: bcs.option(PublicKey),
1356
+ mints: bcs.vector(bcs.tuple([AddressChange, PublicKey])),
1357
+ user_data: UserData
1358
+ });
1359
+ var Mint = bcs.struct("Mint", {
1360
+ token_id: TokenId,
1361
+ amount: Amount
1362
+ });
1363
+ var ClaimData = bcs.vector(bcs.u8());
1364
+ var ExternalClaimBody = bcs.struct("ExternalClaimBody", {
1365
+ verifier_committee: bcs.vector(PublicKey),
1366
+ verifier_quorum: Quorum,
1367
+ claim_data: ClaimData
1368
+ });
1369
+ var ExternalClaim = bcs.struct("ExternalClaim", {
1370
+ claim: ExternalClaimBody,
1371
+ signatures: bcs.vector(bcs.tuple([PublicKey, Signature]))
1372
+ });
1373
+ var ClaimType = bcs.enum("ClaimType", {
1374
+ Transfer,
1375
+ TokenTransfer,
1376
+ TokenCreation,
1377
+ TokenManagement,
1378
+ Mint,
1379
+ ExternalClaim
291
1380
  });
292
- var Transaction = import_bcs.bcs.struct("Transaction", {
1381
+ var Transaction = bcs.struct("Transaction", {
293
1382
  sender: PublicKey,
1383
+ recipient: Address,
294
1384
  nonce: Nonce,
295
- timestamp_nanos: import_bcs.bcs.u128(),
1385
+ timestamp_nanos: bcs.u128(),
296
1386
  claim: ClaimType
297
1387
  });
1388
+ var SubmitTransactionResponse = bcs.struct("SubmitTransactionResponse", {
1389
+ validator: PublicKey,
1390
+ signature: Signature,
1391
+ next_nonce: Nonce,
1392
+ transaction_hash: bcs.vector(bcs.u8())
1393
+ });
1394
+ var TransactionEnvelope = bcs.struct("TransactionEnvelope", {
1395
+ transaction: Transaction,
1396
+ signature: Signature
1397
+ });
1398
+ var TransactionCertificate = bcs.struct("TransactionCertificate", {
1399
+ envelope: TransactionEnvelope,
1400
+ signatures: bcs.vector(bcs.tuple([PublicKey, Signature]))
1401
+ });
298
1402
  function hexToDecimal(hex) {
299
1403
  return BigInt(`0x${hex}`).toString();
300
1404
  }
301
1405
 
302
1406
  // src/sdk/FastsetClient.ts
1407
+ BigInt.prototype.toJSON = function() {
1408
+ return Number(this);
1409
+ };
1410
+ var id = 0;
303
1411
  var FastsetClient = class {
304
- constructor(config) {
305
- this.config = config;
1412
+ constructor(proxyUrl) {
1413
+ this.proxyUrl = proxyUrl;
1414
+ }
1415
+ async request(url, method, params) {
1416
+ const request = this.buildJsonRpcRequest(id++, method, params);
1417
+ const headers = { "Content-Type": "application/json" };
1418
+ const body = this.jsonSerialize(request);
1419
+ const response = await fetch(url, { method: "POST", headers, body });
1420
+ const json = await response.json();
1421
+ return json;
1422
+ }
1423
+ buildJsonRpcRequest(id2, method, params) {
1424
+ return { jsonrpc: "2.0", id: id2, method, params };
1425
+ }
1426
+ jsonSerialize(data) {
1427
+ return JSON.stringify(data, (k, v) => {
1428
+ if (v instanceof Uint8Array) {
1429
+ return Array.from(v);
1430
+ }
1431
+ return v;
1432
+ });
306
1433
  }
307
1434
  async getAccountInfo(address) {
1435
+ return this.request(this.proxyUrl, "set_proxy_getAccountInfo", { address, token_balances_filter: [] });
1436
+ }
1437
+ async getTokenInfo(tokenIds) {
1438
+ return this.request(this.proxyUrl, "set_proxy_getTokenInfo", { tokenIds: [Array.from(tokenIds)] });
1439
+ }
1440
+ async getNextNonce(address) {
1441
+ const addressBytes = typeof address === "string" ? this.addressToBytes(address) : address;
1442
+ const accountInfoRes = await this.getAccountInfo(addressBytes);
1443
+ return accountInfoRes.result?.next_nonce ?? 0;
1444
+ }
1445
+ async submitTransaction(tx, signature) {
1446
+ const submitTxReq = { transaction: tx, signature };
1447
+ const response = await this.request(this.proxyUrl, "set_proxy_submitTransaction", submitTxReq);
1448
+ const proxyCert = this.parse_TransactionCertificate(response.result);
1449
+ console.log("FastSet Transaction Certificate:", proxyCert);
1450
+ return proxyCert;
1451
+ }
1452
+ parse_TransactionCertificate(res) {
1453
+ let bcs_bytes = TransactionCertificate.serialize(res).toBytes();
1454
+ let bcs_value = TransactionCertificate.parse(bcs_bytes);
1455
+ return bcs_value;
1456
+ }
1457
+ addressToBytes(address) {
308
1458
  try {
309
- const response = await this.requestValidator("set_getAccountInfo", {
310
- address: Array.from(address)
311
- });
312
- if (response.error) {
313
- return null;
314
- }
315
- return response.result;
316
- } catch (error) {
317
- return null;
1459
+ const decoded = bech32.bech32m.decode(address);
1460
+ return new Uint8Array(bech32.bech32m.fromWords(decoded.words));
1461
+ } catch {
1462
+ const decoded = bech32.bech32.decode(address);
1463
+ return new Uint8Array(bech32.bech32.fromWords(decoded.words));
318
1464
  }
319
1465
  }
320
- async getNextNonce(senderAddress) {
321
- const accountInfo = await this.getAccountInfo(senderAddress);
322
- return accountInfo?.next_nonce ?? 0;
1466
+ static decodeBech32Address(address) {
1467
+ try {
1468
+ const decoded = bech32.bech32m.decode(address);
1469
+ return new Uint8Array(bech32.bech32m.fromWords(decoded.words));
1470
+ } catch {
1471
+ const decoded = bech32.bech32.decode(address);
1472
+ return new Uint8Array(bech32.bech32.fromWords(decoded.words));
1473
+ }
323
1474
  }
324
- async fundFromFaucet(request) {
325
- const response = await this.requestProxy("faucetDrip", {
326
- recipient: Array.from(request.recipient),
327
- amount: request.amount
328
- });
329
- if (response.error) {
330
- throw new Error(`Faucet request failed: ${response.error.message}`);
1475
+ static encodeBech32Address(publicKey) {
1476
+ const words = bech32.bech32m.toWords(publicKey);
1477
+ return bech32.bech32m.encode("set", words);
1478
+ }
1479
+ };
1480
+
1481
+ // src/helpers/general.ts
1482
+ var getConfiguredFastsetClient = (config, chain2) => {
1483
+ const proxyUrl = (0, import_warps.getProviderUrl)(config, chain2.name, config.env, chain2.defaultApiUrl);
1484
+ return new FastsetClient(proxyUrl);
1485
+ };
1486
+
1487
+ // src/tokens/fastset.ts
1488
+ var FastsetTokens = [
1489
+ {
1490
+ chain: "fastset",
1491
+ identifier: "08413efc81f99e5b8e03b852b3756674083110c6b65e6b7836b39a26e3908d3c",
1492
+ name: "Ethereum",
1493
+ symbol: "ETH",
1494
+ decimals: 18,
1495
+ logoUrl: "https://assets.coingecko.com/coins/images/279/small/ethereum.png",
1496
+ amount: 0n
1497
+ },
1498
+ {
1499
+ chain: "fastset",
1500
+ identifier: "0ee63eaa3ff9bf6e1c84a70133c5461e6e06d3787ed93200b924a6b82f0f35ff",
1501
+ name: "Bitcoin",
1502
+ symbol: "BTC",
1503
+ decimals: 8,
1504
+ logoUrl: "https://assets.coingecko.com/coins/images/1/small/bitcoin.png",
1505
+ amount: 0n
1506
+ },
1507
+ {
1508
+ chain: "fastset",
1509
+ identifier: "b69f0d3a4d7609367bd893ee3191e48b3047f2c4ccd21728c2441bcc2154f70c",
1510
+ name: "Solana",
1511
+ symbol: "SOL",
1512
+ decimals: 9,
1513
+ logoUrl: "https://assets.coingecko.com/coins/images/4128/small/solana.png",
1514
+ amount: 0n
1515
+ },
1516
+ {
1517
+ chain: "fastset",
1518
+ identifier: "c83166ed4e5e3ca88f7b2cf0ce2d310fa8c4d2ee2fc90d741f7b2040279b2687",
1519
+ name: "USD Coin",
1520
+ symbol: "USDC",
1521
+ decimals: 6,
1522
+ logoUrl: "https://assets.coingecko.com/coins/images/6319/small/USD_Coin_icon.png",
1523
+ amount: 0n
1524
+ }
1525
+ ];
1526
+
1527
+ // src/tokens.ts
1528
+ var KnownTokens = {
1529
+ mainnet: FastsetTokens,
1530
+ testnet: FastsetTokens,
1531
+ devnet: FastsetTokens
1532
+ };
1533
+ var findKnownTokenBySymbol = (symbol, env = "mainnet") => {
1534
+ const tokens = KnownTokens[env] || [];
1535
+ return tokens.find((token) => token.symbol === symbol) || null;
1536
+ };
1537
+ var findKnownTokenById = (id2, env = "mainnet") => {
1538
+ const tokens = KnownTokens[env] || [];
1539
+ return tokens.find((token) => token.identifier === id2) || null;
1540
+ };
1541
+
1542
+ // src/WarpFastsetDataLoader.ts
1543
+ var WarpFastsetDataLoader = class {
1544
+ constructor(config, chain2) {
1545
+ this.config = config;
1546
+ this.chain = chain2;
1547
+ this.client = getConfiguredFastsetClient(config, chain2);
1548
+ }
1549
+ async getAccount(address) {
1550
+ const addressBytes = FastsetClient.decodeBech32Address(address);
1551
+ const accountInfo = await this.client.getAccountInfo(addressBytes);
1552
+ return { chain: this.chain.name, address, balance: BigInt(parseInt(accountInfo.result?.balance ?? "0", 16)) };
1553
+ }
1554
+ async getAccountAssets(address) {
1555
+ const addressBytes = FastsetClient.decodeBech32Address(address);
1556
+ const accountInfo = await this.client.getAccountInfo(addressBytes);
1557
+ const assets = [];
1558
+ const balance = BigInt(parseInt(accountInfo.result?.balance ?? "0", 16));
1559
+ if (balance > 0n) {
1560
+ assets.push({ ...this.chain.nativeToken, amount: balance });
331
1561
  }
332
- return response.result;
1562
+ for (const [tokenId, tokenBalance] of accountInfo.result?.token_balance ?? []) {
1563
+ const amount = BigInt(parseInt(tokenBalance, 16));
1564
+ if (amount > 0n) {
1565
+ const assetInfo = await this.getAssetInfo(Buffer.from(tokenId).toString("hex"));
1566
+ if (!assetInfo) continue;
1567
+ assets.push({
1568
+ chain: this.chain.name,
1569
+ identifier: Buffer.from(tokenId).toString("hex"),
1570
+ symbol: assetInfo.symbol,
1571
+ name: assetInfo.name,
1572
+ decimals: assetInfo.decimals,
1573
+ logoUrl: assetInfo.logoUrl || "",
1574
+ amount
1575
+ });
1576
+ }
1577
+ }
1578
+ return assets;
333
1579
  }
334
- async submitTransaction(request) {
335
- const response = await this.requestValidator("set_submitTransaction", {
336
- transaction: this.serializeTransaction(request.transaction),
337
- signature: Array.from(request.signature)
338
- });
339
- if (response.error) {
340
- throw new Error(`Transaction submission failed: ${response.error.message}`);
1580
+ async getAsset(identifier) {
1581
+ if (identifier === this.chain.nativeToken.identifier) {
1582
+ return this.chain.nativeToken;
1583
+ }
1584
+ const assetInfo = await this.getAssetInfo(identifier);
1585
+ if (!assetInfo) {
1586
+ return null;
341
1587
  }
342
- const result = response.result;
343
1588
  return {
344
- transaction_hash: new Uint8Array(result.transaction_hash),
345
- validator: new Uint8Array(result.validator),
346
- signature: new Uint8Array(result.signature)
347
- };
348
- }
349
- async submitCertificate(request) {
350
- const response = await this.requestValidator("set_submitTransactionCertificate", {
351
- transaction: this.serializeTransaction(request.transaction),
352
- signature: Array.from(request.signature),
353
- validator_signatures: request.validator_signatures.map(([validator, signature]) => [Array.from(validator), Array.from(signature)])
354
- });
355
- if (response.error) {
356
- throw new Error(`Certificate submission failed: ${response.error.message}`);
357
- }
358
- }
359
- async executeTransfer(senderPrivateKey, recipient, amount, userData) {
360
- const senderPublicKey = await (0, import_ed25519.getPublicKey)(senderPrivateKey);
361
- const nonce = await this.getNextNonce(senderPublicKey);
362
- const transaction = {
363
- sender: senderPublicKey,
364
- nonce,
365
- timestamp_nanos: BigInt(Date.now()) * 1000000n,
366
- claim: {
367
- Transfer: {
368
- recipient: { FastSet: recipient },
369
- amount,
370
- user_data: userData ?? null
371
- }
372
- }
1589
+ chain: this.chain.name,
1590
+ identifier,
1591
+ symbol: assetInfo.symbol,
1592
+ name: assetInfo.name,
1593
+ decimals: assetInfo.decimals,
1594
+ logoUrl: assetInfo.logoUrl || null,
1595
+ amount: 0n
373
1596
  };
374
- const signature = await this.signTransaction(transaction, senderPrivateKey);
375
- const submitResponse = await this.submitTransaction({
376
- transaction,
377
- signature
378
- });
379
- await this.submitCertificate({
380
- transaction,
381
- signature,
382
- validator_signatures: [[submitResponse.validator, submitResponse.signature]]
383
- });
384
- return submitResponse.transaction_hash;
385
1597
  }
386
- async signTransaction(transaction, privateKey) {
387
- const msg = Transaction.serialize(transaction);
388
- const msgBytes = msg.toBytes();
389
- const prefix = new TextEncoder().encode("Transaction::");
390
- const dataToSign = new Uint8Array(prefix.length + msgBytes.length);
391
- dataToSign.set(prefix, 0);
392
- dataToSign.set(msgBytes, prefix.length);
393
- return (0, import_ed25519.sign)(dataToSign, privateKey);
1598
+ async getAction(identifier, awaitCompleted = false) {
1599
+ return null;
394
1600
  }
395
- serializeTransaction(transaction) {
396
- return JSON.stringify(transaction, this.jsonReplacer);
1601
+ async getAccountActions(address, options) {
1602
+ return [];
397
1603
  }
398
- async requestValidator(method, params) {
399
- return this.request(this.config.validatorUrl, method, params);
1604
+ async getAssetInfo(identifier) {
1605
+ const knownToken = findKnownTokenById(identifier, this.config.env) || findKnownTokenBySymbol(identifier, this.config.env);
1606
+ if (knownToken) {
1607
+ return knownToken;
1608
+ }
1609
+ const tokenInfo = await this.client.getTokenInfo(hexToUint8Array(identifier));
1610
+ const metadata = tokenInfo.result?.requested_token_metadata[0]?.[1];
1611
+ if (metadata) {
1612
+ return {
1613
+ chain: this.chain.name,
1614
+ identifier,
1615
+ symbol: metadata.token_name,
1616
+ name: metadata.token_name,
1617
+ decimals: metadata.decimals,
1618
+ logoUrl: null
1619
+ };
1620
+ }
1621
+ return null;
400
1622
  }
401
- async requestProxy(method, params) {
402
- return this.request(this.config.proxyUrl, method, params);
1623
+ };
1624
+
1625
+ // src/WarpFastsetExecutor.ts
1626
+ var import_warps2 = require("@vleap/warps");
1627
+ var WarpFastsetExecutor = class {
1628
+ constructor(config, chain2) {
1629
+ this.config = config;
1630
+ this.chain = chain2;
1631
+ this.client = getConfiguredFastsetClient(this.config, this.chain);
403
1632
  }
404
- async request(url, method, params) {
405
- const request = {
406
- jsonrpc: "2.0",
407
- id: 1,
408
- method,
409
- params
410
- };
411
- const response = await fetch(url, {
412
- method: "POST",
413
- headers: { "Content-Type": "application/json" },
414
- body: JSON.stringify(request, this.jsonReplacer)
415
- });
416
- if (!response.ok) {
417
- throw new Error(`HTTP request failed: ${response.statusText}`);
418
- }
419
- return response.json();
1633
+ async createTransaction(executable) {
1634
+ const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
1635
+ if (action.type === "transfer") return this.createTransferTransaction(executable);
1636
+ if (action.type === "contract") return this.createContractCallTransaction(executable);
1637
+ if (action.type === "query") throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeQuery instead");
1638
+ if (action.type === "collect")
1639
+ throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeCollect instead");
1640
+ throw new Error(`WarpFastsetExecutor: Invalid action type (${action.type})`);
420
1641
  }
421
- jsonReplacer(key, value) {
422
- if (value instanceof Uint8Array) {
423
- return Array.from(value);
1642
+ async createTransferTransaction(executable) {
1643
+ const userWallet = (0, import_warps2.getWarpWalletAddressFromConfig)(this.config, executable.chain.name);
1644
+ if (!userWallet) throw new Error("WarpFastsetExecutor: createTransfer - user address not set");
1645
+ const senderPubKey = FastsetClient.decodeBech32Address(userWallet);
1646
+ const recipientPubKey = FastsetClient.decodeBech32Address(executable.destination);
1647
+ const nonce = await this.client.getNextNonce(userWallet);
1648
+ const isSingleNativeTransfer = executable.transfers.length === 1 && executable.transfers[0].identifier === this.chain.nativeToken?.identifier;
1649
+ const nativeAmountInTransfers = isSingleNativeTransfer ? executable.transfers[0].amount : 0n;
1650
+ const nativeAmountTotal = nativeAmountInTransfers + executable.value;
1651
+ if (nativeAmountTotal > 0n) {
1652
+ return {
1653
+ sender: senderPubKey,
1654
+ recipient: { FastSet: recipientPubKey },
1655
+ nonce,
1656
+ timestamp_nanos: BigInt(Date.now()) * 1000000n,
1657
+ claim: { Transfer: { amount: nativeAmountTotal.toString(16), user_data: null } }
1658
+ };
1659
+ } else if (executable.transfers.length === 1) {
1660
+ return {
1661
+ sender: senderPubKey,
1662
+ recipient: { FastSet: recipientPubKey },
1663
+ nonce,
1664
+ timestamp_nanos: BigInt(Date.now()) * 1000000n,
1665
+ claim: {
1666
+ TokenTransfer: {
1667
+ token_id: hexToUint8Array(executable.transfers[0].identifier),
1668
+ amount: executable.transfers[0].amount.toString(16),
1669
+ user_data: null
1670
+ }
1671
+ }
1672
+ };
1673
+ } else {
1674
+ throw new Error("WarpFastsetExecutor: No valid transfers provided (maximum 1 transfer allowed)");
424
1675
  }
425
- return value;
426
1676
  }
427
- };
428
-
429
- // src/sdk/utils.ts
430
- var import_bcs2 = require("@mysten/bcs");
431
- function isValidFastsetAddress(address) {
432
- if (typeof address !== "string" || address.length === 0) {
433
- return false;
1677
+ async createContractCallTransaction(executable) {
1678
+ throw new Error("WarpFastsetExecutor: Not implemented");
434
1679
  }
435
- if (address.startsWith("fs") || address.startsWith("pi")) {
436
- return true;
1680
+ async executeQuery(executable) {
1681
+ throw new Error("WarpFastsetExecutor: Not implemented");
437
1682
  }
438
- try {
439
- const decoded = fromBase64(address);
440
- return decoded.length === 32;
441
- } catch {
442
- return false;
1683
+ };
1684
+
1685
+ // src/WarpFastsetExplorer.ts
1686
+ var HEX_PREFIX = "0x";
1687
+ var WarpFastsetExplorer = class {
1688
+ constructor(_chainInfo, _config) {
1689
+ this._chainInfo = _chainInfo;
1690
+ this._config = _config;
1691
+ this.explorerUrl = "https://explorer.fastset.xyz";
443
1692
  }
444
- }
445
- function fromBase64(base64) {
446
- return new Uint8Array(Buffer.from(base64, "base64"));
447
- }
448
- function toBase64String(bytes) {
449
- return (0, import_bcs2.toBase64)(bytes);
450
- }
451
- function toHexString(bytes) {
452
- return (0, import_bcs2.toHex)(bytes);
453
- }
454
- function hexToDecimal2(hex) {
455
- return BigInt(`0x${hex}`).toString();
456
- }
457
- function decimalToHex(decimal) {
458
- return BigInt(decimal).toString(16);
459
- }
460
- function validateAmount(amount) {
461
- try {
462
- const bigInt = BigInt(amount);
463
- return bigInt >= 0;
464
- } catch {
465
- return false;
1693
+ getAccountUrl(address) {
1694
+ return `${this.explorerUrl}/account/${address}`;
466
1695
  }
467
- }
468
- function normalizeAmount(amount) {
469
- try {
470
- const bigInt = BigInt(amount);
471
- return bigInt.toString(16);
472
- } catch {
473
- throw new Error(`Invalid amount format: ${amount}`);
1696
+ getTransactionUrl(hash2) {
1697
+ return `${this.explorerUrl}/txs/${HEX_PREFIX}${hash2}`;
474
1698
  }
475
- }
476
- function validatePrivateKey(privateKey) {
477
- try {
478
- const key = typeof privateKey === "string" ? fromBase64(privateKey) : privateKey;
479
- return key.length === 32;
480
- } catch {
481
- return false;
1699
+ getAssetUrl(identifier) {
1700
+ return `${this.explorerUrl}/asset/${HEX_PREFIX}${identifier}`;
482
1701
  }
483
- }
484
- function validatePublicKey(publicKey) {
485
- try {
486
- const key = typeof publicKey === "string" ? fromBase64(publicKey) : publicKey;
487
- return key.length === 32;
488
- } catch {
489
- return false;
1702
+ getContractUrl(address) {
1703
+ return `${this.explorerUrl}/account/${address}`;
490
1704
  }
491
- }
1705
+ };
1706
+
1707
+ // src/WarpFastsetResults.ts
1708
+ var import_warps4 = require("@vleap/warps");
492
1709
 
493
1710
  // src/WarpFastsetSerializer.ts
494
- var import_warps = require("@vleap/warps");
1711
+ var import_warps3 = require("@vleap/warps");
495
1712
  var WarpFastsetSerializer = class {
496
1713
  constructor() {
497
- this.coreSerializer = new import_warps.WarpSerializer();
1714
+ this.coreSerializer = new import_warps3.WarpSerializer();
498
1715
  }
499
1716
  typedToString(value) {
500
1717
  if (typeof value === "string") {
@@ -507,7 +1724,7 @@ var WarpFastsetSerializer = class {
507
1724
  return `boolean:${value}`;
508
1725
  }
509
1726
  if (typeof value === "bigint") {
510
- return `bigint:${value.toString()}`;
1727
+ return `biguint:${value.toString()}`;
511
1728
  }
512
1729
  if (Array.isArray(value)) {
513
1730
  const items = value.map((item) => this.typedToString(item)).join(",");
@@ -532,7 +1749,7 @@ var WarpFastsetSerializer = class {
532
1749
  return ["boolean", value];
533
1750
  }
534
1751
  if (typeof value === "bigint") {
535
- return ["bigint", value];
1752
+ return ["biguint", value.toString()];
536
1753
  }
537
1754
  return ["string", String(value)];
538
1755
  }
@@ -544,8 +1761,12 @@ var WarpFastsetSerializer = class {
544
1761
  return Number(value);
545
1762
  case "boolean":
546
1763
  return Boolean(value);
547
- case "bigint":
1764
+ case "biguint":
548
1765
  return BigInt(value);
1766
+ case "address":
1767
+ return String(value);
1768
+ case "hex":
1769
+ return String(value);
549
1770
  default:
550
1771
  return String(value);
551
1772
  }
@@ -558,8 +1779,12 @@ var WarpFastsetSerializer = class {
558
1779
  return "number";
559
1780
  case "boolean":
560
1781
  return "boolean";
561
- case "bigint":
562
- return "bigint";
1782
+ case "biguint":
1783
+ return "biguint";
1784
+ case "address":
1785
+ return "address";
1786
+ case "hex":
1787
+ return "hex";
563
1788
  default:
564
1789
  return "string";
565
1790
  }
@@ -578,7 +1803,7 @@ var WarpFastsetSerializer = class {
578
1803
  return Number(stringValue);
579
1804
  case "boolean":
580
1805
  return stringValue === "true";
581
- case "bigint":
1806
+ case "biguint":
582
1807
  return BigInt(stringValue);
583
1808
  case "array":
584
1809
  return stringValue.split(",").map((item) => this.stringToTyped(item));
@@ -592,257 +1817,48 @@ var WarpFastsetSerializer = class {
592
1817
  }
593
1818
  };
594
1819
 
595
- // src/WarpFastsetExecutor.ts
596
- var WarpFastsetExecutor = class {
597
- constructor(config) {
598
- this.config = config;
599
- this.serializer = new WarpFastsetSerializer();
600
- this.fastsetClient = new FastsetClient({
601
- validatorUrl: getFastsetApiUrl(this.config.env, "fastset"),
602
- proxyUrl: getFastsetProxyUrl(this.config.env, "fastset")
603
- });
604
- }
605
- async createTransaction(executable) {
606
- const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
607
- switch (action.type) {
608
- case "transfer":
609
- return this.createTransferTransaction(executable);
610
- case "contract":
611
- return this.createContractCallTransaction(executable);
612
- case "query":
613
- throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeQuery instead");
614
- case "collect":
615
- throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeCollect instead");
616
- default:
617
- throw new Error(`WarpFastsetExecutor: Invalid action type (${action.type})`);
618
- }
619
- }
620
- async createTransferTransaction(executable) {
621
- const userWallet = this.config.user?.wallets?.[executable.chain];
622
- if (!userWallet) throw new Error("WarpFastsetExecutor: createTransfer - user address not set");
623
- if (!isValidFastsetAddress(executable.destination)) {
624
- throw new Error(`WarpFastsetExecutor: Invalid destination address: ${executable.destination}`);
625
- }
626
- if (executable.value < 0) {
627
- throw new Error(`WarpFastsetExecutor: Transfer value cannot be negative: ${executable.value}`);
628
- }
629
- const recipientAddress = fromBase64(executable.destination);
630
- const amount = normalizeAmount(executable.value.toString());
631
- const userData = executable.data ? fromBase64(this.serializer.stringToTyped(executable.data)) : void 0;
632
- return {
633
- type: "fastset-transfer",
634
- recipient: recipientAddress,
635
- amount,
636
- userData,
637
- chain: executable.chain
638
- };
639
- }
640
- async createContractCallTransaction(executable) {
641
- const userWallet = this.config.user?.wallets?.[executable.chain];
642
- if (!userWallet) throw new Error("WarpFastsetExecutor: createContractCall - user address not set");
643
- const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
644
- if (!action || !("func" in action) || !action.func) {
645
- throw new Error("WarpFastsetExecutor: Contract action must have a function name");
646
- }
647
- if (!isValidFastsetAddress(executable.destination)) {
648
- throw new Error(`WarpFastsetExecutor: Invalid contract address: ${executable.destination}`);
649
- }
650
- if (executable.value < 0) {
651
- throw new Error(`WarpFastsetExecutor: Contract call value cannot be negative: ${executable.value}`);
652
- }
653
- try {
654
- const contractAddress = fromBase64(executable.destination);
655
- const encodedData = this.encodeFunctionData(action.func, executable.args);
656
- return {
657
- type: "fastset-contract-call",
658
- contract: contractAddress,
659
- function: action.func,
660
- data: encodedData,
661
- value: executable.value,
662
- chain: executable.chain
663
- };
664
- } catch (error) {
665
- throw new Error(`WarpFastsetExecutor: Failed to encode function data for ${action.func}: ${error}`);
666
- }
667
- }
668
- async executeQuery(executable) {
669
- const action = (0, import_warps2.getWarpActionByIndex)(executable.warp, executable.action);
670
- if (action.type !== "query") {
671
- throw new Error(`WarpFastsetExecutor: Invalid action type for executeQuery: ${action.type}`);
672
- }
673
- if (!action.func) {
674
- throw new Error("WarpFastsetExecutor: Query action must have a function name");
675
- }
676
- if (!isValidFastsetAddress(executable.destination)) {
677
- throw new Error(`WarpFastsetExecutor: Invalid contract address for query: ${executable.destination}`);
678
- }
679
- try {
680
- const contractAddress = fromBase64(executable.destination);
681
- const result = await this.executeFastsetQuery(contractAddress, action.func, executable.args);
682
- return {
683
- success: true,
684
- result,
685
- chain: executable.chain
686
- };
687
- } catch (error) {
688
- return {
689
- success: false,
690
- error: error instanceof Error ? error.message : String(error),
691
- chain: executable.chain
692
- };
693
- }
694
- }
695
- async preprocessInput(chain, input, type, value) {
696
- const typedValue = this.serializer.stringToTyped(value);
697
- switch (type) {
698
- case "address":
699
- if (!isValidFastsetAddress(typedValue)) {
700
- throw new Error(`Invalid Fastset address format: ${typedValue}`);
701
- }
702
- return typedValue;
703
- case "hex":
704
- const hexValue = typedValue.startsWith("0x") ? typedValue.slice(2) : typedValue;
705
- if (!/^[0-9a-fA-F]+$/.test(hexValue)) {
706
- throw new Error(`Invalid hex format: ${typedValue}`);
707
- }
708
- return typedValue;
709
- case "number":
710
- const numValue = Number(typedValue);
711
- if (isNaN(numValue)) {
712
- throw new Error(`Invalid number format: ${typedValue}`);
713
- }
714
- return numValue.toString();
715
- case "biguint":
716
- const bigIntValue = BigInt(typedValue);
717
- if (bigIntValue < 0) {
718
- throw new Error(`Negative value not allowed`);
719
- }
720
- return bigIntValue.toString();
721
- default:
722
- return String(typedValue);
723
- }
724
- }
725
- encodeFunctionData(functionName, args) {
726
- return JSON.stringify({
727
- function: functionName,
728
- arguments: args
729
- });
730
- }
731
- async executeFastsetQuery(contractAddress, functionName, args) {
732
- const response = await fetch(`${getFastsetApiUrl(this.config.env, "fastset")}/query`, {
733
- method: "POST",
734
- headers: {
735
- "Content-Type": "application/json"
736
- },
737
- body: JSON.stringify({
738
- contract: Array.from(contractAddress),
739
- function: functionName,
740
- arguments: args
741
- })
742
- });
743
- if (!response.ok) {
744
- throw new Error(`Fastset query failed: ${response.statusText}`);
745
- }
746
- return response.json();
747
- }
748
- async signMessage(message, privateKey) {
749
- throw new Error("Not implemented");
750
- }
751
- async executeTransfer(executable) {
752
- const userWallet = this.config.user?.wallets?.[executable.chain];
753
- if (!userWallet) throw new Error("WarpFastsetExecutor: executeTransfer - user wallet not set");
754
- const transaction = await this.createTransferTransaction(executable);
755
- return {
756
- success: true,
757
- transaction,
758
- chain: executable.chain,
759
- message: "Transaction created successfully. Use executeTransferWithKey to execute with private key."
760
- };
761
- }
762
- async executeTransferWithKey(executable, privateKey) {
763
- const userWallet = this.config.user?.wallets?.[executable.chain];
764
- if (!userWallet) throw new Error("WarpFastsetExecutor: executeTransfer - user wallet not set");
765
- const transaction = await this.createTransferTransaction(executable);
766
- const privateKeyBytes = fromBase64(privateKey);
767
- const transactionHash = await this.fastsetClient.executeTransfer(
768
- privateKeyBytes,
769
- transaction.recipient,
770
- transaction.amount,
771
- transaction.userData
772
- );
773
- return {
774
- success: true,
775
- transactionHash: Array.from(transactionHash),
776
- chain: executable.chain
777
- };
778
- }
779
- };
780
-
781
- // src/WarpFastsetExplorer.ts
782
- var WarpFastsetExplorer = class {
783
- constructor(chainInfo) {
784
- this.chainInfo = chainInfo;
785
- }
786
- getAccountUrl(address) {
787
- const baseUrl = this.getDefaultExplorerUrl();
788
- return `${baseUrl}/address/${address}`;
789
- }
790
- getTransactionUrl(hash) {
791
- const baseUrl = this.getDefaultExplorerUrl();
792
- return `${baseUrl}/tx/${hash}`;
793
- }
794
- getBlockUrl(blockNumber) {
795
- const baseUrl = this.getDefaultExplorerUrl();
796
- return `${baseUrl}/block/${blockNumber}`;
797
- }
798
- getContractUrl(address) {
799
- const baseUrl = this.getDefaultExplorerUrl();
800
- return `${baseUrl}/contract/${address}`;
801
- }
802
- getTokenUrl(address) {
803
- const baseUrl = this.getDefaultExplorerUrl();
804
- return `${baseUrl}/token/${address}`;
805
- }
806
- getDefaultExplorerUrl() {
807
- return `https://explorer.fastset.xyz`;
808
- }
809
- };
810
-
811
1820
  // src/WarpFastsetResults.ts
812
- var import_warps3 = require("@vleap/warps");
813
1821
  var WarpFastsetResults = class {
814
- constructor(config) {
1822
+ constructor(config, chain2) {
815
1823
  this.config = config;
1824
+ this.chain = chain2;
816
1825
  this.serializer = new WarpFastsetSerializer();
817
1826
  }
818
- async getTransactionExecutionResults(warp, tx) {
1827
+ async getActionExecution(warp, actionIndex, tx) {
819
1828
  const success = this.isTransactionSuccessful(tx);
820
- const gasUsed = this.extractGasUsed(tx);
821
- const gasPrice = this.extractGasPrice(tx);
822
- const blockNumber = this.extractBlockNumber(tx);
823
1829
  const transactionHash = this.extractTransactionHash(tx);
824
- const logs = this.extractLogs(tx);
1830
+ const blockNumber = this.extractBlockNumber(tx);
1831
+ const timestamp = this.extractTimestamp(tx);
1832
+ const rawValues = [transactionHash, blockNumber, timestamp];
1833
+ const stringValues = rawValues.map((v) => String(v));
825
1834
  return {
826
1835
  success,
827
1836
  warp,
828
1837
  action: 0,
829
- user: this.config.user?.wallets?.fastset || null,
1838
+ user: (0, import_warps4.getWarpWalletAddressFromConfig)(this.config, this.chain.name),
830
1839
  txHash: transactionHash,
1840
+ tx,
831
1841
  next: null,
832
- values: [transactionHash, blockNumber, gasUsed, gasPrice, ...logs.length > 0 ? logs : []],
1842
+ values: { string: stringValues, native: rawValues },
833
1843
  results: {},
834
1844
  messages: {}
835
1845
  };
836
1846
  }
837
1847
  async extractQueryResults(warp, typedValues, actionIndex, inputs) {
838
- const values = typedValues.map((t) => this.serializer.typedToString(t));
839
- const valuesRaw = typedValues.map((t) => this.serializer.typedToNative(t)[1]);
1848
+ const stringValues = typedValues.map((t) => this.serializer.typedToString(t));
1849
+ const nativeValues = typedValues.map((t) => this.serializer.typedToNative(t)[1]);
1850
+ const values = { string: stringValues, native: nativeValues };
840
1851
  let results = {};
841
1852
  if (!warp.results) return { values, results };
842
1853
  const getNestedValue = (path) => {
1854
+ const match = path.match(/^out\[(\d+)\]$/);
1855
+ if (match) {
1856
+ const index = parseInt(match[1]) - 1;
1857
+ return nativeValues[index];
1858
+ }
843
1859
  const indices = path.split(".").slice(1).map((i) => parseInt(i) - 1);
844
1860
  if (indices.length === 0) return void 0;
845
- let value = valuesRaw[indices[0]];
1861
+ let value = nativeValues[indices[0]];
846
1862
  for (let i = 1; i < indices.length; i++) {
847
1863
  if (value === void 0 || value === null) return void 0;
848
1864
  value = value[indices[i]];
@@ -850,101 +1866,1147 @@ var WarpFastsetResults = class {
850
1866
  return value;
851
1867
  };
852
1868
  for (const [key, path] of Object.entries(warp.results)) {
853
- if (path.startsWith(import_warps3.WarpConstants.Transform.Prefix)) continue;
854
- const currentActionIndex = (0, import_warps3.parseResultsOutIndex)(path);
1869
+ if (path.startsWith(import_warps4.WarpConstants.Transform.Prefix)) continue;
1870
+ const currentActionIndex = (0, import_warps4.parseResultsOutIndex)(path);
855
1871
  if (currentActionIndex !== null && currentActionIndex !== actionIndex) {
856
1872
  results[key] = null;
857
1873
  continue;
858
1874
  }
859
1875
  if (path.startsWith("out.") || path === "out" || path.startsWith("out[")) {
860
- results[key] = getNestedValue(path) || null;
1876
+ const value = getNestedValue(path);
1877
+ results[key] = value || null;
861
1878
  } else {
862
1879
  results[key] = path;
863
1880
  }
864
1881
  }
865
- return { values, results: await (0, import_warps3.evaluateResultsCommon)(warp, results, actionIndex, inputs) };
1882
+ return {
1883
+ values,
1884
+ results: await (0, import_warps4.evaluateResultsCommon)(
1885
+ warp,
1886
+ results,
1887
+ actionIndex,
1888
+ inputs,
1889
+ this.serializer.coreSerializer,
1890
+ this.config.transform?.runner
1891
+ )
1892
+ };
866
1893
  }
867
1894
  isTransactionSuccessful(tx) {
868
- return tx.status === "success" || tx.status === 1 || tx.success === true;
869
- }
870
- extractGasUsed(tx) {
871
- return tx.gasUsed?.toString() || tx.gas_used?.toString() || "0";
1895
+ if (!tx) return false;
1896
+ if (tx.success === false) return false;
1897
+ if (tx.success === true) return true;
1898
+ if (tx.status === "success") return true;
1899
+ if (tx.status === 1) return true;
1900
+ if (tx.result && tx.result.success === true) return true;
1901
+ return false;
872
1902
  }
873
- extractGasPrice(tx) {
874
- return tx.gasPrice?.toString() || tx.gas_price?.toString() || "0";
1903
+ extractTransactionHash(tx) {
1904
+ if (!tx) return "";
1905
+ return tx.transaction_hash || tx.transactionHash || tx.hash || tx.result && tx.result.transaction_hash || "";
875
1906
  }
876
1907
  extractBlockNumber(tx) {
877
- return tx.blockNumber?.toString() || tx.block_number?.toString() || "0";
1908
+ if (!tx) return "0";
1909
+ return tx.block_number?.toString() || tx.blockNumber?.toString() || tx.result && tx.result.block_number?.toString() || "0";
878
1910
  }
879
- extractTransactionHash(tx) {
880
- return tx.hash || tx.transactionHash || tx.transaction_hash || "";
881
- }
882
- extractLogs(tx) {
883
- const logs = tx.logs || tx.events || [];
884
- return logs.map((log) => ({
885
- address: log.address || log.contract,
886
- topics: log.topics || log.topics || [],
887
- data: log.data || log.payload || "",
888
- blockNumber: log.blockNumber?.toString() || log.block_number?.toString() || "0",
889
- transactionHash: log.transactionHash || log.transaction_hash || "",
890
- index: log.index?.toString() || "0"
891
- }));
1911
+ extractTimestamp(tx) {
1912
+ if (!tx) return "0";
1913
+ return tx.timestamp?.toString() || tx.timestamp_nanos?.toString() || tx.result && tx.result.timestamp?.toString() || Date.now().toString();
1914
+ }
1915
+ };
1916
+
1917
+ // src/WarpFastsetWallet.ts
1918
+ var bip39 = __toESM(require("@scure/bip39"), 1);
1919
+ var import_warps5 = require("@vleap/warps");
1920
+
1921
+ // ../../node_modules/@noble/ed25519/index.js
1922
+ var ed25519_exports = {};
1923
+ __export(ed25519_exports, {
1924
+ Point: () => Point,
1925
+ etc: () => etc,
1926
+ getPublicKey: () => getPublicKey,
1927
+ getPublicKeyAsync: () => getPublicKeyAsync,
1928
+ hash: () => hash,
1929
+ hashes: () => hashes,
1930
+ keygen: () => keygen,
1931
+ keygenAsync: () => keygenAsync,
1932
+ sign: () => sign,
1933
+ signAsync: () => signAsync,
1934
+ utils: () => utils,
1935
+ verify: () => verify,
1936
+ verifyAsync: () => verifyAsync
1937
+ });
1938
+ var ed25519_CURVE = {
1939
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
1940
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
1941
+ h: 8n,
1942
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
1943
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
1944
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
1945
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
1946
+ };
1947
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
1948
+ var L = 32;
1949
+ var L2 = 64;
1950
+ var captureTrace = (...args) => {
1951
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
1952
+ Error.captureStackTrace(...args);
1953
+ }
1954
+ };
1955
+ var err = (message = "") => {
1956
+ const e = new Error(message);
1957
+ captureTrace(e, err);
1958
+ throw e;
1959
+ };
1960
+ var isBig = (n) => typeof n === "bigint";
1961
+ var isStr = (s) => typeof s === "string";
1962
+ var isBytes2 = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1963
+ var abytes = (value, length, title = "") => {
1964
+ const bytes = isBytes2(value);
1965
+ const len = value?.length;
1966
+ const needsLen = length !== void 0;
1967
+ if (!bytes || needsLen && len !== length) {
1968
+ const prefix = title && `"${title}" `;
1969
+ const ofLen = needsLen ? ` of length ${length}` : "";
1970
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
1971
+ err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
1972
+ }
1973
+ return value;
1974
+ };
1975
+ var u8n = (len) => new Uint8Array(len);
1976
+ var u8fr = (buf) => Uint8Array.from(buf);
1977
+ var padh = (n, pad) => n.toString(16).padStart(pad, "0");
1978
+ var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
1979
+ var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
1980
+ var _ch = (ch) => {
1981
+ if (ch >= C._0 && ch <= C._9)
1982
+ return ch - C._0;
1983
+ if (ch >= C.A && ch <= C.F)
1984
+ return ch - (C.A - 10);
1985
+ if (ch >= C.a && ch <= C.f)
1986
+ return ch - (C.a - 10);
1987
+ return;
1988
+ };
1989
+ var hexToBytes = (hex) => {
1990
+ const e = "hex invalid";
1991
+ if (!isStr(hex))
1992
+ return err(e);
1993
+ const hl = hex.length;
1994
+ const al = hl / 2;
1995
+ if (hl % 2)
1996
+ return err(e);
1997
+ const array = u8n(al);
1998
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1999
+ const n1 = _ch(hex.charCodeAt(hi));
2000
+ const n2 = _ch(hex.charCodeAt(hi + 1));
2001
+ if (n1 === void 0 || n2 === void 0)
2002
+ return err(e);
2003
+ array[ai] = n1 * 16 + n2;
2004
+ }
2005
+ return array;
2006
+ };
2007
+ var cr = () => globalThis?.crypto;
2008
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
2009
+ var concatBytes = (...arrs) => {
2010
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
2011
+ let pad = 0;
2012
+ arrs.forEach((a) => {
2013
+ r.set(a, pad);
2014
+ pad += a.length;
2015
+ });
2016
+ return r;
2017
+ };
2018
+ var randomBytes = (len = L) => {
2019
+ const c = cr();
2020
+ return c.getRandomValues(u8n(len));
2021
+ };
2022
+ var big = BigInt;
2023
+ var assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
2024
+ var M = (a, b = P) => {
2025
+ const r = a % b;
2026
+ return r >= 0n ? r : b + r;
2027
+ };
2028
+ var modN = (a) => M(a, N);
2029
+ var invert = (num, md) => {
2030
+ if (num === 0n || md <= 0n)
2031
+ err("no inverse n=" + num + " mod=" + md);
2032
+ let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
2033
+ while (a !== 0n) {
2034
+ const q = b / a, r = b % a;
2035
+ const m = x - u * q, n = y - v * q;
2036
+ b = a, a = r, x = u, y = v, u = m, v = n;
2037
+ }
2038
+ return b === 1n ? M(x, md) : err("no inverse");
2039
+ };
2040
+ var callHash = (name2) => {
2041
+ const fn = hashes[name2];
2042
+ if (typeof fn !== "function")
2043
+ err("hashes." + name2 + " not set");
2044
+ return fn;
2045
+ };
2046
+ var hash = (msg) => callHash("sha512")(msg);
2047
+ var apoint = (p) => p instanceof Point ? p : err("Point expected");
2048
+ var B256 = 2n ** 256n;
2049
+ var _Point = class _Point {
2050
+ constructor(X, Y, Z, T) {
2051
+ __publicField(this, "X");
2052
+ __publicField(this, "Y");
2053
+ __publicField(this, "Z");
2054
+ __publicField(this, "T");
2055
+ const max = B256;
2056
+ this.X = assertRange(X, 0n, max);
2057
+ this.Y = assertRange(Y, 0n, max);
2058
+ this.Z = assertRange(Z, 1n, max);
2059
+ this.T = assertRange(T, 0n, max);
2060
+ Object.freeze(this);
2061
+ }
2062
+ static CURVE() {
2063
+ return ed25519_CURVE;
2064
+ }
2065
+ static fromAffine(p) {
2066
+ return new _Point(p.x, p.y, 1n, M(p.x * p.y));
2067
+ }
2068
+ /** RFC8032 5.1.3: Uint8Array to Point. */
2069
+ static fromBytes(hex, zip215 = false) {
2070
+ const d = _d;
2071
+ const normed = u8fr(abytes(hex, L));
2072
+ const lastByte = hex[31];
2073
+ normed[31] = lastByte & ~128;
2074
+ const y = bytesToNumLE(normed);
2075
+ const max = zip215 ? B256 : P;
2076
+ assertRange(y, 0n, max);
2077
+ const y2 = M(y * y);
2078
+ const u = M(y2 - 1n);
2079
+ const v = M(d * y2 + 1n);
2080
+ let { isValid, value: x } = uvRatio(u, v);
2081
+ if (!isValid)
2082
+ err("bad point: y not sqrt");
2083
+ const isXOdd = (x & 1n) === 1n;
2084
+ const isLastByteOdd = (lastByte & 128) !== 0;
2085
+ if (!zip215 && x === 0n && isLastByteOdd)
2086
+ err("bad point: x==0, isLastByteOdd");
2087
+ if (isLastByteOdd !== isXOdd)
2088
+ x = M(-x);
2089
+ return new _Point(x, y, 1n, M(x * y));
2090
+ }
2091
+ static fromHex(hex, zip215) {
2092
+ return _Point.fromBytes(hexToBytes(hex), zip215);
2093
+ }
2094
+ get x() {
2095
+ return this.toAffine().x;
2096
+ }
2097
+ get y() {
2098
+ return this.toAffine().y;
2099
+ }
2100
+ /** Checks if the point is valid and on-curve. */
2101
+ assertValidity() {
2102
+ const a = _a;
2103
+ const d = _d;
2104
+ const p = this;
2105
+ if (p.is0())
2106
+ return err("bad point: ZERO");
2107
+ const { X, Y, Z, T } = p;
2108
+ const X2 = M(X * X);
2109
+ const Y2 = M(Y * Y);
2110
+ const Z2 = M(Z * Z);
2111
+ const Z4 = M(Z2 * Z2);
2112
+ const aX2 = M(X2 * a);
2113
+ const left = M(Z2 * M(aX2 + Y2));
2114
+ const right = M(Z4 + M(d * M(X2 * Y2)));
2115
+ if (left !== right)
2116
+ return err("bad point: equation left != right (1)");
2117
+ const XY = M(X * Y);
2118
+ const ZT = M(Z * T);
2119
+ if (XY !== ZT)
2120
+ return err("bad point: equation left != right (2)");
2121
+ return this;
2122
+ }
2123
+ /** Equality check: compare points P&Q. */
2124
+ equals(other) {
2125
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2126
+ const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
2127
+ const X1Z2 = M(X1 * Z2);
2128
+ const X2Z1 = M(X2 * Z1);
2129
+ const Y1Z2 = M(Y1 * Z2);
2130
+ const Y2Z1 = M(Y2 * Z1);
2131
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
2132
+ }
2133
+ is0() {
2134
+ return this.equals(I);
2135
+ }
2136
+ /** Flip point over y coordinate. */
2137
+ negate() {
2138
+ return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
2139
+ }
2140
+ /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
2141
+ double() {
2142
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2143
+ const a = _a;
2144
+ const A = M(X1 * X1);
2145
+ const B = M(Y1 * Y1);
2146
+ const C2 = M(2n * M(Z1 * Z1));
2147
+ const D = M(a * A);
2148
+ const x1y1 = X1 + Y1;
2149
+ const E = M(M(x1y1 * x1y1) - A - B);
2150
+ const G2 = D + B;
2151
+ const F = G2 - C2;
2152
+ const H = D - B;
2153
+ const X3 = M(E * F);
2154
+ const Y3 = M(G2 * H);
2155
+ const T3 = M(E * H);
2156
+ const Z3 = M(F * G2);
2157
+ return new _Point(X3, Y3, Z3, T3);
2158
+ }
2159
+ /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
2160
+ add(other) {
2161
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
2162
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
2163
+ const a = _a;
2164
+ const d = _d;
2165
+ const A = M(X1 * X2);
2166
+ const B = M(Y1 * Y2);
2167
+ const C2 = M(T1 * d * T2);
2168
+ const D = M(Z1 * Z2);
2169
+ const E = M((X1 + Y1) * (X2 + Y2) - A - B);
2170
+ const F = M(D - C2);
2171
+ const G2 = M(D + C2);
2172
+ const H = M(B - a * A);
2173
+ const X3 = M(E * F);
2174
+ const Y3 = M(G2 * H);
2175
+ const T3 = M(E * H);
2176
+ const Z3 = M(F * G2);
2177
+ return new _Point(X3, Y3, Z3, T3);
2178
+ }
2179
+ subtract(other) {
2180
+ return this.add(apoint(other).negate());
2181
+ }
2182
+ /**
2183
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
2184
+ * Uses {@link wNAF} for base point.
2185
+ * Uses fake point to mitigate side-channel leakage.
2186
+ * @param n scalar by which point is multiplied
2187
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
2188
+ */
2189
+ multiply(n, safe = true) {
2190
+ if (!safe && (n === 0n || this.is0()))
2191
+ return I;
2192
+ assertRange(n, 1n, N);
2193
+ if (n === 1n)
2194
+ return this;
2195
+ if (this.equals(G))
2196
+ return wNAF(n).p;
2197
+ let p = I;
2198
+ let f = G;
2199
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
2200
+ if (n & 1n)
2201
+ p = p.add(d);
2202
+ else if (safe)
2203
+ f = f.add(d);
2204
+ }
2205
+ return p;
2206
+ }
2207
+ multiplyUnsafe(scalar) {
2208
+ return this.multiply(scalar, false);
2209
+ }
2210
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
2211
+ toAffine() {
2212
+ const { X, Y, Z } = this;
2213
+ if (this.equals(I))
2214
+ return { x: 0n, y: 1n };
2215
+ const iz = invert(Z, P);
2216
+ if (M(Z * iz) !== 1n)
2217
+ err("invalid inverse");
2218
+ const x = M(X * iz);
2219
+ const y = M(Y * iz);
2220
+ return { x, y };
2221
+ }
2222
+ toBytes() {
2223
+ const { x, y } = this.assertValidity().toAffine();
2224
+ const b = numTo32bLE(y);
2225
+ b[31] |= x & 1n ? 128 : 0;
2226
+ return b;
2227
+ }
2228
+ toHex() {
2229
+ return bytesToHex(this.toBytes());
2230
+ }
2231
+ clearCofactor() {
2232
+ return this.multiply(big(h), false);
2233
+ }
2234
+ isSmallOrder() {
2235
+ return this.clearCofactor().is0();
2236
+ }
2237
+ isTorsionFree() {
2238
+ let p = this.multiply(N / 2n, false).double();
2239
+ if (N % 2n)
2240
+ p = p.add(this);
2241
+ return p.is0();
2242
+ }
2243
+ };
2244
+ __publicField(_Point, "BASE");
2245
+ __publicField(_Point, "ZERO");
2246
+ var Point = _Point;
2247
+ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
2248
+ var I = new Point(0n, 1n, 1n, 0n);
2249
+ Point.BASE = G;
2250
+ Point.ZERO = I;
2251
+ var numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
2252
+ var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
2253
+ var pow2 = (x, power) => {
2254
+ let r = x;
2255
+ while (power-- > 0n) {
2256
+ r *= r;
2257
+ r %= P;
2258
+ }
2259
+ return r;
2260
+ };
2261
+ var pow_2_252_3 = (x) => {
2262
+ const x2 = x * x % P;
2263
+ const b2 = x2 * x % P;
2264
+ const b4 = pow2(b2, 2n) * b2 % P;
2265
+ const b5 = pow2(b4, 1n) * x % P;
2266
+ const b10 = pow2(b5, 5n) * b5 % P;
2267
+ const b20 = pow2(b10, 10n) * b10 % P;
2268
+ const b40 = pow2(b20, 20n) * b20 % P;
2269
+ const b80 = pow2(b40, 40n) * b40 % P;
2270
+ const b160 = pow2(b80, 80n) * b80 % P;
2271
+ const b240 = pow2(b160, 80n) * b80 % P;
2272
+ const b250 = pow2(b240, 10n) * b10 % P;
2273
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
2274
+ return { pow_p_5_8, b2 };
2275
+ };
2276
+ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
2277
+ var uvRatio = (u, v) => {
2278
+ const v3 = M(v * v * v);
2279
+ const v7 = M(v3 * v3 * v);
2280
+ const pow = pow_2_252_3(u * v7).pow_p_5_8;
2281
+ let x = M(u * v3 * pow);
2282
+ const vx2 = M(v * x * x);
2283
+ const root1 = x;
2284
+ const root2 = M(x * RM1);
2285
+ const useRoot1 = vx2 === u;
2286
+ const useRoot2 = vx2 === M(-u);
2287
+ const noRoot = vx2 === M(-u * RM1);
2288
+ if (useRoot1)
2289
+ x = root1;
2290
+ if (useRoot2 || noRoot)
2291
+ x = root2;
2292
+ if ((M(x) & 1n) === 1n)
2293
+ x = M(-x);
2294
+ return { isValid: useRoot1 || useRoot2, value: x };
2295
+ };
2296
+ var modL_LE = (hash2) => modN(bytesToNumLE(hash2));
2297
+ var sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
2298
+ var sha512s = (...m) => callHash("sha512")(concatBytes(...m));
2299
+ var hash2extK = (hashed) => {
2300
+ const head = hashed.slice(0, L);
2301
+ head[0] &= 248;
2302
+ head[31] &= 127;
2303
+ head[31] |= 64;
2304
+ const prefix = hashed.slice(L, L2);
2305
+ const scalar = modL_LE(head);
2306
+ const point = G.multiply(scalar);
2307
+ const pointBytes = point.toBytes();
2308
+ return { head, prefix, scalar, point, pointBytes };
2309
+ };
2310
+ var getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
2311
+ var getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
2312
+ var getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
2313
+ var getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
2314
+ var hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
2315
+ var hashFinishS = (res) => res.finish(sha512s(res.hashable));
2316
+ var _sign = (e, rBytes, msg) => {
2317
+ const { pointBytes: P2, scalar: s } = e;
2318
+ const r = modL_LE(rBytes);
2319
+ const R = G.multiply(r).toBytes();
2320
+ const hashable = concatBytes(R, P2, msg);
2321
+ const finish = (hashed) => {
2322
+ const S = modN(r + modL_LE(hashed) * s);
2323
+ return abytes(concatBytes(R, numTo32bLE(S)), L2);
2324
+ };
2325
+ return { hashable, finish };
2326
+ };
2327
+ var signAsync = async (message, secretKey) => {
2328
+ const m = abytes(message);
2329
+ const e = await getExtendedPublicKeyAsync(secretKey);
2330
+ const rBytes = await sha512a(e.prefix, m);
2331
+ return hashFinishA(_sign(e, rBytes, m));
2332
+ };
2333
+ var sign = (message, secretKey) => {
2334
+ const m = abytes(message);
2335
+ const e = getExtendedPublicKey(secretKey);
2336
+ const rBytes = sha512s(e.prefix, m);
2337
+ return hashFinishS(_sign(e, rBytes, m));
2338
+ };
2339
+ var defaultVerifyOpts = { zip215: true };
2340
+ var _verify = (sig, msg, pub, opts = defaultVerifyOpts) => {
2341
+ sig = abytes(sig, L2);
2342
+ msg = abytes(msg);
2343
+ pub = abytes(pub, L);
2344
+ const { zip215 } = opts;
2345
+ let A;
2346
+ let R;
2347
+ let s;
2348
+ let SB;
2349
+ let hashable = Uint8Array.of();
2350
+ try {
2351
+ A = Point.fromBytes(pub, zip215);
2352
+ R = Point.fromBytes(sig.slice(0, L), zip215);
2353
+ s = bytesToNumLE(sig.slice(L, L2));
2354
+ SB = G.multiply(s, false);
2355
+ hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
2356
+ } catch (error) {
2357
+ }
2358
+ const finish = (hashed) => {
2359
+ if (SB == null)
2360
+ return false;
2361
+ if (!zip215 && A.isSmallOrder())
2362
+ return false;
2363
+ const k = modL_LE(hashed);
2364
+ const RkA = R.add(A.multiply(k, false));
2365
+ return RkA.add(SB.negate()).clearCofactor().is0();
2366
+ };
2367
+ return { hashable, finish };
2368
+ };
2369
+ var verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
2370
+ var verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));
2371
+ var etc = {
2372
+ bytesToHex,
2373
+ hexToBytes,
2374
+ concatBytes,
2375
+ mod: M,
2376
+ invert,
2377
+ randomBytes
2378
+ };
2379
+ var hashes = {
2380
+ sha512Async: async (message) => {
2381
+ const s = subtle();
2382
+ const m = concatBytes(message);
2383
+ return u8n(await s.digest("SHA-512", m.buffer));
2384
+ },
2385
+ sha512: void 0
2386
+ };
2387
+ var randomSecretKey = (seed = randomBytes(L)) => seed;
2388
+ var keygen = (seed) => {
2389
+ const secretKey = randomSecretKey(seed);
2390
+ const publicKey = getPublicKey(secretKey);
2391
+ return { secretKey, publicKey };
2392
+ };
2393
+ var keygenAsync = async (seed) => {
2394
+ const secretKey = randomSecretKey(seed);
2395
+ const publicKey = await getPublicKeyAsync(secretKey);
2396
+ return { secretKey, publicKey };
2397
+ };
2398
+ var utils = {
2399
+ getExtendedPublicKeyAsync,
2400
+ getExtendedPublicKey,
2401
+ randomSecretKey
2402
+ };
2403
+ var W = 8;
2404
+ var scalarBits = 256;
2405
+ var pwindows = Math.ceil(scalarBits / W) + 1;
2406
+ var pwindowSize = 2 ** (W - 1);
2407
+ var precompute = () => {
2408
+ const points = [];
2409
+ let p = G;
2410
+ let b = p;
2411
+ for (let w = 0; w < pwindows; w++) {
2412
+ b = p;
2413
+ points.push(b);
2414
+ for (let i = 1; i < pwindowSize; i++) {
2415
+ b = b.add(p);
2416
+ points.push(b);
2417
+ }
2418
+ p = b.double();
2419
+ }
2420
+ return points;
2421
+ };
2422
+ var Gpows = void 0;
2423
+ var ctneg = (cnd, p) => {
2424
+ const n = p.negate();
2425
+ return cnd ? n : p;
2426
+ };
2427
+ var wNAF = (n) => {
2428
+ const comp = Gpows || (Gpows = precompute());
2429
+ let p = I;
2430
+ let f = G;
2431
+ const pow_2_w = 2 ** W;
2432
+ const maxNum = pow_2_w;
2433
+ const mask = big(pow_2_w - 1);
2434
+ const shiftBy = big(W);
2435
+ for (let w = 0; w < pwindows; w++) {
2436
+ let wbits = Number(n & mask);
2437
+ n >>= shiftBy;
2438
+ if (wbits > pwindowSize) {
2439
+ wbits -= maxNum;
2440
+ n += 1n;
2441
+ }
2442
+ const off = w * pwindowSize;
2443
+ const offF = off;
2444
+ const offP = off + Math.abs(wbits) - 1;
2445
+ const isEven = w % 2 !== 0;
2446
+ const isNeg = wbits < 0;
2447
+ if (wbits === 0) {
2448
+ f = f.add(ctneg(isEven, comp[offF]));
2449
+ } else {
2450
+ p = p.add(ctneg(isNeg, comp[offP]));
2451
+ }
2452
+ }
2453
+ if (n !== 0n)
2454
+ err("invalid wnaf");
2455
+ return { p, f };
2456
+ };
2457
+
2458
+ // ../../node_modules/@noble/hashes/esm/utils.js
2459
+ function isBytes3(a) {
2460
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2461
+ }
2462
+ function abytes2(b, ...lengths) {
2463
+ if (!isBytes3(b))
2464
+ throw new Error("Uint8Array expected");
2465
+ if (lengths.length > 0 && !lengths.includes(b.length))
2466
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
2467
+ }
2468
+ function aexists(instance, checkFinished = true) {
2469
+ if (instance.destroyed)
2470
+ throw new Error("Hash instance has been destroyed");
2471
+ if (checkFinished && instance.finished)
2472
+ throw new Error("Hash#digest() has already been called");
2473
+ }
2474
+ function aoutput(out, instance) {
2475
+ abytes2(out);
2476
+ const min = instance.outputLen;
2477
+ if (out.length < min) {
2478
+ throw new Error("digestInto() expects output buffer of length at least " + min);
2479
+ }
2480
+ }
2481
+ function clean(...arrays) {
2482
+ for (let i = 0; i < arrays.length; i++) {
2483
+ arrays[i].fill(0);
2484
+ }
2485
+ }
2486
+ function createView(arr) {
2487
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2488
+ }
2489
+ function utf8ToBytes(str) {
2490
+ if (typeof str !== "string")
2491
+ throw new Error("string expected");
2492
+ return new Uint8Array(new TextEncoder().encode(str));
2493
+ }
2494
+ function toBytes(data) {
2495
+ if (typeof data === "string")
2496
+ data = utf8ToBytes(data);
2497
+ abytes2(data);
2498
+ return data;
2499
+ }
2500
+ var Hash = class {
2501
+ };
2502
+ function createHasher(hashCons) {
2503
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
2504
+ const tmp = hashCons();
2505
+ hashC.outputLen = tmp.outputLen;
2506
+ hashC.blockLen = tmp.blockLen;
2507
+ hashC.create = () => hashCons();
2508
+ return hashC;
2509
+ }
2510
+
2511
+ // ../../node_modules/@noble/hashes/esm/_md.js
2512
+ function setBigUint64(view, byteOffset, value, isLE) {
2513
+ if (typeof view.setBigUint64 === "function")
2514
+ return view.setBigUint64(byteOffset, value, isLE);
2515
+ const _32n2 = BigInt(32);
2516
+ const _u32_max = BigInt(4294967295);
2517
+ const wh = Number(value >> _32n2 & _u32_max);
2518
+ const wl = Number(value & _u32_max);
2519
+ const h2 = isLE ? 4 : 0;
2520
+ const l = isLE ? 0 : 4;
2521
+ view.setUint32(byteOffset + h2, wh, isLE);
2522
+ view.setUint32(byteOffset + l, wl, isLE);
2523
+ }
2524
+ var HashMD = class extends Hash {
2525
+ constructor(blockLen, outputLen, padOffset, isLE) {
2526
+ super();
2527
+ this.finished = false;
2528
+ this.length = 0;
2529
+ this.pos = 0;
2530
+ this.destroyed = false;
2531
+ this.blockLen = blockLen;
2532
+ this.outputLen = outputLen;
2533
+ this.padOffset = padOffset;
2534
+ this.isLE = isLE;
2535
+ this.buffer = new Uint8Array(blockLen);
2536
+ this.view = createView(this.buffer);
2537
+ }
2538
+ update(data) {
2539
+ aexists(this);
2540
+ data = toBytes(data);
2541
+ abytes2(data);
2542
+ const { view, buffer, blockLen } = this;
2543
+ const len = data.length;
2544
+ for (let pos = 0; pos < len; ) {
2545
+ const take = Math.min(blockLen - this.pos, len - pos);
2546
+ if (take === blockLen) {
2547
+ const dataView = createView(data);
2548
+ for (; blockLen <= len - pos; pos += blockLen)
2549
+ this.process(dataView, pos);
2550
+ continue;
2551
+ }
2552
+ buffer.set(data.subarray(pos, pos + take), this.pos);
2553
+ this.pos += take;
2554
+ pos += take;
2555
+ if (this.pos === blockLen) {
2556
+ this.process(view, 0);
2557
+ this.pos = 0;
2558
+ }
2559
+ }
2560
+ this.length += data.length;
2561
+ this.roundClean();
2562
+ return this;
2563
+ }
2564
+ digestInto(out) {
2565
+ aexists(this);
2566
+ aoutput(out, this);
2567
+ this.finished = true;
2568
+ const { buffer, view, blockLen, isLE } = this;
2569
+ let { pos } = this;
2570
+ buffer[pos++] = 128;
2571
+ clean(this.buffer.subarray(pos));
2572
+ if (this.padOffset > blockLen - pos) {
2573
+ this.process(view, 0);
2574
+ pos = 0;
2575
+ }
2576
+ for (let i = pos; i < blockLen; i++)
2577
+ buffer[i] = 0;
2578
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
2579
+ this.process(view, 0);
2580
+ const oview = createView(out);
2581
+ const len = this.outputLen;
2582
+ if (len % 4)
2583
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
2584
+ const outLen = len / 4;
2585
+ const state = this.get();
2586
+ if (outLen > state.length)
2587
+ throw new Error("_sha2: outputLen bigger than state");
2588
+ for (let i = 0; i < outLen; i++)
2589
+ oview.setUint32(4 * i, state[i], isLE);
2590
+ }
2591
+ digest() {
2592
+ const { buffer, outputLen } = this;
2593
+ this.digestInto(buffer);
2594
+ const res = buffer.slice(0, outputLen);
2595
+ this.destroy();
2596
+ return res;
2597
+ }
2598
+ _cloneInto(to) {
2599
+ to || (to = new this.constructor());
2600
+ to.set(...this.get());
2601
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
2602
+ to.destroyed = destroyed;
2603
+ to.finished = finished;
2604
+ to.length = length;
2605
+ to.pos = pos;
2606
+ if (length % blockLen)
2607
+ to.buffer.set(buffer);
2608
+ return to;
2609
+ }
2610
+ clone() {
2611
+ return this._cloneInto();
2612
+ }
2613
+ };
2614
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
2615
+ 1779033703,
2616
+ 4089235720,
2617
+ 3144134277,
2618
+ 2227873595,
2619
+ 1013904242,
2620
+ 4271175723,
2621
+ 2773480762,
2622
+ 1595750129,
2623
+ 1359893119,
2624
+ 2917565137,
2625
+ 2600822924,
2626
+ 725511199,
2627
+ 528734635,
2628
+ 4215389547,
2629
+ 1541459225,
2630
+ 327033209
2631
+ ]);
2632
+
2633
+ // ../../node_modules/@noble/hashes/esm/_u64.js
2634
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2635
+ var _32n = /* @__PURE__ */ BigInt(32);
2636
+ function fromBig(n, le = false) {
2637
+ if (le)
2638
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
2639
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
2640
+ }
2641
+ function split(lst, le = false) {
2642
+ const len = lst.length;
2643
+ let Ah = new Uint32Array(len);
2644
+ let Al = new Uint32Array(len);
2645
+ for (let i = 0; i < len; i++) {
2646
+ const { h: h2, l } = fromBig(lst[i], le);
2647
+ [Ah[i], Al[i]] = [h2, l];
2648
+ }
2649
+ return [Ah, Al];
2650
+ }
2651
+ var shrSH = (h2, _l, s) => h2 >>> s;
2652
+ var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
2653
+ var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
2654
+ var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
2655
+ var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
2656
+ var rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
2657
+ function add(Ah, Al, Bh, Bl) {
2658
+ const l = (Al >>> 0) + (Bl >>> 0);
2659
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
2660
+ }
2661
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
2662
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
2663
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
2664
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
2665
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
2666
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
2667
+
2668
+ // ../../node_modules/@noble/hashes/esm/sha2.js
2669
+ var K512 = /* @__PURE__ */ (() => split([
2670
+ "0x428a2f98d728ae22",
2671
+ "0x7137449123ef65cd",
2672
+ "0xb5c0fbcfec4d3b2f",
2673
+ "0xe9b5dba58189dbbc",
2674
+ "0x3956c25bf348b538",
2675
+ "0x59f111f1b605d019",
2676
+ "0x923f82a4af194f9b",
2677
+ "0xab1c5ed5da6d8118",
2678
+ "0xd807aa98a3030242",
2679
+ "0x12835b0145706fbe",
2680
+ "0x243185be4ee4b28c",
2681
+ "0x550c7dc3d5ffb4e2",
2682
+ "0x72be5d74f27b896f",
2683
+ "0x80deb1fe3b1696b1",
2684
+ "0x9bdc06a725c71235",
2685
+ "0xc19bf174cf692694",
2686
+ "0xe49b69c19ef14ad2",
2687
+ "0xefbe4786384f25e3",
2688
+ "0x0fc19dc68b8cd5b5",
2689
+ "0x240ca1cc77ac9c65",
2690
+ "0x2de92c6f592b0275",
2691
+ "0x4a7484aa6ea6e483",
2692
+ "0x5cb0a9dcbd41fbd4",
2693
+ "0x76f988da831153b5",
2694
+ "0x983e5152ee66dfab",
2695
+ "0xa831c66d2db43210",
2696
+ "0xb00327c898fb213f",
2697
+ "0xbf597fc7beef0ee4",
2698
+ "0xc6e00bf33da88fc2",
2699
+ "0xd5a79147930aa725",
2700
+ "0x06ca6351e003826f",
2701
+ "0x142929670a0e6e70",
2702
+ "0x27b70a8546d22ffc",
2703
+ "0x2e1b21385c26c926",
2704
+ "0x4d2c6dfc5ac42aed",
2705
+ "0x53380d139d95b3df",
2706
+ "0x650a73548baf63de",
2707
+ "0x766a0abb3c77b2a8",
2708
+ "0x81c2c92e47edaee6",
2709
+ "0x92722c851482353b",
2710
+ "0xa2bfe8a14cf10364",
2711
+ "0xa81a664bbc423001",
2712
+ "0xc24b8b70d0f89791",
2713
+ "0xc76c51a30654be30",
2714
+ "0xd192e819d6ef5218",
2715
+ "0xd69906245565a910",
2716
+ "0xf40e35855771202a",
2717
+ "0x106aa07032bbd1b8",
2718
+ "0x19a4c116b8d2d0c8",
2719
+ "0x1e376c085141ab53",
2720
+ "0x2748774cdf8eeb99",
2721
+ "0x34b0bcb5e19b48a8",
2722
+ "0x391c0cb3c5c95a63",
2723
+ "0x4ed8aa4ae3418acb",
2724
+ "0x5b9cca4f7763e373",
2725
+ "0x682e6ff3d6b2b8a3",
2726
+ "0x748f82ee5defb2fc",
2727
+ "0x78a5636f43172f60",
2728
+ "0x84c87814a1f0ab72",
2729
+ "0x8cc702081a6439ec",
2730
+ "0x90befffa23631e28",
2731
+ "0xa4506cebde82bde9",
2732
+ "0xbef9a3f7b2c67915",
2733
+ "0xc67178f2e372532b",
2734
+ "0xca273eceea26619c",
2735
+ "0xd186b8c721c0c207",
2736
+ "0xeada7dd6cde0eb1e",
2737
+ "0xf57d4f7fee6ed178",
2738
+ "0x06f067aa72176fba",
2739
+ "0x0a637dc5a2c898a6",
2740
+ "0x113f9804bef90dae",
2741
+ "0x1b710b35131c471b",
2742
+ "0x28db77f523047d84",
2743
+ "0x32caab7b40c72493",
2744
+ "0x3c9ebe0a15c9bebc",
2745
+ "0x431d67c49c100d4c",
2746
+ "0x4cc5d4becb3e42b6",
2747
+ "0x597f299cfc657e2a",
2748
+ "0x5fcb6fab3ad6faec",
2749
+ "0x6c44198c4a475817"
2750
+ ].map((n) => BigInt(n))))();
2751
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
2752
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
2753
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
2754
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
2755
+ var SHA512 = class extends HashMD {
2756
+ constructor(outputLen = 64) {
2757
+ super(128, outputLen, 16, false);
2758
+ this.Ah = SHA512_IV[0] | 0;
2759
+ this.Al = SHA512_IV[1] | 0;
2760
+ this.Bh = SHA512_IV[2] | 0;
2761
+ this.Bl = SHA512_IV[3] | 0;
2762
+ this.Ch = SHA512_IV[4] | 0;
2763
+ this.Cl = SHA512_IV[5] | 0;
2764
+ this.Dh = SHA512_IV[6] | 0;
2765
+ this.Dl = SHA512_IV[7] | 0;
2766
+ this.Eh = SHA512_IV[8] | 0;
2767
+ this.El = SHA512_IV[9] | 0;
2768
+ this.Fh = SHA512_IV[10] | 0;
2769
+ this.Fl = SHA512_IV[11] | 0;
2770
+ this.Gh = SHA512_IV[12] | 0;
2771
+ this.Gl = SHA512_IV[13] | 0;
2772
+ this.Hh = SHA512_IV[14] | 0;
2773
+ this.Hl = SHA512_IV[15] | 0;
2774
+ }
2775
+ // prettier-ignore
2776
+ get() {
2777
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
2778
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
2779
+ }
2780
+ // prettier-ignore
2781
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
2782
+ this.Ah = Ah | 0;
2783
+ this.Al = Al | 0;
2784
+ this.Bh = Bh | 0;
2785
+ this.Bl = Bl | 0;
2786
+ this.Ch = Ch | 0;
2787
+ this.Cl = Cl | 0;
2788
+ this.Dh = Dh | 0;
2789
+ this.Dl = Dl | 0;
2790
+ this.Eh = Eh | 0;
2791
+ this.El = El | 0;
2792
+ this.Fh = Fh | 0;
2793
+ this.Fl = Fl | 0;
2794
+ this.Gh = Gh | 0;
2795
+ this.Gl = Gl | 0;
2796
+ this.Hh = Hh | 0;
2797
+ this.Hl = Hl | 0;
2798
+ }
2799
+ process(view, offset) {
2800
+ for (let i = 0; i < 16; i++, offset += 4) {
2801
+ SHA512_W_H[i] = view.getUint32(offset);
2802
+ SHA512_W_L[i] = view.getUint32(offset += 4);
2803
+ }
2804
+ for (let i = 16; i < 80; i++) {
2805
+ const W15h = SHA512_W_H[i - 15] | 0;
2806
+ const W15l = SHA512_W_L[i - 15] | 0;
2807
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
2808
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
2809
+ const W2h = SHA512_W_H[i - 2] | 0;
2810
+ const W2l = SHA512_W_L[i - 2] | 0;
2811
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
2812
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
2813
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
2814
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
2815
+ SHA512_W_H[i] = SUMh | 0;
2816
+ SHA512_W_L[i] = SUMl | 0;
2817
+ }
2818
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
2819
+ for (let i = 0; i < 80; i++) {
2820
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
2821
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
2822
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
2823
+ const CHIl = El & Fl ^ ~El & Gl;
2824
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
2825
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
2826
+ const T1l = T1ll | 0;
2827
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
2828
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
2829
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
2830
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
2831
+ Hh = Gh | 0;
2832
+ Hl = Gl | 0;
2833
+ Gh = Fh | 0;
2834
+ Gl = Fl | 0;
2835
+ Fh = Eh | 0;
2836
+ Fl = El | 0;
2837
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
2838
+ Dh = Ch | 0;
2839
+ Dl = Cl | 0;
2840
+ Ch = Bh | 0;
2841
+ Cl = Bl | 0;
2842
+ Bh = Ah | 0;
2843
+ Bl = Al | 0;
2844
+ const All = add3L(T1l, sigma0l, MAJl);
2845
+ Ah = add3H(All, T1h, sigma0h, MAJh);
2846
+ Al = All | 0;
2847
+ }
2848
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
2849
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
2850
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
2851
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
2852
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
2853
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
2854
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
2855
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
2856
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
2857
+ }
2858
+ roundClean() {
2859
+ clean(SHA512_W_H, SHA512_W_L);
2860
+ }
2861
+ destroy() {
2862
+ clean(this.buffer);
2863
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2864
+ }
2865
+ };
2866
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
2867
+
2868
+ // ../../node_modules/@noble/hashes/esm/sha512.js
2869
+ var sha5122 = sha512;
2870
+
2871
+ // src/sdk/ed25519-setup.ts
2872
+ hashes.sha512 = sha5122;
2873
+
2874
+ // src/WarpFastsetWallet.ts
2875
+ var WarpFastsetWallet = class {
2876
+ constructor(config, chain2) {
2877
+ this.config = config;
2878
+ this.chain = chain2;
2879
+ this.client = getConfiguredFastsetClient(this.config, this.chain);
2880
+ }
2881
+ async signTransaction(tx) {
2882
+ const msg = Transaction.serialize(tx);
2883
+ const msgBytes = msg.toBytes();
2884
+ const prefix = new TextEncoder().encode("Transaction::");
2885
+ const dataToSign = new Uint8Array(prefix.length + msgBytes.length);
2886
+ dataToSign.set(prefix, 0);
2887
+ dataToSign.set(msgBytes, prefix.length);
2888
+ const privateKey = (0, import_warps5.getWarpWalletPrivateKeyFromConfig)(this.config, this.chain.name);
2889
+ if (!privateKey) throw new Error("Wallet not initialized - no private key provided");
2890
+ const privateKeyBytes = hexToUint8Array(privateKey);
2891
+ const signature = ed25519_exports.sign(dataToSign, privateKeyBytes);
2892
+ return { ...tx, signature };
2893
+ }
2894
+ async signMessage(message) {
2895
+ const messageBytes = stringToUint8Array(message);
2896
+ const privateKey = (0, import_warps5.getWarpWalletPrivateKeyFromConfig)(this.config, this.chain.name);
2897
+ if (!privateKey) throw new Error("Wallet not initialized - no private key provided");
2898
+ const privateKeyBytes = hexToUint8Array(privateKey);
2899
+ const signature = ed25519_exports.sign(messageBytes, privateKeyBytes);
2900
+ return uint8ArrayToHex(signature);
2901
+ }
2902
+ async signTransactions(txs) {
2903
+ return Promise.all(txs.map(async (tx) => this.signTransaction(tx)));
2904
+ }
2905
+ async sendTransaction(tx) {
2906
+ const { signature, ...transactionWithoutSignature } = tx;
2907
+ const _cert = await this.client.submitTransaction(transactionWithoutSignature, signature);
2908
+ return "TODO";
2909
+ }
2910
+ async sendTransactions(txs) {
2911
+ return Promise.all(txs.map(async (tx) => this.sendTransaction(tx)));
2912
+ }
2913
+ create(mnemonic) {
2914
+ const seed = bip39.mnemonicToSeedSync(mnemonic);
2915
+ const privateKey = seed.slice(0, 32);
2916
+ const publicKey = ed25519_exports.getPublicKey(privateKey);
2917
+ const address = FastsetClient.encodeBech32Address(publicKey);
2918
+ return { address, privateKey: uint8ArrayToHex(privateKey), mnemonic };
2919
+ }
2920
+ generate() {
2921
+ const privateKey = ed25519_exports.utils.randomPrivateKey();
2922
+ const publicKey = ed25519_exports.getPublicKey(privateKey);
2923
+ const address = FastsetClient.encodeBech32Address(publicKey);
2924
+ return { address, privateKey: uint8ArrayToHex(privateKey), mnemonic: null };
2925
+ }
2926
+ getAddress() {
2927
+ return (0, import_warps5.getWarpWalletAddressFromConfig)(this.config, this.chain.name);
892
2928
  }
893
2929
  };
894
2930
 
895
2931
  // src/main.ts
896
- var getFastsetAdapter = (config, fallback) => {
897
- if (!fallback) throw new Error("Fastset adapter requires a fallback adapter");
898
- const chainInfo = {
2932
+ var NativeTokenSet = {
2933
+ chain: import_warps6.WarpChainName.Fastset,
2934
+ identifier: "SET",
2935
+ name: "SET",
2936
+ symbol: "SET",
2937
+ decimals: 0,
2938
+ logoUrl: "https://vleap.ai/images/tokens/set.svg"
2939
+ };
2940
+ function createFastsetAdapter(chainName, chainPrefix, chainInfos) {
2941
+ return (config, fallback) => {
2942
+ const chainInfo = chainInfos[config.env];
2943
+ if (!chainInfo) throw new Error(`FastsetAdapter: chain info not found for chain ${chainName}`);
2944
+ if (!fallback) throw new Error("Fastset adapter requires a fallback adapter");
2945
+ return {
2946
+ chain: chainName,
2947
+ chainInfo,
2948
+ prefix: chainPrefix,
2949
+ builder: () => fallback.builder(),
2950
+ executor: new WarpFastsetExecutor(config, chainInfo),
2951
+ results: new WarpFastsetResults(config, chainInfo),
2952
+ serializer: new WarpFastsetSerializer(),
2953
+ registry: fallback.registry,
2954
+ explorer: new WarpFastsetExplorer(chainInfo, config),
2955
+ abiBuilder: () => fallback.abiBuilder(),
2956
+ brandBuilder: () => fallback.brandBuilder(),
2957
+ dataLoader: new WarpFastsetDataLoader(config, chainInfo),
2958
+ wallet: new WarpFastsetWallet(config, chainInfo)
2959
+ };
2960
+ };
2961
+ }
2962
+ var getFastsetAdapter = createFastsetAdapter(import_warps6.WarpChainName.Fastset, "fastset", {
2963
+ mainnet: {
2964
+ name: import_warps6.WarpChainName.Fastset,
899
2965
  displayName: "FastSet",
900
2966
  chainId: "1",
901
- blockTime: 100,
2967
+ blockTime: 1e3,
902
2968
  addressHrp: "set",
903
- apiUrl: "TODO",
904
- nativeToken: "SET"
905
- };
906
- return {
907
- chain: "fastset",
908
- chainInfo,
909
- prefix: "fastset",
910
- builder: () => new WarpFastsetBuilder(config),
911
- executor: new WarpFastsetExecutor(config),
912
- results: new WarpFastsetResults(config),
913
- serializer: new WarpFastsetSerializer(),
914
- registry: fallback.registry,
915
- explorer: new WarpFastsetExplorer(chainInfo),
916
- abiBuilder: () => fallback.abiBuilder(),
917
- brandBuilder: () => fallback.brandBuilder()
918
- };
919
- };
2969
+ defaultApiUrl: "https://proxy.fastset.xyz",
2970
+ logoUrl: "https://vleap.ai/images/chains/fastset.svg",
2971
+ nativeToken: NativeTokenSet
2972
+ },
2973
+ testnet: {
2974
+ name: import_warps6.WarpChainName.Fastset,
2975
+ displayName: "FastSet Testnet",
2976
+ chainId: "testnet",
2977
+ blockTime: 1e3,
2978
+ addressHrp: "set",
2979
+ defaultApiUrl: "https://proxy.fastset.xyz",
2980
+ logoUrl: "https://vleap.ai/images/chains/fastset.svg",
2981
+ nativeToken: NativeTokenSet
2982
+ },
2983
+ devnet: {
2984
+ name: import_warps6.WarpChainName.Fastset,
2985
+ displayName: "FastSet Devnet",
2986
+ chainId: "devnet",
2987
+ blockTime: 1e3,
2988
+ addressHrp: "set",
2989
+ defaultApiUrl: "https://proxy.fastset.xyz",
2990
+ logoUrl: "https://vleap.ai/images/chains/fastset.svg",
2991
+ nativeToken: NativeTokenSet
2992
+ }
2993
+ });
920
2994
  // Annotate the CommonJS export names for ESM import in node:
921
2995
  0 && (module.exports = {
922
- Address,
923
- Amount,
924
- Bytes32,
925
- ClaimType,
926
- FastsetClient,
927
- Nonce,
928
- PublicKey,
929
- Transaction,
930
- Transfer,
931
- UserData,
932
- WarpFastsetBuilder,
933
- WarpFastsetConstants,
2996
+ NativeTokenSet,
934
2997
  WarpFastsetExecutor,
935
- WarpFastsetExplorer,
936
- WarpFastsetResults,
937
- WarpFastsetSerializer,
938
- decimalToHex,
939
- fromBase64,
940
- getFastsetAdapter,
941
- hexToDecimal,
942
- isValidFastsetAddress,
943
- normalizeAmount,
944
- toBase64String,
945
- toHexString,
946
- validateAmount,
947
- validatePrivateKey,
948
- validatePublicKey
2998
+ WarpFastsetWallet,
2999
+ getFastsetAdapter
949
3000
  });
3001
+ /*! Bundled license information:
3002
+
3003
+ @scure/base/lib/esm/index.js:
3004
+ (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3005
+
3006
+ @noble/ed25519/index.js:
3007
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
3008
+
3009
+ @noble/hashes/esm/utils.js:
3010
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3011
+ */
950
3012
  //# sourceMappingURL=index.js.map