@aboutcircles/sdk-utils 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1901 @@
1
+ // src/circlesConverter.ts
2
+ class CirclesConverter {
3
+ static ONE_64 = 1n << 64n;
4
+ static GAMMA_64 = 18443079296116538654n;
5
+ static BETA_64 = 18450409579521241655n;
6
+ static SECONDS_PER_DAY = 86400n;
7
+ static INFLATION_DAY_ZERO_UNIX = 1602720000n;
8
+ static ATTO_FACTOR = 1000000000000000000n;
9
+ static FACTOR_1E12 = 1000000000000n;
10
+ static V1_ACCURACY = 100000000n;
11
+ static V1_INFLATION_PCT_NUM = 107n;
12
+ static V1_INFLATION_PCT_DEN = 100n;
13
+ static PERIOD_SEC = 31556952n;
14
+ static mul64(a, b) {
15
+ return a * b >> 64n;
16
+ }
17
+ static mulU(factor64x64, value) {
18
+ return factor64x64 * value >> 64n;
19
+ }
20
+ static pow64(base64x64, exp) {
21
+ let base = base64x64;
22
+ let exponent = exp;
23
+ let result = this.ONE_64;
24
+ while (exponent > 0n) {
25
+ if ((exponent & 1n) === 1n) {
26
+ result = this.mul64(result, base);
27
+ }
28
+ base = this.mul64(base, base);
29
+ exponent >>= 1n;
30
+ }
31
+ return result;
32
+ }
33
+ static ONE_36 = 1000000000000000000000000000000000000000n;
34
+ static GAMMA_36 = 999801332008598957430613406568191166n;
35
+ static BETA_36 = 1000198707468214629156271489013303962n;
36
+ static mul36(a, b) {
37
+ return a * b / this.ONE_36;
38
+ }
39
+ static pow36(base36, exp) {
40
+ let result = this.ONE_36;
41
+ let base = base36;
42
+ let e = exp;
43
+ while (e > 0n) {
44
+ const isOdd = (e & 1n) === 1n;
45
+ if (isOdd) {
46
+ result = this.mul36(result, base);
47
+ }
48
+ base = this.mul36(base, base);
49
+ e >>= 1n;
50
+ }
51
+ return result;
52
+ }
53
+ static attoCirclesToCircles(atto) {
54
+ if (atto === 0n)
55
+ return 0;
56
+ const whole = atto / this.ATTO_FACTOR;
57
+ const frac = atto % this.ATTO_FACTOR;
58
+ const MAX_SAFE_INT = BigInt(Number.MAX_SAFE_INTEGER);
59
+ if (whole > MAX_SAFE_INT || whole < -MAX_SAFE_INT) {
60
+ throw new RangeError("Atto value’s integer component exceeds JS double precision.");
61
+ }
62
+ return Number(whole) + Number(frac) / Number(this.ATTO_FACTOR);
63
+ }
64
+ static circlesToAttoCircles(circles) {
65
+ return BigInt(Math.trunc(circles * Number(this.ATTO_FACTOR)));
66
+ }
67
+ static inflationaryToDemurrage(inflationary, day) {
68
+ return this.mulU(this.pow64(this.GAMMA_64, day), inflationary);
69
+ }
70
+ static demurrageToInflationary(demurraged, day) {
71
+ return this.mulU(this.pow64(this.BETA_64, day), demurraged);
72
+ }
73
+ static dayFromTimestamp(unixSeconds) {
74
+ return (unixSeconds - this.INFLATION_DAY_ZERO_UNIX) / this.SECONDS_PER_DAY;
75
+ }
76
+ static attoCirclesToAttoStaticCircles(demurraged, nowUnixSeconds = BigInt(Math.floor(Date.now() / 1000))) {
77
+ return this.demurrageToInflationary(demurraged, this.dayFromTimestamp(nowUnixSeconds));
78
+ }
79
+ static attoStaticCirclesToAttoCircles(staticCircles, nowUnixSeconds = BigInt(Math.floor(Date.now() / 1000))) {
80
+ return this.inflationaryToDemurrage(staticCircles, this.dayFromTimestamp(nowUnixSeconds));
81
+ }
82
+ static inflationaryToDemurrageExact(inflationary, day) {
83
+ const factor = this.pow36(this.GAMMA_36, day);
84
+ return inflationary * factor / this.ONE_36;
85
+ }
86
+ static demurrageToInflationaryExact(demurraged, day) {
87
+ const factor = this.pow36(this.BETA_36, day);
88
+ return demurraged * factor / this.ONE_36;
89
+ }
90
+ static attoCirclesToAttoStaticCirclesExact(demurraged, nowUnixSeconds = BigInt(Math.floor(Date.now() / 1000))) {
91
+ const day = this.dayFromTimestamp(nowUnixSeconds);
92
+ return this.demurrageToInflationaryExact(demurraged, day);
93
+ }
94
+ static attoStaticCirclesToAttoCirclesExact(staticCircles, nowUnixSeconds = BigInt(Math.floor(Date.now() / 1000))) {
95
+ const day = this.dayFromTimestamp(nowUnixSeconds);
96
+ return this.inflationaryToDemurrageExact(staticCircles, day);
97
+ }
98
+ static truncateToInt64(wei) {
99
+ const truncated = wei / this.FACTOR_1E12;
100
+ const MAX_INT64 = 9223372036854775807n;
101
+ return truncated > MAX_INT64 ? MAX_INT64 : truncated;
102
+ }
103
+ static blowUpToBigInt(sixDecimals) {
104
+ return sixDecimals * this.FACTOR_1E12;
105
+ }
106
+ static truncateToSixDecimals(wei) {
107
+ return this.blowUpToBigInt(this.truncateToInt64(wei));
108
+ }
109
+ static v1InflateFactor(periodIdx) {
110
+ if (periodIdx === 0n)
111
+ return this.V1_ACCURACY;
112
+ return this.V1_ACCURACY * this.V1_INFLATION_PCT_NUM ** periodIdx / this.V1_INFLATION_PCT_DEN ** periodIdx;
113
+ }
114
+ static attoCrcToAttoCircles(v1Amount, blockTimestampUtc) {
115
+ const secondsSinceEpoch = blockTimestampUtc - this.INFLATION_DAY_ZERO_UNIX;
116
+ const periodIdx = secondsSinceEpoch / this.PERIOD_SEC;
117
+ const secondsIntoPeriod = secondsSinceEpoch % this.PERIOD_SEC;
118
+ const factorCur = this.v1InflateFactor(periodIdx);
119
+ const factorNext = this.v1InflateFactor(periodIdx + 1n);
120
+ return this.v1ToDemurrage(v1Amount, factorCur, factorNext, secondsIntoPeriod, this.PERIOD_SEC);
121
+ }
122
+ static attoCirclesToAttoCrc(demurraged, blockTimestampUtc) {
123
+ const secondsSinceEpoch = blockTimestampUtc - this.INFLATION_DAY_ZERO_UNIX;
124
+ const periodIdx = secondsSinceEpoch / this.PERIOD_SEC;
125
+ const secondsIntoPeriod = secondsSinceEpoch % this.PERIOD_SEC;
126
+ const factorCur = this.v1InflateFactor(periodIdx);
127
+ const factorNext = this.v1InflateFactor(periodIdx + 1n);
128
+ const rP = factorCur * (this.PERIOD_SEC - secondsIntoPeriod) + factorNext * secondsIntoPeriod;
129
+ return demurraged * 3n * this.V1_ACCURACY * this.PERIOD_SEC / rP;
130
+ }
131
+ static v1ToDemurrage(v1Amount, factorCur, factorNext, secondsInto, periodSec) {
132
+ const rP = factorCur * (periodSec - secondsInto) + factorNext * secondsInto;
133
+ return v1Amount * 3n * this.V1_ACCURACY * periodSec / rP;
134
+ }
135
+ }
136
+ // src/bytes.ts
137
+ var byteToHex = [];
138
+ for (let i = 0;i < 256; i++) {
139
+ byteToHex[i] = i.toString(16).padStart(2, "0");
140
+ }
141
+ function bytesToHex(bytes) {
142
+ let hex = "0x";
143
+ for (let i = 0;i < bytes.length; i++) {
144
+ hex += byteToHex[bytes[i]];
145
+ }
146
+ return hex;
147
+ }
148
+ // ../../node_modules/@noble/hashes/esm/_u64.js
149
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
150
+ var _32n = /* @__PURE__ */ BigInt(32);
151
+ function fromBig(n, le = false) {
152
+ if (le)
153
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
154
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
155
+ }
156
+ function split(lst, le = false) {
157
+ const len = lst.length;
158
+ let Ah = new Uint32Array(len);
159
+ let Al = new Uint32Array(len);
160
+ for (let i = 0;i < len; i++) {
161
+ const { h, l } = fromBig(lst[i], le);
162
+ [Ah[i], Al[i]] = [h, l];
163
+ }
164
+ return [Ah, Al];
165
+ }
166
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
167
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
168
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
169
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
170
+
171
+ // ../../node_modules/@noble/hashes/esm/utils.js
172
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
173
+ function isBytes(a) {
174
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
175
+ }
176
+ function anumber(n) {
177
+ if (!Number.isSafeInteger(n) || n < 0)
178
+ throw new Error("positive integer expected, got " + n);
179
+ }
180
+ function abytes(b, ...lengths) {
181
+ if (!isBytes(b))
182
+ throw new Error("Uint8Array expected");
183
+ if (lengths.length > 0 && !lengths.includes(b.length))
184
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
185
+ }
186
+ function aexists(instance, checkFinished = true) {
187
+ if (instance.destroyed)
188
+ throw new Error("Hash instance has been destroyed");
189
+ if (checkFinished && instance.finished)
190
+ throw new Error("Hash#digest() has already been called");
191
+ }
192
+ function aoutput(out, instance) {
193
+ abytes(out);
194
+ const min = instance.outputLen;
195
+ if (out.length < min) {
196
+ throw new Error("digestInto() expects output buffer of length at least " + min);
197
+ }
198
+ }
199
+ function u32(arr) {
200
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
201
+ }
202
+ function clean(...arrays) {
203
+ for (let i = 0;i < arrays.length; i++) {
204
+ arrays[i].fill(0);
205
+ }
206
+ }
207
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
208
+ function byteSwap(word) {
209
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
210
+ }
211
+ function byteSwap32(arr) {
212
+ for (let i = 0;i < arr.length; i++) {
213
+ arr[i] = byteSwap(arr[i]);
214
+ }
215
+ return arr;
216
+ }
217
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
218
+ function utf8ToBytes(str) {
219
+ if (typeof str !== "string")
220
+ throw new Error("string expected");
221
+ return new Uint8Array(new TextEncoder().encode(str));
222
+ }
223
+ function toBytes(data) {
224
+ if (typeof data === "string")
225
+ data = utf8ToBytes(data);
226
+ abytes(data);
227
+ return data;
228
+ }
229
+ class Hash {
230
+ }
231
+ function createHasher(hashCons) {
232
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
233
+ const tmp = hashCons();
234
+ hashC.outputLen = tmp.outputLen;
235
+ hashC.blockLen = tmp.blockLen;
236
+ hashC.create = () => hashCons();
237
+ return hashC;
238
+ }
239
+
240
+ // ../../node_modules/@noble/hashes/esm/sha3.js
241
+ var _0n = BigInt(0);
242
+ var _1n = BigInt(1);
243
+ var _2n = BigInt(2);
244
+ var _7n = BigInt(7);
245
+ var _256n = BigInt(256);
246
+ var _0x71n = BigInt(113);
247
+ var SHA3_PI = [];
248
+ var SHA3_ROTL = [];
249
+ var _SHA3_IOTA = [];
250
+ for (let round = 0, R = _1n, x = 1, y = 0;round < 24; round++) {
251
+ [x, y] = [y, (2 * x + 3 * y) % 5];
252
+ SHA3_PI.push(2 * (5 * y + x));
253
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
254
+ let t = _0n;
255
+ for (let j = 0;j < 7; j++) {
256
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
257
+ if (R & _2n)
258
+ t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
259
+ }
260
+ _SHA3_IOTA.push(t);
261
+ }
262
+ var IOTAS = split(_SHA3_IOTA, true);
263
+ var SHA3_IOTA_H = IOTAS[0];
264
+ var SHA3_IOTA_L = IOTAS[1];
265
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
266
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
267
+ function keccakP(s, rounds = 24) {
268
+ const B = new Uint32Array(5 * 2);
269
+ for (let round = 24 - rounds;round < 24; round++) {
270
+ for (let x = 0;x < 10; x++)
271
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
272
+ for (let x = 0;x < 10; x += 2) {
273
+ const idx1 = (x + 8) % 10;
274
+ const idx0 = (x + 2) % 10;
275
+ const B0 = B[idx0];
276
+ const B1 = B[idx0 + 1];
277
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
278
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
279
+ for (let y = 0;y < 50; y += 10) {
280
+ s[x + y] ^= Th;
281
+ s[x + y + 1] ^= Tl;
282
+ }
283
+ }
284
+ let curH = s[2];
285
+ let curL = s[3];
286
+ for (let t = 0;t < 24; t++) {
287
+ const shift = SHA3_ROTL[t];
288
+ const Th = rotlH(curH, curL, shift);
289
+ const Tl = rotlL(curH, curL, shift);
290
+ const PI = SHA3_PI[t];
291
+ curH = s[PI];
292
+ curL = s[PI + 1];
293
+ s[PI] = Th;
294
+ s[PI + 1] = Tl;
295
+ }
296
+ for (let y = 0;y < 50; y += 10) {
297
+ for (let x = 0;x < 10; x++)
298
+ B[x] = s[y + x];
299
+ for (let x = 0;x < 10; x++)
300
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
301
+ }
302
+ s[0] ^= SHA3_IOTA_H[round];
303
+ s[1] ^= SHA3_IOTA_L[round];
304
+ }
305
+ clean(B);
306
+ }
307
+
308
+ class Keccak extends Hash {
309
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
310
+ super();
311
+ this.pos = 0;
312
+ this.posOut = 0;
313
+ this.finished = false;
314
+ this.destroyed = false;
315
+ this.enableXOF = false;
316
+ this.blockLen = blockLen;
317
+ this.suffix = suffix;
318
+ this.outputLen = outputLen;
319
+ this.enableXOF = enableXOF;
320
+ this.rounds = rounds;
321
+ anumber(outputLen);
322
+ if (!(0 < blockLen && blockLen < 200))
323
+ throw new Error("only keccak-f1600 function is supported");
324
+ this.state = new Uint8Array(200);
325
+ this.state32 = u32(this.state);
326
+ }
327
+ clone() {
328
+ return this._cloneInto();
329
+ }
330
+ keccak() {
331
+ swap32IfBE(this.state32);
332
+ keccakP(this.state32, this.rounds);
333
+ swap32IfBE(this.state32);
334
+ this.posOut = 0;
335
+ this.pos = 0;
336
+ }
337
+ update(data) {
338
+ aexists(this);
339
+ data = toBytes(data);
340
+ abytes(data);
341
+ const { blockLen, state } = this;
342
+ const len = data.length;
343
+ for (let pos = 0;pos < len; ) {
344
+ const take = Math.min(blockLen - this.pos, len - pos);
345
+ for (let i = 0;i < take; i++)
346
+ state[this.pos++] ^= data[pos++];
347
+ if (this.pos === blockLen)
348
+ this.keccak();
349
+ }
350
+ return this;
351
+ }
352
+ finish() {
353
+ if (this.finished)
354
+ return;
355
+ this.finished = true;
356
+ const { state, suffix, pos, blockLen } = this;
357
+ state[pos] ^= suffix;
358
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
359
+ this.keccak();
360
+ state[blockLen - 1] ^= 128;
361
+ this.keccak();
362
+ }
363
+ writeInto(out) {
364
+ aexists(this, false);
365
+ abytes(out);
366
+ this.finish();
367
+ const bufferOut = this.state;
368
+ const { blockLen } = this;
369
+ for (let pos = 0, len = out.length;pos < len; ) {
370
+ if (this.posOut >= blockLen)
371
+ this.keccak();
372
+ const take = Math.min(blockLen - this.posOut, len - pos);
373
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
374
+ this.posOut += take;
375
+ pos += take;
376
+ }
377
+ return out;
378
+ }
379
+ xofInto(out) {
380
+ if (!this.enableXOF)
381
+ throw new Error("XOF is not possible for this instance");
382
+ return this.writeInto(out);
383
+ }
384
+ xof(bytes) {
385
+ anumber(bytes);
386
+ return this.xofInto(new Uint8Array(bytes));
387
+ }
388
+ digestInto(out) {
389
+ aoutput(out, this);
390
+ if (this.finished)
391
+ throw new Error("digest() was already called");
392
+ this.writeInto(out);
393
+ this.destroy();
394
+ return out;
395
+ }
396
+ digest() {
397
+ return this.digestInto(new Uint8Array(this.outputLen));
398
+ }
399
+ destroy() {
400
+ this.destroyed = true;
401
+ clean(this.state);
402
+ }
403
+ _cloneInto(to) {
404
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
405
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
406
+ to.state32.set(this.state32);
407
+ to.pos = this.pos;
408
+ to.posOut = this.posOut;
409
+ to.finished = this.finished;
410
+ to.rounds = rounds;
411
+ to.suffix = suffix;
412
+ to.outputLen = outputLen;
413
+ to.enableXOF = enableXOF;
414
+ to.destroyed = this.destroyed;
415
+ return to;
416
+ }
417
+ }
418
+ var gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
419
+ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
420
+
421
+ // src/abi.ts
422
+ var HEX_CHARS = 64;
423
+ var BYTES_PER_WORD = 32;
424
+ var strip0x = (hex) => hex.startsWith("0x") ? hex.slice(2) : hex;
425
+ var toHex64 = (num) => num.toString(16).padStart(HEX_CHARS, "0");
426
+ function checksumAddress(address) {
427
+ const addr = address.toLowerCase().replace("0x", "");
428
+ const hash = bytesToHex(keccak_256(new TextEncoder().encode(addr))).slice(2);
429
+ let result = "0x";
430
+ for (let i = 0;i < addr.length; i++) {
431
+ result += parseInt(hash[i], 16) >= 8 ? addr[i].toUpperCase() : addr[i];
432
+ }
433
+ return result;
434
+ }
435
+ function getTypeString(type, components) {
436
+ if (type === "tuple" && components) {
437
+ const types = components.map((c) => getTypeString(c.type, c.components));
438
+ return `(${types.join(",")})`;
439
+ }
440
+ const tupleArrayMatch = type.match(/^tuple(\[\d*\])$/);
441
+ if (tupleArrayMatch && components) {
442
+ const baseType = getTypeString("tuple", components);
443
+ return `${baseType}${tupleArrayMatch[1]}`;
444
+ }
445
+ return type;
446
+ }
447
+ function getFunctionSignature(abiFunction) {
448
+ const inputs = abiFunction.inputs || [];
449
+ const types = inputs.map((input) => getTypeString(input.type, input.components));
450
+ return `${abiFunction.name}(${types.join(",")})`;
451
+ }
452
+ function getFunctionSelector(abiFunction) {
453
+ const signature = getFunctionSignature(abiFunction);
454
+ const hash = keccak_256(new TextEncoder().encode(signature));
455
+ return bytesToHex(hash.slice(0, 4));
456
+ }
457
+ function isDynamicType(type, components) {
458
+ if (type === "string" || type === "bytes")
459
+ return true;
460
+ if (type.includes("[")) {
461
+ const baseType = type.slice(0, type.indexOf("["));
462
+ if (type.endsWith("[]"))
463
+ return true;
464
+ if (baseType === "tuple") {
465
+ return isTupleDynamic(components);
466
+ }
467
+ return isDynamicType(baseType);
468
+ }
469
+ if (type === "tuple") {
470
+ return isTupleDynamic(components);
471
+ }
472
+ return false;
473
+ }
474
+ function isTupleDynamic(components) {
475
+ return components?.some((c) => isDynamicType(c.type, c.components)) ?? false;
476
+ }
477
+ function encodeParam(type, value, components) {
478
+ if (type === "tuple" && components) {
479
+ return encodeTuple(components, value);
480
+ }
481
+ if (type.includes("[")) {
482
+ return encodeArray(type, value, components);
483
+ }
484
+ return encodePrimitive(type, value);
485
+ }
486
+ function encodeArray(type, arr, components) {
487
+ const baseType = type.slice(0, type.indexOf("["));
488
+ const isDynamic = type.endsWith("[]");
489
+ const elementsAreDynamic = isDynamicType(baseType, components);
490
+ let encoded;
491
+ if (elementsAreDynamic) {
492
+ const encodings = arr.map((v) => encodeParam(baseType, v, components));
493
+ let offset = arr.length * BYTES_PER_WORD;
494
+ const offsets = encodings.map((enc) => {
495
+ const currentOffset = offset;
496
+ offset += enc.length / 2;
497
+ return toHex64(currentOffset);
498
+ });
499
+ encoded = offsets.join("") + encodings.join("");
500
+ } else {
501
+ encoded = arr.map((v) => encodeParam(baseType, v, components)).join("");
502
+ }
503
+ return isDynamic ? toHex64(arr.length) + encoded : encoded;
504
+ }
505
+ function encodeTuple(components, value) {
506
+ const isArray = Array.isArray(value);
507
+ const encodings = [];
508
+ const dynamicData = [];
509
+ const isDynamic = [];
510
+ for (let i = 0;i < components.length; i++) {
511
+ const component = components[i];
512
+ const val = isArray ? value[i] : value[component.name || ""];
513
+ const dynamic = isDynamicType(component.type, component.components);
514
+ isDynamic.push(dynamic);
515
+ if (dynamic) {
516
+ encodings.push("");
517
+ dynamicData.push(encodeParam(component.type, val, component.components));
518
+ } else {
519
+ encodings.push(encodeParam(component.type, val, component.components));
520
+ }
521
+ }
522
+ if (dynamicData.length > 0) {
523
+ let offset = encodings.reduce((sum, enc, i) => sum + (isDynamic[i] ? BYTES_PER_WORD : enc.length / 2), 0);
524
+ let result = "";
525
+ let dynamicIndex = 0;
526
+ for (let i = 0;i < components.length; i++) {
527
+ if (isDynamic[i]) {
528
+ result += toHex64(offset);
529
+ offset += dynamicData[dynamicIndex].length / 2;
530
+ dynamicIndex++;
531
+ } else {
532
+ result += encodings[i];
533
+ }
534
+ }
535
+ return result + dynamicData.join("");
536
+ }
537
+ return encodings.join("");
538
+ }
539
+ function encodePrimitive(type, value) {
540
+ if (type === "address") {
541
+ return strip0x(value).toLowerCase().padStart(HEX_CHARS, "0");
542
+ }
543
+ if (type === "bool") {
544
+ return toHex64(value ? 1 : 0);
545
+ }
546
+ if (type.startsWith("uint")) {
547
+ const num = typeof value === "bigint" ? value : BigInt(value);
548
+ return toHex64(num);
549
+ }
550
+ if (type.startsWith("int")) {
551
+ let num = typeof value === "bigint" ? value : BigInt(value);
552
+ if (num < 0n) {
553
+ const bits = type === "int" ? 256 : parseInt(type.slice(3));
554
+ num = (1n << BigInt(bits)) + num;
555
+ }
556
+ return toHex64(num);
557
+ }
558
+ if (type.startsWith("bytes") && type !== "bytes") {
559
+ return strip0x(value).padEnd(HEX_CHARS, "0");
560
+ }
561
+ if (type === "bytes") {
562
+ const bytes = strip0x(value);
563
+ const length = toHex64(bytes.length / 2);
564
+ const padded = bytes.padEnd(Math.ceil(bytes.length / HEX_CHARS) * HEX_CHARS, "0");
565
+ return length + padded;
566
+ }
567
+ if (type === "string") {
568
+ const bytes = Array.from(new TextEncoder().encode(value)).map((b) => b.toString(16).padStart(2, "0")).join("");
569
+ const length = toHex64(bytes.length / 2);
570
+ const padded = bytes.padEnd(Math.ceil(bytes.length / HEX_CHARS) * HEX_CHARS, "0");
571
+ return length + padded;
572
+ }
573
+ throw new Error(`Unsupported type: ${type}`);
574
+ }
575
+ function decodeParam(type, data, offset = 0, components) {
576
+ if (type === "tuple" && components) {
577
+ return decodeTuple(components, data, offset);
578
+ }
579
+ if (type.includes("[")) {
580
+ return decodeArray(type, data, offset, components);
581
+ }
582
+ return decodePrimitive(type, data, offset);
583
+ }
584
+ function decodeArray(type, data, offset, components) {
585
+ const baseType = type.slice(0, type.indexOf("["));
586
+ const chunk = data.slice(offset, offset + HEX_CHARS);
587
+ if (type.endsWith("[]")) {
588
+ const dataOffset = parseInt(chunk, 16) * 2;
589
+ const length = parseInt(data.slice(dataOffset, dataOffset + HEX_CHARS), 16);
590
+ const values = [];
591
+ let currentOffset = dataOffset + HEX_CHARS;
592
+ for (let i = 0;i < length; i++) {
593
+ const result = decodeParam(baseType, data, currentOffset, components);
594
+ values.push(result.value);
595
+ currentOffset += result.consumed;
596
+ }
597
+ return { value: values, consumed: HEX_CHARS };
598
+ }
599
+ const match = type.match(/\[(\d+)\]$/);
600
+ if (match) {
601
+ const length = parseInt(match[1]);
602
+ const values = [];
603
+ let consumed = 0;
604
+ for (let i = 0;i < length; i++) {
605
+ const result = decodeParam(baseType, data, offset + consumed, components);
606
+ values.push(result.value);
607
+ consumed += result.consumed;
608
+ }
609
+ return { value: values, consumed };
610
+ }
611
+ throw new Error(`Invalid array type: ${type}`);
612
+ }
613
+ function decodeTuple(components, data, offset) {
614
+ const values = [];
615
+ let currentOffset = offset;
616
+ for (const component of components) {
617
+ const result = decodeParam(component.type, data, currentOffset, component.components);
618
+ values.push(result.value);
619
+ currentOffset += result.consumed;
620
+ }
621
+ return { value: values, consumed: currentOffset - offset };
622
+ }
623
+ function decodePrimitive(type, data, offset) {
624
+ const chunk = data.slice(offset, offset + HEX_CHARS);
625
+ if (type === "address") {
626
+ return {
627
+ value: checksumAddress("0x" + chunk.slice(24)),
628
+ consumed: HEX_CHARS
629
+ };
630
+ }
631
+ if (type === "bool") {
632
+ return {
633
+ value: parseInt(chunk, 16) !== 0,
634
+ consumed: HEX_CHARS
635
+ };
636
+ }
637
+ if (type.startsWith("uint")) {
638
+ return {
639
+ value: BigInt("0x" + chunk),
640
+ consumed: HEX_CHARS
641
+ };
642
+ }
643
+ if (type.startsWith("int")) {
644
+ const value = BigInt("0x" + chunk);
645
+ const bits = type === "int" ? 256 : parseInt(type.slice(3));
646
+ const signBit = 1n << BigInt(bits - 1);
647
+ return {
648
+ value: value >= signBit ? value - (1n << BigInt(bits)) : value,
649
+ consumed: HEX_CHARS
650
+ };
651
+ }
652
+ if (type.startsWith("bytes") && type !== "bytes") {
653
+ const size = parseInt(type.match(/^bytes(\d+)$/)[1]);
654
+ return {
655
+ value: "0x" + chunk.slice(0, size * 2),
656
+ consumed: HEX_CHARS
657
+ };
658
+ }
659
+ if (type === "bytes") {
660
+ const dataOffset = parseInt(chunk, 16) * 2;
661
+ const length = parseInt(data.slice(dataOffset, dataOffset + HEX_CHARS), 16) * 2;
662
+ return {
663
+ value: "0x" + data.slice(dataOffset + HEX_CHARS, dataOffset + HEX_CHARS + length),
664
+ consumed: HEX_CHARS
665
+ };
666
+ }
667
+ if (type === "string") {
668
+ const dataOffset = parseInt(chunk, 16) * 2;
669
+ const length = parseInt(data.slice(dataOffset, dataOffset + HEX_CHARS), 16) * 2;
670
+ const bytes = data.slice(dataOffset + HEX_CHARS, dataOffset + HEX_CHARS + length);
671
+ const byteArray = new Uint8Array(bytes.match(/.{2}/g)?.map((b) => parseInt(b, 16)) || []);
672
+ return {
673
+ value: new TextDecoder().decode(byteArray),
674
+ consumed: HEX_CHARS
675
+ };
676
+ }
677
+ throw new Error(`Unsupported type: ${type}`);
678
+ }
679
+ function encodeFunctionData(config) {
680
+ const { abi, functionName, args = [] } = config;
681
+ const abiFunction = abi.find((item) => item.type === "function" && item.name === functionName);
682
+ if (!abiFunction) {
683
+ throw new Error(`Function "${functionName}" not found in ABI`);
684
+ }
685
+ const selector = getFunctionSelector(abiFunction);
686
+ const inputs = abiFunction.inputs || [];
687
+ if (inputs.length === 0)
688
+ return selector;
689
+ if (args.length !== inputs.length) {
690
+ throw new Error(`Expected ${inputs.length} arguments, got ${args.length}`);
691
+ }
692
+ const encodings = [];
693
+ const dynamicData = [];
694
+ const isDynamic = [];
695
+ for (let i = 0;i < inputs.length; i++) {
696
+ const input = inputs[i];
697
+ const components = input.components;
698
+ const dynamic = isDynamicType(input.type, components);
699
+ isDynamic.push(dynamic);
700
+ if (dynamic) {
701
+ encodings.push("");
702
+ dynamicData.push(encodeParam(input.type, args[i], components));
703
+ } else {
704
+ encodings.push(encodeParam(input.type, args[i], components));
705
+ }
706
+ }
707
+ if (dynamicData.length === 0) {
708
+ return selector + encodings.join("");
709
+ }
710
+ let offset = encodings.reduce((sum, enc, i) => sum + (isDynamic[i] ? BYTES_PER_WORD : enc.length / 2), 0);
711
+ let result = "";
712
+ let dynamicIndex = 0;
713
+ for (let i = 0;i < inputs.length; i++) {
714
+ if (isDynamic[i]) {
715
+ result += toHex64(offset);
716
+ offset += dynamicData[dynamicIndex].length / 2;
717
+ dynamicIndex++;
718
+ } else {
719
+ result += encodings[i];
720
+ }
721
+ }
722
+ return selector + result + dynamicData.join("");
723
+ }
724
+ function decodeFunctionResult(config) {
725
+ const { abi, functionName, data } = config;
726
+ const abiFunction = abi.find((item) => item.type === "function" && item.name === functionName);
727
+ if (!abiFunction) {
728
+ throw new Error(`Function "${functionName}" not found in ABI`);
729
+ }
730
+ const outputs = abiFunction.outputs || [];
731
+ if (outputs.length === 0)
732
+ return;
733
+ const cleanData = strip0x(data);
734
+ if (outputs.length === 1) {
735
+ return decodeParam(outputs[0].type, cleanData, 0, outputs[0].components).value;
736
+ }
737
+ const results = [];
738
+ let offset = 0;
739
+ for (const output of outputs) {
740
+ const result = decodeParam(output.type, cleanData, offset, output.components);
741
+ results.push(result.value);
742
+ offset += result.consumed;
743
+ }
744
+ return results;
745
+ }
746
+ function getErrorSelector(errorItem) {
747
+ const inputs = errorItem.inputs || [];
748
+ const types = inputs.map((input) => getTypeString(input.type, input.components));
749
+ const signature = `${errorItem.name}(${types.join(",")})`;
750
+ const hash = keccak_256(new TextEncoder().encode(signature));
751
+ return bytesToHex(hash.slice(0, 4));
752
+ }
753
+ function decodeErrorResult(config) {
754
+ const { abi, data } = config;
755
+ if (!data || data.length < 10) {
756
+ return null;
757
+ }
758
+ const selector = data.slice(0, 10).toLowerCase();
759
+ const cleanData = strip0x(data.slice(10));
760
+ const errors = abi.filter((item) => item.type === "error");
761
+ for (const errorItem of errors) {
762
+ const errorSelector = getErrorSelector(errorItem);
763
+ if (errorSelector.toLowerCase() === selector) {
764
+ const inputs = errorItem.inputs || [];
765
+ if (inputs.length === 0) {
766
+ return { errorName: errorItem.name };
767
+ }
768
+ const decodedArgs = [];
769
+ let offset = 0;
770
+ for (const input of inputs) {
771
+ const result = decodeParam(input.type, cleanData, offset, input.components);
772
+ decodedArgs.push(result.value);
773
+ offset += result.consumed;
774
+ }
775
+ return {
776
+ errorName: errorItem.name,
777
+ args: decodedArgs
778
+ };
779
+ }
780
+ }
781
+ return null;
782
+ }
783
+ // ../../node_modules/multiformats/dist/src/bytes.js
784
+ var empty = new Uint8Array(0);
785
+ function equals(aa, bb) {
786
+ if (aa === bb) {
787
+ return true;
788
+ }
789
+ if (aa.byteLength !== bb.byteLength) {
790
+ return false;
791
+ }
792
+ for (let ii = 0;ii < aa.byteLength; ii++) {
793
+ if (aa[ii] !== bb[ii]) {
794
+ return false;
795
+ }
796
+ }
797
+ return true;
798
+ }
799
+ function coerce(o) {
800
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
801
+ return o;
802
+ }
803
+ if (o instanceof ArrayBuffer) {
804
+ return new Uint8Array(o);
805
+ }
806
+ if (ArrayBuffer.isView(o)) {
807
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
808
+ }
809
+ throw new Error("Unknown type, must be binary type");
810
+ }
811
+
812
+ // ../../node_modules/multiformats/dist/src/vendor/base-x.js
813
+ function base(ALPHABET, name) {
814
+ if (ALPHABET.length >= 255) {
815
+ throw new TypeError("Alphabet too long");
816
+ }
817
+ var BASE_MAP = new Uint8Array(256);
818
+ for (var j = 0;j < BASE_MAP.length; j++) {
819
+ BASE_MAP[j] = 255;
820
+ }
821
+ for (var i = 0;i < ALPHABET.length; i++) {
822
+ var x = ALPHABET.charAt(i);
823
+ var xc = x.charCodeAt(0);
824
+ if (BASE_MAP[xc] !== 255) {
825
+ throw new TypeError(x + " is ambiguous");
826
+ }
827
+ BASE_MAP[xc] = i;
828
+ }
829
+ var BASE = ALPHABET.length;
830
+ var LEADER = ALPHABET.charAt(0);
831
+ var FACTOR = Math.log(BASE) / Math.log(256);
832
+ var iFACTOR = Math.log(256) / Math.log(BASE);
833
+ function encode(source) {
834
+ if (source instanceof Uint8Array)
835
+ ;
836
+ else if (ArrayBuffer.isView(source)) {
837
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
838
+ } else if (Array.isArray(source)) {
839
+ source = Uint8Array.from(source);
840
+ }
841
+ if (!(source instanceof Uint8Array)) {
842
+ throw new TypeError("Expected Uint8Array");
843
+ }
844
+ if (source.length === 0) {
845
+ return "";
846
+ }
847
+ var zeroes = 0;
848
+ var length = 0;
849
+ var pbegin = 0;
850
+ var pend = source.length;
851
+ while (pbegin !== pend && source[pbegin] === 0) {
852
+ pbegin++;
853
+ zeroes++;
854
+ }
855
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
856
+ var b58 = new Uint8Array(size);
857
+ while (pbegin !== pend) {
858
+ var carry = source[pbegin];
859
+ var i2 = 0;
860
+ for (var it1 = size - 1;(carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) {
861
+ carry += 256 * b58[it1] >>> 0;
862
+ b58[it1] = carry % BASE >>> 0;
863
+ carry = carry / BASE >>> 0;
864
+ }
865
+ if (carry !== 0) {
866
+ throw new Error("Non-zero carry");
867
+ }
868
+ length = i2;
869
+ pbegin++;
870
+ }
871
+ var it2 = size - length;
872
+ while (it2 !== size && b58[it2] === 0) {
873
+ it2++;
874
+ }
875
+ var str = LEADER.repeat(zeroes);
876
+ for (;it2 < size; ++it2) {
877
+ str += ALPHABET.charAt(b58[it2]);
878
+ }
879
+ return str;
880
+ }
881
+ function decodeUnsafe(source) {
882
+ if (typeof source !== "string") {
883
+ throw new TypeError("Expected String");
884
+ }
885
+ if (source.length === 0) {
886
+ return new Uint8Array;
887
+ }
888
+ var psz = 0;
889
+ if (source[psz] === " ") {
890
+ return;
891
+ }
892
+ var zeroes = 0;
893
+ var length = 0;
894
+ while (source[psz] === LEADER) {
895
+ zeroes++;
896
+ psz++;
897
+ }
898
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
899
+ var b256 = new Uint8Array(size);
900
+ while (source[psz]) {
901
+ var carry = BASE_MAP[source.charCodeAt(psz)];
902
+ if (carry === 255) {
903
+ return;
904
+ }
905
+ var i2 = 0;
906
+ for (var it3 = size - 1;(carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) {
907
+ carry += BASE * b256[it3] >>> 0;
908
+ b256[it3] = carry % 256 >>> 0;
909
+ carry = carry / 256 >>> 0;
910
+ }
911
+ if (carry !== 0) {
912
+ throw new Error("Non-zero carry");
913
+ }
914
+ length = i2;
915
+ psz++;
916
+ }
917
+ if (source[psz] === " ") {
918
+ return;
919
+ }
920
+ var it4 = size - length;
921
+ while (it4 !== size && b256[it4] === 0) {
922
+ it4++;
923
+ }
924
+ var vch = new Uint8Array(zeroes + (size - it4));
925
+ var j2 = zeroes;
926
+ while (it4 !== size) {
927
+ vch[j2++] = b256[it4++];
928
+ }
929
+ return vch;
930
+ }
931
+ function decode(string) {
932
+ var buffer = decodeUnsafe(string);
933
+ if (buffer) {
934
+ return buffer;
935
+ }
936
+ throw new Error(`Non-${name} character`);
937
+ }
938
+ return {
939
+ encode,
940
+ decodeUnsafe,
941
+ decode
942
+ };
943
+ }
944
+ var src = base;
945
+ var _brrp__multiformats_scope_baseX = src;
946
+ var base_x_default = _brrp__multiformats_scope_baseX;
947
+
948
+ // ../../node_modules/multiformats/dist/src/bases/base.js
949
+ class Encoder {
950
+ name;
951
+ prefix;
952
+ baseEncode;
953
+ constructor(name, prefix, baseEncode) {
954
+ this.name = name;
955
+ this.prefix = prefix;
956
+ this.baseEncode = baseEncode;
957
+ }
958
+ encode(bytes) {
959
+ if (bytes instanceof Uint8Array) {
960
+ return `${this.prefix}${this.baseEncode(bytes)}`;
961
+ } else {
962
+ throw Error("Unknown type, must be binary type");
963
+ }
964
+ }
965
+ }
966
+
967
+ class Decoder {
968
+ name;
969
+ prefix;
970
+ baseDecode;
971
+ prefixCodePoint;
972
+ constructor(name, prefix, baseDecode) {
973
+ this.name = name;
974
+ this.prefix = prefix;
975
+ const prefixCodePoint = prefix.codePointAt(0);
976
+ if (prefixCodePoint === undefined) {
977
+ throw new Error("Invalid prefix character");
978
+ }
979
+ this.prefixCodePoint = prefixCodePoint;
980
+ this.baseDecode = baseDecode;
981
+ }
982
+ decode(text) {
983
+ if (typeof text === "string") {
984
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
985
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
986
+ }
987
+ return this.baseDecode(text.slice(this.prefix.length));
988
+ } else {
989
+ throw Error("Can only multibase decode strings");
990
+ }
991
+ }
992
+ or(decoder) {
993
+ return or(this, decoder);
994
+ }
995
+ }
996
+
997
+ class ComposedDecoder {
998
+ decoders;
999
+ constructor(decoders) {
1000
+ this.decoders = decoders;
1001
+ }
1002
+ or(decoder) {
1003
+ return or(this, decoder);
1004
+ }
1005
+ decode(input) {
1006
+ const prefix = input[0];
1007
+ const decoder = this.decoders[prefix];
1008
+ if (decoder != null) {
1009
+ return decoder.decode(input);
1010
+ } else {
1011
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
1012
+ }
1013
+ }
1014
+ }
1015
+ function or(left, right) {
1016
+ return new ComposedDecoder({
1017
+ ...left.decoders ?? { [left.prefix]: left },
1018
+ ...right.decoders ?? { [right.prefix]: right }
1019
+ });
1020
+ }
1021
+
1022
+ class Codec {
1023
+ name;
1024
+ prefix;
1025
+ baseEncode;
1026
+ baseDecode;
1027
+ encoder;
1028
+ decoder;
1029
+ constructor(name, prefix, baseEncode, baseDecode) {
1030
+ this.name = name;
1031
+ this.prefix = prefix;
1032
+ this.baseEncode = baseEncode;
1033
+ this.baseDecode = baseDecode;
1034
+ this.encoder = new Encoder(name, prefix, baseEncode);
1035
+ this.decoder = new Decoder(name, prefix, baseDecode);
1036
+ }
1037
+ encode(input) {
1038
+ return this.encoder.encode(input);
1039
+ }
1040
+ decode(input) {
1041
+ return this.decoder.decode(input);
1042
+ }
1043
+ }
1044
+ function from({ name, prefix, encode, decode }) {
1045
+ return new Codec(name, prefix, encode, decode);
1046
+ }
1047
+ function baseX({ name, prefix, alphabet }) {
1048
+ const { encode, decode } = base_x_default(alphabet, name);
1049
+ return from({
1050
+ prefix,
1051
+ name,
1052
+ encode,
1053
+ decode: (text) => coerce(decode(text))
1054
+ });
1055
+ }
1056
+ function decode(string, alphabetIdx, bitsPerChar, name) {
1057
+ let end = string.length;
1058
+ while (string[end - 1] === "=") {
1059
+ --end;
1060
+ }
1061
+ const out = new Uint8Array(end * bitsPerChar / 8 | 0);
1062
+ let bits = 0;
1063
+ let buffer = 0;
1064
+ let written = 0;
1065
+ for (let i = 0;i < end; ++i) {
1066
+ const value = alphabetIdx[string[i]];
1067
+ if (value === undefined) {
1068
+ throw new SyntaxError(`Non-${name} character`);
1069
+ }
1070
+ buffer = buffer << bitsPerChar | value;
1071
+ bits += bitsPerChar;
1072
+ if (bits >= 8) {
1073
+ bits -= 8;
1074
+ out[written++] = 255 & buffer >> bits;
1075
+ }
1076
+ }
1077
+ if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) {
1078
+ throw new SyntaxError("Unexpected end of data");
1079
+ }
1080
+ return out;
1081
+ }
1082
+ function encode(data, alphabet, bitsPerChar) {
1083
+ const pad = alphabet[alphabet.length - 1] === "=";
1084
+ const mask = (1 << bitsPerChar) - 1;
1085
+ let out = "";
1086
+ let bits = 0;
1087
+ let buffer = 0;
1088
+ for (let i = 0;i < data.length; ++i) {
1089
+ buffer = buffer << 8 | data[i];
1090
+ bits += 8;
1091
+ while (bits > bitsPerChar) {
1092
+ bits -= bitsPerChar;
1093
+ out += alphabet[mask & buffer >> bits];
1094
+ }
1095
+ }
1096
+ if (bits !== 0) {
1097
+ out += alphabet[mask & buffer << bitsPerChar - bits];
1098
+ }
1099
+ if (pad) {
1100
+ while ((out.length * bitsPerChar & 7) !== 0) {
1101
+ out += "=";
1102
+ }
1103
+ }
1104
+ return out;
1105
+ }
1106
+ function createAlphabetIdx(alphabet) {
1107
+ const alphabetIdx = {};
1108
+ for (let i = 0;i < alphabet.length; ++i) {
1109
+ alphabetIdx[alphabet[i]] = i;
1110
+ }
1111
+ return alphabetIdx;
1112
+ }
1113
+ function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
1114
+ const alphabetIdx = createAlphabetIdx(alphabet);
1115
+ return from({
1116
+ prefix,
1117
+ name,
1118
+ encode(input) {
1119
+ return encode(input, alphabet, bitsPerChar);
1120
+ },
1121
+ decode(input) {
1122
+ return decode(input, alphabetIdx, bitsPerChar, name);
1123
+ }
1124
+ });
1125
+ }
1126
+
1127
+ // ../../node_modules/multiformats/dist/src/bases/base32.js
1128
+ var base32 = rfc4648({
1129
+ prefix: "b",
1130
+ name: "base32",
1131
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567",
1132
+ bitsPerChar: 5
1133
+ });
1134
+ var base32upper = rfc4648({
1135
+ prefix: "B",
1136
+ name: "base32upper",
1137
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
1138
+ bitsPerChar: 5
1139
+ });
1140
+ var base32pad = rfc4648({
1141
+ prefix: "c",
1142
+ name: "base32pad",
1143
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
1144
+ bitsPerChar: 5
1145
+ });
1146
+ var base32padupper = rfc4648({
1147
+ prefix: "C",
1148
+ name: "base32padupper",
1149
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
1150
+ bitsPerChar: 5
1151
+ });
1152
+ var base32hex = rfc4648({
1153
+ prefix: "v",
1154
+ name: "base32hex",
1155
+ alphabet: "0123456789abcdefghijklmnopqrstuv",
1156
+ bitsPerChar: 5
1157
+ });
1158
+ var base32hexupper = rfc4648({
1159
+ prefix: "V",
1160
+ name: "base32hexupper",
1161
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
1162
+ bitsPerChar: 5
1163
+ });
1164
+ var base32hexpad = rfc4648({
1165
+ prefix: "t",
1166
+ name: "base32hexpad",
1167
+ alphabet: "0123456789abcdefghijklmnopqrstuv=",
1168
+ bitsPerChar: 5
1169
+ });
1170
+ var base32hexpadupper = rfc4648({
1171
+ prefix: "T",
1172
+ name: "base32hexpadupper",
1173
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
1174
+ bitsPerChar: 5
1175
+ });
1176
+ var base32z = rfc4648({
1177
+ prefix: "h",
1178
+ name: "base32z",
1179
+ alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
1180
+ bitsPerChar: 5
1181
+ });
1182
+
1183
+ // ../../node_modules/multiformats/dist/src/bases/base36.js
1184
+ var base36 = baseX({
1185
+ prefix: "k",
1186
+ name: "base36",
1187
+ alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
1188
+ });
1189
+ var base36upper = baseX({
1190
+ prefix: "K",
1191
+ name: "base36upper",
1192
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1193
+ });
1194
+
1195
+ // ../../node_modules/multiformats/dist/src/bases/base58.js
1196
+ var base58btc = baseX({
1197
+ name: "base58btc",
1198
+ prefix: "z",
1199
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
1200
+ });
1201
+ var base58flickr = baseX({
1202
+ name: "base58flickr",
1203
+ prefix: "Z",
1204
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
1205
+ });
1206
+
1207
+ // ../../node_modules/multiformats/dist/src/vendor/varint.js
1208
+ var encode_1 = encode2;
1209
+ var MSB = 128;
1210
+ var REST = 127;
1211
+ var MSBALL = ~REST;
1212
+ var INT = Math.pow(2, 31);
1213
+ function encode2(num, out, offset) {
1214
+ out = out || [];
1215
+ offset = offset || 0;
1216
+ var oldOffset = offset;
1217
+ while (num >= INT) {
1218
+ out[offset++] = num & 255 | MSB;
1219
+ num /= 128;
1220
+ }
1221
+ while (num & MSBALL) {
1222
+ out[offset++] = num & 255 | MSB;
1223
+ num >>>= 7;
1224
+ }
1225
+ out[offset] = num | 0;
1226
+ encode2.bytes = offset - oldOffset + 1;
1227
+ return out;
1228
+ }
1229
+ var decode2 = read;
1230
+ var MSB$1 = 128;
1231
+ var REST$1 = 127;
1232
+ function read(buf, offset) {
1233
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
1234
+ do {
1235
+ if (counter >= l) {
1236
+ read.bytes = 0;
1237
+ throw new RangeError("Could not decode varint");
1238
+ }
1239
+ b = buf[counter++];
1240
+ res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
1241
+ shift += 7;
1242
+ } while (b >= MSB$1);
1243
+ read.bytes = counter - offset;
1244
+ return res;
1245
+ }
1246
+ var N1 = Math.pow(2, 7);
1247
+ var N2 = Math.pow(2, 14);
1248
+ var N3 = Math.pow(2, 21);
1249
+ var N4 = Math.pow(2, 28);
1250
+ var N5 = Math.pow(2, 35);
1251
+ var N6 = Math.pow(2, 42);
1252
+ var N7 = Math.pow(2, 49);
1253
+ var N8 = Math.pow(2, 56);
1254
+ var N9 = Math.pow(2, 63);
1255
+ var length = function(value) {
1256
+ return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;
1257
+ };
1258
+ var varint = {
1259
+ encode: encode_1,
1260
+ decode: decode2,
1261
+ encodingLength: length
1262
+ };
1263
+ var _brrp_varint = varint;
1264
+ var varint_default = _brrp_varint;
1265
+
1266
+ // ../../node_modules/multiformats/dist/src/varint.js
1267
+ function decode3(data, offset = 0) {
1268
+ const code = varint_default.decode(data, offset);
1269
+ return [code, varint_default.decode.bytes];
1270
+ }
1271
+ function encodeTo(int, target, offset = 0) {
1272
+ varint_default.encode(int, target, offset);
1273
+ return target;
1274
+ }
1275
+ function encodingLength(int) {
1276
+ return varint_default.encodingLength(int);
1277
+ }
1278
+
1279
+ // ../../node_modules/multiformats/dist/src/hashes/digest.js
1280
+ function create(code, digest) {
1281
+ const size = digest.byteLength;
1282
+ const sizeOffset = encodingLength(code);
1283
+ const digestOffset = sizeOffset + encodingLength(size);
1284
+ const bytes = new Uint8Array(digestOffset + size);
1285
+ encodeTo(code, bytes, 0);
1286
+ encodeTo(size, bytes, sizeOffset);
1287
+ bytes.set(digest, digestOffset);
1288
+ return new Digest(code, size, digest, bytes);
1289
+ }
1290
+ function decode4(multihash) {
1291
+ const bytes = coerce(multihash);
1292
+ const [code, sizeOffset] = decode3(bytes);
1293
+ const [size, digestOffset] = decode3(bytes.subarray(sizeOffset));
1294
+ const digest = bytes.subarray(sizeOffset + digestOffset);
1295
+ if (digest.byteLength !== size) {
1296
+ throw new Error("Incorrect length");
1297
+ }
1298
+ return new Digest(code, size, digest, bytes);
1299
+ }
1300
+ function equals2(a, b) {
1301
+ if (a === b) {
1302
+ return true;
1303
+ } else {
1304
+ const data = b;
1305
+ return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes);
1306
+ }
1307
+ }
1308
+
1309
+ class Digest {
1310
+ code;
1311
+ size;
1312
+ digest;
1313
+ bytes;
1314
+ constructor(code, size, digest, bytes) {
1315
+ this.code = code;
1316
+ this.size = size;
1317
+ this.digest = digest;
1318
+ this.bytes = bytes;
1319
+ }
1320
+ }
1321
+
1322
+ // ../../node_modules/multiformats/dist/src/cid.js
1323
+ function format(link, base2) {
1324
+ const { bytes, version } = link;
1325
+ switch (version) {
1326
+ case 0:
1327
+ return toStringV0(bytes, baseCache(link), base2 ?? base58btc.encoder);
1328
+ default:
1329
+ return toStringV1(bytes, baseCache(link), base2 ?? base32.encoder);
1330
+ }
1331
+ }
1332
+ var cache = new WeakMap;
1333
+ function baseCache(cid) {
1334
+ const baseCache2 = cache.get(cid);
1335
+ if (baseCache2 == null) {
1336
+ const baseCache3 = new Map;
1337
+ cache.set(cid, baseCache3);
1338
+ return baseCache3;
1339
+ }
1340
+ return baseCache2;
1341
+ }
1342
+
1343
+ class CID {
1344
+ code;
1345
+ version;
1346
+ multihash;
1347
+ bytes;
1348
+ "/";
1349
+ constructor(version, code, multihash, bytes) {
1350
+ this.code = code;
1351
+ this.version = version;
1352
+ this.multihash = multihash;
1353
+ this.bytes = bytes;
1354
+ this["/"] = bytes;
1355
+ }
1356
+ get asCID() {
1357
+ return this;
1358
+ }
1359
+ get byteOffset() {
1360
+ return this.bytes.byteOffset;
1361
+ }
1362
+ get byteLength() {
1363
+ return this.bytes.byteLength;
1364
+ }
1365
+ toV0() {
1366
+ switch (this.version) {
1367
+ case 0: {
1368
+ return this;
1369
+ }
1370
+ case 1: {
1371
+ const { code, multihash } = this;
1372
+ if (code !== DAG_PB_CODE) {
1373
+ throw new Error("Cannot convert a non dag-pb CID to CIDv0");
1374
+ }
1375
+ if (multihash.code !== SHA_256_CODE) {
1376
+ throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
1377
+ }
1378
+ return CID.createV0(multihash);
1379
+ }
1380
+ default: {
1381
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
1382
+ }
1383
+ }
1384
+ }
1385
+ toV1() {
1386
+ switch (this.version) {
1387
+ case 0: {
1388
+ const { code, digest } = this.multihash;
1389
+ const multihash = create(code, digest);
1390
+ return CID.createV1(this.code, multihash);
1391
+ }
1392
+ case 1: {
1393
+ return this;
1394
+ }
1395
+ default: {
1396
+ throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
1397
+ }
1398
+ }
1399
+ }
1400
+ equals(other) {
1401
+ return CID.equals(this, other);
1402
+ }
1403
+ static equals(self, other) {
1404
+ const unknown = other;
1405
+ return unknown != null && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash);
1406
+ }
1407
+ toString(base2) {
1408
+ return format(this, base2);
1409
+ }
1410
+ toJSON() {
1411
+ return { "/": format(this) };
1412
+ }
1413
+ link() {
1414
+ return this;
1415
+ }
1416
+ [Symbol.toStringTag] = "CID";
1417
+ [Symbol.for("nodejs.util.inspect.custom")]() {
1418
+ return `CID(${this.toString()})`;
1419
+ }
1420
+ static asCID(input) {
1421
+ if (input == null) {
1422
+ return null;
1423
+ }
1424
+ const value = input;
1425
+ if (value instanceof CID) {
1426
+ return value;
1427
+ } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
1428
+ const { version, code, multihash, bytes } = value;
1429
+ return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
1430
+ } else if (value[cidSymbol] === true) {
1431
+ const { version, multihash, code } = value;
1432
+ const digest = decode4(multihash);
1433
+ return CID.create(version, code, digest);
1434
+ } else {
1435
+ return null;
1436
+ }
1437
+ }
1438
+ static create(version, code, digest) {
1439
+ if (typeof code !== "number") {
1440
+ throw new Error("String codecs are no longer supported");
1441
+ }
1442
+ if (!(digest.bytes instanceof Uint8Array)) {
1443
+ throw new Error("Invalid digest");
1444
+ }
1445
+ switch (version) {
1446
+ case 0: {
1447
+ if (code !== DAG_PB_CODE) {
1448
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
1449
+ } else {
1450
+ return new CID(version, code, digest, digest.bytes);
1451
+ }
1452
+ }
1453
+ case 1: {
1454
+ const bytes = encodeCID(version, code, digest.bytes);
1455
+ return new CID(version, code, digest, bytes);
1456
+ }
1457
+ default: {
1458
+ throw new Error("Invalid version");
1459
+ }
1460
+ }
1461
+ }
1462
+ static createV0(digest) {
1463
+ return CID.create(0, DAG_PB_CODE, digest);
1464
+ }
1465
+ static createV1(code, digest) {
1466
+ return CID.create(1, code, digest);
1467
+ }
1468
+ static decode(bytes) {
1469
+ const [cid, remainder] = CID.decodeFirst(bytes);
1470
+ if (remainder.length !== 0) {
1471
+ throw new Error("Incorrect length");
1472
+ }
1473
+ return cid;
1474
+ }
1475
+ static decodeFirst(bytes) {
1476
+ const specs = CID.inspectBytes(bytes);
1477
+ const prefixSize = specs.size - specs.multihashSize;
1478
+ const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
1479
+ if (multihashBytes.byteLength !== specs.multihashSize) {
1480
+ throw new Error("Incorrect length");
1481
+ }
1482
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
1483
+ const digest = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
1484
+ const cid = specs.version === 0 ? CID.createV0(digest) : CID.createV1(specs.codec, digest);
1485
+ return [cid, bytes.subarray(specs.size)];
1486
+ }
1487
+ static inspectBytes(initialBytes) {
1488
+ let offset = 0;
1489
+ const next = () => {
1490
+ const [i, length2] = decode3(initialBytes.subarray(offset));
1491
+ offset += length2;
1492
+ return i;
1493
+ };
1494
+ let version = next();
1495
+ let codec = DAG_PB_CODE;
1496
+ if (version === 18) {
1497
+ version = 0;
1498
+ offset = 0;
1499
+ } else {
1500
+ codec = next();
1501
+ }
1502
+ if (version !== 0 && version !== 1) {
1503
+ throw new RangeError(`Invalid CID version ${version}`);
1504
+ }
1505
+ const prefixSize = offset;
1506
+ const multihashCode = next();
1507
+ const digestSize = next();
1508
+ const size = offset + digestSize;
1509
+ const multihashSize = size - prefixSize;
1510
+ return { version, codec, multihashCode, digestSize, multihashSize, size };
1511
+ }
1512
+ static parse(source, base2) {
1513
+ const [prefix, bytes] = parseCIDtoBytes(source, base2);
1514
+ const cid = CID.decode(bytes);
1515
+ if (cid.version === 0 && source[0] !== "Q") {
1516
+ throw Error("Version 0 CID string must not include multibase prefix");
1517
+ }
1518
+ baseCache(cid).set(prefix, source);
1519
+ return cid;
1520
+ }
1521
+ }
1522
+ function parseCIDtoBytes(source, base2) {
1523
+ switch (source[0]) {
1524
+ case "Q": {
1525
+ const decoder = base2 ?? base58btc;
1526
+ return [
1527
+ base58btc.prefix,
1528
+ decoder.decode(`${base58btc.prefix}${source}`)
1529
+ ];
1530
+ }
1531
+ case base58btc.prefix: {
1532
+ const decoder = base2 ?? base58btc;
1533
+ return [base58btc.prefix, decoder.decode(source)];
1534
+ }
1535
+ case base32.prefix: {
1536
+ const decoder = base2 ?? base32;
1537
+ return [base32.prefix, decoder.decode(source)];
1538
+ }
1539
+ case base36.prefix: {
1540
+ const decoder = base2 ?? base36;
1541
+ return [base36.prefix, decoder.decode(source)];
1542
+ }
1543
+ default: {
1544
+ if (base2 == null) {
1545
+ throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");
1546
+ }
1547
+ return [source[0], base2.decode(source)];
1548
+ }
1549
+ }
1550
+ }
1551
+ function toStringV0(bytes, cache2, base2) {
1552
+ const { prefix } = base2;
1553
+ if (prefix !== base58btc.prefix) {
1554
+ throw Error(`Cannot string encode V0 in ${base2.name} encoding`);
1555
+ }
1556
+ const cid = cache2.get(prefix);
1557
+ if (cid == null) {
1558
+ const cid2 = base2.encode(bytes).slice(1);
1559
+ cache2.set(prefix, cid2);
1560
+ return cid2;
1561
+ } else {
1562
+ return cid;
1563
+ }
1564
+ }
1565
+ function toStringV1(bytes, cache2, base2) {
1566
+ const { prefix } = base2;
1567
+ const cid = cache2.get(prefix);
1568
+ if (cid == null) {
1569
+ const cid2 = base2.encode(bytes);
1570
+ cache2.set(prefix, cid2);
1571
+ return cid2;
1572
+ } else {
1573
+ return cid;
1574
+ }
1575
+ }
1576
+ var DAG_PB_CODE = 112;
1577
+ var SHA_256_CODE = 18;
1578
+ function encodeCID(version, code, multihash) {
1579
+ const codeOffset = encodingLength(version);
1580
+ const hashOffset = codeOffset + encodingLength(code);
1581
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
1582
+ encodeTo(version, bytes, 0);
1583
+ encodeTo(code, bytes, codeOffset);
1584
+ bytes.set(multihash, hashOffset);
1585
+ return bytes;
1586
+ }
1587
+ var cidSymbol = Symbol.for("@ipld/js-cid/CID");
1588
+
1589
+ // src/cid.ts
1590
+ function cidV0ToHex(cidV0) {
1591
+ const cid = CID.parse(cidV0, base58btc);
1592
+ if (cid.version !== 0) {
1593
+ throw new Error(`Expected CIDv0, got CIDv${cid.version}`);
1594
+ }
1595
+ if (cid.multihash.code !== 18) {
1596
+ throw new Error("Unsupported hash algorithm. Only SHA-256 is supported for CIDv0.");
1597
+ }
1598
+ const digest = cid.multihash.digest;
1599
+ const hexString = `0x${Array.from(digest).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
1600
+ return hexString;
1601
+ }
1602
+ function cidV0ToUint8Array(cidV0) {
1603
+ const cid = CID.parse(cidV0, base58btc);
1604
+ if (cid.version !== 0) {
1605
+ throw new Error(`Expected CIDv0, got CIDv${cid.version}`);
1606
+ }
1607
+ if (cid.multihash.code !== 18) {
1608
+ throw new Error("Unsupported hash algorithm. Only SHA-256 is supported for CIDv0.");
1609
+ }
1610
+ return cid.multihash.digest;
1611
+ }
1612
+ // src/address.ts
1613
+ function uint256ToAddress(uint256) {
1614
+ const hex = uint256.toString(16);
1615
+ const paddedHex = hex.padStart(64, "0");
1616
+ const addressHex = paddedHex.slice(-40);
1617
+ return `0x${addressHex}`;
1618
+ }
1619
+ // src/constants.ts
1620
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
1621
+ // src/errors.ts
1622
+ class CirclesError extends Error {
1623
+ name;
1624
+ code;
1625
+ source;
1626
+ cause;
1627
+ context;
1628
+ constructor(name, message, options) {
1629
+ super(message);
1630
+ this.name = name;
1631
+ this.code = options?.code;
1632
+ this.source = options?.source ?? "UNKNOWN";
1633
+ this.cause = options?.cause;
1634
+ this.context = options?.context;
1635
+ if (Error.captureStackTrace) {
1636
+ Error.captureStackTrace(this, this.constructor);
1637
+ }
1638
+ }
1639
+ toJSON() {
1640
+ return {
1641
+ name: this.name,
1642
+ message: this.message,
1643
+ code: this.code,
1644
+ source: this.source,
1645
+ context: this.context,
1646
+ cause: this.cause instanceof Error ? {
1647
+ name: this.cause.name,
1648
+ message: this.cause.message
1649
+ } : this.cause,
1650
+ stack: this.stack
1651
+ };
1652
+ }
1653
+ toString() {
1654
+ let result = `[${this.source}] ${this.name}: ${this.message}`;
1655
+ if (this.code) {
1656
+ result += ` (Code: ${this.code})`;
1657
+ }
1658
+ if (this.context) {
1659
+ result += `
1660
+ Context: ${JSON.stringify(this.context, null, 2)}`;
1661
+ }
1662
+ return result;
1663
+ }
1664
+ }
1665
+
1666
+ class ValidationError extends CirclesError {
1667
+ constructor(message, options) {
1668
+ super("ValidationError", message, { ...options, source: "VALIDATION" });
1669
+ }
1670
+ static invalidAddress(address) {
1671
+ return new ValidationError("Invalid Ethereum address", {
1672
+ code: "VALIDATION_INVALID_ADDRESS",
1673
+ context: { address }
1674
+ });
1675
+ }
1676
+ static invalidAmount(amount, reason) {
1677
+ return new ValidationError(reason || "Invalid amount", {
1678
+ code: "VALIDATION_INVALID_AMOUNT",
1679
+ context: { amount, reason }
1680
+ });
1681
+ }
1682
+ static missingParameter(paramName) {
1683
+ return new ValidationError(`Missing required parameter: ${paramName}`, {
1684
+ code: "VALIDATION_MISSING_PARAM",
1685
+ context: { paramName }
1686
+ });
1687
+ }
1688
+ static invalidParameter(paramName, value, reason) {
1689
+ return new ValidationError(`Invalid parameter '${paramName}': ${reason || "value is invalid"}`, {
1690
+ code: "VALIDATION_INVALID_PARAM",
1691
+ context: { paramName, value, reason }
1692
+ });
1693
+ }
1694
+ }
1695
+
1696
+ class EncodingError extends CirclesError {
1697
+ constructor(message, options) {
1698
+ super("EncodingError", message, { ...options, source: "ENCODING" });
1699
+ }
1700
+ static abiEncoding(functionName, cause) {
1701
+ return new EncodingError("Failed to encode ABI data", {
1702
+ code: "ENCODING_ABI_FAILED",
1703
+ cause,
1704
+ context: { functionName }
1705
+ });
1706
+ }
1707
+ static cidConversion(cid, cause) {
1708
+ return new EncodingError("Failed to convert CID", {
1709
+ code: "ENCODING_CID_FAILED",
1710
+ cause,
1711
+ context: { cid }
1712
+ });
1713
+ }
1714
+ }
1715
+ function wrapError(error, source = "UNKNOWN") {
1716
+ if (error instanceof CirclesError) {
1717
+ return error;
1718
+ }
1719
+ if (error instanceof Error) {
1720
+ return new CirclesError(error.name || "UnknownError", error.message, {
1721
+ source,
1722
+ cause: error
1723
+ });
1724
+ }
1725
+ return new CirclesError("UnknownError", String(error), {
1726
+ source,
1727
+ cause: error
1728
+ });
1729
+ }
1730
+ function isCirclesError(error) {
1731
+ return error instanceof CirclesError;
1732
+ }
1733
+ function getErrorMessage(error) {
1734
+ if (isCirclesError(error)) {
1735
+ return error.message;
1736
+ }
1737
+ if (error instanceof Error) {
1738
+ return error.message;
1739
+ }
1740
+ return String(error);
1741
+ }
1742
+
1743
+ // src/contractErrors.ts
1744
+ var ERROR_CODE_MESSAGES = {
1745
+ 0: "Avatar already registered",
1746
+ 1: "Avatar must be registered before inviting",
1747
+ 2: "Invalid invitation",
1748
+ 3: "Avatar must be registered",
1749
+ 4: "Only self can register",
1750
+ 5: "Maximum value reached",
1751
+ 6: "Inflationary supply already set",
1752
+ 7: "Group has no collateral",
1753
+ 161: "Trust to zero address is not allowed",
1754
+ 16: "Invalid parameter"
1755
+ };
1756
+ function extractErrorData(error) {
1757
+ if (error?.details && typeof error.details === "string") {
1758
+ const match = error.details.match(/err:\s*(0x[0-9a-fA-F]+)/);
1759
+ if (match) {
1760
+ return match[1];
1761
+ }
1762
+ }
1763
+ if (error?.data && typeof error.data === "string" && error.data.startsWith("0x")) {
1764
+ return error.data;
1765
+ }
1766
+ let currentError = error;
1767
+ while (currentError) {
1768
+ if (currentError.data && typeof currentError.data === "string") {
1769
+ return currentError.data;
1770
+ }
1771
+ currentError = currentError.cause;
1772
+ }
1773
+ return null;
1774
+ }
1775
+ function formatErrorMessage(errorName, args, errorAbi) {
1776
+ if (!args || args.length === 0) {
1777
+ return errorName;
1778
+ }
1779
+ if (!errorAbi || !errorAbi.inputs) {
1780
+ const formattedArgs = args.map((arg) => {
1781
+ if (typeof arg === "bigint") {
1782
+ return arg.toString();
1783
+ }
1784
+ return String(arg);
1785
+ }).join(", ");
1786
+ return `${errorName}(${formattedArgs})`;
1787
+ }
1788
+ const codeIndex = errorAbi.inputs.findIndex((input) => input.name === "code" || input.name === "" && input.type === "uint8");
1789
+ let baseMessage = errorName;
1790
+ let detailsParts = [];
1791
+ if (codeIndex !== -1) {
1792
+ const code = Number(args[codeIndex]);
1793
+ const humanMessage = ERROR_CODE_MESSAGES[code];
1794
+ if (humanMessage) {
1795
+ baseMessage = humanMessage;
1796
+ }
1797
+ }
1798
+ errorAbi.inputs.forEach((input, index) => {
1799
+ const arg = args[index];
1800
+ const name = input.name || `arg${index}`;
1801
+ if (!input.name && input.type === "uint8") {
1802
+ return;
1803
+ }
1804
+ let formattedValue;
1805
+ if (typeof arg === "bigint") {
1806
+ formattedValue = arg.toString();
1807
+ } else if (typeof arg === "string" && arg.startsWith("0x")) {
1808
+ formattedValue = arg;
1809
+ } else {
1810
+ formattedValue = String(arg);
1811
+ }
1812
+ if (name === "code" || input.type === "uint8") {
1813
+ formattedValue = `0x${Number(arg).toString(16)}`;
1814
+ }
1815
+ detailsParts.push(`${name}: ${formattedValue}`);
1816
+ });
1817
+ if (detailsParts.length > 0) {
1818
+ return `${baseMessage} (${detailsParts.join(", ")})`;
1819
+ }
1820
+ return baseMessage;
1821
+ }
1822
+ function parseContractError(error, abi) {
1823
+ const errorData = extractErrorData(error);
1824
+ if (!errorData) {
1825
+ return null;
1826
+ }
1827
+ const decoded = decodeErrorResult({ abi, data: errorData });
1828
+ if (!decoded) {
1829
+ return null;
1830
+ }
1831
+ const errorAbi = abi.find((item) => item.type === "error" && item.name === decoded.errorName);
1832
+ const selector = errorData.slice(0, 10);
1833
+ const formattedMessage = formatErrorMessage(decoded.errorName, decoded.args, errorAbi);
1834
+ return {
1835
+ errorName: decoded.errorName,
1836
+ args: decoded.args,
1837
+ selector,
1838
+ rawData: errorData,
1839
+ formattedMessage
1840
+ };
1841
+ }
1842
+
1843
+ class ContractError extends CirclesError {
1844
+ decodedError;
1845
+ constructor(message, options) {
1846
+ super("ContractError", message, { ...options, source: "CORE" });
1847
+ this.decodedError = options?.decodedError;
1848
+ }
1849
+ static fromTransactionError(error, abi, context) {
1850
+ const decoded = parseContractError(error, abi);
1851
+ if (decoded) {
1852
+ return new ContractError(`Transaction failed: ${decoded.formattedMessage}`, {
1853
+ code: decoded.selector,
1854
+ cause: error,
1855
+ context: {
1856
+ ...context,
1857
+ errorName: decoded.errorName,
1858
+ errorArgs: decoded.args
1859
+ },
1860
+ decodedError: decoded
1861
+ });
1862
+ }
1863
+ const message = error?.message || String(error);
1864
+ return new ContractError(`Transaction failed: ${message}`, {
1865
+ cause: error,
1866
+ context
1867
+ });
1868
+ }
1869
+ toString() {
1870
+ let result = super.toString();
1871
+ if (this.decodedError) {
1872
+ result += `
1873
+ Decoded Error: ${this.decodedError.formattedMessage}`;
1874
+ if (this.decodedError.args && this.decodedError.args.length > 0) {
1875
+ result += `
1876
+ Arguments: ${JSON.stringify(this.decodedError.args, (_, v) => typeof v === "bigint" ? v.toString() : v)}`;
1877
+ }
1878
+ }
1879
+ return result;
1880
+ }
1881
+ }
1882
+ export {
1883
+ wrapError,
1884
+ uint256ToAddress,
1885
+ parseContractError,
1886
+ isCirclesError,
1887
+ getErrorMessage,
1888
+ encodeFunctionData,
1889
+ decodeFunctionResult,
1890
+ decodeErrorResult,
1891
+ cidV0ToUint8Array,
1892
+ cidV0ToHex,
1893
+ checksumAddress,
1894
+ bytesToHex,
1895
+ ZERO_ADDRESS,
1896
+ ValidationError,
1897
+ EncodingError,
1898
+ ContractError,
1899
+ CirclesError,
1900
+ CirclesConverter
1901
+ };