@glacislabs/stablegenie-zerodelta 4.12.0 → 4.13.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/LICENSE +21 -21
- package/README.md +223 -223
- package/dist/{chunk-A7ADZJXA.js → chunk-52MY5D3D.js} +1232 -202
- package/dist/{chunk-MA2VYFG3.js → chunk-BYAKXZ5E.js} +756 -54
- package/dist/core/index.cjs +1880 -214
- package/dist/core/index.d.cts +367 -40
- package/dist/core/index.d.ts +367 -40
- package/dist/core/index.js +1 -1
- package/dist/ed25519-FZW4JEOV.js +526 -0
- package/dist/ed25519-GAMEXARB.js +11 -0
- package/dist/index.cjs +2678 -377
- package/dist/index.d.cts +96 -4
- package/dist/index.d.ts +96 -4
- package/dist/index.js +2 -2
- package/dist/{mount-xruGixNZ.d.cts → mount-BR3wWmjt.d.cts} +1 -1
- package/dist/{mount-hxb3zioQ.d.ts → mount-bKSKIGmW.d.ts} +1 -1
- package/dist/mount.cjs +2669 -375
- package/dist/mount.d.cts +2 -2
- package/dist/mount.d.ts +2 -2
- package/dist/mount.js +2 -2
- package/dist/standalone.global.js +12 -9
- package/dist/{verify-D8tr1yY1.d.cts → verify-DdSA23GJ.d.cts} +78 -68
- package/dist/{verify-D8tr1yY1.d.ts → verify-DdSA23GJ.d.ts} +78 -68
- package/package.json +134 -133
package/dist/index.cjs
CHANGED
|
@@ -4,7 +4,575 @@ var react = require('react');
|
|
|
4
4
|
var jsxRuntime = require('react/jsx-runtime');
|
|
5
5
|
var client = require('react-dom/client');
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
var __defProp = Object.defineProperty;
|
|
8
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
9
|
+
var __esm = (fn, res) => function __init() {
|
|
10
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// node_modules/@noble/ed25519/index.js
|
|
18
|
+
var ed25519_exports = {};
|
|
19
|
+
__export(ed25519_exports, {
|
|
20
|
+
Point: () => Point,
|
|
21
|
+
etc: () => etc,
|
|
22
|
+
getPublicKey: () => getPublicKey,
|
|
23
|
+
getPublicKeyAsync: () => getPublicKeyAsync,
|
|
24
|
+
hash: () => hash,
|
|
25
|
+
hashes: () => hashes,
|
|
26
|
+
keygen: () => keygen,
|
|
27
|
+
keygenAsync: () => keygenAsync,
|
|
28
|
+
sign: () => sign,
|
|
29
|
+
signAsync: () => signAsync,
|
|
30
|
+
utils: () => utils,
|
|
31
|
+
verify: () => verify,
|
|
32
|
+
verifyAsync: () => verifyAsync
|
|
33
|
+
});
|
|
34
|
+
var ed25519_CURVE, P2, N, Gx, Gy, _a, _d, h, L, L2, captureTrace, err, isBig, isStr, isBytes, abytes, u8n, u8fr, padh, bytesToHex, C, _ch, hexToBytes, cr, subtle, concatBytes, randomBytes, big, assertRange, M, modN, invert, callHash, hash, apoint, B256, Point, G, I, numTo32bLE, bytesToNumLE, pow2, pow_2_252_3, RM1, uvRatio, modL_LE, sha512a, sha512s, hash2extK, getExtendedPublicKeyAsync, getExtendedPublicKey, getPublicKeyAsync, getPublicKey, hashFinishA, hashFinishS, _sign, signAsync, sign, defaultVerifyOpts, _verify, verifyAsync, verify, etc, hashes, randomSecretKey, keygen, keygenAsync, utils, W, scalarBits, pwindows, pwindowSize, precompute, Gpows, ctneg, wNAF;
|
|
35
|
+
var init_ed25519 = __esm({
|
|
36
|
+
"node_modules/@noble/ed25519/index.js"() {
|
|
37
|
+
ed25519_CURVE = {
|
|
38
|
+
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
|
|
39
|
+
n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
|
|
40
|
+
h: 8n,
|
|
41
|
+
a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
|
|
42
|
+
d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
|
|
43
|
+
Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
|
|
44
|
+
Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
|
|
45
|
+
};
|
|
46
|
+
({ p: P2, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE);
|
|
47
|
+
L = 32;
|
|
48
|
+
L2 = 64;
|
|
49
|
+
captureTrace = (...args) => {
|
|
50
|
+
if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
|
|
51
|
+
Error.captureStackTrace(...args);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
err = (message = "") => {
|
|
55
|
+
const e = new Error(message);
|
|
56
|
+
captureTrace(e, err);
|
|
57
|
+
throw e;
|
|
58
|
+
};
|
|
59
|
+
isBig = (n) => typeof n === "bigint";
|
|
60
|
+
isStr = (s) => typeof s === "string";
|
|
61
|
+
isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
62
|
+
abytes = (value, length, title = "") => {
|
|
63
|
+
const bytes = isBytes(value);
|
|
64
|
+
const len = value?.length;
|
|
65
|
+
const needsLen = length !== void 0;
|
|
66
|
+
if (!bytes || needsLen && len !== length) {
|
|
67
|
+
const prefix = title && `"${title}" `;
|
|
68
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
69
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
70
|
+
err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
};
|
|
74
|
+
u8n = (len) => new Uint8Array(len);
|
|
75
|
+
u8fr = (buf) => Uint8Array.from(buf);
|
|
76
|
+
padh = (n, pad) => n.toString(16).padStart(pad, "0");
|
|
77
|
+
bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
|
|
78
|
+
C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
79
|
+
_ch = (ch) => {
|
|
80
|
+
if (ch >= C._0 && ch <= C._9)
|
|
81
|
+
return ch - C._0;
|
|
82
|
+
if (ch >= C.A && ch <= C.F)
|
|
83
|
+
return ch - (C.A - 10);
|
|
84
|
+
if (ch >= C.a && ch <= C.f)
|
|
85
|
+
return ch - (C.a - 10);
|
|
86
|
+
return;
|
|
87
|
+
};
|
|
88
|
+
hexToBytes = (hex) => {
|
|
89
|
+
const e = "hex invalid";
|
|
90
|
+
if (!isStr(hex))
|
|
91
|
+
return err(e);
|
|
92
|
+
const hl = hex.length;
|
|
93
|
+
const al = hl / 2;
|
|
94
|
+
if (hl % 2)
|
|
95
|
+
return err(e);
|
|
96
|
+
const array = u8n(al);
|
|
97
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
98
|
+
const n1 = _ch(hex.charCodeAt(hi));
|
|
99
|
+
const n2 = _ch(hex.charCodeAt(hi + 1));
|
|
100
|
+
if (n1 === void 0 || n2 === void 0)
|
|
101
|
+
return err(e);
|
|
102
|
+
array[ai] = n1 * 16 + n2;
|
|
103
|
+
}
|
|
104
|
+
return array;
|
|
105
|
+
};
|
|
106
|
+
cr = () => globalThis?.crypto;
|
|
107
|
+
subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
|
|
108
|
+
concatBytes = (...arrs) => {
|
|
109
|
+
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
|
|
110
|
+
let pad = 0;
|
|
111
|
+
arrs.forEach((a) => {
|
|
112
|
+
r.set(a, pad);
|
|
113
|
+
pad += a.length;
|
|
114
|
+
});
|
|
115
|
+
return r;
|
|
116
|
+
};
|
|
117
|
+
randomBytes = (len = L) => {
|
|
118
|
+
const c = cr();
|
|
119
|
+
return c.getRandomValues(u8n(len));
|
|
120
|
+
};
|
|
121
|
+
big = BigInt;
|
|
122
|
+
assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
|
|
123
|
+
M = (a, b = P2) => {
|
|
124
|
+
const r = a % b;
|
|
125
|
+
return r >= 0n ? r : b + r;
|
|
126
|
+
};
|
|
127
|
+
modN = (a) => M(a, N);
|
|
128
|
+
invert = (num, md) => {
|
|
129
|
+
if (num === 0n || md <= 0n)
|
|
130
|
+
err("no inverse n=" + num + " mod=" + md);
|
|
131
|
+
let a = M(num, md), b = md, x = 0n, u = 1n;
|
|
132
|
+
while (a !== 0n) {
|
|
133
|
+
const q = b / a, r = b % a;
|
|
134
|
+
const m = x - u * q;
|
|
135
|
+
b = a, a = r, x = u, u = m;
|
|
136
|
+
}
|
|
137
|
+
return b === 1n ? M(x, md) : err("no inverse");
|
|
138
|
+
};
|
|
139
|
+
callHash = (name) => {
|
|
140
|
+
const fn = hashes[name];
|
|
141
|
+
if (typeof fn !== "function")
|
|
142
|
+
err("hashes." + name + " not set");
|
|
143
|
+
return fn;
|
|
144
|
+
};
|
|
145
|
+
hash = (msg) => callHash("sha512")(msg);
|
|
146
|
+
apoint = (p) => p instanceof Point ? p : err("Point expected");
|
|
147
|
+
B256 = 2n ** 256n;
|
|
148
|
+
Point = class _Point {
|
|
149
|
+
static BASE;
|
|
150
|
+
static ZERO;
|
|
151
|
+
X;
|
|
152
|
+
Y;
|
|
153
|
+
Z;
|
|
154
|
+
T;
|
|
155
|
+
constructor(X, Y, Z, T) {
|
|
156
|
+
const max = B256;
|
|
157
|
+
this.X = assertRange(X, 0n, max);
|
|
158
|
+
this.Y = assertRange(Y, 0n, max);
|
|
159
|
+
this.Z = assertRange(Z, 1n, max);
|
|
160
|
+
this.T = assertRange(T, 0n, max);
|
|
161
|
+
Object.freeze(this);
|
|
162
|
+
}
|
|
163
|
+
static CURVE() {
|
|
164
|
+
return ed25519_CURVE;
|
|
165
|
+
}
|
|
166
|
+
static fromAffine(p) {
|
|
167
|
+
return new _Point(p.x, p.y, 1n, M(p.x * p.y));
|
|
168
|
+
}
|
|
169
|
+
/** RFC8032 5.1.3: Uint8Array to Point. */
|
|
170
|
+
static fromBytes(hex, zip215 = false) {
|
|
171
|
+
const d = _d;
|
|
172
|
+
const normed = u8fr(abytes(hex, L));
|
|
173
|
+
const lastByte = hex[31];
|
|
174
|
+
normed[31] = lastByte & -129;
|
|
175
|
+
const y = bytesToNumLE(normed);
|
|
176
|
+
const max = zip215 ? B256 : P2;
|
|
177
|
+
assertRange(y, 0n, max);
|
|
178
|
+
const y2 = M(y * y);
|
|
179
|
+
const u = M(y2 - 1n);
|
|
180
|
+
const v = M(d * y2 + 1n);
|
|
181
|
+
let { isValid, value: x } = uvRatio(u, v);
|
|
182
|
+
if (!isValid)
|
|
183
|
+
err("bad point: y not sqrt");
|
|
184
|
+
const isXOdd = (x & 1n) === 1n;
|
|
185
|
+
const isLastByteOdd = (lastByte & 128) !== 0;
|
|
186
|
+
if (!zip215 && x === 0n && isLastByteOdd)
|
|
187
|
+
err("bad point: x==0, isLastByteOdd");
|
|
188
|
+
if (isLastByteOdd !== isXOdd)
|
|
189
|
+
x = M(-x);
|
|
190
|
+
return new _Point(x, y, 1n, M(x * y));
|
|
191
|
+
}
|
|
192
|
+
static fromHex(hex, zip215) {
|
|
193
|
+
return _Point.fromBytes(hexToBytes(hex), zip215);
|
|
194
|
+
}
|
|
195
|
+
get x() {
|
|
196
|
+
return this.toAffine().x;
|
|
197
|
+
}
|
|
198
|
+
get y() {
|
|
199
|
+
return this.toAffine().y;
|
|
200
|
+
}
|
|
201
|
+
/** Checks if the point is valid and on-curve. */
|
|
202
|
+
assertValidity() {
|
|
203
|
+
const a = _a;
|
|
204
|
+
const d = _d;
|
|
205
|
+
const p = this;
|
|
206
|
+
if (p.is0())
|
|
207
|
+
return err("bad point: ZERO");
|
|
208
|
+
const { X, Y, Z, T } = p;
|
|
209
|
+
const X2 = M(X * X);
|
|
210
|
+
const Y2 = M(Y * Y);
|
|
211
|
+
const Z2 = M(Z * Z);
|
|
212
|
+
const Z4 = M(Z2 * Z2);
|
|
213
|
+
const aX2 = M(X2 * a);
|
|
214
|
+
const left = M(Z2 * M(aX2 + Y2));
|
|
215
|
+
const right = M(Z4 + M(d * M(X2 * Y2)));
|
|
216
|
+
if (left !== right)
|
|
217
|
+
return err("bad point: equation left != right (1)");
|
|
218
|
+
const XY = M(X * Y);
|
|
219
|
+
const ZT = M(Z * T);
|
|
220
|
+
if (XY !== ZT)
|
|
221
|
+
return err("bad point: equation left != right (2)");
|
|
222
|
+
return this;
|
|
223
|
+
}
|
|
224
|
+
/** Equality check: compare points P&Q. */
|
|
225
|
+
equals(other) {
|
|
226
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
227
|
+
const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
|
|
228
|
+
const X1Z2 = M(X1 * Z2);
|
|
229
|
+
const X2Z1 = M(X2 * Z1);
|
|
230
|
+
const Y1Z2 = M(Y1 * Z2);
|
|
231
|
+
const Y2Z1 = M(Y2 * Z1);
|
|
232
|
+
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
|
233
|
+
}
|
|
234
|
+
is0() {
|
|
235
|
+
return this.equals(I);
|
|
236
|
+
}
|
|
237
|
+
/** Flip point over y coordinate. */
|
|
238
|
+
negate() {
|
|
239
|
+
return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
|
|
240
|
+
}
|
|
241
|
+
/** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
|
|
242
|
+
double() {
|
|
243
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
244
|
+
const a = _a;
|
|
245
|
+
const A = M(X1 * X1);
|
|
246
|
+
const B = M(Y1 * Y1);
|
|
247
|
+
const C2 = M(2n * M(Z1 * Z1));
|
|
248
|
+
const D2 = M(a * A);
|
|
249
|
+
const x1y1 = X1 + Y1;
|
|
250
|
+
const E = M(M(x1y1 * x1y1) - A - B);
|
|
251
|
+
const G2 = D2 + B;
|
|
252
|
+
const F = G2 - C2;
|
|
253
|
+
const H = D2 - B;
|
|
254
|
+
const X3 = M(E * F);
|
|
255
|
+
const Y3 = M(G2 * H);
|
|
256
|
+
const T3 = M(E * H);
|
|
257
|
+
const Z3 = M(F * G2);
|
|
258
|
+
return new _Point(X3, Y3, Z3, T3);
|
|
259
|
+
}
|
|
260
|
+
/** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
|
|
261
|
+
add(other) {
|
|
262
|
+
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
|
263
|
+
const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
|
|
264
|
+
const a = _a;
|
|
265
|
+
const d = _d;
|
|
266
|
+
const A = M(X1 * X2);
|
|
267
|
+
const B = M(Y1 * Y2);
|
|
268
|
+
const C2 = M(T1 * d * T2);
|
|
269
|
+
const D2 = M(Z1 * Z2);
|
|
270
|
+
const E = M((X1 + Y1) * (X2 + Y2) - A - B);
|
|
271
|
+
const F = M(D2 - C2);
|
|
272
|
+
const G2 = M(D2 + C2);
|
|
273
|
+
const H = M(B - a * A);
|
|
274
|
+
const X3 = M(E * F);
|
|
275
|
+
const Y3 = M(G2 * H);
|
|
276
|
+
const T3 = M(E * H);
|
|
277
|
+
const Z3 = M(F * G2);
|
|
278
|
+
return new _Point(X3, Y3, Z3, T3);
|
|
279
|
+
}
|
|
280
|
+
subtract(other) {
|
|
281
|
+
return this.add(apoint(other).negate());
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
|
|
285
|
+
* Uses {@link wNAF} for base point.
|
|
286
|
+
* Uses fake point to mitigate side-channel leakage.
|
|
287
|
+
* @param n scalar by which point is multiplied
|
|
288
|
+
* @param safe safe mode guards against timing attacks; unsafe mode is faster
|
|
289
|
+
*/
|
|
290
|
+
multiply(n, safe = true) {
|
|
291
|
+
if (!safe && (n === 0n || this.is0()))
|
|
292
|
+
return I;
|
|
293
|
+
assertRange(n, 1n, N);
|
|
294
|
+
if (n === 1n)
|
|
295
|
+
return this;
|
|
296
|
+
if (this.equals(G))
|
|
297
|
+
return wNAF(n).p;
|
|
298
|
+
let p = I;
|
|
299
|
+
let f = G;
|
|
300
|
+
for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
|
|
301
|
+
if (n & 1n)
|
|
302
|
+
p = p.add(d);
|
|
303
|
+
else if (safe)
|
|
304
|
+
f = f.add(d);
|
|
305
|
+
}
|
|
306
|
+
return p;
|
|
307
|
+
}
|
|
308
|
+
multiplyUnsafe(scalar) {
|
|
309
|
+
return this.multiply(scalar, false);
|
|
310
|
+
}
|
|
311
|
+
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
|
|
312
|
+
toAffine() {
|
|
313
|
+
const { X, Y, Z } = this;
|
|
314
|
+
if (this.equals(I))
|
|
315
|
+
return { x: 0n, y: 1n };
|
|
316
|
+
const iz = invert(Z, P2);
|
|
317
|
+
if (M(Z * iz) !== 1n)
|
|
318
|
+
err("invalid inverse");
|
|
319
|
+
const x = M(X * iz);
|
|
320
|
+
const y = M(Y * iz);
|
|
321
|
+
return { x, y };
|
|
322
|
+
}
|
|
323
|
+
toBytes() {
|
|
324
|
+
const { x, y } = this.assertValidity().toAffine();
|
|
325
|
+
const b = numTo32bLE(y);
|
|
326
|
+
b[31] |= x & 1n ? 128 : 0;
|
|
327
|
+
return b;
|
|
328
|
+
}
|
|
329
|
+
toHex() {
|
|
330
|
+
return bytesToHex(this.toBytes());
|
|
331
|
+
}
|
|
332
|
+
clearCofactor() {
|
|
333
|
+
return this.multiply(big(h), false);
|
|
334
|
+
}
|
|
335
|
+
isSmallOrder() {
|
|
336
|
+
return this.clearCofactor().is0();
|
|
337
|
+
}
|
|
338
|
+
isTorsionFree() {
|
|
339
|
+
let p = this.multiply(N / 2n, false).double();
|
|
340
|
+
if (N % 2n)
|
|
341
|
+
p = p.add(this);
|
|
342
|
+
return p.is0();
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
G = new Point(Gx, Gy, 1n, M(Gx * Gy));
|
|
346
|
+
I = new Point(0n, 1n, 1n, 0n);
|
|
347
|
+
Point.BASE = G;
|
|
348
|
+
Point.ZERO = I;
|
|
349
|
+
numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
|
|
350
|
+
bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
|
|
351
|
+
pow2 = (x, power) => {
|
|
352
|
+
let r = x;
|
|
353
|
+
while (power-- > 0n) {
|
|
354
|
+
r *= r;
|
|
355
|
+
r %= P2;
|
|
356
|
+
}
|
|
357
|
+
return r;
|
|
358
|
+
};
|
|
359
|
+
pow_2_252_3 = (x) => {
|
|
360
|
+
const x2 = x * x % P2;
|
|
361
|
+
const b2 = x2 * x % P2;
|
|
362
|
+
const b4 = pow2(b2, 2n) * b2 % P2;
|
|
363
|
+
const b5 = pow2(b4, 1n) * x % P2;
|
|
364
|
+
const b10 = pow2(b5, 5n) * b5 % P2;
|
|
365
|
+
const b20 = pow2(b10, 10n) * b10 % P2;
|
|
366
|
+
const b40 = pow2(b20, 20n) * b20 % P2;
|
|
367
|
+
const b80 = pow2(b40, 40n) * b40 % P2;
|
|
368
|
+
const b160 = pow2(b80, 80n) * b80 % P2;
|
|
369
|
+
const b240 = pow2(b160, 80n) * b80 % P2;
|
|
370
|
+
const b250 = pow2(b240, 10n) * b10 % P2;
|
|
371
|
+
const pow_p_5_8 = pow2(b250, 2n) * x % P2;
|
|
372
|
+
return { pow_p_5_8, b2 };
|
|
373
|
+
};
|
|
374
|
+
RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
|
|
375
|
+
uvRatio = (u, v) => {
|
|
376
|
+
const v3 = M(v * v * v);
|
|
377
|
+
const v7 = M(v3 * v3 * v);
|
|
378
|
+
const pow3 = pow_2_252_3(u * v7).pow_p_5_8;
|
|
379
|
+
let x = M(u * v3 * pow3);
|
|
380
|
+
const vx2 = M(v * x * x);
|
|
381
|
+
const root1 = x;
|
|
382
|
+
const root2 = M(x * RM1);
|
|
383
|
+
const useRoot1 = vx2 === u;
|
|
384
|
+
const useRoot2 = vx2 === M(-u);
|
|
385
|
+
const noRoot = vx2 === M(-u * RM1);
|
|
386
|
+
if (useRoot1)
|
|
387
|
+
x = root1;
|
|
388
|
+
if (useRoot2 || noRoot)
|
|
389
|
+
x = root2;
|
|
390
|
+
if ((M(x) & 1n) === 1n)
|
|
391
|
+
x = M(-x);
|
|
392
|
+
return { isValid: useRoot1 || useRoot2, value: x };
|
|
393
|
+
};
|
|
394
|
+
modL_LE = (hash2) => modN(bytesToNumLE(hash2));
|
|
395
|
+
sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
|
|
396
|
+
sha512s = (...m) => callHash("sha512")(concatBytes(...m));
|
|
397
|
+
hash2extK = (hashed) => {
|
|
398
|
+
const head = hashed.slice(0, L);
|
|
399
|
+
head[0] &= 248;
|
|
400
|
+
head[31] &= 127;
|
|
401
|
+
head[31] |= 64;
|
|
402
|
+
const prefix = hashed.slice(L, L2);
|
|
403
|
+
const scalar = modL_LE(head);
|
|
404
|
+
const point = G.multiply(scalar);
|
|
405
|
+
const pointBytes = point.toBytes();
|
|
406
|
+
return { head, prefix, scalar, point, pointBytes };
|
|
407
|
+
};
|
|
408
|
+
getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
|
|
409
|
+
getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
|
|
410
|
+
getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
|
|
411
|
+
getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
|
|
412
|
+
hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
|
|
413
|
+
hashFinishS = (res) => res.finish(sha512s(res.hashable));
|
|
414
|
+
_sign = (e, rBytes, msg) => {
|
|
415
|
+
const { pointBytes: P3, scalar: s } = e;
|
|
416
|
+
const r = modL_LE(rBytes);
|
|
417
|
+
const R = G.multiply(r).toBytes();
|
|
418
|
+
const hashable = concatBytes(R, P3, msg);
|
|
419
|
+
const finish = (hashed) => {
|
|
420
|
+
const S = modN(r + modL_LE(hashed) * s);
|
|
421
|
+
return abytes(concatBytes(R, numTo32bLE(S)), L2);
|
|
422
|
+
};
|
|
423
|
+
return { hashable, finish };
|
|
424
|
+
};
|
|
425
|
+
signAsync = async (message, secretKey) => {
|
|
426
|
+
const m = abytes(message);
|
|
427
|
+
const e = await getExtendedPublicKeyAsync(secretKey);
|
|
428
|
+
const rBytes = await sha512a(e.prefix, m);
|
|
429
|
+
return hashFinishA(_sign(e, rBytes, m));
|
|
430
|
+
};
|
|
431
|
+
sign = (message, secretKey) => {
|
|
432
|
+
const m = abytes(message);
|
|
433
|
+
const e = getExtendedPublicKey(secretKey);
|
|
434
|
+
const rBytes = sha512s(e.prefix, m);
|
|
435
|
+
return hashFinishS(_sign(e, rBytes, m));
|
|
436
|
+
};
|
|
437
|
+
defaultVerifyOpts = { zip215: true };
|
|
438
|
+
_verify = (sig, msg, pub, opts = defaultVerifyOpts) => {
|
|
439
|
+
sig = abytes(sig, L2);
|
|
440
|
+
msg = abytes(msg);
|
|
441
|
+
pub = abytes(pub, L);
|
|
442
|
+
const { zip215 } = opts;
|
|
443
|
+
let A;
|
|
444
|
+
let R;
|
|
445
|
+
let s;
|
|
446
|
+
let SB;
|
|
447
|
+
let hashable = Uint8Array.of();
|
|
448
|
+
try {
|
|
449
|
+
A = Point.fromBytes(pub, zip215);
|
|
450
|
+
R = Point.fromBytes(sig.slice(0, L), zip215);
|
|
451
|
+
s = bytesToNumLE(sig.slice(L, L2));
|
|
452
|
+
SB = G.multiply(s, false);
|
|
453
|
+
hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
}
|
|
456
|
+
const finish = (hashed) => {
|
|
457
|
+
if (SB == null)
|
|
458
|
+
return false;
|
|
459
|
+
if (!zip215 && A.isSmallOrder())
|
|
460
|
+
return false;
|
|
461
|
+
const k = modL_LE(hashed);
|
|
462
|
+
const RkA = R.add(A.multiply(k, false));
|
|
463
|
+
return RkA.add(SB.negate()).clearCofactor().is0();
|
|
464
|
+
};
|
|
465
|
+
return { hashable, finish };
|
|
466
|
+
};
|
|
467
|
+
verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
|
|
468
|
+
verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));
|
|
469
|
+
etc = {
|
|
470
|
+
bytesToHex,
|
|
471
|
+
hexToBytes,
|
|
472
|
+
concatBytes,
|
|
473
|
+
mod: M,
|
|
474
|
+
invert,
|
|
475
|
+
randomBytes
|
|
476
|
+
};
|
|
477
|
+
hashes = {
|
|
478
|
+
sha512Async: async (message) => {
|
|
479
|
+
const s = subtle();
|
|
480
|
+
const m = concatBytes(message);
|
|
481
|
+
return u8n(await s.digest("SHA-512", m.buffer));
|
|
482
|
+
},
|
|
483
|
+
sha512: void 0
|
|
484
|
+
};
|
|
485
|
+
randomSecretKey = (seed = randomBytes(L)) => seed;
|
|
486
|
+
keygen = (seed) => {
|
|
487
|
+
const secretKey = randomSecretKey(seed);
|
|
488
|
+
const publicKey = getPublicKey(secretKey);
|
|
489
|
+
return { secretKey, publicKey };
|
|
490
|
+
};
|
|
491
|
+
keygenAsync = async (seed) => {
|
|
492
|
+
const secretKey = randomSecretKey(seed);
|
|
493
|
+
const publicKey = await getPublicKeyAsync(secretKey);
|
|
494
|
+
return { secretKey, publicKey };
|
|
495
|
+
};
|
|
496
|
+
utils = {
|
|
497
|
+
getExtendedPublicKeyAsync,
|
|
498
|
+
getExtendedPublicKey,
|
|
499
|
+
randomSecretKey
|
|
500
|
+
};
|
|
501
|
+
W = 8;
|
|
502
|
+
scalarBits = 256;
|
|
503
|
+
pwindows = Math.ceil(scalarBits / W) + 1;
|
|
504
|
+
pwindowSize = 2 ** (W - 1);
|
|
505
|
+
precompute = () => {
|
|
506
|
+
const points = [];
|
|
507
|
+
let p = G;
|
|
508
|
+
let b = p;
|
|
509
|
+
for (let w = 0; w < pwindows; w++) {
|
|
510
|
+
b = p;
|
|
511
|
+
points.push(b);
|
|
512
|
+
for (let i = 1; i < pwindowSize; i++) {
|
|
513
|
+
b = b.add(p);
|
|
514
|
+
points.push(b);
|
|
515
|
+
}
|
|
516
|
+
p = b.double();
|
|
517
|
+
}
|
|
518
|
+
return points;
|
|
519
|
+
};
|
|
520
|
+
Gpows = void 0;
|
|
521
|
+
ctneg = (cnd, p) => {
|
|
522
|
+
const n = p.negate();
|
|
523
|
+
return cnd ? n : p;
|
|
524
|
+
};
|
|
525
|
+
wNAF = (n) => {
|
|
526
|
+
const comp = Gpows || (Gpows = precompute());
|
|
527
|
+
let p = I;
|
|
528
|
+
let f = G;
|
|
529
|
+
const pow_2_w = 2 ** W;
|
|
530
|
+
const maxNum = pow_2_w;
|
|
531
|
+
const mask = big(pow_2_w - 1);
|
|
532
|
+
const shiftBy = big(W);
|
|
533
|
+
for (let w = 0; w < pwindows; w++) {
|
|
534
|
+
let wbits = Number(n & mask);
|
|
535
|
+
n >>= shiftBy;
|
|
536
|
+
if (wbits > pwindowSize) {
|
|
537
|
+
wbits -= maxNum;
|
|
538
|
+
n += 1n;
|
|
539
|
+
}
|
|
540
|
+
const off = w * pwindowSize;
|
|
541
|
+
const offF = off;
|
|
542
|
+
const offP = off + Math.abs(wbits) - 1;
|
|
543
|
+
const isEven = w % 2 !== 0;
|
|
544
|
+
const isNeg = wbits < 0;
|
|
545
|
+
if (wbits === 0) {
|
|
546
|
+
f = f.add(ctneg(isEven, comp[offF]));
|
|
547
|
+
} else {
|
|
548
|
+
p = p.add(ctneg(isNeg, comp[offP]));
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
if (n !== 0n)
|
|
552
|
+
err("invalid wnaf");
|
|
553
|
+
return { p, f };
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
// src/core/ed25519.ts
|
|
559
|
+
var ed25519_exports2 = {};
|
|
560
|
+
__export(ed25519_exports2, {
|
|
561
|
+
eventPublicKey: () => eventPublicKey,
|
|
562
|
+
eventSignature: () => eventSignature
|
|
563
|
+
});
|
|
564
|
+
async function eventPublicKey(seed) {
|
|
565
|
+
const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
|
|
566
|
+
return ed.getPublicKeyAsync(seed);
|
|
567
|
+
}
|
|
568
|
+
async function eventSignature(message, seed) {
|
|
569
|
+
const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
|
|
570
|
+
return ed.signAsync(message, seed);
|
|
571
|
+
}
|
|
572
|
+
var init_ed255192 = __esm({
|
|
573
|
+
"src/core/ed25519.ts"() {
|
|
574
|
+
}
|
|
575
|
+
});
|
|
8
576
|
var ConfigContext = react.createContext({});
|
|
9
577
|
function StableGenieProvider({ children, ...config }) {
|
|
10
578
|
return /* @__PURE__ */ jsxRuntime.jsx(ConfigContext.Provider, { value: config, children });
|
|
@@ -107,7 +675,10 @@ var CANONICAL_ESCROW = Object.freeze({
|
|
|
107
675
|
// Plume
|
|
108
676
|
});
|
|
109
677
|
var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
|
|
110
|
-
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
|
|
678
|
+
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
|
|
679
|
+
9745: 2500n * 10n ** 18n,
|
|
680
|
+
98866: 5000n * 10n ** 18n
|
|
681
|
+
};
|
|
111
682
|
function maxNativeFeeWei(chainId) {
|
|
112
683
|
return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
|
|
113
684
|
}
|
|
@@ -225,6 +796,247 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
|
|
|
225
796
|
1151111081099710: "Solana"
|
|
226
797
|
});
|
|
227
798
|
|
|
799
|
+
// src/core/solana.ts
|
|
800
|
+
var SOLANA_CHAIN_ID = 1151111081099710;
|
|
801
|
+
function isSolanaChainId(value) {
|
|
802
|
+
return Number(value) === SOLANA_CHAIN_ID;
|
|
803
|
+
}
|
|
804
|
+
var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
805
|
+
function base58Encode(bytes) {
|
|
806
|
+
let zeros = 0;
|
|
807
|
+
while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
|
|
808
|
+
let value = 0n;
|
|
809
|
+
for (const byte of bytes) value = value << 8n | BigInt(byte);
|
|
810
|
+
let out = "";
|
|
811
|
+
while (value > 0n) {
|
|
812
|
+
out = BASE58_ALPHABET[Number(value % 58n)] + out;
|
|
813
|
+
value /= 58n;
|
|
814
|
+
}
|
|
815
|
+
return "1".repeat(zeros) + out;
|
|
816
|
+
}
|
|
817
|
+
function base58Decode(text) {
|
|
818
|
+
let value = 0n;
|
|
819
|
+
for (const char of text) {
|
|
820
|
+
const digit = BASE58_ALPHABET.indexOf(char);
|
|
821
|
+
if (digit < 0) return null;
|
|
822
|
+
value = value * 58n + BigInt(digit);
|
|
823
|
+
}
|
|
824
|
+
const body = [];
|
|
825
|
+
while (value > 0n) {
|
|
826
|
+
body.unshift(Number(value & 0xffn));
|
|
827
|
+
value >>= 8n;
|
|
828
|
+
}
|
|
829
|
+
let zeros = 0;
|
|
830
|
+
while (zeros < text.length && text[zeros] === "1") zeros += 1;
|
|
831
|
+
return new Uint8Array([...new Array(zeros).fill(0), ...body]);
|
|
832
|
+
}
|
|
833
|
+
function isSolanaAddress(value) {
|
|
834
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
835
|
+
return text.length >= 32 && text.length <= 44 && base58Decode(text)?.length === 32;
|
|
836
|
+
}
|
|
837
|
+
function solanaKeyHex(value) {
|
|
838
|
+
if (!isSolanaAddress(value)) return null;
|
|
839
|
+
return `0x${Array.from(base58Decode(value.trim()), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
840
|
+
}
|
|
841
|
+
function hexToSolanaKey(value) {
|
|
842
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(value)) return null;
|
|
843
|
+
return base58Encode(Uint8Array.from(value.slice(2).match(/../g), (byte) => Number.parseInt(byte, 16)));
|
|
844
|
+
}
|
|
845
|
+
var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
846
|
+
var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
|
|
847
|
+
var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
|
|
848
|
+
var pin = (symbol, decimals, bridge, tokenProgram) => Object.freeze({ symbol, decimals, bridge, tokenProgram });
|
|
849
|
+
var SOLANA_DESTINATION_ASSETS = Object.freeze({
|
|
850
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: pin("USDC", 6, "cctp", TOKEN_PROGRAM),
|
|
851
|
+
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": pin("PYUSD", 6, "layerzero", TOKEN_2022_PROGRAM),
|
|
852
|
+
DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT: pin("USDE", 9, "layerzero", TOKEN_PROGRAM),
|
|
853
|
+
"2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": pin("USDG", 6, "layerzero", TOKEN_2022_PROGRAM),
|
|
854
|
+
AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
|
|
855
|
+
});
|
|
856
|
+
function solanaDestinationAsset(mint) {
|
|
857
|
+
const key = typeof mint === "string" ? mint.trim() : "";
|
|
858
|
+
return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
|
|
859
|
+
}
|
|
860
|
+
function solanaBridgeOf(token) {
|
|
861
|
+
const pinned = solanaDestinationAsset(token.address);
|
|
862
|
+
if (!pinned || pinned.symbol !== token.symbol.trim().toUpperCase()) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
863
|
+
return pinned.bridge;
|
|
864
|
+
}
|
|
865
|
+
var K = new Uint32Array([
|
|
866
|
+
1116352408,
|
|
867
|
+
1899447441,
|
|
868
|
+
3049323471,
|
|
869
|
+
3921009573,
|
|
870
|
+
961987163,
|
|
871
|
+
1508970993,
|
|
872
|
+
2453635748,
|
|
873
|
+
2870763221,
|
|
874
|
+
3624381080,
|
|
875
|
+
310598401,
|
|
876
|
+
607225278,
|
|
877
|
+
1426881987,
|
|
878
|
+
1925078388,
|
|
879
|
+
2162078206,
|
|
880
|
+
2614888103,
|
|
881
|
+
3248222580,
|
|
882
|
+
3835390401,
|
|
883
|
+
4022224774,
|
|
884
|
+
264347078,
|
|
885
|
+
604807628,
|
|
886
|
+
770255983,
|
|
887
|
+
1249150122,
|
|
888
|
+
1555081692,
|
|
889
|
+
1996064986,
|
|
890
|
+
2554220882,
|
|
891
|
+
2821834349,
|
|
892
|
+
2952996808,
|
|
893
|
+
3210313671,
|
|
894
|
+
3336571891,
|
|
895
|
+
3584528711,
|
|
896
|
+
113926993,
|
|
897
|
+
338241895,
|
|
898
|
+
666307205,
|
|
899
|
+
773529912,
|
|
900
|
+
1294757372,
|
|
901
|
+
1396182291,
|
|
902
|
+
1695183700,
|
|
903
|
+
1986661051,
|
|
904
|
+
2177026350,
|
|
905
|
+
2456956037,
|
|
906
|
+
2730485921,
|
|
907
|
+
2820302411,
|
|
908
|
+
3259730800,
|
|
909
|
+
3345764771,
|
|
910
|
+
3516065817,
|
|
911
|
+
3600352804,
|
|
912
|
+
4094571909,
|
|
913
|
+
275423344,
|
|
914
|
+
430227734,
|
|
915
|
+
506948616,
|
|
916
|
+
659060556,
|
|
917
|
+
883997877,
|
|
918
|
+
958139571,
|
|
919
|
+
1322822218,
|
|
920
|
+
1537002063,
|
|
921
|
+
1747873779,
|
|
922
|
+
1955562222,
|
|
923
|
+
2024104815,
|
|
924
|
+
2227730452,
|
|
925
|
+
2361852424,
|
|
926
|
+
2428436474,
|
|
927
|
+
2756734187,
|
|
928
|
+
3204031479,
|
|
929
|
+
3329325298
|
|
930
|
+
]);
|
|
931
|
+
function sha256(data) {
|
|
932
|
+
const bitLen = data.length * 8;
|
|
933
|
+
const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
|
|
934
|
+
padded.set(data);
|
|
935
|
+
padded[data.length] = 128;
|
|
936
|
+
const view = new DataView(padded.buffer);
|
|
937
|
+
view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
|
|
938
|
+
view.setUint32(padded.length - 4, bitLen >>> 0);
|
|
939
|
+
const h2 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
|
|
940
|
+
const w = new Uint32Array(64);
|
|
941
|
+
const rotr = (x, n) => x >>> n | x << 32 - n;
|
|
942
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
943
|
+
for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
|
|
944
|
+
for (let i = 16; i < 64; i += 1) {
|
|
945
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
|
|
946
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
|
|
947
|
+
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
948
|
+
}
|
|
949
|
+
let [a, b, c, d, e, f, g, hh] = h2;
|
|
950
|
+
for (let i = 0; i < 64; i += 1) {
|
|
951
|
+
const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
|
|
952
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
953
|
+
hh = g;
|
|
954
|
+
g = f;
|
|
955
|
+
f = e;
|
|
956
|
+
e = d + t1 >>> 0;
|
|
957
|
+
d = c;
|
|
958
|
+
c = b;
|
|
959
|
+
b = a;
|
|
960
|
+
a = t1 + t2 >>> 0;
|
|
961
|
+
}
|
|
962
|
+
h2[0] = h2[0] + a >>> 0;
|
|
963
|
+
h2[1] = h2[1] + b >>> 0;
|
|
964
|
+
h2[2] = h2[2] + c >>> 0;
|
|
965
|
+
h2[3] = h2[3] + d >>> 0;
|
|
966
|
+
h2[4] = h2[4] + e >>> 0;
|
|
967
|
+
h2[5] = h2[5] + f >>> 0;
|
|
968
|
+
h2[6] = h2[6] + g >>> 0;
|
|
969
|
+
h2[7] = h2[7] + hh >>> 0;
|
|
970
|
+
}
|
|
971
|
+
const out = new Uint8Array(32);
|
|
972
|
+
const outView = new DataView(out.buffer);
|
|
973
|
+
for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h2[i]);
|
|
974
|
+
return out;
|
|
975
|
+
}
|
|
976
|
+
var P = 2n ** 255n - 19n;
|
|
977
|
+
var mod = (a) => (a % P + P) % P;
|
|
978
|
+
var pow = (base, exp) => {
|
|
979
|
+
let result = 1n;
|
|
980
|
+
let b = mod(base);
|
|
981
|
+
for (let e = exp; e > 0n; e >>= 1n) {
|
|
982
|
+
if (e & 1n) result = result * b % P;
|
|
983
|
+
b = b * b % P;
|
|
984
|
+
}
|
|
985
|
+
return result;
|
|
986
|
+
};
|
|
987
|
+
var D = mod(-121665n * pow(121666n, P - 2n));
|
|
988
|
+
function isOnEd25519Curve(bytes) {
|
|
989
|
+
let y = 0n;
|
|
990
|
+
for (let i = 31; i >= 0; i -= 1) y = y << 8n | BigInt(bytes[i]);
|
|
991
|
+
y = mod(y & (1n << 255n) - 1n);
|
|
992
|
+
const yy = y * y % P;
|
|
993
|
+
const u = mod(yy - 1n);
|
|
994
|
+
const v = mod(D * yy + 1n);
|
|
995
|
+
if (v === 0n) return u === 0n;
|
|
996
|
+
const x2 = u * pow(v, P - 2n) % P;
|
|
997
|
+
return x2 === 0n || pow(x2, (P - 1n) / 2n) === 1n;
|
|
998
|
+
}
|
|
999
|
+
function keyBytes(base58) {
|
|
1000
|
+
const bytes = base58Decode(base58);
|
|
1001
|
+
if (!bytes || bytes.length !== 32) throw new Error("Not a valid Solana address.");
|
|
1002
|
+
return bytes;
|
|
1003
|
+
}
|
|
1004
|
+
function findProgramAddress(seeds, programId) {
|
|
1005
|
+
const program = keyBytes(programId);
|
|
1006
|
+
const marker = new TextEncoder().encode("ProgramDerivedAddress");
|
|
1007
|
+
for (let bump = 255; bump >= 1; bump -= 1) {
|
|
1008
|
+
const parts = [...seeds, Uint8Array.of(bump), program, marker];
|
|
1009
|
+
const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
1010
|
+
let at = 0;
|
|
1011
|
+
for (const part of parts) {
|
|
1012
|
+
buf.set(part, at);
|
|
1013
|
+
at += part.length;
|
|
1014
|
+
}
|
|
1015
|
+
const candidate = sha256(buf);
|
|
1016
|
+
if (!isOnEd25519Curve(candidate)) return candidate;
|
|
1017
|
+
}
|
|
1018
|
+
throw new Error("Could not derive a program address.");
|
|
1019
|
+
}
|
|
1020
|
+
function associatedTokenAddress(owner, mint, tokenProgram) {
|
|
1021
|
+
return base58Encode(findProgramAddress([keyBytes(owner), keyBytes(tokenProgram), keyBytes(mint)], ASSOCIATED_TOKEN_PROGRAM));
|
|
1022
|
+
}
|
|
1023
|
+
function expectedSolanaDelivery(recipient2, mint) {
|
|
1024
|
+
if (!isSolanaAddress(recipient2)) throw new Error("Not a valid Solana address.");
|
|
1025
|
+
const pinned = solanaDestinationAsset(mint);
|
|
1026
|
+
if (!pinned) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
1027
|
+
const target = pinned.bridge === "cctp" ? associatedTokenAddress(recipient2.trim(), mint.trim(), pinned.tokenProgram) : recipient2.trim();
|
|
1028
|
+
return solanaKeyHex(target);
|
|
1029
|
+
}
|
|
1030
|
+
function checkSolanaReceiver(request, intended, mint) {
|
|
1031
|
+
if (!isSolanaAddress(intended)) throw new Error("Not a valid Solana address.");
|
|
1032
|
+
if (request.destinationReceiverOwner !== intended.trim()) throw new Error("The quote was not made out to your Solana recipient; refusing to sign.");
|
|
1033
|
+
const receiver = request.destinationReceiver || "";
|
|
1034
|
+
const display = hexToSolanaKey(receiver);
|
|
1035
|
+
if (!display) throw new Error("The quote carries no Solana delivery account; refusing to sign.");
|
|
1036
|
+
if (request.destinationReceiverBase58 && request.destinationReceiverBase58 !== display) throw new Error("The quote names two different Solana delivery accounts; refusing to sign.");
|
|
1037
|
+
if (receiver.toLowerCase() !== expectedSolanaDelivery(intended, mint)) throw new Error("The quote would deliver to an account that is not your Solana recipient's; refusing to sign.");
|
|
1038
|
+
}
|
|
1039
|
+
|
|
228
1040
|
// src/core/address.ts
|
|
229
1041
|
function symbolKey(value) {
|
|
230
1042
|
return String(value || "").trim().toUpperCase();
|
|
@@ -241,66 +1053,26 @@ function assertAddress(value, label) {
|
|
|
241
1053
|
if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label} is not a valid EVM address.`);
|
|
242
1054
|
return normalized;
|
|
243
1055
|
}
|
|
244
|
-
function resolveSwapReceiver(
|
|
1056
|
+
function resolveSwapReceiver(recipient2, payer, destinationChainId) {
|
|
245
1057
|
const payerAddr = assertAddress(payer, "Swap wallet");
|
|
246
|
-
if (
|
|
247
|
-
|
|
1058
|
+
if (isSolanaChainId(destinationChainId)) return assertChainAddress(destinationChainId, recipient2, "Deposit recipient");
|
|
1059
|
+
if (recipient2 === void 0 || recipient2 === null || recipient2 === "") return payerAddr;
|
|
1060
|
+
const normalized = normalizeAddress(recipient2);
|
|
248
1061
|
if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
|
|
249
1062
|
return normalized;
|
|
250
1063
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
function assetDecimals(token) {
|
|
254
|
-
const sym = symbolKey(token?.symbol);
|
|
255
|
-
const registry = Number(token?.decimals);
|
|
256
|
-
const canonical = CANONICAL_DECIMALS[sym];
|
|
257
|
-
if (canonical !== void 0) {
|
|
258
|
-
if (!Number.isInteger(registry)) {
|
|
259
|
-
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
260
|
-
}
|
|
261
|
-
if (registry !== canonical) {
|
|
262
|
-
throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
263
|
-
}
|
|
264
|
-
return canonical;
|
|
265
|
-
}
|
|
266
|
-
if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
|
|
267
|
-
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
268
|
-
}
|
|
269
|
-
return registry;
|
|
1064
|
+
function isChainAddress(chainId, value) {
|
|
1065
|
+
return isSolanaChainId(chainId) ? isSolanaAddress(value) : isAddress(value);
|
|
270
1066
|
}
|
|
271
|
-
function
|
|
272
|
-
const text = String(value || "")
|
|
273
|
-
|
|
274
|
-
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
275
|
-
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
276
|
-
if (text.includes(",")) return "";
|
|
277
|
-
return text;
|
|
1067
|
+
function chainAddressKey(chainId, value) {
|
|
1068
|
+
const text = String(value || "");
|
|
1069
|
+
return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
|
|
278
1070
|
}
|
|
279
|
-
function
|
|
280
|
-
|
|
281
|
-
if (
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
285
|
-
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
286
|
-
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
287
|
-
return value;
|
|
288
|
-
}
|
|
289
|
-
function scaleDecimals(amount, fromDecimals, toDecimals) {
|
|
290
|
-
if (toDecimals === fromDecimals) return amount;
|
|
291
|
-
if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
|
292
|
-
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
293
|
-
}
|
|
294
|
-
function formatUnits(raw, decimals, maxDecimals = 6) {
|
|
295
|
-
const value = BigInt(raw || "0");
|
|
296
|
-
const base = 10n ** BigInt(decimals);
|
|
297
|
-
const whole = value / base;
|
|
298
|
-
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
299
|
-
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
300
|
-
return frac ? `${whole}.${frac}` : whole.toString();
|
|
301
|
-
}
|
|
302
|
-
function finalOf(quote) {
|
|
303
|
-
return BigInt(quote?.finalAmount || quote?.toAmount || "0");
|
|
1071
|
+
function assertChainAddress(chainId, value, label) {
|
|
1072
|
+
if (!isSolanaChainId(chainId)) return assertAddress(value, label);
|
|
1073
|
+
if (!String(value || "").trim()) throw new Error("Connect a Solana wallet or enter a Solana recipient address.");
|
|
1074
|
+
if (!isSolanaAddress(value)) throw new Error("Not a valid Solana address.");
|
|
1075
|
+
return String(value).trim();
|
|
304
1076
|
}
|
|
305
1077
|
|
|
306
1078
|
// src/core/abi.ts
|
|
@@ -379,8 +1151,6 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
|
|
|
379
1151
|
}).join("");
|
|
380
1152
|
return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
|
|
381
1153
|
}
|
|
382
|
-
var EVM_BYTES_PAYLOAD_BYTES = 64;
|
|
383
|
-
var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
|
|
384
1154
|
var MAX_DECODED_ORDERS = 16;
|
|
385
1155
|
function decodeSubmitOrderCalldata(data) {
|
|
386
1156
|
const hex = strip0x(String(data || "")).toLowerCase();
|
|
@@ -401,12 +1171,14 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
401
1171
|
const w = word(byteOffset);
|
|
402
1172
|
return w === null || w > MAX_UINT64 ? null : w;
|
|
403
1173
|
};
|
|
404
|
-
const
|
|
1174
|
+
const keyBytesAt = (byteOffset) => {
|
|
405
1175
|
const len = word(byteOffset);
|
|
406
|
-
if (len !== 20n) return null;
|
|
407
|
-
const
|
|
408
|
-
|
|
409
|
-
|
|
1176
|
+
if (len !== 20n && len !== 32n) return null;
|
|
1177
|
+
const length = Number(len);
|
|
1178
|
+
const padded = Math.ceil(length / 32) * 32;
|
|
1179
|
+
const content = body.slice((byteOffset + 32) * 2, (byteOffset + 32 + padded) * 2);
|
|
1180
|
+
if (content.length !== padded * 2 || content.slice(length * 2) !== "0".repeat((padded - length) * 2)) return null;
|
|
1181
|
+
return { value: `0x${content.slice(0, length * 2)}`, size: 32 + padded };
|
|
410
1182
|
};
|
|
411
1183
|
if (word(0) !== 64n) return null;
|
|
412
1184
|
if (word(32) === null) return null;
|
|
@@ -415,12 +1187,12 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
415
1187
|
if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
|
|
416
1188
|
const n = Number(count);
|
|
417
1189
|
const arrayBase = 96;
|
|
418
|
-
|
|
1190
|
+
let next = arrayBase + 32 * n;
|
|
419
1191
|
const orders = [];
|
|
420
1192
|
for (let i = 0; i < n; i += 1) {
|
|
421
1193
|
const rel = word(arrayBase + i * 32);
|
|
422
|
-
if (rel === null || rel !== BigInt(
|
|
423
|
-
const base =
|
|
1194
|
+
if (rel === null || rel !== BigInt(next - arrayBase)) return null;
|
|
1195
|
+
const base = next;
|
|
424
1196
|
const owner = addressAt(base);
|
|
425
1197
|
const bidToken = addressAt(base + 32);
|
|
426
1198
|
const bidTokenAmount = word(base + 64);
|
|
@@ -430,14 +1202,17 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
430
1202
|
const destinationChainId = uint64At(base + 192);
|
|
431
1203
|
const executionChainId = uint64At(base + 224);
|
|
432
1204
|
const deadline = uint64At(base + 256);
|
|
433
|
-
if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES
|
|
1205
|
+
if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES) {
|
|
434
1206
|
return null;
|
|
435
1207
|
}
|
|
436
|
-
const askToken =
|
|
437
|
-
|
|
1208
|
+
const askToken = keyBytesAt(base + Number(askOffset));
|
|
1209
|
+
if (!askToken || receiverOffset !== ORDER_HEAD_BYTES + BigInt(askToken.size)) return null;
|
|
1210
|
+
const destinationReceiver = keyBytesAt(base + Number(receiverOffset));
|
|
438
1211
|
if (askToken === null || destinationReceiver === null) return null;
|
|
439
|
-
|
|
1212
|
+
next = base + Number(ORDER_HEAD_BYTES) + askToken.size + destinationReceiver.size;
|
|
1213
|
+
orders.push({ owner, bidToken, bidTokenAmount, askToken: askToken.value, askTokenAmount, destinationReceiver: destinationReceiver.value, destinationChainId, executionChainId, deadline });
|
|
440
1214
|
}
|
|
1215
|
+
if (next !== totalBytes) return null;
|
|
441
1216
|
return { partnerId, orders };
|
|
442
1217
|
}
|
|
443
1218
|
function toHexQuantity(value) {
|
|
@@ -445,47 +1220,343 @@ function toHexQuantity(value) {
|
|
|
445
1220
|
return `0x${n.toString(16)}`;
|
|
446
1221
|
}
|
|
447
1222
|
|
|
448
|
-
// src/core/
|
|
449
|
-
function
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
1223
|
+
// src/core/solana-tx.ts
|
|
1224
|
+
function bytesEqual(a, b) {
|
|
1225
|
+
return a.length === b.length && a.every((v, i) => v === b[i]);
|
|
1226
|
+
}
|
|
1227
|
+
function hexBytes(hex) {
|
|
1228
|
+
const h2 = strip0x(hex);
|
|
1229
|
+
if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
|
|
1230
|
+
return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
|
|
1231
|
+
}
|
|
1232
|
+
function solanaKeyBytes(key) {
|
|
1233
|
+
if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
|
|
1234
|
+
return base58Decode(key);
|
|
1235
|
+
}
|
|
1236
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1237
|
+
function base64Decode(text) {
|
|
1238
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) throw new Error("Invalid base64.");
|
|
1239
|
+
const out = [];
|
|
1240
|
+
let value = 0, bits = 0;
|
|
1241
|
+
for (const ch of text.replace(/=+$/, "")) {
|
|
1242
|
+
value = value << 6 | B64.indexOf(ch);
|
|
1243
|
+
bits += 6;
|
|
1244
|
+
if (bits >= 8) {
|
|
1245
|
+
bits -= 8;
|
|
1246
|
+
out.push(value >> bits & 255);
|
|
1247
|
+
}
|
|
454
1248
|
}
|
|
455
|
-
|
|
456
|
-
|
|
1249
|
+
const bytes = Uint8Array.from(out);
|
|
1250
|
+
if (base64Encode(bytes) !== text) throw new Error("Noncanonical base64.");
|
|
1251
|
+
return bytes;
|
|
1252
|
+
}
|
|
1253
|
+
function base64Encode(bytes) {
|
|
1254
|
+
let out = "";
|
|
1255
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
1256
|
+
const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
|
|
1257
|
+
out += B64[n >>> 18 & 63] + B64[n >>> 12 & 63] + (i + 1 < bytes.length ? B64[n >>> 6 & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
|
|
457
1258
|
}
|
|
458
|
-
|
|
459
|
-
|
|
1259
|
+
return out;
|
|
1260
|
+
}
|
|
1261
|
+
var Reader = class {
|
|
1262
|
+
constructor(bytes) {
|
|
1263
|
+
this.bytes = bytes;
|
|
1264
|
+
}
|
|
1265
|
+
bytes;
|
|
1266
|
+
at = 0;
|
|
1267
|
+
take(n) {
|
|
1268
|
+
if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error("Truncated Solana data.");
|
|
1269
|
+
const v = this.bytes.slice(this.at, this.at + n);
|
|
1270
|
+
this.at += n;
|
|
1271
|
+
return v;
|
|
1272
|
+
}
|
|
1273
|
+
byte() {
|
|
1274
|
+
return this.take(1)[0];
|
|
1275
|
+
}
|
|
1276
|
+
compact() {
|
|
1277
|
+
let n = 0;
|
|
1278
|
+
for (let i = 0; i < 3; i++) {
|
|
1279
|
+
const b = this.byte();
|
|
1280
|
+
if (i === 2 && b > 3) throw new Error("Invalid compact-u16.");
|
|
1281
|
+
n |= (b & 127) << 7 * i;
|
|
1282
|
+
if (!(b & 128)) {
|
|
1283
|
+
if (i && b === 0) throw new Error("Noncanonical compact-u16.");
|
|
1284
|
+
return n;
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
throw new Error("Invalid compact-u16.");
|
|
460
1288
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
1289
|
+
u64() {
|
|
1290
|
+
const b = this.take(8);
|
|
1291
|
+
let n = 0n;
|
|
1292
|
+
for (let i = 7; i >= 0; i--) n = n << 8n | BigInt(b[i]);
|
|
1293
|
+
return n;
|
|
464
1294
|
}
|
|
465
|
-
|
|
1295
|
+
vec() {
|
|
1296
|
+
const b = this.take(4);
|
|
1297
|
+
return this.take(new DataView(b.buffer).getUint32(0, true));
|
|
1298
|
+
}
|
|
1299
|
+
end() {
|
|
1300
|
+
if (this.at !== this.bytes.length) throw new Error("Trailing Solana data.");
|
|
1301
|
+
}
|
|
1302
|
+
};
|
|
1303
|
+
function parseSolanaTransaction(input) {
|
|
1304
|
+
const bytes = new Uint8Array(input), r = new Reader(bytes);
|
|
1305
|
+
const count = r.compact(), signatureOffset = r.at;
|
|
1306
|
+
if (count < 1 || count > 127) throw new Error("Invalid signature count.");
|
|
1307
|
+
r.take(count * 64);
|
|
1308
|
+
const messageOffset = r.at, first = r.byte();
|
|
1309
|
+
if (first & 128 && first !== 128) throw new Error("Unsupported Solana message version.");
|
|
1310
|
+
const version = first === 128 ? 0 : "legacy";
|
|
1311
|
+
const requiredSignatures = version === 0 ? r.byte() : first;
|
|
1312
|
+
const readonlySigned = r.byte(), readonlyUnsigned = r.byte();
|
|
1313
|
+
const keyCount = r.compact();
|
|
1314
|
+
if (requiredSignatures !== count || requiredSignatures > keyCount || readonlySigned >= count || readonlyUnsigned > keyCount - count || keyCount > 256) throw new Error("Invalid Solana message header.");
|
|
1315
|
+
const staticKeys = Array.from({ length: keyCount }, () => base58Encode(r.take(32)));
|
|
1316
|
+
const blockhashOffset = r.at;
|
|
1317
|
+
r.take(32);
|
|
1318
|
+
const instructions = Array.from({ length: r.compact() }, () => {
|
|
1319
|
+
const programIdIndex = r.byte();
|
|
1320
|
+
const accounts = Array.from(r.take(r.compact()));
|
|
1321
|
+
return { programIdIndex, accounts, data: r.take(r.compact()) };
|
|
1322
|
+
});
|
|
1323
|
+
const lookups = version === 0 ? Array.from({ length: r.compact() }, () => ({
|
|
1324
|
+
address: base58Encode(r.take(32)),
|
|
1325
|
+
writable: Array.from(r.take(r.compact())),
|
|
1326
|
+
readonly: Array.from(r.take(r.compact()))
|
|
1327
|
+
})) : [];
|
|
1328
|
+
r.end();
|
|
1329
|
+
const all = keyCount + lookups.reduce((n, l) => n + l.writable.length + l.readonly.length, 0);
|
|
1330
|
+
if (all > 256 || instructions.some((ix) => ix.programIdIndex >= keyCount || ix.accounts.some((i) => i >= all))) throw new Error("Invalid Solana account index.");
|
|
1331
|
+
return { bytes, messageOffset, blockhashOffset, version, requiredSignatures, signatureOffset, staticKeys, instructions, lookups };
|
|
1332
|
+
}
|
|
1333
|
+
function overwriteBlockhash(input, blockhash) {
|
|
1334
|
+
const tx = parseSolanaTransaction(input), out = new Uint8Array(input);
|
|
1335
|
+
out.set(solanaKeyBytes(blockhash), tx.blockhashOffset);
|
|
1336
|
+
return out;
|
|
466
1337
|
}
|
|
467
|
-
function
|
|
468
|
-
const
|
|
469
|
-
|
|
1338
|
+
function placeSignature(input, publicKey, signature) {
|
|
1339
|
+
const tx = parseSolanaTransaction(input), index = tx.staticKeys.slice(0, tx.requiredSignatures).indexOf(publicKey);
|
|
1340
|
+
if (index < 0 || signature.length !== 64) throw new Error("Missing Solana signer slot.");
|
|
1341
|
+
const out = new Uint8Array(input);
|
|
1342
|
+
out.set(signature, tx.signatureOffset + index * 64);
|
|
1343
|
+
return out;
|
|
470
1344
|
}
|
|
471
|
-
function
|
|
472
|
-
|
|
1345
|
+
function assertWalletMessage(original, signed) {
|
|
1346
|
+
const a = parseSolanaTransaction(original), b = parseSolanaTransaction(signed);
|
|
1347
|
+
if (!bytesEqual(a.bytes.subarray(a.messageOffset), b.bytes.subarray(b.messageOffset))) throw new Error("The wallet modified the transaction message; refusing to send.");
|
|
1348
|
+
for (let i = 1; i < a.requiredSignatures; i++) {
|
|
1349
|
+
const start2 = a.signatureOffset + 64 * i;
|
|
1350
|
+
if (!bytesEqual(a.bytes.subarray(start2, start2 + 64), b.bytes.subarray(b.signatureOffset + i * 64, b.signatureOffset + (i + 1) * 64))) throw new Error("The wallet removed a co-signature; refusing to send.");
|
|
1351
|
+
}
|
|
1352
|
+
if (!b.bytes.subarray(b.signatureOffset, b.signatureOffset + 64).some(Boolean)) throw new Error("The wallet returned no fee-payer signature.");
|
|
1353
|
+
}
|
|
1354
|
+
var SUBMIT_ORDER_DISCRIMINATOR = [230, 150, 200, 53, 92, 208, 109, 108];
|
|
1355
|
+
function isSubmitOrder(data) {
|
|
1356
|
+
return data.length >= 8 && SUBMIT_ORDER_DISCRIMINATOR.every((v, i) => data[i] === v);
|
|
1357
|
+
}
|
|
1358
|
+
function decodeSolanaSubmitOrder(data) {
|
|
1359
|
+
if (!isSubmitOrder(data)) throw new Error("Not a submit_order instruction.");
|
|
1360
|
+
const r = new Reader(data);
|
|
1361
|
+
r.take(8);
|
|
1362
|
+
const owner = r.take(20), askToken = r.vec();
|
|
1363
|
+
let askTokenAmount = 0n;
|
|
1364
|
+
for (const b of r.take(32)) askTokenAmount = askTokenAmount << 8n | BigInt(b);
|
|
1365
|
+
const bidTokenAmount = r.u64(), destinationReceiver = r.vec(), destinationChainId = r.u64(), executionChainId = r.u64(), deadline = r.u64();
|
|
1366
|
+
const tag = r.byte();
|
|
1367
|
+
if (tag !== 0 && tag !== 1) throw new Error("Invalid submit_order partner tag.");
|
|
1368
|
+
const partnerId = tag === 1 ? r.take(32) : null;
|
|
1369
|
+
r.end();
|
|
1370
|
+
return { owner, askToken, askTokenAmount, bidTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline, partnerId };
|
|
1371
|
+
}
|
|
1372
|
+
function verifySolanaSubmit(p, e) {
|
|
1373
|
+
const fail = (field) => {
|
|
1374
|
+
throw new Error(`Solana order mismatch (${field}); refusing to sign.`);
|
|
1375
|
+
};
|
|
1376
|
+
if (hexBytes(e.owner).length !== 20 || !bytesEqual(p.owner, hexBytes(e.owner))) fail("owner");
|
|
1377
|
+
if (!bytesEqual(p.askToken, hexBytes(e.askToken))) fail("ask token");
|
|
1378
|
+
if (p.askTokenAmount <= 0n) fail("non-positive output");
|
|
1379
|
+
if (p.askTokenAmount < BigInt(e.minAskTokenAmount)) fail("minimum received");
|
|
1380
|
+
if (p.askTokenAmount > BigInt(e.maxAskTokenAmount)) fail("maximum received");
|
|
1381
|
+
if (p.bidTokenAmount !== BigInt(e.bidTokenAmount)) fail("amount sent");
|
|
1382
|
+
if (!bytesEqual(p.destinationReceiver, hexBytes(e.destinationReceiver))) fail("receiver");
|
|
1383
|
+
if (p.destinationChainId !== BigInt(e.destinationChainId)) fail("destination chain");
|
|
1384
|
+
if (p.executionChainId !== BigInt(e.executionChainId)) fail("execution chain");
|
|
1385
|
+
if (p.deadline !== BigInt(e.deadline)) fail("deadline");
|
|
1386
|
+
if (p.partnerId !== null !== (e.partnerId !== null)) fail("subsidy marker");
|
|
1387
|
+
}
|
|
1388
|
+
var PREPARATION_INSTRUCTIONS = [
|
|
1389
|
+
{ discriminator: [225, 205, 234, 143, 17, 186, 50, 220], signer: 2 },
|
|
1390
|
+
// create_profile
|
|
1391
|
+
{ discriminator: [223, 99, 118, 101, 213, 29, 215, 137], signer: 3 },
|
|
1392
|
+
// initialize_buffer_data
|
|
1393
|
+
{ discriminator: [105, 254, 33, 182, 188, 80, 204, 204], signer: 3 },
|
|
1394
|
+
// write_buffer_data
|
|
1395
|
+
{ discriminator: [179, 249, 129, 154, 80, 167, 138, 18], signer: 3 },
|
|
1396
|
+
// finalize_buffer_data
|
|
1397
|
+
{ discriminator: [23, 25, 65, 45, 74, 9, 223, 23], signer: 2 }
|
|
1398
|
+
// close_buffer_data
|
|
1399
|
+
];
|
|
1400
|
+
var SUBMIT_SIGNER_ACCOUNT = 11;
|
|
1401
|
+
function preparationInstruction(data) {
|
|
1402
|
+
return data.length >= 8 ? PREPARATION_INSTRUCTIONS.find((p) => p.discriminator.every((byte, i) => data[i] === byte)) : void 0;
|
|
1403
|
+
}
|
|
1404
|
+
function verifySolanaTransaction(tx, expected, keys, mustSubmit) {
|
|
1405
|
+
if (tx.staticKeys[0] !== expected.signer) throw new Error("Wrong Solana fee payer; refusing to sign.");
|
|
1406
|
+
if (!mustSubmit && tx.requiredSignatures !== 1) throw new Error("Unexpected co-signer on a preparation step; refusing to sign.");
|
|
1407
|
+
let submits = 0, buffer = null;
|
|
1408
|
+
for (const ix of tx.instructions) {
|
|
1409
|
+
if (tx.staticKeys[ix.programIdIndex] !== expected.program) throw new Error("Foreign program instruction; refusing to sign.");
|
|
1410
|
+
const preparation = preparationInstruction(ix.data);
|
|
1411
|
+
if (!isSubmitOrder(ix.data) && !preparation) throw new Error("Unexpected ZeroDelta instruction; refusing to sign.");
|
|
1412
|
+
const signerSlot = preparation ? preparation.signer : SUBMIT_SIGNER_ACCOUNT;
|
|
1413
|
+
if (keys[ix.accounts[signerSlot]] !== expected.signer) throw new Error("ZeroDelta instruction names another signer; refusing to sign.");
|
|
1414
|
+
if (!isSubmitOrder(ix.data)) continue;
|
|
1415
|
+
submits++;
|
|
1416
|
+
verifySolanaSubmit(decodeSolanaSubmitOrder(ix.data), expected);
|
|
1417
|
+
if (keys[ix.accounts[1]] !== expected.mint) throw new Error("Wrong source mint; refusing to sign.");
|
|
1418
|
+
buffer = keys[ix.accounts[8]] ?? null;
|
|
1419
|
+
if (!buffer) throw new Error("Missing route buffer; refusing to sign.");
|
|
1420
|
+
}
|
|
1421
|
+
if (submits !== (mustSubmit ? 1 : 0)) throw new Error("Expected exactly one submit_order in submit and none in preparation; refusing to sign.");
|
|
1422
|
+
return buffer;
|
|
1423
|
+
}
|
|
1424
|
+
function parseAddressLookupTable(data) {
|
|
1425
|
+
if (data.length < 56 || (data.length - 56) % 32 || new DataView(data.buffer, data.byteOffset, 4).getUint32(0, true) !== 1) throw new Error("Invalid address lookup table.");
|
|
1426
|
+
return Array.from({ length: (data.length - 56) / 32 }, (_, i) => base58Encode(data.subarray(56 + 32 * i, 88 + 32 * i)));
|
|
1427
|
+
}
|
|
1428
|
+
async function resolveSolanaKeys(tx, rpc) {
|
|
1429
|
+
if (!tx.lookups.length) return [...tx.staticKeys];
|
|
1430
|
+
const result = await rpc("getMultipleAccounts", [tx.lookups.map((l) => l.address), { encoding: "base64", commitment: "confirmed" }]);
|
|
1431
|
+
if (!Array.isArray(result.value) || result.value.length !== tx.lookups.length) throw new Error("Missing lookup tables.");
|
|
1432
|
+
const writable = [], readonly = [];
|
|
1433
|
+
tx.lookups.forEach((lookup, i) => {
|
|
1434
|
+
const account = result.value[i];
|
|
1435
|
+
if (account?.owner !== "AddressLookupTab1e1111111111111111111111111" || account.data[1] !== "base64") throw new Error("Invalid lookup table account.");
|
|
1436
|
+
const table = parseAddressLookupTable(base64Decode(account.data[0]));
|
|
1437
|
+
for (const [indexes, into] of [[lookup.writable, writable], [lookup.readonly, readonly]]) for (const index of indexes) {
|
|
1438
|
+
if (!table[index]) throw new Error("Lookup table index out of range.");
|
|
1439
|
+
into.push(table[index]);
|
|
1440
|
+
}
|
|
1441
|
+
});
|
|
1442
|
+
return [...tx.staticKeys, ...writable, ...readonly];
|
|
1443
|
+
}
|
|
1444
|
+
function encodeNextSolanaOrders(legs) {
|
|
1445
|
+
return legs.length ? hexBytes(`0x${uintWord(32)}${encodeSubmitOrder(legs).slice(10 + 128)}`) : new Uint8Array();
|
|
1446
|
+
}
|
|
1447
|
+
function checkSolanaRouteBuffer(account, expected) {
|
|
1448
|
+
if (!account || account.owner !== expected.program || account.data[1] !== "base64") throw new Error("Route buffer is not a ZeroDelta account.");
|
|
1449
|
+
const d = base64Decode(account.data[0]);
|
|
1450
|
+
if (d.length < 53) throw new Error("Route buffer truncated.");
|
|
1451
|
+
if (base58Encode(d.subarray(9, 41)) !== expected.signer) throw new Error("Route buffer signer mismatch.");
|
|
1452
|
+
const len = new DataView(d.buffer, d.byteOffset + 49, 4).getUint32(0, true);
|
|
1453
|
+
if (d.length < 53 + len || !bytesEqual(d.subarray(53, 53 + len), encodeNextSolanaOrders(expected.nextOrders))) throw new Error("Route buffer legs mismatch.");
|
|
1454
|
+
}
|
|
1455
|
+
function checkSolanaProgram(gateway, pinned, registry2) {
|
|
1456
|
+
const program = gateway || registry2 || "";
|
|
1457
|
+
solanaKeyBytes(program);
|
|
1458
|
+
if (pinned ? program !== pinned : gateway && registry2 && gateway !== registry2) throw new Error("Solana program does not match pin or chains registry.");
|
|
1459
|
+
return program;
|
|
1460
|
+
}
|
|
1461
|
+
function checkSolanaPlan(txs) {
|
|
1462
|
+
if (!Array.isArray(txs) || !txs.length || txs.length > 64 || txs.some((tx) => !["setup", "buffer", "write", "submit"].includes(tx.actionType) || typeof tx.transaction !== "string") || txs.filter((tx) => tx.actionType === "submit").length !== 1 || txs[txs.length - 1].actionType !== "submit" || txs.some((tx) => tx.buildData && tx.actionType !== "submit")) throw new Error("Plan must end in exactly one submit; buildData is only allowed on it.");
|
|
1463
|
+
}
|
|
1464
|
+
async function deriveSolanaEvent(signer, salt) {
|
|
1465
|
+
const s = hexBytes(salt), material = new Uint8Array(32 + s.length);
|
|
1466
|
+
material.set(solanaKeyBytes(signer));
|
|
1467
|
+
material.set(s, 32);
|
|
1468
|
+
const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", material));
|
|
1469
|
+
const { eventPublicKey: eventPublicKey2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
|
|
1470
|
+
return { seed, publicKey: base58Encode(await eventPublicKey2(seed)) };
|
|
1471
|
+
}
|
|
1472
|
+
async function cosignSolanaEvent(bytes, signer, build) {
|
|
1473
|
+
const event = await deriveSolanaEvent(signer, build.salt);
|
|
1474
|
+
if (event.publicKey !== build.messageSentEventData) throw new Error("Event buildData key mismatch; refusing to sign.");
|
|
1475
|
+
const tx = parseSolanaTransaction(bytes);
|
|
1476
|
+
const { eventSignature: eventSignature2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
|
|
1477
|
+
return placeSignature(bytes, event.publicKey, await eventSignature2(tx.bytes.subarray(tx.messageOffset), event.seed));
|
|
1478
|
+
}
|
|
1479
|
+
async function pollSolanaConfirmation(rpc, signature) {
|
|
1480
|
+
const deadline = Date.now() + 9e4;
|
|
1481
|
+
while (Date.now() < deadline) {
|
|
1482
|
+
const { value } = await rpc("getSignatureStatuses", [[signature]]);
|
|
1483
|
+
const status = value?.[0];
|
|
1484
|
+
if (status?.err) throw new Error(`Transaction failed on chain: ${JSON.stringify(status.err)}`);
|
|
1485
|
+
if (["confirmed", "finalized"].includes(status?.confirmationStatus)) return;
|
|
1486
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
1487
|
+
}
|
|
1488
|
+
throw new Error("Transaction confirmation timed out; check the signature before retrying.");
|
|
473
1489
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
1490
|
+
|
|
1491
|
+
// src/core/units.ts
|
|
1492
|
+
function assetDecimals(token) {
|
|
1493
|
+
const sym = symbolKey(token?.symbol);
|
|
1494
|
+
const registry2 = Number(token?.decimals);
|
|
1495
|
+
const canonical = isSolanaChainId(token?.chainId) ? solanaDestinationAsset(token?.address)?.decimals : CANONICAL_DECIMALS[sym];
|
|
1496
|
+
if (canonical !== void 0) {
|
|
1497
|
+
if (!Number.isInteger(registry2)) {
|
|
1498
|
+
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
1499
|
+
}
|
|
1500
|
+
if (registry2 !== canonical) {
|
|
1501
|
+
throw new Error(`ZeroDelta token registry reported ${registry2} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
1502
|
+
}
|
|
1503
|
+
return canonical;
|
|
479
1504
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
1505
|
+
if (!Number.isInteger(registry2) || registry2 < 0 || registry2 > 36) {
|
|
1506
|
+
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
1507
|
+
}
|
|
1508
|
+
return registry2;
|
|
483
1509
|
}
|
|
484
|
-
function
|
|
485
|
-
const
|
|
486
|
-
if (
|
|
487
|
-
if (
|
|
488
|
-
|
|
1510
|
+
function normalizeDecimalText(value) {
|
|
1511
|
+
const text = String(value || "").trim().replace(/\s+/g, "");
|
|
1512
|
+
if (!text) return "";
|
|
1513
|
+
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
1514
|
+
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
1515
|
+
if (text.includes(",")) return "";
|
|
1516
|
+
return text;
|
|
1517
|
+
}
|
|
1518
|
+
function parseUnitsDecimal(amount, decimals) {
|
|
1519
|
+
const text = normalizeDecimalText(amount);
|
|
1520
|
+
if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
|
|
1521
|
+
const [whole, frac = ""] = text.split(".");
|
|
1522
|
+
if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
|
|
1523
|
+
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
1524
|
+
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
1525
|
+
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
1526
|
+
return value;
|
|
1527
|
+
}
|
|
1528
|
+
function scaleDecimals(amount, fromDecimals, toDecimals) {
|
|
1529
|
+
if (toDecimals === fromDecimals) return amount;
|
|
1530
|
+
if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
|
1531
|
+
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
1532
|
+
}
|
|
1533
|
+
function formatUnits(raw2, decimals, maxDecimals = 6) {
|
|
1534
|
+
const value = BigInt(raw2 || "0");
|
|
1535
|
+
const base = 10n ** BigInt(decimals);
|
|
1536
|
+
const whole = value / base;
|
|
1537
|
+
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
1538
|
+
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
1539
|
+
return frac ? `${whole}.${frac}` : whole.toString();
|
|
1540
|
+
}
|
|
1541
|
+
function finalOf(quote) {
|
|
1542
|
+
return BigInt(quote?.finalAmount || quote?.toAmount || "0");
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
// src/core/ask-scale.ts
|
|
1546
|
+
function askTokenDecimals(quote, tokens, _from, to) {
|
|
1547
|
+
const requests = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
|
|
1548
|
+
const execution = Number(requests[requests.length - 1]?.executionChainId || quote.executionChainId);
|
|
1549
|
+
if (!Number.isSafeInteger(execution) || execution <= 0) throw new Error("Could not verify the quote amount precision.");
|
|
1550
|
+
if (execution === Number(to.chainId)) return assetDecimals(to);
|
|
1551
|
+
const row = tokens.find((token) => Number(token.chainId) === execution && symbolKey(token.symbol) === symbolKey(to.symbol));
|
|
1552
|
+
if (row) return assetDecimals(row);
|
|
1553
|
+
if (isSolanaChainId(to.chainId)) throw new Error("Could not verify the quote amount precision.");
|
|
1554
|
+
return assetDecimals(to);
|
|
1555
|
+
}
|
|
1556
|
+
function askCovers(ask, final, askDecimals, finalDecimals) {
|
|
1557
|
+
if (![askDecimals, finalDecimals].every((n) => Number.isInteger(n) && n >= 0 && n <= 36)) throw new Error("Could not verify the quote amount precision.");
|
|
1558
|
+
const shift = askDecimals - finalDecimals;
|
|
1559
|
+
return shift >= 0 ? ask >= final * 10n ** BigInt(shift) : ask * 10n ** BigInt(-shift) >= final;
|
|
489
1560
|
}
|
|
490
1561
|
|
|
491
1562
|
// src/core/ticker.ts
|
|
@@ -526,7 +1597,7 @@ function counterpartTokens(tokens, selected) {
|
|
|
526
1597
|
return tokens.filter((token) => assetClassOf(token.symbol) === want);
|
|
527
1598
|
}
|
|
528
1599
|
function tokenKey(chainId, address) {
|
|
529
|
-
return `${Number(chainId)}:${
|
|
1600
|
+
return `${Number(chainId)}:${chainAddressKey(chainId, address)}`;
|
|
530
1601
|
}
|
|
531
1602
|
function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
|
|
532
1603
|
return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
|
|
@@ -562,35 +1633,35 @@ function isSourceToken(token, ctx) {
|
|
|
562
1633
|
if (!ctx.sourceChains.has(chainId)) return false;
|
|
563
1634
|
return ctx.execution.has(chainId) || !isKnownUnbridgeable(token.bridge) && ctx.source.has(tokenKey(chainId, token.address));
|
|
564
1635
|
}
|
|
565
|
-
function directLaneOK(token,
|
|
566
|
-
if (!
|
|
567
|
-
if (symbolKey(
|
|
568
|
-
if (Number(
|
|
569
|
-
return lanes.has(laneKey(
|
|
1636
|
+
function directLaneOK(token, source2, lanes) {
|
|
1637
|
+
if (!source2 || !lanes) return true;
|
|
1638
|
+
if (symbolKey(source2.symbol) !== symbolKey(token.symbol)) return true;
|
|
1639
|
+
if (Number(source2.chainId) === Number(token.chainId)) return true;
|
|
1640
|
+
return lanes.has(laneKey(source2.chainId, source2.address, token.chainId, token.address));
|
|
570
1641
|
}
|
|
571
|
-
function brokenLaneFor(token,
|
|
572
|
-
if (!
|
|
573
|
-
return brokenLanes.get(laneKey(
|
|
1642
|
+
function brokenLaneFor(token, source2, brokenLanes) {
|
|
1643
|
+
if (!source2 || !brokenLanes) return void 0;
|
|
1644
|
+
return brokenLanes.get(laneKey(source2.chainId, source2.address, token.chainId, token.address));
|
|
574
1645
|
}
|
|
575
|
-
function laneLimitFor(token,
|
|
576
|
-
if (!
|
|
577
|
-
return limitedLanes2.get(laneKey(
|
|
1646
|
+
function laneLimitFor(token, source2, limitedLanes2) {
|
|
1647
|
+
if (!source2 || !limitedLanes2) return void 0;
|
|
1648
|
+
return limitedLanes2.get(laneKey(source2.chainId, source2.address, token.chainId, token.address));
|
|
578
1649
|
}
|
|
579
|
-
function destinationAvailability(token, ctx,
|
|
580
|
-
if (brokenLaneFor(token,
|
|
581
|
-
if (directLaneOK(token,
|
|
1650
|
+
function destinationAvailability(token, ctx, source2) {
|
|
1651
|
+
if (brokenLaneFor(token, source2 ?? void 0, ctx.brokenLanes)) return "unreachable";
|
|
1652
|
+
if (directLaneOK(token, source2 ?? void 0, ctx.lanes)) {
|
|
582
1653
|
if (ctx.execution.has(Number(token.chainId))) return "available";
|
|
583
1654
|
if (token.isChainedDestination === true) return "available";
|
|
584
1655
|
if (!isKnownUnbridgeable(token.bridge) && ctx.destination.has(tokenKey(token.chainId, token.address))) return "available";
|
|
585
1656
|
}
|
|
586
1657
|
return ctx.hubSymbols.has(symbolKey(token.symbol)) ? "hub-only" : "unreachable";
|
|
587
1658
|
}
|
|
588
|
-
function hasReachableDestination(
|
|
1659
|
+
function hasReachableDestination(source2, catalogue, ctx) {
|
|
589
1660
|
if (catalogue.length === 0) return true;
|
|
590
|
-
const from = tokenKey(
|
|
1661
|
+
const from = tokenKey(source2.chainId, source2.address);
|
|
591
1662
|
for (const candidate of catalogue) {
|
|
592
1663
|
if (tokenKey(candidate.chainId, candidate.address) === from) continue;
|
|
593
|
-
if (destinationAvailability(candidate, ctx,
|
|
1664
|
+
if (destinationAvailability(candidate, ctx, source2) === "available") return true;
|
|
594
1665
|
}
|
|
595
1666
|
return false;
|
|
596
1667
|
}
|
|
@@ -604,7 +1675,7 @@ function buildCatalogue(input) {
|
|
|
604
1675
|
const sourceChains = new Set([...registryChainIds].filter((id) => supportedChainIds.has(id)));
|
|
605
1676
|
const execution = executionChainIds(enabledChains);
|
|
606
1677
|
const projected = product === "rwa" ? routes.filter((route) => route.isEnabled !== false) : executableRoutes(routes);
|
|
607
|
-
const
|
|
1678
|
+
const source2 = sourceKeys(projected);
|
|
608
1679
|
const destination = destinationKeys(projected);
|
|
609
1680
|
const lanes = laneKeys(projected);
|
|
610
1681
|
const chainIds = new Set(sourceChains);
|
|
@@ -612,19 +1683,19 @@ function buildCatalogue(input) {
|
|
|
612
1683
|
const id = Number(route.toChainId);
|
|
613
1684
|
if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
|
|
614
1685
|
}
|
|
615
|
-
const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
|
|
1686
|
+
const allowed = tokens.filter((token) => token.isEnabled !== false && isChainAddress(token.chainId, token.address) && allowedAssets.has(symbolKey(token.symbol)));
|
|
616
1687
|
const projectedCatalogue = allowed.filter((token) => {
|
|
617
1688
|
if (!chainIds.has(Number(token.chainId))) return false;
|
|
618
1689
|
if (product === "rwa") return true;
|
|
619
1690
|
if (!isExecutableBridge(token)) return false;
|
|
620
1691
|
const key = tokenKey(token.chainId, token.address);
|
|
621
|
-
return
|
|
1692
|
+
return source2.has(key) || destination.has(key) || execution.has(Number(token.chainId));
|
|
622
1693
|
});
|
|
623
1694
|
const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
|
|
624
1695
|
const catalogue = ready ? projectedCatalogue : allowed;
|
|
625
1696
|
const hubSymbols = hubDeliverableSymbols(catalogue, execution);
|
|
626
|
-
const ctx = { source, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
|
|
627
|
-
const
|
|
1697
|
+
const ctx = { source: source2, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
|
|
1698
|
+
const sources2 = ready ? catalogue.filter((token) => isSourceToken(token, ctx) && hasReachableDestination(token, catalogue, ctx)) : (
|
|
628
1699
|
// Unprojected: the only rule we can still apply with confidence is the escrow-chain bound,
|
|
629
1700
|
// which comes from this build's own pins rather than from the registry.
|
|
630
1701
|
catalogue.filter((token) => sourceChains.has(Number(token.chainId)))
|
|
@@ -635,7 +1706,7 @@ function buildCatalogue(input) {
|
|
|
635
1706
|
...ctx,
|
|
636
1707
|
product,
|
|
637
1708
|
tokens: catalogue,
|
|
638
|
-
sources,
|
|
1709
|
+
sources: sources2,
|
|
639
1710
|
chainIds,
|
|
640
1711
|
chains: [...byId.values()],
|
|
641
1712
|
ready,
|
|
@@ -646,19 +1717,19 @@ function buildCatalogue(input) {
|
|
|
646
1717
|
|
|
647
1718
|
// src/core/options.ts
|
|
648
1719
|
function chainNameOf(chainId, chains) {
|
|
649
|
-
const
|
|
650
|
-
return
|
|
1720
|
+
const chain2 = chains.find((item) => Number(item.chainId) === Number(chainId));
|
|
1721
|
+
return chain2?.displayName || chain2?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
|
|
651
1722
|
}
|
|
652
1723
|
function chainById(chains, chainId) {
|
|
653
|
-
return chains.find((
|
|
1724
|
+
return chains.find((chain2) => Number(chain2.chainId) === Number(chainId)) || null;
|
|
654
1725
|
}
|
|
655
|
-
function chainSelectable(
|
|
1726
|
+
function chainSelectable(chain2, chainId) {
|
|
656
1727
|
if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
|
|
657
|
-
if (!
|
|
658
|
-
return
|
|
1728
|
+
if (!chain2) return true;
|
|
1729
|
+
return chain2.isEnabled !== false;
|
|
659
1730
|
}
|
|
660
1731
|
function tokenEnabled(token) {
|
|
661
|
-
return token?.isEnabled !== false &&
|
|
1732
|
+
return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
|
|
662
1733
|
}
|
|
663
1734
|
function findToken(tokens, chainId, symbol) {
|
|
664
1735
|
const key = symbolKey(symbol);
|
|
@@ -694,8 +1765,8 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
694
1765
|
for (const token of universe) {
|
|
695
1766
|
if (!tokenEnabled(token)) continue;
|
|
696
1767
|
const chainId = Number(token.chainId);
|
|
697
|
-
const
|
|
698
|
-
if (!chainSelectable(
|
|
1768
|
+
const chain2 = chainById(chains, chainId);
|
|
1769
|
+
if (!chainSelectable(chain2, chainId)) continue;
|
|
699
1770
|
const key = tokenKey(chainId, token.address);
|
|
700
1771
|
if (seen.has(key)) continue;
|
|
701
1772
|
if (refusal(token)) continue;
|
|
@@ -717,38 +1788,503 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
717
1788
|
direct
|
|
718
1789
|
});
|
|
719
1790
|
}
|
|
720
|
-
options.sort((a, b) => {
|
|
721
|
-
const walletChain = Number(walletChainId || 0);
|
|
722
|
-
if (walletChain) {
|
|
723
|
-
if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
|
|
724
|
-
if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
|
|
725
|
-
}
|
|
726
|
-
if (a.direct !== b.direct) return a.direct ? -1 : 1;
|
|
727
|
-
if (a.symbolKey !== b.symbolKey) {
|
|
728
|
-
if (a.symbolKey === invoiceKey) return -1;
|
|
729
|
-
if (b.symbolKey === invoiceKey) return 1;
|
|
730
|
-
return a.symbolKey.localeCompare(b.symbolKey);
|
|
1791
|
+
options.sort((a, b) => {
|
|
1792
|
+
const walletChain = Number(walletChainId || 0);
|
|
1793
|
+
if (walletChain) {
|
|
1794
|
+
if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
|
|
1795
|
+
if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
|
|
1796
|
+
}
|
|
1797
|
+
if (a.direct !== b.direct) return a.direct ? -1 : 1;
|
|
1798
|
+
if (a.symbolKey !== b.symbolKey) {
|
|
1799
|
+
if (a.symbolKey === invoiceKey) return -1;
|
|
1800
|
+
if (b.symbolKey === invoiceKey) return 1;
|
|
1801
|
+
return a.symbolKey.localeCompare(b.symbolKey);
|
|
1802
|
+
}
|
|
1803
|
+
if (a.sameChain !== b.sameChain) return a.sameChain ? -1 : 1;
|
|
1804
|
+
return a.chainId - b.chainId;
|
|
1805
|
+
});
|
|
1806
|
+
return options;
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
// src/core/solana-source.ts
|
|
1810
|
+
var CANONICAL_SOLANA_PROGRAM = "zd1E5feCJLNYaPPsBAYkCPMKGVnipYf8God9h917W33";
|
|
1811
|
+
var MAX_ASK_OVER_FINAL_BPS = 200n;
|
|
1812
|
+
var states = /* @__PURE__ */ new WeakMap();
|
|
1813
|
+
var quoteRequests = /* @__PURE__ */ new WeakMap();
|
|
1814
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
1815
|
+
var activeSigners = /* @__PURE__ */ new Set();
|
|
1816
|
+
var clone = (value) => JSON.parse(JSON.stringify(value));
|
|
1817
|
+
function freeze(value) {
|
|
1818
|
+
if (value && typeof value === "object") {
|
|
1819
|
+
for (const v of Object.values(value)) freeze(v);
|
|
1820
|
+
Object.freeze(value);
|
|
1821
|
+
}
|
|
1822
|
+
return value;
|
|
1823
|
+
}
|
|
1824
|
+
function raw(value, label, positive = false) {
|
|
1825
|
+
if (typeof value !== "string" || !/^\d+$/.test(value) || positive && BigInt(value) <= 0n || BigInt(value) >= 1n << 256n) throw new Error(`Invalid ${label}.`);
|
|
1826
|
+
return value;
|
|
1827
|
+
}
|
|
1828
|
+
function chain(value) {
|
|
1829
|
+
const text = String(value);
|
|
1830
|
+
if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) >= 1n << 64n) throw new Error("Invalid order chain.");
|
|
1831
|
+
return text;
|
|
1832
|
+
}
|
|
1833
|
+
function same(a, b) {
|
|
1834
|
+
return a.toLowerCase() === b.toLowerCase();
|
|
1835
|
+
}
|
|
1836
|
+
function recipient(input) {
|
|
1837
|
+
const to = input.recipient || (isSolanaChainId(input.toChainId) ? input.sender : input.owner);
|
|
1838
|
+
if (!isChainAddress(input.toChainId, to)) throw new Error("Invalid destination recipient.");
|
|
1839
|
+
return chainAddressKey(input.toChainId, to);
|
|
1840
|
+
}
|
|
1841
|
+
function validateInput(input) {
|
|
1842
|
+
if (input.fromChainId !== void 0 && input.fromChainId !== SOLANA_CHAIN_ID) throw new Error("Solana source chain required.");
|
|
1843
|
+
if (!Number.isSafeInteger(input.toChainId) || input.toChainId <= 0) throw new Error("Invalid destination chain.");
|
|
1844
|
+
if (!SUPPORTED_ASSETS.has(symbolKey(input.fromToken)) || !SUPPORTED_ASSETS.has(symbolKey(input.toToken))) throw new Error("Unsupported Solana source asset.");
|
|
1845
|
+
assertAddress(input.owner, "EVM order owner");
|
|
1846
|
+
solanaKeyBytes(input.sender);
|
|
1847
|
+
recipient(input);
|
|
1848
|
+
const span = input.deadlineSpanSeconds ?? 7200, slip = input.slippageBps ?? 0;
|
|
1849
|
+
if (!Number.isInteger(span) || span < 1 || span > 86400) throw new Error("Invalid Solana deadline span.");
|
|
1850
|
+
if (!Number.isInteger(slip) || slip < 0 || slip > 1e4) throw new Error("Invalid slippage tolerance.");
|
|
1851
|
+
}
|
|
1852
|
+
function selections(input, tokens) {
|
|
1853
|
+
validateInput(input);
|
|
1854
|
+
const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
|
|
1855
|
+
if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
|
|
1856
|
+
solanaKeyBytes(from.address);
|
|
1857
|
+
assertPinnedSolanaSource(from);
|
|
1858
|
+
if (!isChainAddress(input.toChainId, to.address)) throw new Error("Invalid destination token.");
|
|
1859
|
+
const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
|
|
1860
|
+
raw(amount, "input amount", true);
|
|
1861
|
+
if (BigInt(amount) >= 1n << 64n) throw new Error("Solana bid exceeds u64.");
|
|
1862
|
+
return { from, to, amount };
|
|
1863
|
+
}
|
|
1864
|
+
function assertPinnedSolanaSource(token) {
|
|
1865
|
+
const pinned = solanaDestinationAsset(token.address);
|
|
1866
|
+
if (!pinned || pinned.symbol !== symbolKey(token.symbol) || pinned.decimals !== Number(token.decimals)) {
|
|
1867
|
+
throw new Error("This Solana token is not supported for payment; refusing to sign.");
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
function makeRequest(input, from, to, amount) {
|
|
1871
|
+
return {
|
|
1872
|
+
inputChain: SOLANA_CHAIN_ID,
|
|
1873
|
+
outputChain: input.toChainId,
|
|
1874
|
+
inputToken: from.symbol,
|
|
1875
|
+
outputToken: to.symbol,
|
|
1876
|
+
inputAmount: amount,
|
|
1877
|
+
owners: { evm: input.owner },
|
|
1878
|
+
destinationWallet: recipient(input),
|
|
1879
|
+
sender: input.sender,
|
|
1880
|
+
deadline: String(Math.floor(Date.now() / 1e3) + (input.deadlineSpanSeconds ?? 7200))
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
function normalizePreview(request, quote, to, amount) {
|
|
1884
|
+
const option = quote?.options?.[0];
|
|
1885
|
+
if (!option) throw new Error("Native quote returned no options.");
|
|
1886
|
+
const receive = raw(option.finalAmount, "quoted output", true);
|
|
1887
|
+
return {
|
|
1888
|
+
receive: formatUnits(receive, assetDecimals(to)),
|
|
1889
|
+
receiveRaw: receive,
|
|
1890
|
+
fromAmount: amount,
|
|
1891
|
+
fromToken: request.inputToken,
|
|
1892
|
+
toToken: request.outputToken,
|
|
1893
|
+
bridge: option.bridge || "",
|
|
1894
|
+
feeBps: Number(option.feeBps || 0),
|
|
1895
|
+
estimatedDuration: Number(option.estimatedTimeSec || 0),
|
|
1896
|
+
via: null,
|
|
1897
|
+
nativeFeeRaw: String(option.gasCostSource || "0"),
|
|
1898
|
+
quote,
|
|
1899
|
+
option,
|
|
1900
|
+
txData: option.txData,
|
|
1901
|
+
request
|
|
1902
|
+
};
|
|
1903
|
+
}
|
|
1904
|
+
async function quoteSolanaSource(api, input) {
|
|
1905
|
+
const { from, to, amount } = selections(input, await api.fetchTokens());
|
|
1906
|
+
const request = makeRequest(input, from, to, amount);
|
|
1907
|
+
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
1908
|
+
const preview = normalizePreview(request, quote, to, input.amountIn);
|
|
1909
|
+
quoteRequests.set(preview, { api, request: clone(request) });
|
|
1910
|
+
return preview;
|
|
1911
|
+
}
|
|
1912
|
+
async function previewSolanaSource(api, input) {
|
|
1913
|
+
const tokens = await api.fetchTokens();
|
|
1914
|
+
const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
|
|
1915
|
+
if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
|
|
1916
|
+
assertPinnedSolanaSource(from);
|
|
1917
|
+
const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
|
|
1918
|
+
raw(amount, "input amount", true);
|
|
1919
|
+
const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
|
|
1920
|
+
const request = body;
|
|
1921
|
+
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
1922
|
+
const option = quote?.options?.[0];
|
|
1923
|
+
if (!option) throw new Error("Native quote returned no options.");
|
|
1924
|
+
const receive = raw(option.finalAmount, "quoted output", true);
|
|
1925
|
+
return {
|
|
1926
|
+
receive: formatUnits(receive, assetDecimals(to)),
|
|
1927
|
+
receiveRaw: receive,
|
|
1928
|
+
fromAmount: input.amountIn,
|
|
1929
|
+
fromToken: request.inputToken,
|
|
1930
|
+
toToken: request.outputToken,
|
|
1931
|
+
bridge: option.bridge || "",
|
|
1932
|
+
feeBps: Number(option.feeBps || 0),
|
|
1933
|
+
estimatedDuration: Number(option.estimatedTimeSec || 0),
|
|
1934
|
+
via: null,
|
|
1935
|
+
nativeFeeRaw: "0"
|
|
1936
|
+
};
|
|
1937
|
+
}
|
|
1938
|
+
function denied(value) {
|
|
1939
|
+
return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
|
|
1940
|
+
}
|
|
1941
|
+
async function checkActiveScreens(api, input) {
|
|
1942
|
+
const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
|
|
1943
|
+
const screens = await Promise.all(addresses.map(async (address) => {
|
|
1944
|
+
try {
|
|
1945
|
+
return await api.screenWallet(address);
|
|
1946
|
+
} catch {
|
|
1947
|
+
return void 0;
|
|
1948
|
+
}
|
|
1949
|
+
}));
|
|
1950
|
+
if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
|
|
1951
|
+
}
|
|
1952
|
+
function jsonGuards(input, preview, tokens, chains) {
|
|
1953
|
+
const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
|
|
1954
|
+
const wanted = makeRequest(input, from, to, amount);
|
|
1955
|
+
for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
|
|
1956
|
+
if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
|
|
1957
|
+
}
|
|
1958
|
+
if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
|
|
1959
|
+
const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
|
|
1960
|
+
if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
|
|
1961
|
+
if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
|
|
1962
|
+
if (denied(preview.quote.compliance) || denied(preview.quote.complianceDecision) || denied(preview.quote.complianceStatus) || denied(option.compliance) || denied(option.complianceDecision)) throw new Error("Compliance DENY; refusing to sign.");
|
|
1963
|
+
if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
|
|
1964
|
+
if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
|
|
1965
|
+
if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
|
|
1966
|
+
if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
|
|
1967
|
+
checkSolanaPlan(option.txData);
|
|
1968
|
+
const orders = option.orderRequests;
|
|
1969
|
+
if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
|
|
1970
|
+
const first = orders[0], last = orders[orders.length - 1];
|
|
1971
|
+
if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
|
|
1972
|
+
if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
|
|
1973
|
+
const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
|
|
1974
|
+
if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
|
|
1975
|
+
if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
|
|
1976
|
+
for (let i = 0; i < orders.length; i++) {
|
|
1977
|
+
const order = orders[i];
|
|
1978
|
+
if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
|
|
1979
|
+
raw(order.askTokenAmount, "ask amount", true);
|
|
1980
|
+
raw(order.bidTokenAmount, "bid amount", true);
|
|
1981
|
+
chain(order.destinationChainId);
|
|
1982
|
+
chain(order.executionChainId);
|
|
1983
|
+
if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
|
|
1984
|
+
if (isSolanaChainId(order.destinationChainId)) {
|
|
1985
|
+
if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
|
|
1986
|
+
solanaBridgeOf(to);
|
|
1987
|
+
checkSolanaReceiver(order, recipient(input), to.address);
|
|
1988
|
+
} else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
|
|
1989
|
+
if (i === 0 ? String(order.deadline) !== request.deadline : String(order.deadline) !== "0" && String(order.deadline) !== request.deadline) throw new Error("Order deadline differs from requested deadline.");
|
|
1990
|
+
if (i) {
|
|
1991
|
+
const previous = orders[i - 1];
|
|
1992
|
+
if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
|
|
1993
|
+
if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
const quoteForScale = { ...option, orderRequests: orders };
|
|
1997
|
+
const execution = Number(last.executionChainId);
|
|
1998
|
+
if (execution !== Number(to.chainId) && !tokens.some((t) => Number(t.chainId) === execution && symbolKey(t.symbol) === symbolKey(to.symbol))) throw new Error("Cannot resolve ask amount precision.");
|
|
1999
|
+
const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
|
|
2000
|
+
const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
|
|
2001
|
+
const minFinal = final * (10000n - slip) / 10000n;
|
|
2002
|
+
if (!askCovers(BigInt(last.askTokenAmount), minFinal, askScale, finalScale) || !askCovers(BigInt(last.askTokenAmount), BigInt(raw(input.minReceiveRaw ?? minFinal.toString(), "minimum output")), askScale, finalScale)) throw new Error("Ask below receive floor.");
|
|
2003
|
+
if (!askCovers(BigInt(final) * (10000n + MAX_ASK_OVER_FINAL_BPS), BigInt(last.askTokenAmount) * 10000n, finalScale, askScale)) throw new Error("Ask far above the displayed receive amount; refusing to sign.");
|
|
2004
|
+
const registry2 = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
|
|
2005
|
+
const contracts = registry2?.contracts;
|
|
2006
|
+
const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry2?.escrowContract);
|
|
2007
|
+
const marker = option.partnerId ?? preview.quote.partnerId;
|
|
2008
|
+
if (marker !== void 0 && marker !== null && !/^0x[0-9a-fA-F]{64}$/.test(String(marker))) throw new Error("Invalid partner marker; re-quote with both wallets.");
|
|
2009
|
+
const ask = BigInt(first.askTokenAmount);
|
|
2010
|
+
return {
|
|
2011
|
+
program,
|
|
2012
|
+
signer: input.sender,
|
|
2013
|
+
mint: from.address,
|
|
2014
|
+
owner: input.owner,
|
|
2015
|
+
askToken: first.askToken,
|
|
2016
|
+
minAskTokenAmount: ask.toString(),
|
|
2017
|
+
maxAskTokenAmount: ask.toString(),
|
|
2018
|
+
bidTokenAmount: amount,
|
|
2019
|
+
destinationReceiver: first.destinationReceiver,
|
|
2020
|
+
destinationChainId: String(first.destinationChainId),
|
|
2021
|
+
executionChainId: String(first.executionChainId),
|
|
2022
|
+
deadline: request.deadline,
|
|
2023
|
+
partnerId: marker == null ? null : String(marker),
|
|
2024
|
+
nextOrders: orders.slice(1)
|
|
2025
|
+
};
|
|
2026
|
+
}
|
|
2027
|
+
async function buildSolanaSourcePlan(api, input, quoted) {
|
|
2028
|
+
const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
|
|
2029
|
+
const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
|
|
2030
|
+
if (!original || original.api !== api || JSON.stringify(original.request) !== JSON.stringify(served.request)) throw new Error("Quote request provenance changed; fetch a fresh native quote.");
|
|
2031
|
+
const preview = clone(served);
|
|
2032
|
+
const expected = jsonGuards(input, preview, tokens, chains);
|
|
2033
|
+
await checkActiveScreens(api, input);
|
|
2034
|
+
const plan = freeze({ preview, expected, txData: preview.option.txData });
|
|
2035
|
+
const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
|
|
2036
|
+
states.set(plan, {
|
|
2037
|
+
api,
|
|
2038
|
+
input: clone(input),
|
|
2039
|
+
plan,
|
|
2040
|
+
failed: false,
|
|
2041
|
+
busy: false,
|
|
2042
|
+
originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
|
|
2043
|
+
signatures: [],
|
|
2044
|
+
done: 0
|
|
2045
|
+
});
|
|
2046
|
+
return plan;
|
|
2047
|
+
}
|
|
2048
|
+
function createSolanaRpc(api) {
|
|
2049
|
+
return async (method, params) => {
|
|
2050
|
+
const body = await api.apiRequest("/solana-rpc", {
|
|
2051
|
+
method: "POST",
|
|
2052
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
2053
|
+
timeoutMs: 15e3
|
|
2054
|
+
});
|
|
2055
|
+
if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
|
|
2056
|
+
return body.result;
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
var SolanaSendError = class extends Error {
|
|
2060
|
+
constructor(message, signature, sentAt) {
|
|
2061
|
+
super(message);
|
|
2062
|
+
this.signature = signature;
|
|
2063
|
+
this.sentAt = sentAt;
|
|
2064
|
+
this.name = "SolanaSendError";
|
|
2065
|
+
}
|
|
2066
|
+
signature;
|
|
2067
|
+
sentAt;
|
|
2068
|
+
};
|
|
2069
|
+
async function executeSolanaPlan(input) {
|
|
2070
|
+
const signature = await runSolanaPlan(input, false);
|
|
2071
|
+
if (!signature) throw new Error("Missing final Solana submit.");
|
|
2072
|
+
return signature;
|
|
2073
|
+
}
|
|
2074
|
+
async function executeSolanaPlanStaged(input) {
|
|
2075
|
+
const signature = await runSolanaPlan(input, true);
|
|
2076
|
+
return signature ? { status: "sent", signature } : { status: "prepared" };
|
|
2077
|
+
}
|
|
2078
|
+
function solanaPlanNeedsPreparation(plan) {
|
|
2079
|
+
const state = states.get(plan);
|
|
2080
|
+
const live = state?.plan ?? plan;
|
|
2081
|
+
return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
|
|
2082
|
+
}
|
|
2083
|
+
async function runSolanaPlan(input, stopBeforeSubmit) {
|
|
2084
|
+
const state = states.get(input.plan);
|
|
2085
|
+
if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
|
|
2086
|
+
if (state.sent) return state.sent;
|
|
2087
|
+
if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
|
|
2088
|
+
if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
|
|
2089
|
+
state.busy = true;
|
|
2090
|
+
activeSigners.add(input.signer.publicKey);
|
|
2091
|
+
let index = 0, completedBeforeRun = state.signatures.length;
|
|
2092
|
+
const progress = (stage) => {
|
|
2093
|
+
const pending = inFlight.get(input.signer.publicKey);
|
|
2094
|
+
try {
|
|
2095
|
+
input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
|
|
2096
|
+
} catch {
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
2099
|
+
try {
|
|
2100
|
+
progress("preparing");
|
|
2101
|
+
const pending = inFlight.get(input.signer.publicKey);
|
|
2102
|
+
if (pending) {
|
|
2103
|
+
const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
|
|
2104
|
+
const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
|
|
2105
|
+
if (status?.err) inFlight.delete(input.signer.publicKey);
|
|
2106
|
+
else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
|
|
2107
|
+
inFlight.delete(input.signer.publicKey);
|
|
2108
|
+
if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
|
|
2109
|
+
if (pending.final) {
|
|
2110
|
+
pending.state.sent = pending.signature;
|
|
2111
|
+
reportSolana(pending.state, pending.signature);
|
|
2112
|
+
if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
|
|
2113
|
+
progress("sent");
|
|
2114
|
+
return pending.signature;
|
|
2115
|
+
}
|
|
2116
|
+
} else {
|
|
2117
|
+
if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
|
|
2118
|
+
throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
|
|
2119
|
+
}
|
|
2120
|
+
inFlight.delete(input.signer.publicKey);
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
if (state.failed) {
|
|
2124
|
+
const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
|
|
2125
|
+
if (!same(retried.expected.askToken, state.plan.expected.askToken) || retried.expected.executionChainId !== state.plan.expected.executionChainId || retried.expected.destinationChainId !== state.plan.expected.destinationChainId) throw new Error("Retry changed connector route; request a new order.");
|
|
2126
|
+
state.plan = retried;
|
|
2127
|
+
state.done = 0;
|
|
2128
|
+
state.failed = false;
|
|
2129
|
+
}
|
|
2130
|
+
const plan = state.plan;
|
|
2131
|
+
checkSolanaPlan(plan.txData);
|
|
2132
|
+
for (const tx of plan.txData) {
|
|
2133
|
+
const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
|
|
2134
|
+
verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
|
|
2135
|
+
}
|
|
2136
|
+
for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
|
|
2137
|
+
completedBeforeRun = state.signatures.length;
|
|
2138
|
+
const startAt = state.done;
|
|
2139
|
+
for (index = startAt; index < plan.txData.length; index++) {
|
|
2140
|
+
if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
|
|
2141
|
+
progress("ready");
|
|
2142
|
+
return null;
|
|
2143
|
+
}
|
|
2144
|
+
if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
|
|
2145
|
+
await checkActiveScreens(state.api, state.input);
|
|
2146
|
+
const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
|
|
2147
|
+
const keys = await resolveSolanaKeys(parsed, input.rpc);
|
|
2148
|
+
const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
|
|
2149
|
+
if (buffer) {
|
|
2150
|
+
const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
|
|
2151
|
+
checkSolanaRouteBuffer(account.value, plan.expected);
|
|
2152
|
+
}
|
|
2153
|
+
const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
|
|
2154
|
+
let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
|
|
2155
|
+
if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
|
|
2156
|
+
verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
|
|
2157
|
+
progress("signing");
|
|
2158
|
+
const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
|
|
2159
|
+
assertWalletMessage(bytes, signed);
|
|
2160
|
+
verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
|
|
2161
|
+
const signedTx = parseSolanaTransaction(signed);
|
|
2162
|
+
const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
|
|
2163
|
+
const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
|
|
2164
|
+
inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
|
|
2165
|
+
progress("sending");
|
|
2166
|
+
try {
|
|
2167
|
+
const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
|
|
2168
|
+
if (returned !== signature) throw new Error("RPC returned a different signature.");
|
|
2169
|
+
if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
|
|
2170
|
+
} catch (error) {
|
|
2171
|
+
throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
|
|
2172
|
+
}
|
|
2173
|
+
inFlight.delete(input.signer.publicKey);
|
|
2174
|
+
state.signatures.push(signature);
|
|
2175
|
+
state.done = index + 1;
|
|
2176
|
+
if (tx.actionType === "submit") {
|
|
2177
|
+
state.sent = signature;
|
|
2178
|
+
reportSolana(state, signature);
|
|
2179
|
+
progress("sent");
|
|
2180
|
+
return signature;
|
|
2181
|
+
}
|
|
2182
|
+
progress("ready");
|
|
2183
|
+
}
|
|
2184
|
+
throw new Error("Missing final Solana submit.");
|
|
2185
|
+
} catch (error) {
|
|
2186
|
+
state.failed = true;
|
|
2187
|
+
progress("failed");
|
|
2188
|
+
throw error;
|
|
2189
|
+
} finally {
|
|
2190
|
+
state.busy = false;
|
|
2191
|
+
activeSigners.delete(input.signer.publicKey);
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
function reportSolana(state, signature) {
|
|
2195
|
+
try {
|
|
2196
|
+
void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
|
|
2197
|
+
});
|
|
2198
|
+
} catch {
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
async function readSolanaBalance(rpc, owner, mint) {
|
|
2202
|
+
try {
|
|
2203
|
+
solanaKeyBytes(owner);
|
|
2204
|
+
solanaKeyBytes(mint);
|
|
2205
|
+
const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
|
|
2206
|
+
if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
|
|
2207
|
+
let total = 0n, decimals;
|
|
2208
|
+
for (const item of result.value) {
|
|
2209
|
+
const amount = item.account?.data?.parsed?.info?.tokenAmount;
|
|
2210
|
+
if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
|
|
2211
|
+
decimals = amount.decimals;
|
|
2212
|
+
total += BigInt(raw(amount.amount, "token balance"));
|
|
731
2213
|
}
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
2214
|
+
return total;
|
|
2215
|
+
} catch {
|
|
2216
|
+
return void 0;
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
async function simulateSolanaCost(rpc, plan) {
|
|
2220
|
+
checkSolanaPlan(plan.txData);
|
|
2221
|
+
const signer = plan.expected.signer;
|
|
2222
|
+
const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
|
|
2223
|
+
const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
|
|
2224
|
+
if (sim.value?.err) throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
|
|
2225
|
+
const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
|
|
2226
|
+
if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
|
|
2227
|
+
const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
|
|
2228
|
+
return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
// src/core/escrow.ts
|
|
2232
|
+
function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
|
|
2233
|
+
const fromQuote = normalizeAddress(quoteEscrow);
|
|
2234
|
+
const fromChains = normalizeAddress(chainsEscrow);
|
|
2235
|
+
if (!fromChains || fromChains === ZERO_ADDRESS) {
|
|
2236
|
+
throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
|
|
2237
|
+
}
|
|
2238
|
+
if (!fromQuote || fromQuote === ZERO_ADDRESS) {
|
|
2239
|
+
throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
|
|
2240
|
+
}
|
|
2241
|
+
if (fromQuote !== fromChains) {
|
|
2242
|
+
throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
|
|
2243
|
+
}
|
|
2244
|
+
const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
|
|
2245
|
+
if (pinned && pinned !== fromChains) {
|
|
2246
|
+
throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
|
|
2247
|
+
}
|
|
2248
|
+
return fromChains;
|
|
2249
|
+
}
|
|
2250
|
+
function isLayerZeroRoute(quote, option = {}) {
|
|
2251
|
+
const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
|
|
2252
|
+
return bridge.includes("layerzero") || bridge.includes("layer zero");
|
|
2253
|
+
}
|
|
2254
|
+
function sourceAssetKey(quote, option = {}) {
|
|
2255
|
+
return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
|
|
2256
|
+
}
|
|
2257
|
+
function requiresNativeBridgeFee(quote, option = {}) {
|
|
2258
|
+
const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
|
|
2259
|
+
const execChainId = Number(quote?.executionChainId);
|
|
2260
|
+
if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
|
|
2261
|
+
return false;
|
|
2262
|
+
}
|
|
2263
|
+
const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
|
|
2264
|
+
if (canonical) return canonical === "layerzero";
|
|
2265
|
+
return isLayerZeroRoute(quote, option);
|
|
2266
|
+
}
|
|
2267
|
+
function applyLayerZeroBuffer(quote, option = {}) {
|
|
2268
|
+
const gas = BigInt(quote?.gasCostSource || "0");
|
|
2269
|
+
if (gas <= 0n) return 0n;
|
|
2270
|
+
if (!requiresNativeBridgeFee(quote, option)) return 0n;
|
|
2271
|
+
return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
|
|
736
2272
|
}
|
|
737
2273
|
|
|
738
2274
|
// src/core/native-fee.ts
|
|
739
2275
|
function routeNativeValue(route) {
|
|
740
2276
|
try {
|
|
741
|
-
const
|
|
742
|
-
if (
|
|
743
|
-
const value = BigInt(
|
|
2277
|
+
const raw2 = route?.quote?.msgValue;
|
|
2278
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
|
|
2279
|
+
const value = BigInt(raw2);
|
|
744
2280
|
return value > 0n ? value : 0n;
|
|
745
2281
|
} catch {
|
|
746
2282
|
return 0n;
|
|
747
2283
|
}
|
|
748
2284
|
}
|
|
749
2285
|
function nativeSymbol(chainId, chains = []) {
|
|
750
|
-
const
|
|
751
|
-
const fromRegistry = typeof
|
|
2286
|
+
const registry2 = chainById(chains, Number(chainId))?.nativeCurrency;
|
|
2287
|
+
const fromRegistry = typeof registry2 === "string" ? registry2.trim() : "";
|
|
752
2288
|
return fromRegistry || BUNDLED_NATIVE_SYMBOL[Number(chainId)] || "ETH";
|
|
753
2289
|
}
|
|
754
2290
|
function formatNative(wei) {
|
|
@@ -775,6 +2311,11 @@ function nativeFeeShortMessage(check2, symbol, chainName3) {
|
|
|
775
2311
|
}
|
|
776
2312
|
|
|
777
2313
|
// src/core/route-health.ts
|
|
2314
|
+
function healthLaneKey(value) {
|
|
2315
|
+
if (typeof value !== "string") return "";
|
|
2316
|
+
const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
|
|
2317
|
+
return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
|
|
2318
|
+
}
|
|
778
2319
|
var EMPTY = /* @__PURE__ */ new Map();
|
|
779
2320
|
var NO_LIMITS = /* @__PURE__ */ new Map();
|
|
780
2321
|
function laneAvailabilityState(lane) {
|
|
@@ -794,7 +2335,7 @@ function suppressedLanes(health) {
|
|
|
794
2335
|
const out = /* @__PURE__ */ new Map();
|
|
795
2336
|
for (const lane of health.lanes) {
|
|
796
2337
|
if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
|
|
797
|
-
const key =
|
|
2338
|
+
const key = healthLaneKey(lane.laneKey);
|
|
798
2339
|
if (!key) continue;
|
|
799
2340
|
const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
|
|
800
2341
|
const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
|
|
@@ -814,7 +2355,7 @@ function limitedLanes(health) {
|
|
|
814
2355
|
const out = /* @__PURE__ */ new Map();
|
|
815
2356
|
for (const lane of health.lanes) {
|
|
816
2357
|
if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
|
|
817
|
-
const key =
|
|
2358
|
+
const key = healthLaneKey(lane.laneKey);
|
|
818
2359
|
const limit = lane.availability?.limit;
|
|
819
2360
|
if (!key || !limit || typeof limit !== "object") continue;
|
|
820
2361
|
const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
|
|
@@ -837,14 +2378,14 @@ function limitedLanes(health) {
|
|
|
837
2378
|
}
|
|
838
2379
|
function exceedsLaneLimit(limit, amount, bidDecimals) {
|
|
839
2380
|
if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
|
|
840
|
-
let
|
|
2381
|
+
let raw2;
|
|
841
2382
|
try {
|
|
842
|
-
|
|
2383
|
+
raw2 = parseUnitsDecimal(amount, bidDecimals);
|
|
843
2384
|
} catch {
|
|
844
2385
|
return false;
|
|
845
2386
|
}
|
|
846
2387
|
const scale = Math.max(bidDecimals, limit.decimals);
|
|
847
|
-
return scaleDecimals(
|
|
2388
|
+
return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
|
|
848
2389
|
}
|
|
849
2390
|
function laneLimitAmount(limit) {
|
|
850
2391
|
return formatUnits(limit.maxAmount, limit.decimals);
|
|
@@ -1010,12 +2551,12 @@ function stripBundlePrefix(head) {
|
|
|
1010
2551
|
if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
|
|
1011
2552
|
return { head, source: null };
|
|
1012
2553
|
}
|
|
1013
|
-
function complianceReasonHead(
|
|
1014
|
-
return stripBundlePrefix((
|
|
2554
|
+
function complianceReasonHead(raw2) {
|
|
2555
|
+
return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
|
|
1015
2556
|
}
|
|
1016
|
-
function usd(
|
|
1017
|
-
const n = Number(
|
|
1018
|
-
if (!Number.isFinite(n)) return `$${
|
|
2557
|
+
function usd(raw2) {
|
|
2558
|
+
const n = Number(raw2);
|
|
2559
|
+
if (!Number.isFinite(n)) return `$${raw2}`;
|
|
1019
2560
|
return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
|
|
1020
2561
|
}
|
|
1021
2562
|
function capFromDetail(detail) {
|
|
@@ -1026,11 +2567,11 @@ function categoryPhrase(detail) {
|
|
|
1026
2567
|
const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
|
|
1027
2568
|
return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
|
|
1028
2569
|
}
|
|
1029
|
-
function humanizeComplianceReason(
|
|
1030
|
-
const [headRaw, ...restParts] =
|
|
2570
|
+
function humanizeComplianceReason(raw2) {
|
|
2571
|
+
const [headRaw, ...restParts] = raw2.split(":");
|
|
1031
2572
|
const detail = restParts.join(":").trim();
|
|
1032
|
-
const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
|
|
1033
|
-
const scope =
|
|
2573
|
+
const { head, source: source2 } = stripBundlePrefix((headRaw ?? "").trim());
|
|
2574
|
+
const scope = source2 === "legislation" ? "applicable regulations" : "the applicable policy";
|
|
1034
2575
|
switch (head) {
|
|
1035
2576
|
case "asset_pair_not_allowed": {
|
|
1036
2577
|
const m = detail.match(/^(\S+)->(\S+)\s+in\s+(\S+)/);
|
|
@@ -1104,8 +2645,8 @@ var CHECK_HEADS = {
|
|
|
1104
2645
|
function distinctScreenedWallets(compliance) {
|
|
1105
2646
|
const seen = /* @__PURE__ */ new Set();
|
|
1106
2647
|
const wallets = [];
|
|
1107
|
-
for (const
|
|
1108
|
-
const address =
|
|
2648
|
+
for (const raw2 of compliance?.screenedWallets ?? []) {
|
|
2649
|
+
const address = raw2?.trim();
|
|
1109
2650
|
if (!address) continue;
|
|
1110
2651
|
const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
|
|
1111
2652
|
if (seen.has(key)) continue;
|
|
@@ -1125,11 +2666,11 @@ function screeningLabel(wallets) {
|
|
|
1125
2666
|
function complianceChecks(compliance, cv = complianceView(compliance)) {
|
|
1126
2667
|
if (cv.tone === "neutral") return [];
|
|
1127
2668
|
const byControl = /* @__PURE__ */ new Map();
|
|
1128
|
-
for (const
|
|
1129
|
-
const head = complianceReasonHead(
|
|
2669
|
+
for (const raw2 of compliance?.reasons ?? []) {
|
|
2670
|
+
const head = complianceReasonHead(raw2);
|
|
1130
2671
|
const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
|
|
1131
2672
|
if (!id) continue;
|
|
1132
|
-
byControl.set(id, [...byControl.get(id) ?? [],
|
|
2673
|
+
byControl.set(id, [...byControl.get(id) ?? [], raw2]);
|
|
1133
2674
|
}
|
|
1134
2675
|
const screenedWallets = distinctScreenedWallets(compliance);
|
|
1135
2676
|
const wallets = screenedWallets.length;
|
|
@@ -1153,8 +2694,8 @@ function complianceControlsEvaluated(compliance, cv = complianceView(compliance)
|
|
|
1153
2694
|
const checks = complianceChecks(compliance, cv);
|
|
1154
2695
|
if (checks.length === 0) return 0;
|
|
1155
2696
|
const named = /* @__PURE__ */ new Set();
|
|
1156
|
-
for (const
|
|
1157
|
-
const name =
|
|
2697
|
+
for (const raw2 of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
|
|
2698
|
+
const name = raw2?.trim();
|
|
1158
2699
|
if (name) named.add(name.toLowerCase());
|
|
1159
2700
|
}
|
|
1160
2701
|
return checks.length + named.size;
|
|
@@ -1194,8 +2735,8 @@ var BLOCK_CATEGORY_LABELS = {
|
|
|
1194
2735
|
};
|
|
1195
2736
|
var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
|
|
1196
2737
|
function blockLabelFor(categories) {
|
|
1197
|
-
for (const
|
|
1198
|
-
const label = BLOCK_CATEGORY_LABELS[String(
|
|
2738
|
+
for (const raw2 of categories) {
|
|
2739
|
+
const label = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
|
|
1199
2740
|
if (label) return label;
|
|
1200
2741
|
}
|
|
1201
2742
|
return BLOCK_LABEL_DEFAULT;
|
|
@@ -1216,8 +2757,8 @@ var REASON_TAGS = {
|
|
|
1216
2757
|
dest_chain_not_allowed: "Chain not allowed",
|
|
1217
2758
|
jurisdiction_out_of_scope: "Out of scope"
|
|
1218
2759
|
};
|
|
1219
|
-
function complianceReasonTag(
|
|
1220
|
-
const head = complianceReasonHead(
|
|
2760
|
+
function complianceReasonTag(raw2) {
|
|
2761
|
+
const head = complianceReasonHead(raw2);
|
|
1221
2762
|
return REASON_TAGS[head] ?? head.replace(/_/g, " ");
|
|
1222
2763
|
}
|
|
1223
2764
|
function complianceTagOf(compliance) {
|
|
@@ -1280,8 +2821,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1280
2821
|
const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
|
|
1281
2822
|
const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
|
|
1282
2823
|
const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
|
|
1283
|
-
const enforcePayCeiling = (
|
|
1284
|
-
if (maxPayRaw > 0n && BigInt(
|
|
2824
|
+
const enforcePayCeiling = (raw2) => {
|
|
2825
|
+
if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
|
|
1285
2826
|
throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
|
|
1286
2827
|
}
|
|
1287
2828
|
};
|
|
@@ -1305,7 +2846,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1305
2846
|
if (BigInt(quote?.fromAmount || "0") !== guessSent) {
|
|
1306
2847
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
1307
2848
|
}
|
|
1308
|
-
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
2849
|
+
const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
|
|
1309
2850
|
const final = finalOf(quote);
|
|
1310
2851
|
if (final > bestFinal) {
|
|
1311
2852
|
bestFinal = final;
|
|
@@ -1342,7 +2883,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1342
2883
|
directTransfer: false,
|
|
1343
2884
|
quote: best,
|
|
1344
2885
|
youPayRaw: bestGuess.toString(),
|
|
1345
|
-
recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
|
|
2886
|
+
recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
|
|
1346
2887
|
targetRaw: targetRaw.toString(),
|
|
1347
2888
|
overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
|
|
1348
2889
|
meetsTarget: bestFinal >= targetRaw,
|
|
@@ -1364,7 +2905,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
1364
2905
|
if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
|
|
1365
2906
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
1366
2907
|
}
|
|
1367
|
-
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
2908
|
+
const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
|
|
1368
2909
|
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
1369
2910
|
return {
|
|
1370
2911
|
directTransfer: false,
|
|
@@ -1395,13 +2936,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
|
|
|
1395
2936
|
const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
|
|
1396
2937
|
const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
|
|
1397
2938
|
if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
|
|
2939
|
+
const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
|
|
2940
|
+
const keyBytes2 = (value, label) => {
|
|
2941
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label} is not a valid 32-byte Solana key.`);
|
|
2942
|
+
return String(value).toLowerCase();
|
|
2943
|
+
};
|
|
1398
2944
|
return {
|
|
1399
2945
|
owner: assertAddress(order.owner || payer, "Order owner"),
|
|
1400
2946
|
bidToken: assertAddress(order.bidToken, "Bid token"),
|
|
1401
2947
|
bidTokenAmount: String(order.bidTokenAmount || "0"),
|
|
1402
|
-
askToken: assertAddress(order.askToken, "Ask token"),
|
|
2948
|
+
askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
|
|
1403
2949
|
askTokenAmount: String(order.askTokenAmount || "0"),
|
|
1404
|
-
destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
|
|
2950
|
+
destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
|
|
2951
|
+
...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
|
|
1405
2952
|
destinationChainId: String(order.destinationChainId || destination.chainId),
|
|
1406
2953
|
executionChainId,
|
|
1407
2954
|
deadline
|
|
@@ -1413,17 +2960,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
|
|
|
1413
2960
|
(request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
|
|
1414
2961
|
);
|
|
1415
2962
|
}
|
|
1416
|
-
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
|
|
2963
|
+
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
|
|
1417
2964
|
const list = orders?.length ? orders : [order];
|
|
1418
2965
|
const sourceOrder = list[0];
|
|
1419
2966
|
const finalOrder = list[list.length - 1];
|
|
1420
2967
|
const now = Math.floor(Date.now() / 1e3);
|
|
1421
2968
|
const deadline = Number(sourceOrder.deadline || 0);
|
|
2969
|
+
const solana = isSolanaChainId(destination.chainId);
|
|
2970
|
+
if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
|
|
2971
|
+
throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
2972
|
+
}
|
|
1422
2973
|
for (const current of list) {
|
|
1423
2974
|
if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
|
|
1424
2975
|
throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
|
|
1425
2976
|
}
|
|
1426
|
-
if (
|
|
2977
|
+
if (isSolanaChainId(current.destinationChainId)) {
|
|
2978
|
+
if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
|
|
2979
|
+
checkSolanaReceiver(current, destination.address, destinationToken.address);
|
|
2980
|
+
} else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
|
|
1427
2981
|
throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
|
|
1428
2982
|
}
|
|
1429
2983
|
if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
|
|
@@ -1433,9 +2987,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
1433
2987
|
if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
|
|
1434
2988
|
throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
|
|
1435
2989
|
}
|
|
1436
|
-
if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
2990
|
+
if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
1437
2991
|
throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
|
|
1438
2992
|
}
|
|
2993
|
+
if (solana && finalOrder.askTokenBase58 && finalOrder.askTokenBase58 !== destinationToken.address) throw new Error("ZeroDelta quote returned an ask token mint that does not match the destination asset.");
|
|
1439
2994
|
if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
|
|
1440
2995
|
throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
|
|
1441
2996
|
}
|
|
@@ -1454,10 +3009,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
1454
3009
|
if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
|
|
1455
3010
|
throw new Error("ZeroDelta quote returned a non-positive output amount.");
|
|
1456
3011
|
}
|
|
1457
|
-
|
|
3012
|
+
const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
|
|
3013
|
+
const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
|
|
3014
|
+
if (!covers(result.targetRaw)) {
|
|
1458
3015
|
throw new Error("ZeroDelta quote would not cover the requested destination amount.");
|
|
1459
3016
|
}
|
|
1460
|
-
if (
|
|
3017
|
+
if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
|
|
1461
3018
|
throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
|
|
1462
3019
|
}
|
|
1463
3020
|
const maxDeadline = maxDeadlineSeconds(quote);
|
|
@@ -1489,8 +3046,8 @@ function routeDeltaLabel(result, quote) {
|
|
|
1489
3046
|
return "~0";
|
|
1490
3047
|
}
|
|
1491
3048
|
function quotePartnerId(quote) {
|
|
1492
|
-
const
|
|
1493
|
-
return typeof
|
|
3049
|
+
const raw2 = quote.partnerId;
|
|
3050
|
+
return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
|
|
1494
3051
|
}
|
|
1495
3052
|
function optionTicker(option) {
|
|
1496
3053
|
return option.ticker || option.symbol;
|
|
@@ -1501,14 +3058,15 @@ function routeLabelFor(option, destinationToken, result) {
|
|
|
1501
3058
|
return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
|
|
1502
3059
|
}
|
|
1503
3060
|
function tokenAt(tokens, chainId, address) {
|
|
1504
|
-
const
|
|
3061
|
+
const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
|
|
3062
|
+
const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
|
|
1505
3063
|
if (!wanted || !tokens?.length) return void 0;
|
|
1506
|
-
return tokens.find((t) => Number(t.chainId) === Number(chainId) &&
|
|
3064
|
+
return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
|
|
1507
3065
|
}
|
|
1508
|
-
function legAmount(
|
|
3066
|
+
function legAmount(raw2, decimals) {
|
|
1509
3067
|
if (decimals === void 0) return "";
|
|
1510
3068
|
try {
|
|
1511
|
-
return formatUnits(
|
|
3069
|
+
return formatUnits(raw2 || "0", decimals);
|
|
1512
3070
|
} catch {
|
|
1513
3071
|
return "";
|
|
1514
3072
|
}
|
|
@@ -1539,7 +3097,7 @@ function buildLegs(orders, ctx) {
|
|
|
1539
3097
|
toTicker,
|
|
1540
3098
|
toChainId,
|
|
1541
3099
|
toChainName: chainNameOf(toChainId, ctx.chains),
|
|
1542
|
-
toAmount: legAmount(order.askTokenAmount, toDecimals),
|
|
3100
|
+
toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
|
|
1543
3101
|
executionChainId,
|
|
1544
3102
|
executionChainName: chainNameOf(executionChainId, ctx.chains)
|
|
1545
3103
|
});
|
|
@@ -1643,8 +3201,12 @@ async function buildRoute({
|
|
|
1643
3201
|
const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
|
|
1644
3202
|
const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
|
|
1645
3203
|
const order = orders[0];
|
|
1646
|
-
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
|
|
1647
|
-
const
|
|
3204
|
+
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
|
|
3205
|
+
const echoedExecution = Number(quote.executionChainId || 0);
|
|
3206
|
+
if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
|
|
3207
|
+
throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
|
|
3208
|
+
}
|
|
3209
|
+
const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
|
|
1648
3210
|
if (needsNativeFee) {
|
|
1649
3211
|
let rawFee;
|
|
1650
3212
|
try {
|
|
@@ -1688,7 +3250,7 @@ async function buildRoute({
|
|
|
1688
3250
|
},
|
|
1689
3251
|
routeLabel: routeLabelFor(option, destinationToken, result),
|
|
1690
3252
|
deltaLabel: routeDeltaLabel(result, quote),
|
|
1691
|
-
legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
|
|
3253
|
+
legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
|
|
1692
3254
|
transactions: [
|
|
1693
3255
|
{
|
|
1694
3256
|
id: "approve",
|
|
@@ -1721,6 +3283,7 @@ async function buildRoute({
|
|
|
1721
3283
|
gasCostSource: quote.gasCostSource,
|
|
1722
3284
|
msgValue: valueRaw.toString(),
|
|
1723
3285
|
deadline: order.deadline,
|
|
3286
|
+
...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
|
|
1724
3287
|
partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
|
|
1725
3288
|
iterations: result.iterations,
|
|
1726
3289
|
// Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
|
|
@@ -1736,10 +3299,10 @@ var CHANNEL_HEADER = "x-zd-channel";
|
|
|
1736
3299
|
var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
|
|
1737
3300
|
var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
|
|
1738
3301
|
var WIDGET_CHANNEL = "widget";
|
|
1739
|
-
var WIDGET_VERSION = "4.
|
|
3302
|
+
var WIDGET_VERSION = "4.13.0" ;
|
|
1740
3303
|
var MAX_CHANNEL_VERSION_LEN = 32;
|
|
1741
|
-
function sanitizeVersion(
|
|
1742
|
-
const v = String(
|
|
3304
|
+
function sanitizeVersion(raw2) {
|
|
3305
|
+
const v = String(raw2).trim();
|
|
1743
3306
|
if (!v) return "";
|
|
1744
3307
|
const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
|
|
1745
3308
|
return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
|
|
@@ -1775,9 +3338,9 @@ function isReportableSubmission(report) {
|
|
|
1775
3338
|
|
|
1776
3339
|
// src/core/api.ts
|
|
1777
3340
|
function apiError(message, props = {}) {
|
|
1778
|
-
const
|
|
1779
|
-
Object.assign(
|
|
1780
|
-
return
|
|
3341
|
+
const err2 = new Error(message);
|
|
3342
|
+
Object.assign(err2, props);
|
|
3343
|
+
return err2;
|
|
1781
3344
|
}
|
|
1782
3345
|
function toQuery(params) {
|
|
1783
3346
|
const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== "" && v !== null);
|
|
@@ -1795,14 +3358,14 @@ function sanitizeMessage(value, fallback) {
|
|
|
1795
3358
|
return text.length > MAX_MESSAGE_LEN ? `${text.slice(0, MAX_MESSAGE_LEN - 1)}\u2026` : text;
|
|
1796
3359
|
}
|
|
1797
3360
|
function apiMessage(json, fallback) {
|
|
1798
|
-
const
|
|
1799
|
-
if (
|
|
1800
|
-
if (Array.isArray(
|
|
1801
|
-
const head = sanitizeMessage(
|
|
1802
|
-
const detail = sanitizeMessage(
|
|
3361
|
+
const err2 = json?.error || json;
|
|
3362
|
+
if (err2?.fieldErrors?.[0]?.message) return sanitizeMessage(err2.fieldErrors[0].message, fallback);
|
|
3363
|
+
if (Array.isArray(err2?.reasons) && err2.reasons.length) {
|
|
3364
|
+
const head = sanitizeMessage(err2.message, fallback);
|
|
3365
|
+
const detail = sanitizeMessage(err2.reasons.filter((r) => typeof r === "string").join(", "), "");
|
|
1803
3366
|
return detail ? `${head}: ${detail}` : head;
|
|
1804
3367
|
}
|
|
1805
|
-
return sanitizeMessage(
|
|
3368
|
+
return sanitizeMessage(err2?.message, fallback);
|
|
1806
3369
|
}
|
|
1807
3370
|
function isStructuredComplianceBlock(error) {
|
|
1808
3371
|
const code = String(error?.code || "").toUpperCase();
|
|
@@ -1942,9 +3505,9 @@ function createApiClient(cfg) {
|
|
|
1942
3505
|
if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
|
|
1943
3506
|
return once("chains", async () => {
|
|
1944
3507
|
const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
|
|
1945
|
-
const normalized = (Array.isArray(chains) ? chains : []).map((
|
|
1946
|
-
const escrow = normalizeAddress(
|
|
1947
|
-
return escrow ? { ...
|
|
3508
|
+
const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
|
|
3509
|
+
const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
|
|
3510
|
+
return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
|
|
1948
3511
|
});
|
|
1949
3512
|
cache.chains = { at: Date.now(), value: normalized };
|
|
1950
3513
|
return normalized;
|
|
@@ -2047,14 +3610,16 @@ function createApiClient(cfg) {
|
|
|
2047
3610
|
async function screenWallet(address, chainId) {
|
|
2048
3611
|
const addr = String(address || "").trim();
|
|
2049
3612
|
if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
|
|
2050
|
-
const
|
|
3613
|
+
const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
|
|
3614
|
+
if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
|
|
3615
|
+
const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
|
|
2051
3616
|
const hit = screenCache.get(key);
|
|
2052
3617
|
if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
|
|
2053
3618
|
const inflight = screenInflight.get(key);
|
|
2054
3619
|
if (inflight) return inflight;
|
|
2055
3620
|
const request = apiRequest("/screen/wallet", {
|
|
2056
3621
|
method: "POST",
|
|
2057
|
-
body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
|
|
3622
|
+
body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
|
|
2058
3623
|
timeoutMs: 12e3
|
|
2059
3624
|
}).then((screen) => {
|
|
2060
3625
|
if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
|
|
@@ -2094,7 +3659,7 @@ function createApiClient(cfg) {
|
|
|
2094
3659
|
|
|
2095
3660
|
// src/core/plan.ts
|
|
2096
3661
|
function optionBalanceKey(option) {
|
|
2097
|
-
return `${Number(option.chainId)}:${
|
|
3662
|
+
return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
|
|
2098
3663
|
}
|
|
2099
3664
|
function hasPositiveBalance(option, balances) {
|
|
2100
3665
|
try {
|
|
@@ -2104,7 +3669,8 @@ function hasPositiveBalance(option, balances) {
|
|
|
2104
3669
|
}
|
|
2105
3670
|
}
|
|
2106
3671
|
function validateDestination(destination) {
|
|
2107
|
-
|
|
3672
|
+
const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
|
|
3673
|
+
if (isSolanaChainId(destination.chainId)) destination.address = address;
|
|
2108
3674
|
const chainId = Number(destination.chainId);
|
|
2109
3675
|
const asset = symbolKey(destination.asset);
|
|
2110
3676
|
if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
|
|
@@ -2162,8 +3728,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
2162
3728
|
if (directOptions.length) {
|
|
2163
3729
|
const parties = [];
|
|
2164
3730
|
const seenParty = /* @__PURE__ */ new Set();
|
|
2165
|
-
for (const
|
|
2166
|
-
const addr = String(
|
|
3731
|
+
for (const raw2 of [payer, destination.address]) {
|
|
3732
|
+
const addr = String(raw2 || "").trim();
|
|
2167
3733
|
if (!addr) continue;
|
|
2168
3734
|
const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
|
|
2169
3735
|
if (seenParty.has(key)) continue;
|
|
@@ -2271,7 +3837,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
|
|
|
2271
3837
|
if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
|
|
2272
3838
|
const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
|
|
2273
3839
|
const option = buildPayOptions({ invoiceAsset: destination.asset, invoiceChainId: destination.chainId, tokens, routes, chains, walletChainId: wallet.chainId, catalogue }).find(
|
|
2274
|
-
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && o.address
|
|
3840
|
+
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
|
|
2275
3841
|
);
|
|
2276
3842
|
if (!option) throw new Error("That funding option is not available for this payment right now.");
|
|
2277
3843
|
return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
|
|
@@ -2294,8 +3860,10 @@ function viaOf(quote, tokens) {
|
|
|
2294
3860
|
const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
|
|
2295
3861
|
if (orders.length < 2) return null;
|
|
2296
3862
|
const first = orders[0];
|
|
2297
|
-
const
|
|
2298
|
-
const
|
|
3863
|
+
const chainId = Number(first?.destinationChainId);
|
|
3864
|
+
const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
|
|
3865
|
+
const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
|
|
3866
|
+
const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
|
|
2299
3867
|
return token ? tokenTicker(token) : "";
|
|
2300
3868
|
}
|
|
2301
3869
|
async function quoteSwapPreview(api, swap, owner) {
|
|
@@ -2307,7 +3875,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
2307
3875
|
if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
|
|
2308
3876
|
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
2309
3877
|
const account = normalizeAddress(owner) || PREVIEW_OWNER;
|
|
2310
|
-
const previewReceiver = normalizeAddress(swap.recipient) || account;
|
|
3878
|
+
const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
|
|
2311
3879
|
const quote = await api.fetchQuote({
|
|
2312
3880
|
fromChainId: v.fromChainId,
|
|
2313
3881
|
toChainId: v.toChainId,
|
|
@@ -2315,7 +3883,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
2315
3883
|
toToken: destToken.symbol,
|
|
2316
3884
|
fromAmount: amountInRaw.toString(),
|
|
2317
3885
|
owner: account,
|
|
2318
|
-
destinationReceiver: previewReceiver
|
|
3886
|
+
...previewReceiver ? { destinationReceiver: previewReceiver } : {}
|
|
2319
3887
|
});
|
|
2320
3888
|
const final = finalOf(quote);
|
|
2321
3889
|
return {
|
|
@@ -2340,7 +3908,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
2340
3908
|
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
|
|
2341
3909
|
if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
|
|
2342
3910
|
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
2343
|
-
const receiver = resolveSwapReceiver(swap.recipient, account);
|
|
3911
|
+
const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
|
|
2344
3912
|
const option = {
|
|
2345
3913
|
symbol: sourceToken.symbol,
|
|
2346
3914
|
symbolKey: symbolKey(sourceToken.symbol),
|
|
@@ -2410,9 +3978,9 @@ function rawEquals(value, expected) {
|
|
|
2410
3978
|
}
|
|
2411
3979
|
function planMsgValueHex(route) {
|
|
2412
3980
|
try {
|
|
2413
|
-
const
|
|
2414
|
-
if (
|
|
2415
|
-
return "0x" + BigInt(
|
|
3981
|
+
const raw2 = route?.quote?.msgValue;
|
|
3982
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
|
|
3983
|
+
return "0x" + BigInt(raw2).toString(16);
|
|
2416
3984
|
} catch {
|
|
2417
3985
|
return null;
|
|
2418
3986
|
}
|
|
@@ -2439,15 +4007,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
|
2439
4007
|
if (!decoded) return false;
|
|
2440
4008
|
const first = decoded.orders[0];
|
|
2441
4009
|
const last = decoded.orders[decoded.orders.length - 1];
|
|
2442
|
-
return decoded.partnerId === lower(route.quote?.partnerId || NO_PARTNER_ID) && lower(first.bidToken) === lower(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower(last.askToken) === lower(route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && lower(last.destinationReceiver) === lower(expectedRecipient);
|
|
4010
|
+
return decoded.partnerId === lower(route.quote?.partnerId || NO_PARTNER_ID) && lower(first.bidToken) === lower(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower(last.askToken) === lower(isSolanaChainId(route.receive.chainId) ? solanaKeyHex(route.receive.tokenAddress || "") : route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && (isSolanaChainId(route.receive.chainId) ? solanaDeliveryMatches(last.destinationReceiver, expectedRecipient, route.receive.tokenAddress) : lower(last.destinationReceiver) === lower(expectedRecipient));
|
|
2443
4011
|
}
|
|
2444
4012
|
return false;
|
|
2445
4013
|
}
|
|
4014
|
+
function solanaDeliveryMatches(encoded, recipient2, mint) {
|
|
4015
|
+
try {
|
|
4016
|
+
return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
|
|
4017
|
+
} catch {
|
|
4018
|
+
return false;
|
|
4019
|
+
}
|
|
4020
|
+
}
|
|
2446
4021
|
async function allowanceCovers(tx, account, ethCall2) {
|
|
2447
4022
|
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
2448
4023
|
try {
|
|
2449
|
-
const
|
|
2450
|
-
return BigInt(
|
|
4024
|
+
const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
|
|
4025
|
+
return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
2451
4026
|
} catch {
|
|
2452
4027
|
return false;
|
|
2453
4028
|
}
|
|
@@ -2458,9 +4033,9 @@ var TX_VERIFY_ATTEMPTS = 5;
|
|
|
2458
4033
|
var TX_VERIFY_INTERVAL_MS = 2500;
|
|
2459
4034
|
var TX_VERIFY_FETCH_MS = 5e3;
|
|
2460
4035
|
var TX_VERIFY_DEADLINE_MS = 18e3;
|
|
2461
|
-
function registryRpc(
|
|
2462
|
-
if (!
|
|
2463
|
-
const candidates = [
|
|
4036
|
+
function registryRpc(chain2) {
|
|
4037
|
+
if (!chain2) return "";
|
|
4038
|
+
const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
|
|
2464
4039
|
const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
|
|
2465
4040
|
return found || "";
|
|
2466
4041
|
}
|
|
@@ -2541,8 +4116,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2541
4116
|
}
|
|
2542
4117
|
return null;
|
|
2543
4118
|
}
|
|
2544
|
-
async function verifySubmittedTx({ chainId, hash, from, to, data, value, minNonce }) {
|
|
2545
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(String(
|
|
4119
|
+
async function verifySubmittedTx({ chainId, hash: hash2, from, to, data, value, minNonce }) {
|
|
4120
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash2 || ""))) return { status: "mismatch" };
|
|
2546
4121
|
if (!normalizeAddress(from) || typeof minNonce !== "number") return { status: "unconfirmed", reason: "no-binding" };
|
|
2547
4122
|
const rpcUrl = await chainRpcUrl(chainId);
|
|
2548
4123
|
if (!rpcUrl) return { status: "unconfirmed", reason: "no-rpc" };
|
|
@@ -2553,7 +4128,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2553
4128
|
if (!matched) {
|
|
2554
4129
|
let tx = null;
|
|
2555
4130
|
try {
|
|
2556
|
-
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [
|
|
4131
|
+
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash2]);
|
|
2557
4132
|
} catch {
|
|
2558
4133
|
tx = null;
|
|
2559
4134
|
}
|
|
@@ -2565,7 +4140,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2565
4140
|
if (matched) {
|
|
2566
4141
|
let receipt = null;
|
|
2567
4142
|
try {
|
|
2568
|
-
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [
|
|
4143
|
+
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash2]);
|
|
2569
4144
|
} catch {
|
|
2570
4145
|
receipt = null;
|
|
2571
4146
|
}
|
|
@@ -2607,9 +4182,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2607
4182
|
}
|
|
2608
4183
|
function record(target, hex) {
|
|
2609
4184
|
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
|
|
2610
|
-
const
|
|
4185
|
+
const raw2 = BigInt(hex || "0x0").toString();
|
|
2611
4186
|
const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
2612
|
-
out[key] = { raw, formatted: formatUnits(
|
|
4187
|
+
out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
|
|
2613
4188
|
return true;
|
|
2614
4189
|
}
|
|
2615
4190
|
async function readOne(rpcUrl, target) {
|
|
@@ -2675,9 +4250,9 @@ function isSameOriginPath(value) {
|
|
|
2675
4250
|
return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
|
|
2676
4251
|
}
|
|
2677
4252
|
function resolveApiBase(value) {
|
|
2678
|
-
const
|
|
2679
|
-
if (isSameOriginPath(
|
|
2680
|
-
return parseAllowedApiBase(
|
|
4253
|
+
const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
|
|
4254
|
+
if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
|
|
4255
|
+
return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
|
|
2681
4256
|
}
|
|
2682
4257
|
function canAttachApiKey(apiBase, trustedOrigin) {
|
|
2683
4258
|
if (isSameOriginPath(apiBase)) return true;
|
|
@@ -2716,31 +4291,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
|
|
|
2716
4291
|
}
|
|
2717
4292
|
|
|
2718
4293
|
// src/core/index.ts
|
|
4294
|
+
var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
|
|
2719
4295
|
function sanitizeLegs(legs) {
|
|
2720
4296
|
if (!Array.isArray(legs) || !legs.length) return void 0;
|
|
2721
4297
|
const text = (v, max) => String(v ?? "").slice(0, max);
|
|
2722
|
-
const
|
|
4298
|
+
const chain2 = (v) => Number(v) || 0;
|
|
2723
4299
|
const ticker = (value, asset) => safeTicker(value, asset) || void 0;
|
|
2724
4300
|
return legs.slice(0, 8).map((leg, i) => ({
|
|
2725
4301
|
index: Number(leg?.index) || i + 1,
|
|
2726
4302
|
fromAsset: text(leg?.fromAsset, 12),
|
|
2727
4303
|
fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
|
|
2728
|
-
fromChainId:
|
|
4304
|
+
fromChainId: chain2(leg?.fromChainId),
|
|
2729
4305
|
fromChainName: text(leg?.fromChainName, 40),
|
|
2730
4306
|
fromAmount: text(leg?.fromAmount, 40),
|
|
2731
4307
|
toAsset: text(leg?.toAsset, 12),
|
|
2732
4308
|
toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
|
|
2733
|
-
toChainId:
|
|
4309
|
+
toChainId: chain2(leg?.toChainId),
|
|
2734
4310
|
toChainName: text(leg?.toChainName, 40),
|
|
2735
4311
|
toAmount: text(leg?.toAmount, 40),
|
|
2736
|
-
executionChainId:
|
|
4312
|
+
executionChainId: chain2(leg?.executionChainId),
|
|
2737
4313
|
executionChainName: text(leg?.executionChainName, 40)
|
|
2738
4314
|
}));
|
|
2739
4315
|
}
|
|
2740
4316
|
function sanitizeTxEntry(entry) {
|
|
2741
4317
|
return {
|
|
2742
4318
|
kind: entry.kind === "swap" ? "swap" : "payment",
|
|
2743
|
-
|
|
4319
|
+
// A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
|
|
4320
|
+
hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) || isSolanaChainId(entry.chainId) && /^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
|
|
2744
4321
|
txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
|
|
2745
4322
|
chainId: Number(entry.chainId) || null,
|
|
2746
4323
|
chainName: String(entry.chainName || "").slice(0, 40),
|
|
@@ -2751,7 +4328,7 @@ function sanitizeTxEntry(entry) {
|
|
|
2751
4328
|
payAmount: String(entry.payAmount || "").slice(0, 40),
|
|
2752
4329
|
receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
|
|
2753
4330
|
account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
|
|
2754
|
-
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
|
|
4331
|
+
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
|
|
2755
4332
|
settlement: entry.settlement === "direct" ? "direct" : "escrow",
|
|
2756
4333
|
status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
|
|
2757
4334
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -2762,6 +4339,7 @@ function createEngine(config = {}) {
|
|
|
2762
4339
|
const resolved = resolveConfig(config);
|
|
2763
4340
|
const api = createApiClient(resolved);
|
|
2764
4341
|
const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
|
|
4342
|
+
const solanaRpc = createSolanaRpc(api);
|
|
2765
4343
|
return {
|
|
2766
4344
|
api,
|
|
2767
4345
|
verifier,
|
|
@@ -2772,7 +4350,7 @@ function createEngine(config = {}) {
|
|
|
2772
4350
|
fetchRouteHealth: api.fetchRouteHealth,
|
|
2773
4351
|
fetchQuote: api.fetchQuote,
|
|
2774
4352
|
fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
|
|
2775
|
-
fetchCatalogue: async (allowedAssets, product) => {
|
|
4353
|
+
fetchCatalogue: async (allowedAssets, product, options) => {
|
|
2776
4354
|
const [chains, registryTokens, routes, health, vaults] = await Promise.all([
|
|
2777
4355
|
api.fetchChains().catch(() => []),
|
|
2778
4356
|
api.fetchTokens().catch(() => []),
|
|
@@ -2789,7 +4367,9 @@ function createEngine(config = {}) {
|
|
|
2789
4367
|
routes,
|
|
2790
4368
|
product,
|
|
2791
4369
|
...allowed ? { allowedAssets: allowed } : {},
|
|
2792
|
-
|
|
4370
|
+
// Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
|
|
4371
|
+
// Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
|
|
4372
|
+
supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
|
|
2793
4373
|
brokenLanes: suppressedLanes(health),
|
|
2794
4374
|
// Same read, same degraded mode: a null health response limits nothing.
|
|
2795
4375
|
limitedLanes: limitedLanes(health),
|
|
@@ -2800,6 +4380,13 @@ function createEngine(config = {}) {
|
|
|
2800
4380
|
quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
|
|
2801
4381
|
quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
|
|
2802
4382
|
buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
|
|
4383
|
+
quoteSolanaSource: (input) => quoteSolanaSource(api, input),
|
|
4384
|
+
buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
|
|
4385
|
+
executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
|
|
4386
|
+
executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
|
|
4387
|
+
previewSolanaSource: (input) => previewSolanaSource(api, input),
|
|
4388
|
+
readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
|
|
4389
|
+
simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
|
|
2803
4390
|
payerNonceBaseline: verifier.payerNonceBaseline,
|
|
2804
4391
|
verifySubmittedTx: verifier.verifySubmittedTx,
|
|
2805
4392
|
readBalances: verifier.readBalances,
|
|
@@ -2898,8 +4485,8 @@ function addChainParams(chainId) {
|
|
|
2898
4485
|
rpcUrls: [rpc]
|
|
2899
4486
|
};
|
|
2900
4487
|
}
|
|
2901
|
-
function rpcErrorCode(
|
|
2902
|
-
let cur =
|
|
4488
|
+
function rpcErrorCode(err2) {
|
|
4489
|
+
let cur = err2;
|
|
2903
4490
|
const seen = /* @__PURE__ */ new Set();
|
|
2904
4491
|
while (cur && typeof cur === "object" && !seen.has(cur)) {
|
|
2905
4492
|
seen.add(cur);
|
|
@@ -2913,50 +4500,50 @@ function rpcErrorCode(err) {
|
|
|
2913
4500
|
async function switchChain(provider, chainId) {
|
|
2914
4501
|
try {
|
|
2915
4502
|
await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainHex(chainId) }] });
|
|
2916
|
-
} catch (
|
|
4503
|
+
} catch (err2) {
|
|
2917
4504
|
const params = addChainParams(chainId);
|
|
2918
|
-
if (rpcErrorCode(
|
|
4505
|
+
if (rpcErrorCode(err2) === 4902 && params) {
|
|
2919
4506
|
await provider.request({ method: "wallet_addEthereumChain", params: [params] });
|
|
2920
4507
|
await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainHex(chainId) }] });
|
|
2921
4508
|
return;
|
|
2922
4509
|
}
|
|
2923
|
-
throw
|
|
4510
|
+
throw err2;
|
|
2924
4511
|
}
|
|
2925
4512
|
}
|
|
2926
|
-
function shortWalletMessage(
|
|
2927
|
-
if (
|
|
2928
|
-
const e =
|
|
4513
|
+
function shortWalletMessage(err2) {
|
|
4514
|
+
if (err2 && typeof err2 === "object") {
|
|
4515
|
+
const e = err2;
|
|
2929
4516
|
if (typeof e.shortMessage === "string" && e.shortMessage) return e.shortMessage;
|
|
2930
4517
|
if (typeof e.message === "string" && e.message) return e.message;
|
|
2931
4518
|
}
|
|
2932
4519
|
return void 0;
|
|
2933
4520
|
}
|
|
2934
|
-
function normalizeWalletError(
|
|
2935
|
-
if (!
|
|
2936
|
-
const code = rpcErrorCode(
|
|
2937
|
-
const name =
|
|
4521
|
+
function normalizeWalletError(err2, fallback = "Transaction failed.") {
|
|
4522
|
+
if (!err2) return fallback;
|
|
4523
|
+
const code = rpcErrorCode(err2);
|
|
4524
|
+
const name = err2 && typeof err2 === "object" && "name" in err2 ? err2.name : void 0;
|
|
2938
4525
|
if (code === -32002) return "Open your wallet \u2014 a request is already pending.";
|
|
2939
4526
|
if (code === 4001 || name === "UserRejectedRequestError") return "Request was rejected in your wallet.";
|
|
2940
4527
|
if (code === 4902) return "This chain isn't set up in your wallet. Approve adding it and try again.";
|
|
2941
|
-
if (code === -32603) return shortWalletMessage(
|
|
2942
|
-
return shortWalletMessage(
|
|
4528
|
+
if (code === -32603) return shortWalletMessage(err2) || "Your wallet returned an internal error. Try again.";
|
|
4529
|
+
return shortWalletMessage(err2) || fallback;
|
|
2943
4530
|
}
|
|
2944
4531
|
async function sendTransaction(provider, tx) {
|
|
2945
|
-
const
|
|
4532
|
+
const hash2 = await provider.request({
|
|
2946
4533
|
method: "eth_sendTransaction",
|
|
2947
4534
|
params: [{ from: tx.from, to: tx.to, data: tx.data, value: tx.value || "0x0" }]
|
|
2948
4535
|
});
|
|
2949
|
-
return
|
|
4536
|
+
return hash2;
|
|
2950
4537
|
}
|
|
2951
4538
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2952
|
-
async function waitForReceipt(provider,
|
|
4539
|
+
async function waitForReceipt(provider, hash2, opts = {}) {
|
|
2953
4540
|
const timeoutMs = opts.timeoutMs ?? 9e4;
|
|
2954
4541
|
const pollMs = opts.pollMs ?? 2500;
|
|
2955
4542
|
const deadline = Date.now() + timeoutMs;
|
|
2956
4543
|
for (; ; ) {
|
|
2957
4544
|
let receipt = null;
|
|
2958
4545
|
try {
|
|
2959
|
-
receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [
|
|
4546
|
+
receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash2] });
|
|
2960
4547
|
} catch {
|
|
2961
4548
|
}
|
|
2962
4549
|
if (receipt && receipt.status != null) {
|
|
@@ -2977,9 +4564,9 @@ async function ethCall(provider, to, data) {
|
|
|
2977
4564
|
}
|
|
2978
4565
|
async function nativeBalance(provider, account) {
|
|
2979
4566
|
try {
|
|
2980
|
-
const
|
|
2981
|
-
if (typeof
|
|
2982
|
-
return BigInt(
|
|
4567
|
+
const raw2 = await provider.request({ method: "eth_getBalance", params: [account, "latest"] });
|
|
4568
|
+
if (typeof raw2 !== "string" || !/^0x[0-9a-fA-F]*$/.test(raw2)) return null;
|
|
4569
|
+
return BigInt(raw2 || "0x0");
|
|
2983
4570
|
} catch {
|
|
2984
4571
|
return null;
|
|
2985
4572
|
}
|
|
@@ -3065,9 +4652,9 @@ function isEntry(v) {
|
|
|
3065
4652
|
function readTxHistory(account, storage2 = defaultStorage()) {
|
|
3066
4653
|
if (!storage2 || !validAccount(account)) return [];
|
|
3067
4654
|
try {
|
|
3068
|
-
const
|
|
3069
|
-
if (!
|
|
3070
|
-
const parsed = JSON.parse(
|
|
4655
|
+
const raw2 = storage2.getItem(txHistoryKey(account));
|
|
4656
|
+
if (!raw2) return [];
|
|
4657
|
+
const parsed = JSON.parse(raw2);
|
|
3071
4658
|
return Array.isArray(parsed) ? parsed.filter(isEntry) : [];
|
|
3072
4659
|
} catch {
|
|
3073
4660
|
return [];
|
|
@@ -3286,7 +4873,7 @@ function useFlow(args) {
|
|
|
3286
4873
|
const account = wallet.account;
|
|
3287
4874
|
if (!route || !provider || !account) return;
|
|
3288
4875
|
busyRef.current = true;
|
|
3289
|
-
const
|
|
4876
|
+
const recipient2 = recipientFor(account);
|
|
3290
4877
|
const sourceChainId = route.source.chainId;
|
|
3291
4878
|
const txSteps = route.transactions.map((tx) => ({ id: tx.id, label: tx.label, state: "pending" }));
|
|
3292
4879
|
txSteps.push({ id: "verify", label: "Confirm on-chain", state: "pending" });
|
|
@@ -3294,7 +4881,7 @@ function useFlow(args) {
|
|
|
3294
4881
|
setStatus("submitting");
|
|
3295
4882
|
setError(null);
|
|
3296
4883
|
setVerdict(null);
|
|
3297
|
-
const patch = (id, s,
|
|
4884
|
+
const patch = (id, s, hash2) => setSteps((prev) => prev.map((st) => st.id === id ? { ...st, state: s, ...hash2 ? { hash: hash2 } : {} } : st));
|
|
3298
4885
|
try {
|
|
3299
4886
|
const current = await getChainId(provider);
|
|
3300
4887
|
if (current !== Number(sourceChainId)) {
|
|
@@ -3324,17 +4911,17 @@ function useFlow(args) {
|
|
|
3324
4911
|
patch(tx.id, "done");
|
|
3325
4912
|
continue;
|
|
3326
4913
|
}
|
|
3327
|
-
if (!validatePlannedTransaction(tx, route,
|
|
4914
|
+
if (!validatePlannedTransaction(tx, route, recipient2)) {
|
|
3328
4915
|
throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
|
|
3329
4916
|
}
|
|
3330
4917
|
patch(tx.id, "active");
|
|
3331
|
-
const
|
|
4918
|
+
const hash2 = await sendTransaction(provider, { from: account, to: tx.to, data: tx.data, value: tx.value });
|
|
3332
4919
|
if (!isFinal) {
|
|
3333
|
-
await waitForReceipt(provider,
|
|
4920
|
+
await waitForReceipt(provider, hash2);
|
|
3334
4921
|
}
|
|
3335
|
-
patch(tx.id, "done",
|
|
4922
|
+
patch(tx.id, "done", hash2);
|
|
3336
4923
|
if (tx.kind !== "approve") {
|
|
3337
|
-
settleHash =
|
|
4924
|
+
settleHash = hash2;
|
|
3338
4925
|
settleTx = tx;
|
|
3339
4926
|
}
|
|
3340
4927
|
}
|
|
@@ -3362,7 +4949,7 @@ function useFlow(args) {
|
|
|
3362
4949
|
payAmount: route.source.payAmount,
|
|
3363
4950
|
receiveAmount: route.receive.amount,
|
|
3364
4951
|
account,
|
|
3365
|
-
recipient,
|
|
4952
|
+
recipient: recipient2,
|
|
3366
4953
|
settlement: route.state === "DIRECT" ? "direct" : "escrow",
|
|
3367
4954
|
status: v.status === "confirmed" ? "confirmed" : v.status === "mismatch" || v.status === "reverted" ? "error" : "unconfirmed",
|
|
3368
4955
|
// One signature can be several orders. Record them, or the history of a chained RWA trade
|
|
@@ -3490,18 +5077,18 @@ function groupDecimal(value) {
|
|
|
3490
5077
|
var SIGNIFICANT_DIGITS = 7;
|
|
3491
5078
|
var MIN_FRACTION_DIGITS = 4;
|
|
3492
5079
|
function formatCalculatedAmount(value, decimals) {
|
|
3493
|
-
let
|
|
5080
|
+
let raw2 = typeof value === "number" ? String(value) : value.trim();
|
|
3494
5081
|
if (typeof value === "number") {
|
|
3495
|
-
if (!Number.isFinite(value)) return
|
|
3496
|
-
if (/e/i.test(
|
|
3497
|
-
|
|
5082
|
+
if (!Number.isFinite(value)) return raw2;
|
|
5083
|
+
if (/e/i.test(raw2)) {
|
|
5084
|
+
raw2 = value.toLocaleString("en-US", {
|
|
3498
5085
|
useGrouping: false,
|
|
3499
5086
|
maximumFractionDigits: 20
|
|
3500
5087
|
});
|
|
3501
5088
|
}
|
|
3502
5089
|
}
|
|
3503
|
-
const match =
|
|
3504
|
-
if (!match) return
|
|
5090
|
+
const match = raw2.match(/^([+-]?)(\d*)(?:\.(\d*))?$/);
|
|
5091
|
+
if (!match) return raw2;
|
|
3505
5092
|
const negative = match[1] === "-";
|
|
3506
5093
|
const integer = (match[2] || "0").replace(/^0+(?=\d)/, "");
|
|
3507
5094
|
const fraction = match[3] ?? "";
|
|
@@ -3526,15 +5113,15 @@ function formatCalculatedAmount(value, decimals) {
|
|
|
3526
5113
|
const out = groupDecimal(trimFraction(fixed));
|
|
3527
5114
|
return negative && out !== "0" ? `-${out}` : out;
|
|
3528
5115
|
}
|
|
3529
|
-
function exactAmountTitle(
|
|
3530
|
-
const full = typeof
|
|
5116
|
+
function exactAmountTitle(raw2, shown) {
|
|
5117
|
+
const full = typeof raw2 === "number" ? String(raw2) : raw2.trim();
|
|
3531
5118
|
if (!full || /e/i.test(full)) return void 0;
|
|
3532
5119
|
const normalized = full.includes(".") ? trimFraction(full) : full;
|
|
3533
5120
|
const grouped = groupDecimal(normalized);
|
|
3534
5121
|
return grouped === shown ? void 0 : grouped;
|
|
3535
5122
|
}
|
|
3536
|
-
function sanitizeAmount(
|
|
3537
|
-
const cleaned =
|
|
5123
|
+
function sanitizeAmount(raw2) {
|
|
5124
|
+
const cleaned = raw2.replace(/[^0-9.]/g, "");
|
|
3538
5125
|
const first = cleaned.indexOf(".");
|
|
3539
5126
|
if (first === -1) return cleaned;
|
|
3540
5127
|
return cleaned.slice(0, first + 1) + cleaned.slice(first + 1).replace(/\./g, "");
|
|
@@ -4447,9 +6034,9 @@ function useGroupedAmountInput(amount, onAmount) {
|
|
|
4447
6034
|
});
|
|
4448
6035
|
const onChange = (e) => {
|
|
4449
6036
|
const input = e.target;
|
|
4450
|
-
const
|
|
4451
|
-
caret.current = { input, kept: sanitizeAmount(
|
|
4452
|
-
onAmount(sanitizeAmount(
|
|
6037
|
+
const raw2 = input.value;
|
|
6038
|
+
caret.current = { input, kept: sanitizeAmount(raw2.slice(0, input.selectionEnd ?? raw2.length)).length };
|
|
6039
|
+
onAmount(sanitizeAmount(raw2));
|
|
4453
6040
|
rerender();
|
|
4454
6041
|
};
|
|
4455
6042
|
const onKeyDown = (e) => {
|
|
@@ -4573,11 +6160,11 @@ var METHODS = [
|
|
|
4573
6160
|
function isLiveMethod(m) {
|
|
4574
6161
|
return m === "stablecoin";
|
|
4575
6162
|
}
|
|
4576
|
-
function balanceRank(
|
|
4577
|
-
if (
|
|
6163
|
+
function balanceRank(raw2, decimals) {
|
|
6164
|
+
if (raw2 == null) return 0n;
|
|
4578
6165
|
try {
|
|
4579
6166
|
const d = Number.isFinite(Number(decimals)) ? Math.max(0, Math.trunc(Number(decimals))) : 18;
|
|
4580
|
-
const v = BigInt(
|
|
6167
|
+
const v = BigInt(raw2);
|
|
4581
6168
|
return d <= 18 ? v * 10n ** BigInt(18 - d) : v / 10n ** BigInt(d - 18);
|
|
4582
6169
|
} catch {
|
|
4583
6170
|
return 0n;
|
|
@@ -4617,7 +6204,7 @@ function RouteList(props) {
|
|
|
4617
6204
|
visible.map((r) => {
|
|
4618
6205
|
const selected = props.selectedId === r.id;
|
|
4619
6206
|
const bal = props.balances?.[routeBalanceKey(r)];
|
|
4620
|
-
const
|
|
6207
|
+
const short2 = props.shortIds?.has(r.id) ?? false;
|
|
4621
6208
|
const held = props.heldIds?.has(r.id) ?? false;
|
|
4622
6209
|
return (
|
|
4623
6210
|
// a11y note: a native radio cannot contain the rich
|
|
@@ -4629,7 +6216,7 @@ function RouteList(props) {
|
|
|
4629
6216
|
{
|
|
4630
6217
|
className: "sg-route-item",
|
|
4631
6218
|
"data-selected": selected,
|
|
4632
|
-
"data-short":
|
|
6219
|
+
"data-short": short2 || void 0,
|
|
4633
6220
|
"data-held": held || void 0,
|
|
4634
6221
|
role: "radio",
|
|
4635
6222
|
"aria-checked": selected,
|
|
@@ -4664,7 +6251,7 @@ function RouteList(props) {
|
|
|
4664
6251
|
"bal ",
|
|
4665
6252
|
bal.formatted
|
|
4666
6253
|
] }) : null,
|
|
4667
|
-
|
|
6254
|
+
short2 ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Short" }) : r.state === "DIRECT" ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Direct" }) : r.recommended ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "accent", children: "Best" }) : null,
|
|
4668
6255
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-radio", "aria-hidden": "true" })
|
|
4669
6256
|
] })
|
|
4670
6257
|
]
|
|
@@ -4911,9 +6498,9 @@ function buildChainSearchTerms(chains) {
|
|
|
4911
6498
|
const byId = /* @__PURE__ */ new Map();
|
|
4912
6499
|
const ids = /* @__PURE__ */ new Set([...chains.map((c) => Number(c.chainId)), ...Object.keys(CHAIN_LABELS).map(Number)]);
|
|
4913
6500
|
for (const id of ids) {
|
|
4914
|
-
const
|
|
6501
|
+
const chain2 = chains.find((c) => Number(c.chainId) === id);
|
|
4915
6502
|
const terms = /* @__PURE__ */ new Set();
|
|
4916
|
-
for (const label of [
|
|
6503
|
+
for (const label of [chain2?.displayName, chain2?.name, typeof chain2?.slug === "string" ? chain2.slug : void 0, CHAIN_LABELS[id]]) {
|
|
4917
6504
|
if (label) for (const form of labelForms(label)) terms.add(form);
|
|
4918
6505
|
}
|
|
4919
6506
|
for (const alias of CHAIN_ALIASES[id] ?? []) terms.add(alias);
|
|
@@ -5403,7 +6990,7 @@ function durationLabel(seconds) {
|
|
|
5403
6990
|
}
|
|
5404
6991
|
function TokenButton(props) {
|
|
5405
6992
|
const shown = props.token ? tokenTicker(props.token) : props.symbol ?? "";
|
|
5406
|
-
const
|
|
6993
|
+
const chain2 = props.chainId ? CHAIN_LABELS[props.chainId] || `Chain ${props.chainId}` : "";
|
|
5407
6994
|
return /* @__PURE__ */ jsxRuntime.jsxs(
|
|
5408
6995
|
"button",
|
|
5409
6996
|
{
|
|
@@ -5412,13 +6999,13 @@ function TokenButton(props) {
|
|
|
5412
6999
|
className: "sg-tokbtn",
|
|
5413
7000
|
disabled: props.disabled,
|
|
5414
7001
|
onClick: props.onClick,
|
|
5415
|
-
"aria-label": `${props.label}: ${props.symbol ? `${shown} on ${
|
|
7002
|
+
"aria-label": `${props.label}: ${props.symbol ? `${shown} on ${chain2}` : "select token"}`,
|
|
5416
7003
|
children: [
|
|
5417
7004
|
props.symbol && props.chainId ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
5418
7005
|
/* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: props.symbol, logoUrl: props.token?.logoUrl, chainId: props.chainId, size: "xs" }),
|
|
5419
7006
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-tokbtn-text", children: [
|
|
5420
7007
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-sym", children: shown }),
|
|
5421
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chain", children:
|
|
7008
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chain", children: chain2 })
|
|
5422
7009
|
] })
|
|
5423
7010
|
] }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-text", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-sym", children: "Select" }) }),
|
|
5424
7011
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chev", children: /* @__PURE__ */ jsxRuntime.jsx(ChevronRight, {}) })
|
|
@@ -6060,6 +7647,444 @@ function TxHistoryPanel(props) {
|
|
|
6060
7647
|
selected ? /* @__PURE__ */ jsxRuntime.jsx(TxDetail, { entry: selected, tokens: props.tokens, vaultIcons: props.vaultIcons }) : /* @__PURE__ */ jsxRuntime.jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
|
|
6061
7648
|
] });
|
|
6062
7649
|
}
|
|
7650
|
+
|
|
7651
|
+
// src/provider/solana-wallet.ts
|
|
7652
|
+
var sources = /* @__PURE__ */ new WeakMap();
|
|
7653
|
+
var infos = /* @__PURE__ */ new WeakMap();
|
|
7654
|
+
var connected = /* @__PURE__ */ new WeakMap();
|
|
7655
|
+
var registries = /* @__PURE__ */ new WeakMap();
|
|
7656
|
+
var EMPTY2 = Object.freeze([]);
|
|
7657
|
+
function normalizeSolanaWalletName(name) {
|
|
7658
|
+
return name.trim().toLowerCase().replace(/\s+(wallet|evm|solana)$/i, "");
|
|
7659
|
+
}
|
|
7660
|
+
function solanaWalletInfo(provider) {
|
|
7661
|
+
const standard = "features" in provider;
|
|
7662
|
+
if (standard ? !provider.chains?.some((chain2) => chain2.startsWith("solana:")) || typeof provider.features?.["standard:connect"]?.connect !== "function" : typeof provider.connect !== "function") return null;
|
|
7663
|
+
let info = infos.get(provider);
|
|
7664
|
+
if (!info) {
|
|
7665
|
+
const name = provider.name || (!standard && provider.isPhantom ? "Phantom" : !standard && provider.isSolflare ? "Solflare" : "Solana wallet");
|
|
7666
|
+
info = Object.freeze({ name, icon: standard ? provider.icon : void 0, kind: standard ? "standard" : "legacy" });
|
|
7667
|
+
infos.set(provider, info);
|
|
7668
|
+
sources.set(info, provider);
|
|
7669
|
+
}
|
|
7670
|
+
return info;
|
|
7671
|
+
}
|
|
7672
|
+
function targetWindow(win) {
|
|
7673
|
+
return win ?? (typeof window === "undefined" ? void 0 : window);
|
|
7674
|
+
}
|
|
7675
|
+
function registry(win) {
|
|
7676
|
+
const existing = registries.get(win);
|
|
7677
|
+
if (existing) return existing;
|
|
7678
|
+
const standard = /* @__PURE__ */ new Set();
|
|
7679
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7680
|
+
let snapshot = EMPTY2;
|
|
7681
|
+
const read = () => {
|
|
7682
|
+
const candidates = [...standard].map(solanaWalletInfo);
|
|
7683
|
+
for (const [provider, name] of [[win.phantom?.solana, "Phantom"], [win.solflare, "Solflare"], [win.solana, void 0]]) {
|
|
7684
|
+
if (!provider || typeof provider.connect !== "function") continue;
|
|
7685
|
+
let info = solanaWalletInfo(provider);
|
|
7686
|
+
if (info && name && info.name === "Solana wallet") {
|
|
7687
|
+
info = Object.freeze({ ...info, name });
|
|
7688
|
+
infos.set(provider, info);
|
|
7689
|
+
sources.set(info, provider);
|
|
7690
|
+
}
|
|
7691
|
+
candidates.push(info);
|
|
7692
|
+
}
|
|
7693
|
+
const names = /* @__PURE__ */ new Set();
|
|
7694
|
+
const providers = /* @__PURE__ */ new Set();
|
|
7695
|
+
const next = candidates.filter((info) => {
|
|
7696
|
+
if (!info) return false;
|
|
7697
|
+
const name = normalizeSolanaWalletName(info.name);
|
|
7698
|
+
const provider = sources.get(info);
|
|
7699
|
+
if (names.has(name) || providers.has(provider)) return false;
|
|
7700
|
+
names.add(name);
|
|
7701
|
+
providers.add(provider);
|
|
7702
|
+
return true;
|
|
7703
|
+
});
|
|
7704
|
+
if (next.length !== snapshot.length || next.some((info) => !snapshot.includes(info))) snapshot = Object.freeze(next);
|
|
7705
|
+
return snapshot;
|
|
7706
|
+
};
|
|
7707
|
+
const refresh = () => {
|
|
7708
|
+
const previous = snapshot;
|
|
7709
|
+
read();
|
|
7710
|
+
if (previous !== snapshot) for (const cb of listeners) cb();
|
|
7711
|
+
};
|
|
7712
|
+
const api = {
|
|
7713
|
+
register(...wallets) {
|
|
7714
|
+
const added = wallets.filter((wallet) => !standard.has(wallet));
|
|
7715
|
+
for (const wallet of added) standard.add(wallet);
|
|
7716
|
+
refresh();
|
|
7717
|
+
return () => {
|
|
7718
|
+
for (const wallet of added) standard.delete(wallet);
|
|
7719
|
+
refresh();
|
|
7720
|
+
};
|
|
7721
|
+
}
|
|
7722
|
+
};
|
|
7723
|
+
const result = { read, watch: (cb) => {
|
|
7724
|
+
listeners.add(cb);
|
|
7725
|
+
return () => {
|
|
7726
|
+
listeners.delete(cb);
|
|
7727
|
+
};
|
|
7728
|
+
} };
|
|
7729
|
+
registries.set(win, result);
|
|
7730
|
+
win.addEventListener("wallet-standard:register-wallet", (event) => {
|
|
7731
|
+
const callback = event.detail;
|
|
7732
|
+
if (typeof callback === "function") callback(api);
|
|
7733
|
+
});
|
|
7734
|
+
win.addEventListener("focus", refresh);
|
|
7735
|
+
const EventClass = win.CustomEvent;
|
|
7736
|
+
win.dispatchEvent(new EventClass("wallet-standard:app-ready", { detail: api }));
|
|
7737
|
+
read();
|
|
7738
|
+
return result;
|
|
7739
|
+
}
|
|
7740
|
+
function discoverSolanaWallets(win) {
|
|
7741
|
+
const target = targetWindow(win);
|
|
7742
|
+
return target ? registry(target).read() : EMPTY2;
|
|
7743
|
+
}
|
|
7744
|
+
function watchSolanaWallets(cb, win) {
|
|
7745
|
+
const target = targetWindow(win);
|
|
7746
|
+
if (!target) return () => {
|
|
7747
|
+
};
|
|
7748
|
+
const store = registry(target);
|
|
7749
|
+
const unsubscribe = store.watch(() => cb(store.read()));
|
|
7750
|
+
cb(store.read());
|
|
7751
|
+
return unsubscribe;
|
|
7752
|
+
}
|
|
7753
|
+
function source(info) {
|
|
7754
|
+
const provider = sources.get(info);
|
|
7755
|
+
if (!provider) throw new Error("Solana wallet is no longer available. Discover it before connecting.");
|
|
7756
|
+
return provider;
|
|
7757
|
+
}
|
|
7758
|
+
function validAddress(value) {
|
|
7759
|
+
const address = value?.toString().trim();
|
|
7760
|
+
return address && isSolanaAddress(address) ? address : null;
|
|
7761
|
+
}
|
|
7762
|
+
function accountAddress(accounts) {
|
|
7763
|
+
const account = accounts?.find((item) => !item.chains?.length || item.chains.some((chain2) => chain2.startsWith("solana:")));
|
|
7764
|
+
return validAddress(account?.address);
|
|
7765
|
+
}
|
|
7766
|
+
function connectedSolanaAddress(info) {
|
|
7767
|
+
const provider = source(info);
|
|
7768
|
+
return "features" in provider ? accountAddress(provider.accounts) : validAddress(provider.publicKey);
|
|
7769
|
+
}
|
|
7770
|
+
async function connectSolanaWallet(info, options = {}) {
|
|
7771
|
+
const provider = source(info);
|
|
7772
|
+
let address;
|
|
7773
|
+
if ("features" in provider) {
|
|
7774
|
+
const result = await provider.features["standard:connect"].connect(options.silent ? { silent: true } : void 0);
|
|
7775
|
+
const accounts = result?.accounts ?? provider.accounts;
|
|
7776
|
+
connected.set(provider, accounts ?? []);
|
|
7777
|
+
address = accountAddress(accounts);
|
|
7778
|
+
} else {
|
|
7779
|
+
const result = await provider.connect(options.silent ? { onlyIfTrusted: true } : void 0);
|
|
7780
|
+
address = validAddress(result?.publicKey ?? provider.publicKey);
|
|
7781
|
+
connected.set(provider, address ? [{ address }] : []);
|
|
7782
|
+
}
|
|
7783
|
+
if (!address) throw new Error("The wallet did not return a valid Solana address.");
|
|
7784
|
+
return address;
|
|
7785
|
+
}
|
|
7786
|
+
async function disconnectSolanaWallet(info) {
|
|
7787
|
+
const provider = source(info);
|
|
7788
|
+
if ("features" in provider) await provider.features["standard:disconnect"]?.disconnect();
|
|
7789
|
+
else await provider.disconnect?.();
|
|
7790
|
+
connected.delete(provider);
|
|
7791
|
+
}
|
|
7792
|
+
var CANNOT_PAY = "This wallet cannot pay from Solana here; use a Wallet Standard wallet (Phantom, Solflare, Backpack).";
|
|
7793
|
+
function solanaWalletSigner(info) {
|
|
7794
|
+
const provider = source(info);
|
|
7795
|
+
const accounts = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
|
|
7796
|
+
const address = accountAddress(accounts);
|
|
7797
|
+
if (!connected.has(provider) || !address) throw new Error("Connect a Solana wallet before paying.");
|
|
7798
|
+
if ("features" in provider ? typeof provider.features["solana:signTransaction"]?.signTransaction !== "function" : typeof provider.signTransactionBytes !== "function") throw new Error(CANNOT_PAY);
|
|
7799
|
+
return {
|
|
7800
|
+
publicKey: address,
|
|
7801
|
+
async signTransaction(bytes) {
|
|
7802
|
+
const current = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
|
|
7803
|
+
const account = current?.find((a) => a.address === address);
|
|
7804
|
+
if (!connected.has(provider) || !account || accountAddress(current) !== address) throw new Error("Solana wallet account changed; reconnect before paying.");
|
|
7805
|
+
let signed;
|
|
7806
|
+
if ("features" in provider) {
|
|
7807
|
+
if (!provider.chains.includes("solana:mainnet") || account.chains?.length && !account.chains.includes("solana:mainnet")) throw new Error("This wallet account cannot pay on Solana mainnet.");
|
|
7808
|
+
const result = await provider.features["solana:signTransaction"].signTransaction({ account, chain: "solana:mainnet", transaction: new Uint8Array(bytes) });
|
|
7809
|
+
if (result.length !== 1) throw new Error("Wallet returned an invalid Solana signing result.");
|
|
7810
|
+
signed = result[0]?.signedTransaction;
|
|
7811
|
+
} else signed = await provider.signTransactionBytes(new Uint8Array(bytes));
|
|
7812
|
+
if (!(signed instanceof Uint8Array)) throw new Error("Wallet did not return signed transaction bytes.");
|
|
7813
|
+
return new Uint8Array(signed);
|
|
7814
|
+
}
|
|
7815
|
+
};
|
|
7816
|
+
}
|
|
7817
|
+
function onSolanaAccountChange(info, cb) {
|
|
7818
|
+
const provider = source(info);
|
|
7819
|
+
if ("features" in provider) return provider.features["standard:events"]?.on("change", (change) => {
|
|
7820
|
+
if (change.accounts !== void 0) {
|
|
7821
|
+
connected.set(provider, change.accounts);
|
|
7822
|
+
cb(accountAddress(change.accounts));
|
|
7823
|
+
}
|
|
7824
|
+
}) ?? (() => {
|
|
7825
|
+
});
|
|
7826
|
+
const changed = (key) => {
|
|
7827
|
+
const address = validAddress(key);
|
|
7828
|
+
connected.set(provider, address ? [{ address }] : []);
|
|
7829
|
+
cb(address);
|
|
7830
|
+
};
|
|
7831
|
+
const disconnected = () => {
|
|
7832
|
+
connected.delete(provider);
|
|
7833
|
+
cb(null);
|
|
7834
|
+
};
|
|
7835
|
+
provider.on?.("accountChanged", changed);
|
|
7836
|
+
provider.on?.("connect", changed);
|
|
7837
|
+
provider.on?.("disconnect", disconnected);
|
|
7838
|
+
return () => {
|
|
7839
|
+
const off = provider.off ?? provider.removeListener;
|
|
7840
|
+
off?.call(provider, "accountChanged", changed);
|
|
7841
|
+
off?.call(provider, "connect", changed);
|
|
7842
|
+
off?.call(provider, "disconnect", disconnected);
|
|
7843
|
+
};
|
|
7844
|
+
}
|
|
7845
|
+
|
|
7846
|
+
// src/react/hooks/useSolanaWallet.ts
|
|
7847
|
+
var STORAGE_KEY = "sg-solana-wallet";
|
|
7848
|
+
function remember(name) {
|
|
7849
|
+
try {
|
|
7850
|
+
if (name) window.localStorage.setItem(STORAGE_KEY, name);
|
|
7851
|
+
else window.localStorage.removeItem(STORAGE_KEY);
|
|
7852
|
+
} catch {
|
|
7853
|
+
}
|
|
7854
|
+
}
|
|
7855
|
+
function remembered() {
|
|
7856
|
+
try {
|
|
7857
|
+
return window.localStorage.getItem(STORAGE_KEY);
|
|
7858
|
+
} catch {
|
|
7859
|
+
return null;
|
|
7860
|
+
}
|
|
7861
|
+
}
|
|
7862
|
+
var INITIAL = { address: null, walletName: null, status: "idle", error: null };
|
|
7863
|
+
function useSolanaWallet(provider) {
|
|
7864
|
+
const override = react.useMemo(() => provider ? solanaWalletInfo(provider) : null, [provider]);
|
|
7865
|
+
const [discovered, setDiscovered] = react.useState(discoverSolanaWallets);
|
|
7866
|
+
const wallets = react.useMemo(() => provider ? override ? [override] : [] : discovered, [provider, override, discovered]);
|
|
7867
|
+
const [state, setState] = react.useState(INITIAL);
|
|
7868
|
+
const active = react.useRef(null);
|
|
7869
|
+
const unsubscribe = react.useRef(() => {
|
|
7870
|
+
});
|
|
7871
|
+
const generation = react.useRef(0);
|
|
7872
|
+
const attempted = react.useRef(false);
|
|
7873
|
+
react.useEffect(() => {
|
|
7874
|
+
attempted.current = false;
|
|
7875
|
+
setState(INITIAL);
|
|
7876
|
+
return () => {
|
|
7877
|
+
generation.current += 1;
|
|
7878
|
+
unsubscribe.current();
|
|
7879
|
+
active.current = null;
|
|
7880
|
+
};
|
|
7881
|
+
}, [provider]);
|
|
7882
|
+
react.useEffect(() => provider ? void 0 : watchSolanaWallets(setDiscovered), [provider]);
|
|
7883
|
+
const runConnect = react.useCallback(async (info, silent = false) => {
|
|
7884
|
+
const request = ++generation.current;
|
|
7885
|
+
unsubscribe.current();
|
|
7886
|
+
active.current = null;
|
|
7887
|
+
setState({ ...INITIAL, status: "connecting" });
|
|
7888
|
+
try {
|
|
7889
|
+
const address = await connectSolanaWallet(info, { silent });
|
|
7890
|
+
if (request !== generation.current) return;
|
|
7891
|
+
active.current = info;
|
|
7892
|
+
unsubscribe.current = onSolanaAccountChange(info, (next) => {
|
|
7893
|
+
if (request !== generation.current) return;
|
|
7894
|
+
setState({ address: next, walletName: next ? info.name : null, status: next ? "connected" : "idle", error: null });
|
|
7895
|
+
if (!next) {
|
|
7896
|
+
generation.current += 1;
|
|
7897
|
+
unsubscribe.current();
|
|
7898
|
+
active.current = null;
|
|
7899
|
+
remember(null);
|
|
7900
|
+
}
|
|
7901
|
+
});
|
|
7902
|
+
setState({ address, walletName: info.name, status: "connected", error: null });
|
|
7903
|
+
remember(info.name);
|
|
7904
|
+
return address;
|
|
7905
|
+
} catch (error) {
|
|
7906
|
+
if (request === generation.current) setState(silent ? INITIAL : {
|
|
7907
|
+
...INITIAL,
|
|
7908
|
+
status: "error",
|
|
7909
|
+
error: error instanceof Error ? error.message : "Could not connect a Solana wallet."
|
|
7910
|
+
});
|
|
7911
|
+
}
|
|
7912
|
+
}, []);
|
|
7913
|
+
react.useEffect(() => {
|
|
7914
|
+
if (attempted.current || active.current) return;
|
|
7915
|
+
const name = remembered();
|
|
7916
|
+
const info = wallets.find((wallet) => connectedSolanaAddress(wallet)) ?? (name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : void 0);
|
|
7917
|
+
if (!info) return;
|
|
7918
|
+
attempted.current = true;
|
|
7919
|
+
void runConnect(info, true);
|
|
7920
|
+
}, [wallets, runConnect]);
|
|
7921
|
+
const connect = react.useCallback(async (name) => {
|
|
7922
|
+
if (!name && wallets.length > 1) return wallets;
|
|
7923
|
+
attempted.current = true;
|
|
7924
|
+
const info = name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : wallets[0];
|
|
7925
|
+
if (!info) {
|
|
7926
|
+
setState({ ...INITIAL, status: "error", error: name ? "Solana wallet is not available." : "No Solana wallet found." });
|
|
7927
|
+
return;
|
|
7928
|
+
}
|
|
7929
|
+
return runConnect(info);
|
|
7930
|
+
}, [wallets, runConnect]);
|
|
7931
|
+
const disconnect = react.useCallback(async () => {
|
|
7932
|
+
attempted.current = true;
|
|
7933
|
+
generation.current += 1;
|
|
7934
|
+
unsubscribe.current();
|
|
7935
|
+
const info = active.current;
|
|
7936
|
+
active.current = null;
|
|
7937
|
+
setState(INITIAL);
|
|
7938
|
+
remember(null);
|
|
7939
|
+
if (info) {
|
|
7940
|
+
try {
|
|
7941
|
+
await disconnectSolanaWallet(info);
|
|
7942
|
+
} catch {
|
|
7943
|
+
}
|
|
7944
|
+
}
|
|
7945
|
+
}, []);
|
|
7946
|
+
return { ...state, wallets, connect, disconnect };
|
|
7947
|
+
}
|
|
7948
|
+
|
|
7949
|
+
// src/react/hooks/useRecipient.ts
|
|
7950
|
+
function useRecipient(destinationChainId, hostRecipient, opts = {}) {
|
|
7951
|
+
const recipientFamily = isSolanaChainId(destinationChainId) ? "solana" : "evm";
|
|
7952
|
+
const own = useSolanaWallet();
|
|
7953
|
+
const wallet = opts.solanaWallet ?? own;
|
|
7954
|
+
const [custom, setCustom] = react.useState({});
|
|
7955
|
+
const [open, setOpen] = react.useState(false);
|
|
7956
|
+
const triggerRef = react.useRef(null);
|
|
7957
|
+
const evmManaged = recipientFamily === "evm" && Boolean(opts.sourceIsSolana);
|
|
7958
|
+
const managed = hostRecipient === void 0 && (recipientFamily === "solana" || evmManaged);
|
|
7959
|
+
const error = hostRecipient === void 0 ? null : recipientFamily === "solana" && !isSolanaAddress(hostRecipient) ? "The configured recipient is not a Solana address." : evmManaged && !isAddress(hostRecipient) ? "The configured recipient is not an EVM address." : null;
|
|
7960
|
+
const recipient2 = hostRecipient !== void 0 ? hostRecipient : recipientFamily === "solana" ? custom.solana || wallet.address || void 0 : evmManaged ? custom.evm || opts.evm?.account || void 0 : void 0;
|
|
7961
|
+
const missing = managed && !recipient2;
|
|
7962
|
+
const familyWallet = recipientFamily === "solana" ? { address: wallet.address, wallets: wallet.wallets, connecting: wallet.status === "connecting", error: wallet.error } : { address: opts.evm?.account ?? null, wallets: [], connecting: Boolean(opts.evm?.connecting), error: null };
|
|
7963
|
+
const close = () => {
|
|
7964
|
+
setOpen(false);
|
|
7965
|
+
requestAnimationFrame(() => triggerRef.current?.focus());
|
|
7966
|
+
};
|
|
7967
|
+
const selectAddress = (address) => {
|
|
7968
|
+
setCustom((prev) => ({ ...prev, [recipientFamily]: address }));
|
|
7969
|
+
close();
|
|
7970
|
+
};
|
|
7971
|
+
const connect = async (name) => {
|
|
7972
|
+
if (recipientFamily === "evm") {
|
|
7973
|
+
if (opts.evm?.account) selectAddress("");
|
|
7974
|
+
else opts.evm?.connect();
|
|
7975
|
+
return;
|
|
7976
|
+
}
|
|
7977
|
+
if (wallet.address && !name) {
|
|
7978
|
+
selectAddress("");
|
|
7979
|
+
return;
|
|
7980
|
+
}
|
|
7981
|
+
if (!name && wallet.wallets.length !== 1) {
|
|
7982
|
+
setOpen(true);
|
|
7983
|
+
return;
|
|
7984
|
+
}
|
|
7985
|
+
const address = await wallet.connect(name);
|
|
7986
|
+
if (typeof address === "string") selectAddress("");
|
|
7987
|
+
else setOpen(true);
|
|
7988
|
+
};
|
|
7989
|
+
const recipientFor = (account) => recipientFamily === "solana" || evmManaged ? recipient2 || "" : hostRecipient || account;
|
|
7990
|
+
return { recipientFamily, recipient: recipient2, recipientFor, managed, missing, error, wallet, familyWallet, open: open && managed, show: () => setOpen(true), close, selectAddress, connect, triggerRef };
|
|
7991
|
+
}
|
|
7992
|
+
var short = (address) => `${address.slice(0, 4)}\u2026${address.slice(-4)}`;
|
|
7993
|
+
function RecipientNote({ state, disabled }) {
|
|
7994
|
+
if (state.error) return /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: state.error });
|
|
7995
|
+
if (!state.managed) return null;
|
|
7996
|
+
const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
|
|
7997
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", justifyContent: "center", gap: 6, marginTop: 10, fontSize: 13, color: "var(--sg-text-muted)", flexWrap: "wrap" }, children: [
|
|
7998
|
+
state.recipient ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
7999
|
+
"To ",
|
|
8000
|
+
/* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", title: state.recipient, style: { color: "var(--sg-text)" }, children: short(state.recipient) }),
|
|
8001
|
+
" on ",
|
|
8002
|
+
family,
|
|
8003
|
+
" \xB7 "
|
|
8004
|
+
] }) : null,
|
|
8005
|
+
/* @__PURE__ */ jsxRuntime.jsx("button", { ref: state.triggerRef, type: "button", className: "sg-cp-link", onClick: state.show, disabled, "aria-haspopup": "dialog", children: state.recipient ? "Change" : "Send to a different address" })
|
|
8006
|
+
] });
|
|
8007
|
+
}
|
|
8008
|
+
function RecipientSheet({ state, symbol }) {
|
|
8009
|
+
const [draft, setDraft] = react.useState(state.recipient ?? "");
|
|
8010
|
+
const id = react.useId();
|
|
8011
|
+
const inputRef = react.useRef(null);
|
|
8012
|
+
const sheetRef = react.useRef(null);
|
|
8013
|
+
const closeRef = react.useRef(state.close);
|
|
8014
|
+
closeRef.current = state.close;
|
|
8015
|
+
const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
|
|
8016
|
+
const valid = state.recipientFamily === "solana" ? isSolanaAddress(draft) : /^0x[0-9a-fA-F]{40}$/.test(draft.trim());
|
|
8017
|
+
const invalid = Boolean(draft.trim()) && !valid;
|
|
8018
|
+
const noWallet = state.recipientFamily === "solana" && !state.familyWallet.address && !state.familyWallet.wallets.length;
|
|
8019
|
+
react.useEffect(() => {
|
|
8020
|
+
(noWallet ? inputRef : sheetRef).current?.focus();
|
|
8021
|
+
const onKey = (event) => {
|
|
8022
|
+
if (event.key === "Escape") {
|
|
8023
|
+
event.stopPropagation();
|
|
8024
|
+
closeRef.current();
|
|
8025
|
+
}
|
|
8026
|
+
};
|
|
8027
|
+
document.addEventListener("keydown", onKey, true);
|
|
8028
|
+
return () => document.removeEventListener("keydown", onKey, true);
|
|
8029
|
+
}, [noWallet]);
|
|
8030
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet", role: "dialog", "aria-modal": "true", "aria-label": `${family} recipient`, ref: sheetRef, tabIndex: -1, children: [
|
|
8031
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet-head", children: [
|
|
8032
|
+
/* @__PURE__ */ jsxRuntime.jsxs("h4", { className: "sg-cp-sheet-title", children: [
|
|
8033
|
+
family,
|
|
8034
|
+
" recipient"
|
|
8035
|
+
] }),
|
|
8036
|
+
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cp-close", onClick: state.close, "aria-label": "Close recipient", children: /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m6 6 12 12M18 6 6 18", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }) }) })
|
|
8037
|
+
] }),
|
|
8038
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet-body", children: [
|
|
8039
|
+
/* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cp-card", children: [
|
|
8040
|
+
/* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", style: { margin: "0 0 12px" }, children: [
|
|
8041
|
+
symbol,
|
|
8042
|
+
" is delivered to a ",
|
|
8043
|
+
family,
|
|
8044
|
+
" wallet. Your EVM wallet stays the owner of the order and can cancel it."
|
|
8045
|
+
] }),
|
|
8046
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: () => noWallet ? inputRef.current?.focus() : void state.connect(), busy: state.familyWallet.connecting, children: state.familyWallet.address ? `Use ${short(state.familyWallet.address)}` : `Connect ${family} wallet` }),
|
|
8047
|
+
!state.familyWallet.address && state.familyWallet.wallets.length > 1 ? state.familyWallet.wallets.map((wallet) => /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => void state.connect(wallet.name), disabled: state.familyWallet.connecting, children: wallet.name }, wallet.name)) : null,
|
|
8048
|
+
noWallet ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", children: [
|
|
8049
|
+
"No ",
|
|
8050
|
+
family,
|
|
8051
|
+
" wallet found. Enter a ",
|
|
8052
|
+
family,
|
|
8053
|
+
" address instead."
|
|
8054
|
+
] }) : null,
|
|
8055
|
+
state.familyWallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: state.familyWallet.error }) : null
|
|
8056
|
+
] }),
|
|
8057
|
+
/* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cp-card", children: [
|
|
8058
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-field", style: { margin: 0 }, children: [
|
|
8059
|
+
/* @__PURE__ */ jsxRuntime.jsx("label", { className: "sg-label", htmlFor: id, children: "Send to a different address" }),
|
|
8060
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
|
8061
|
+
"input",
|
|
8062
|
+
{
|
|
8063
|
+
ref: inputRef,
|
|
8064
|
+
id,
|
|
8065
|
+
className: "sg-input sg-mono",
|
|
8066
|
+
style: { fontSize: 14, padding: "12px 14px", border: "1px solid var(--sg-border)", borderRadius: "var(--sg-radius-control)", width: "100%", boxSizing: "border-box", background: "var(--sg-bg)" },
|
|
8067
|
+
placeholder: `${family} recipient address`,
|
|
8068
|
+
"aria-label": `${family} recipient address`,
|
|
8069
|
+
"aria-invalid": invalid || void 0,
|
|
8070
|
+
"aria-describedby": `${id}-help${invalid ? ` ${id}-error` : ""}`,
|
|
8071
|
+
value: draft,
|
|
8072
|
+
onChange: (event) => setDraft(event.target.value),
|
|
8073
|
+
spellCheck: false
|
|
8074
|
+
}
|
|
8075
|
+
)
|
|
8076
|
+
] }),
|
|
8077
|
+
invalid ? /* @__PURE__ */ jsxRuntime.jsx("div", { id: `${id}-error`, children: /* @__PURE__ */ jsxRuntime.jsxs(StatusPanel, { tone: "error", children: [
|
|
8078
|
+
"Not a valid ",
|
|
8079
|
+
family,
|
|
8080
|
+
" address."
|
|
8081
|
+
] }) }) : null,
|
|
8082
|
+
/* @__PURE__ */ jsxRuntime.jsx("p", { id: `${id}-help`, className: "sg-cp-summary-sub", style: { margin: "8px 0 12px" }, children: "Double-check it: a payment sent to a wrong address cannot be recovered." }),
|
|
8083
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { disabled: !valid, onClick: () => state.selectAddress(draft.trim()), children: "Use this address" })
|
|
8084
|
+
] })
|
|
8085
|
+
] })
|
|
8086
|
+
] });
|
|
8087
|
+
}
|
|
6063
8088
|
var IDENTITY_KEY_PREFIX = "sg:link:v1:";
|
|
6064
8089
|
var LEGACY_IDENTITY_KEY = "zd-link-identity";
|
|
6065
8090
|
var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
@@ -6074,10 +8099,10 @@ function storage() {
|
|
|
6074
8099
|
return null;
|
|
6075
8100
|
}
|
|
6076
8101
|
}
|
|
6077
|
-
function parseIdentity(
|
|
6078
|
-
if (!
|
|
8102
|
+
function parseIdentity(raw2) {
|
|
8103
|
+
if (!raw2) return null;
|
|
6079
8104
|
try {
|
|
6080
|
-
const p = JSON.parse(
|
|
8105
|
+
const p = JSON.parse(raw2);
|
|
6081
8106
|
if (!p || typeof p !== "object") return null;
|
|
6082
8107
|
const walletAddress = typeof p.walletAddress === "string" ? p.walletAddress : "";
|
|
6083
8108
|
if (!ADDRESS_RE.test(walletAddress)) return null;
|
|
@@ -6417,14 +8442,17 @@ function PaymentIsland(props) {
|
|
|
6417
8442
|
const exQuotable = !rampMode && exAmountValid && !exOverLimit && Boolean(exFromChainId && exFromAsset && exToChainId && exToAsset);
|
|
6418
8443
|
const payFundingAssets = props.fundingAssets?.length ? props.fundingAssets : ["USDC", "USDT", "USDE"];
|
|
6419
8444
|
const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${payFundingAssets.join(",")}`;
|
|
6420
|
-
const
|
|
8445
|
+
const recipientState = useRecipient(isPay ? null : exToChainId ?? null, props.recipient);
|
|
8446
|
+
const recipient2 = recipientState.recipient;
|
|
8447
|
+
const needsRecipient = !isPay && (recipientState.missing || !!recipientState.error);
|
|
8448
|
+
const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${recipient2 ?? ""}`;
|
|
6421
8449
|
const flow = useFlow({
|
|
6422
8450
|
engine,
|
|
6423
8451
|
wallet,
|
|
6424
8452
|
kind: isPay ? "payment" : "swap",
|
|
6425
8453
|
// Bank settlement parks the card, so gate the network work off too — otherwise the island would
|
|
6426
8454
|
// quote (and fire onQuote) for a payment whose CTA it never shows.
|
|
6427
|
-
enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable,
|
|
8455
|
+
enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable && !needsRecipient,
|
|
6428
8456
|
paramsKey: isPay ? payParamsKey : exParamsKey,
|
|
6429
8457
|
loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
|
|
6430
8458
|
chainId,
|
|
@@ -6436,11 +8464,11 @@ function PaymentIsland(props) {
|
|
|
6436
8464
|
fromToken: exFromAsset,
|
|
6437
8465
|
toToken: exToAsset,
|
|
6438
8466
|
amountIn: normEx,
|
|
6439
|
-
recipient:
|
|
8467
|
+
recipient: recipient2
|
|
6440
8468
|
},
|
|
6441
8469
|
payer
|
|
6442
8470
|
),
|
|
6443
|
-
recipientFor: (account) => isPay ? props.recipient :
|
|
8471
|
+
recipientFor: (account) => isPay ? props.recipient : recipientState.recipientFor(account),
|
|
6444
8472
|
onQuote: config.onQuote,
|
|
6445
8473
|
onSuccess: config.onSuccess,
|
|
6446
8474
|
onError: config.onError
|
|
@@ -6532,27 +8560,27 @@ function PaymentIsland(props) {
|
|
|
6532
8560
|
}, [isPay, exProduct, catalogue, exSourceTokens, exchangeTokens, props.defaultFromAsset, props.defaultToAsset]);
|
|
6533
8561
|
const exDestinationStates = react.useMemo(() => {
|
|
6534
8562
|
if (!catalogue?.ready) return void 0;
|
|
6535
|
-
const
|
|
8563
|
+
const states2 = {};
|
|
6536
8564
|
for (const token of catalogue.tokens) {
|
|
6537
8565
|
const key = balanceKey(Number(token.chainId), token.address);
|
|
6538
8566
|
const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
|
|
6539
8567
|
if (measured) {
|
|
6540
|
-
|
|
8568
|
+
states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
6541
8569
|
continue;
|
|
6542
8570
|
}
|
|
6543
8571
|
const verdict = destinationAvailability(token, catalogue, exFromToken);
|
|
6544
8572
|
if (verdict === "available") {
|
|
6545
8573
|
const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
|
|
6546
|
-
if (limit)
|
|
8574
|
+
if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
|
|
6547
8575
|
continue;
|
|
6548
8576
|
}
|
|
6549
|
-
|
|
8577
|
+
states2[key] = {
|
|
6550
8578
|
disabled: true,
|
|
6551
8579
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
6552
8580
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
6553
8581
|
};
|
|
6554
8582
|
}
|
|
6555
|
-
return
|
|
8583
|
+
return states2;
|
|
6556
8584
|
}, [catalogue, exFromToken]);
|
|
6557
8585
|
const exFromBal = exFrom && exFromToken ? exBalances[balanceKey(exFrom.chainId, exFromToken.address)] : void 0;
|
|
6558
8586
|
const fundingTokens = react.useMemo(() => {
|
|
@@ -6758,12 +8786,12 @@ function PaymentIsland(props) {
|
|
|
6758
8786
|
const activeStep = flow.steps.find((s) => s.state === "active");
|
|
6759
8787
|
const liveMsg = flow.status === "loading" ? isPay ? "Finding the best way to pay." : "Finding the best route." : flow.status === "submitting" ? `${activeStep?.label ?? (isPay ? "Processing your payment" : `Processing your ${verb.present.toLowerCase()}`)} \u2014 in progress.` : flow.status === "success" || flow.status === "pending" ? flow.verdict?.status === "confirmed" ? isPay ? "Payment confirmed on-chain \u2014 the merchant has been settled." : `${verb.past} \u2014 confirmed on-chain.` : isPay ? "Payment sent \u2014 confirmation is still pending." : "Submitted \u2014 confirmation is still pending." : "";
|
|
6760
8788
|
const loading = flow.status === "loading";
|
|
6761
|
-
const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel);
|
|
8789
|
+
const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel) && !needsRecipient;
|
|
6762
8790
|
const ctaLabel = submitting ? isPay ? "Paying\u2026" : kind === "swap" ? "Swapping\u2026" : "Exchanging\u2026" : flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall ? flow.nativeShortfall : loading ? "Getting a price\u2026" : isPay ? sel && selectedVisible ? `Pay ${sel.source.payAmount} ${sel.source.ticker || sel.source.asset}` : "Pay" : kind === "swap" ? "Swap" : "Exchange";
|
|
6763
8791
|
const exPct = (p) => {
|
|
6764
8792
|
if (!exFromBal || !exFromToken) return;
|
|
6765
|
-
const
|
|
6766
|
-
setExAmount(formatUnits(p === 100 ?
|
|
8793
|
+
const raw2 = BigInt(exFromBal.raw);
|
|
8794
|
+
setExAmount(formatUnits(p === 100 ? raw2 : raw2 * BigInt(p) / 100n, assetDecimals(exFromToken)));
|
|
6767
8795
|
};
|
|
6768
8796
|
const exGatewayAmountError = !isPay && exQuotable && flow.status === "error" && flow.steps.length === 0 ? flow.fieldError : null;
|
|
6769
8797
|
const exAmountError = exOverLimit && exLaneLimit ? laneLimitError(exLaneLimit, exLimitSymbol) : exGatewayAmountError;
|
|
@@ -6840,6 +8868,8 @@ function PaymentIsland(props) {
|
|
|
6840
8868
|
}
|
|
6841
8869
|
}
|
|
6842
8870
|
);
|
|
8871
|
+
} else if (recipientState.open && !isPay) {
|
|
8872
|
+
body = /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: destTicker });
|
|
6843
8873
|
} else if (rampMode) {
|
|
6844
8874
|
body = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-soonpanel", children: [
|
|
6845
8875
|
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-soonpanel-title", children: mode === "onramp" ? "Buying with fiat is coming soon" : "Cashing out to fiat is coming soon" }),
|
|
@@ -6890,7 +8920,7 @@ function PaymentIsland(props) {
|
|
|
6890
8920
|
] }),
|
|
6891
8921
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
|
|
6892
8922
|
confirmed ? "Confirmed on-chain" : "Confirmation pending",
|
|
6893
|
-
|
|
8923
|
+
(flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : ""
|
|
6894
8924
|
] })
|
|
6895
8925
|
] }),
|
|
6896
8926
|
!identityMatchesWallet ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-remember", children: [
|
|
@@ -7006,16 +9036,23 @@ function PaymentIsland(props) {
|
|
|
7006
9036
|
quoteError ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: flow.error || "Couldn't get a price right now." }) : null,
|
|
7007
9037
|
walletError ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: flow.error || "The wallet could not complete this payment." }) : null,
|
|
7008
9038
|
submitting || walletError ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { variant: "rich", steps: flow.steps, verdict: flow.verdict }) : null,
|
|
7009
|
-
/* @__PURE__ */ jsxRuntime.
|
|
7010
|
-
Button,
|
|
7011
|
-
|
|
7012
|
-
|
|
7013
|
-
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
|
|
7017
|
-
|
|
7018
|
-
|
|
9039
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
9040
|
+
recipientState.missing && !isPay && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
|
|
9041
|
+
"Connect ",
|
|
9042
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
9043
|
+
" wallet"
|
|
9044
|
+
] }) : quoteError ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.reload, children: "Try again" }) : walletError ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: payReady ? flow.submit : void 0, disabled: !payReady, children: "Try again" }) : /* @__PURE__ */ jsxRuntime.jsx(
|
|
9045
|
+
Button,
|
|
9046
|
+
{
|
|
9047
|
+
onClick: payReady && !submitting && !flow.insufficient && !flow.nativeShortfall && !loading ? flow.submit : void 0,
|
|
9048
|
+
busy: submitting || loading,
|
|
9049
|
+
softDisabled: submitting,
|
|
9050
|
+
disabled: !submitting && (!payReady || flow.insufficient || !!flow.nativeShortfall || loading),
|
|
9051
|
+
children: ctaLabel
|
|
9052
|
+
}
|
|
9053
|
+
),
|
|
9054
|
+
!isPay ? /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null
|
|
9055
|
+
] })
|
|
7019
9056
|
] })
|
|
7020
9057
|
] });
|
|
7021
9058
|
}
|
|
@@ -7477,6 +9514,9 @@ function StableGenieSwap(props) {
|
|
|
7477
9514
|
const [toChainId, setToChainId] = react.useState(props.defaultToChainId ?? 8453);
|
|
7478
9515
|
const [toAsset, setToAsset] = react.useState(props.defaultToAsset ?? "USDC");
|
|
7479
9516
|
const [amount, setAmount] = react.useState(props.defaultAmount ?? "");
|
|
9517
|
+
const recipientState = useRecipient(toChainId, props.recipient);
|
|
9518
|
+
const recipient2 = recipientState.recipient;
|
|
9519
|
+
const needsRecipient = recipientState.missing || !!recipientState.error;
|
|
7480
9520
|
const [catalogue, setCatalogue] = react.useState(null);
|
|
7481
9521
|
react.useEffect(() => {
|
|
7482
9522
|
if (props.variant === "pill") return;
|
|
@@ -7506,15 +9546,15 @@ function StableGenieSwap(props) {
|
|
|
7506
9546
|
}, [catalogue]);
|
|
7507
9547
|
const amountValid = /^\d+(\.\d+)?$/.test(amount.replace(",", ".")) && Number(amount.replace(",", ".")) > 0;
|
|
7508
9548
|
const enabled = amountValid && props.variant !== "pill";
|
|
7509
|
-
const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${
|
|
9549
|
+
const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${recipient2 ?? ""}`;
|
|
7510
9550
|
const flow = useFlow({
|
|
7511
9551
|
engine,
|
|
7512
9552
|
wallet,
|
|
7513
9553
|
kind: "swap",
|
|
7514
|
-
enabled,
|
|
9554
|
+
enabled: enabled && !needsRecipient,
|
|
7515
9555
|
paramsKey,
|
|
7516
|
-
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient:
|
|
7517
|
-
recipientFor:
|
|
9556
|
+
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient: recipient2 }, payer),
|
|
9557
|
+
recipientFor: recipientState.recipientFor,
|
|
7518
9558
|
onQuote: config.onQuote,
|
|
7519
9559
|
onSuccess: config.onSuccess,
|
|
7520
9560
|
onError: config.onError
|
|
@@ -7557,6 +9597,7 @@ function StableGenieSwap(props) {
|
|
|
7557
9597
|
if (hist && wallet.account) {
|
|
7558
9598
|
return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) });
|
|
7559
9599
|
}
|
|
9600
|
+
if (recipientState.open) return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: toAsset }) });
|
|
7560
9601
|
if (flow.status === "success" || flow.status === "pending") {
|
|
7561
9602
|
return /* @__PURE__ */ jsxRuntime.jsxs(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: [
|
|
7562
9603
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
@@ -7568,7 +9609,7 @@ function StableGenieSwap(props) {
|
|
|
7568
9609
|
] }),
|
|
7569
9610
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
|
|
7570
9611
|
flow.verdict?.status === "confirmed" ? "Confirmed on-chain" : "Submitted \u2014 awaiting confirmation",
|
|
7571
|
-
props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
9612
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
7572
9613
|
] })
|
|
7573
9614
|
] }),
|
|
7574
9615
|
lastTxOwned ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cta-wrap", children: /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: flow.lastTxEntry }), children: "View transaction" }) }) : null
|
|
@@ -7597,11 +9638,169 @@ function StableGenieSwap(props) {
|
|
|
7597
9638
|
flow.selected && flow.status !== "loading" ? /* @__PURE__ */ jsxRuntime.jsx(CompliancePanel, { compliance: flow.selected.quote.compliance, direct: flow.selected.state === "DIRECT" }) : null,
|
|
7598
9639
|
submitting ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { steps: flow.steps }) : null,
|
|
7599
9640
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
7600
|
-
!wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : /* @__PURE__ */ jsxRuntime.
|
|
9641
|
+
!wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : recipientState.missing && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
|
|
9642
|
+
"Connect ",
|
|
9643
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
9644
|
+
" wallet"
|
|
9645
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.submit, busy: submitting, disabled: needsRecipient || !flow.selected || flow.insufficient || !!flow.nativeShortfall || !enabled || flow.status === "loading", children: swapLabel }),
|
|
9646
|
+
/* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }),
|
|
7601
9647
|
wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
|
|
7602
9648
|
] })
|
|
7603
9649
|
] });
|
|
7604
9650
|
}
|
|
9651
|
+
function keyOf(a) {
|
|
9652
|
+
return `${a.fromSymbol}|${a.toChainId}|${a.toSymbol}|${a.amount}|${a.owner ?? ""}|${a.payer ?? ""}|${a.recipient ?? ""}`;
|
|
9653
|
+
}
|
|
9654
|
+
function useSolanaSourceFlow(args) {
|
|
9655
|
+
const { engine, enabled, fromSymbol, fromMint, toChainId, toSymbol, amount, owner, payer, recipient: recipient2 } = args;
|
|
9656
|
+
const [status, setStatus] = react.useState("idle");
|
|
9657
|
+
const [preview, setPreview] = react.useState(null);
|
|
9658
|
+
const [plan, setPlan] = react.useState(null);
|
|
9659
|
+
const [error, setError] = react.useState(null);
|
|
9660
|
+
const [balanceRaw, setBalanceRaw] = react.useState(void 0);
|
|
9661
|
+
const [cost, setCost] = react.useState(null);
|
|
9662
|
+
const [progress, setProgress] = react.useState(null);
|
|
9663
|
+
const [signature, setSignature] = react.useState(null);
|
|
9664
|
+
const [lastTxEntry, setLastTxEntry] = react.useState(null);
|
|
9665
|
+
const [sent, setSent] = react.useState(null);
|
|
9666
|
+
const [nonce, setNonce] = react.useState(0);
|
|
9667
|
+
const req = react.useRef(0);
|
|
9668
|
+
const busy = react.useRef(false);
|
|
9669
|
+
const latest = react.useRef(args);
|
|
9670
|
+
latest.current = args;
|
|
9671
|
+
const planKey = react.useRef(null);
|
|
9672
|
+
const planArgs = react.useRef(null);
|
|
9673
|
+
const changedWhileBusy = react.useRef(false);
|
|
9674
|
+
const addressed = Boolean(owner && payer && recipient2);
|
|
9675
|
+
const key = keyOf(args);
|
|
9676
|
+
react.useEffect(() => {
|
|
9677
|
+
const id = ++req.current;
|
|
9678
|
+
if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
|
|
9679
|
+
setStatus("idle");
|
|
9680
|
+
setPreview(null);
|
|
9681
|
+
setPlan(null);
|
|
9682
|
+
setError(null);
|
|
9683
|
+
setCost(null);
|
|
9684
|
+
return;
|
|
9685
|
+
}
|
|
9686
|
+
if (busy.current) {
|
|
9687
|
+
changedWhileBusy.current = true;
|
|
9688
|
+
return;
|
|
9689
|
+
}
|
|
9690
|
+
setStatus("quoting");
|
|
9691
|
+
planKey.current = null;
|
|
9692
|
+
planArgs.current = null;
|
|
9693
|
+
setError(null);
|
|
9694
|
+
setPlan(null);
|
|
9695
|
+
setCost(null);
|
|
9696
|
+
const timer2 = setTimeout(async () => {
|
|
9697
|
+
try {
|
|
9698
|
+
if (!addressed) {
|
|
9699
|
+
const next = await engine.previewSolanaSource({ toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount });
|
|
9700
|
+
if (id !== req.current) return;
|
|
9701
|
+
setPreview(next);
|
|
9702
|
+
setStatus("ready");
|
|
9703
|
+
return;
|
|
9704
|
+
}
|
|
9705
|
+
const input = { toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount, owner, sender: payer, recipient: recipient2 };
|
|
9706
|
+
const quoted = await engine.quoteSolanaSource(input);
|
|
9707
|
+
const built = await engine.buildSolanaSourcePlan(input, quoted);
|
|
9708
|
+
if (id !== req.current) return;
|
|
9709
|
+
planKey.current = key;
|
|
9710
|
+
planArgs.current = { ...latest.current };
|
|
9711
|
+
setPreview(quoted);
|
|
9712
|
+
setPlan(built);
|
|
9713
|
+
setStatus("ready");
|
|
9714
|
+
engine.simulateSolanaCost(built).then(
|
|
9715
|
+
(c) => id === req.current && setCost(c),
|
|
9716
|
+
() => id === req.current && setCost(null)
|
|
9717
|
+
);
|
|
9718
|
+
} catch (e) {
|
|
9719
|
+
if (id !== req.current) return;
|
|
9720
|
+
setStatus("error");
|
|
9721
|
+
setError(e instanceof Error ? e.message : String(e));
|
|
9722
|
+
}
|
|
9723
|
+
}, 350);
|
|
9724
|
+
return () => clearTimeout(timer2);
|
|
9725
|
+
}, [engine, enabled, key, addressed, nonce]);
|
|
9726
|
+
react.useEffect(() => {
|
|
9727
|
+
let alive = true;
|
|
9728
|
+
setBalanceRaw(void 0);
|
|
9729
|
+
if (!enabled || !payer || !fromMint) return;
|
|
9730
|
+
engine.readSolanaBalance(payer, fromMint).then((b) => {
|
|
9731
|
+
if (alive) setBalanceRaw(b);
|
|
9732
|
+
});
|
|
9733
|
+
return () => {
|
|
9734
|
+
alive = false;
|
|
9735
|
+
};
|
|
9736
|
+
}, [engine, enabled, payer, fromMint]);
|
|
9737
|
+
const needsPreparation = plan ? solanaPlanNeedsPreparation(plan) : false;
|
|
9738
|
+
const run = react.useCallback(async () => {
|
|
9739
|
+
const current = plan;
|
|
9740
|
+
if (!current || busy.current) return;
|
|
9741
|
+
if (planKey.current !== keyOf(latest.current)) {
|
|
9742
|
+
setError("The order changed; review the new quote before signing.");
|
|
9743
|
+
setNonce((n) => n + 1);
|
|
9744
|
+
return;
|
|
9745
|
+
}
|
|
9746
|
+
busy.current = true;
|
|
9747
|
+
let broadcast = false;
|
|
9748
|
+
setError(null);
|
|
9749
|
+
setStatus(needsPreparation ? "preparing" : "submitting");
|
|
9750
|
+
try {
|
|
9751
|
+
const result = await engine.executeSolanaPlanStaged({ plan: current, signer: latest.current.signer(), onProgress: setProgress });
|
|
9752
|
+
if (result.status === "prepared") {
|
|
9753
|
+
setStatus("prepared");
|
|
9754
|
+
return;
|
|
9755
|
+
}
|
|
9756
|
+
const a = planArgs.current ?? latest.current;
|
|
9757
|
+
broadcast = true;
|
|
9758
|
+
setSent({ receive: current.preview.receive, toTicker: a.toTicker, recipient: a.recipient ?? "" });
|
|
9759
|
+
setSignature(result.signature);
|
|
9760
|
+
setStatus("sent");
|
|
9761
|
+
const entry = engine.recordTransaction({
|
|
9762
|
+
kind: "swap",
|
|
9763
|
+
hash: result.signature,
|
|
9764
|
+
txKind: "submitOrder",
|
|
9765
|
+
chainId: SOLANA_CHAIN_ID,
|
|
9766
|
+
chainName: a.chainName,
|
|
9767
|
+
fromAsset: a.fromSymbol ?? "",
|
|
9768
|
+
toAsset: a.toSymbol ?? "",
|
|
9769
|
+
fromTicker: a.fromTicker,
|
|
9770
|
+
toTicker: a.toTicker,
|
|
9771
|
+
payAmount: a.amount,
|
|
9772
|
+
receiveAmount: current.preview.receive,
|
|
9773
|
+
account: a.owner ?? "",
|
|
9774
|
+
recipient: a.recipient ?? "",
|
|
9775
|
+
settlement: "escrow",
|
|
9776
|
+
status: "submitted"
|
|
9777
|
+
});
|
|
9778
|
+
setLastTxEntry(entry.hash ? entry : null);
|
|
9779
|
+
appendTxHistory(a.owner, entry);
|
|
9780
|
+
} catch (e) {
|
|
9781
|
+
const err2 = e instanceof Error ? e : new Error(String(e));
|
|
9782
|
+
setStatus("failed");
|
|
9783
|
+
setError(err2.message);
|
|
9784
|
+
latest.current.onError?.(err2);
|
|
9785
|
+
} finally {
|
|
9786
|
+
busy.current = false;
|
|
9787
|
+
if (changedWhileBusy.current) {
|
|
9788
|
+
changedWhileBusy.current = false;
|
|
9789
|
+
if (!broadcast && planKey.current !== keyOf(latest.current)) setNonce((n) => n + 1);
|
|
9790
|
+
}
|
|
9791
|
+
}
|
|
9792
|
+
}, [engine, plan, needsPreparation]);
|
|
9793
|
+
const insufficient = balanceRaw !== void 0 && plan ? balanceRaw < BigInt(plan.expected.bidTokenAmount) : false;
|
|
9794
|
+
const solShort = cost ? !cost.sufficient : false;
|
|
9795
|
+
const reset = react.useCallback(() => {
|
|
9796
|
+
setSignature(null);
|
|
9797
|
+
setLastTxEntry(null);
|
|
9798
|
+
setSent(null);
|
|
9799
|
+
setProgress(null);
|
|
9800
|
+
setNonce((n) => n + 1);
|
|
9801
|
+
}, []);
|
|
9802
|
+
return { status, preview, plan, error, balanceRaw, cost, progress, signature, lastTxEntry, sent, addressed, needsPreparation, insufficient, solShort, run, reset };
|
|
9803
|
+
}
|
|
7605
9804
|
function QuoteSheet(props) {
|
|
7606
9805
|
const sheetRef = react.useRef(null);
|
|
7607
9806
|
const onCloseRef = react.useRef(props.onClose);
|
|
@@ -7710,7 +9909,7 @@ function ExchangeCard(props) {
|
|
|
7710
9909
|
react.useEffect(() => {
|
|
7711
9910
|
if (isPill) return;
|
|
7712
9911
|
let alive = true;
|
|
7713
|
-
engine.fetchCatalogue(allowed, product).then((next) => {
|
|
9912
|
+
engine.fetchCatalogue(allowed, product, { solanaSources: true }).then((next) => {
|
|
7714
9913
|
if (alive) setCatalogue(next);
|
|
7715
9914
|
});
|
|
7716
9915
|
return () => {
|
|
@@ -7743,6 +9942,16 @@ function ExchangeCard(props) {
|
|
|
7743
9942
|
() => props.defaultToChainId && props.defaultToAsset ? { chainId: props.defaultToChainId, symbol: symbolKey(props.defaultToAsset) } : null
|
|
7744
9943
|
);
|
|
7745
9944
|
const [amount, setAmount] = react.useState(props.defaultAmount ?? "");
|
|
9945
|
+
const solanaWallet = useSolanaWallet();
|
|
9946
|
+
const [payerChooser, setPayerChooser] = react.useState(false);
|
|
9947
|
+
const sourceIsSolana = isSolanaChainId(from?.chainId);
|
|
9948
|
+
const recipientState = useRecipient(to?.chainId ?? null, props.recipient, {
|
|
9949
|
+
solanaWallet,
|
|
9950
|
+
sourceIsSolana,
|
|
9951
|
+
evm: { account: wallet.account, connect: wallet.connect, connecting: wallet.connecting }
|
|
9952
|
+
});
|
|
9953
|
+
const recipient2 = recipientState.recipient;
|
|
9954
|
+
const needsRecipient = recipientState.missing || !!recipientState.error;
|
|
7746
9955
|
const onInputChange = react.useRef(props.onInputChange);
|
|
7747
9956
|
onInputChange.current = props.onInputChange;
|
|
7748
9957
|
const fromChainId = from?.chainId ?? null;
|
|
@@ -7773,27 +9982,27 @@ function ExchangeCard(props) {
|
|
|
7773
9982
|
}, [product, catalogue, sourceTokens, tokens, props.defaultFromAsset, props.defaultToAsset]);
|
|
7774
9983
|
const destinationStates = react.useMemo(() => {
|
|
7775
9984
|
if (!catalogue?.ready) return void 0;
|
|
7776
|
-
const
|
|
9985
|
+
const states2 = {};
|
|
7777
9986
|
for (const token of catalogue.tokens) {
|
|
7778
9987
|
const key = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
|
|
7779
9988
|
const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
|
|
7780
9989
|
if (measured) {
|
|
7781
|
-
|
|
9990
|
+
states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
7782
9991
|
continue;
|
|
7783
9992
|
}
|
|
7784
9993
|
const verdict = destinationAvailability(token, catalogue, fromToken);
|
|
7785
9994
|
if (verdict === "available") {
|
|
7786
9995
|
const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
|
|
7787
|
-
if (limit)
|
|
9996
|
+
if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
|
|
7788
9997
|
continue;
|
|
7789
9998
|
}
|
|
7790
|
-
|
|
9999
|
+
states2[key] = {
|
|
7791
10000
|
disabled: true,
|
|
7792
10001
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
7793
10002
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
7794
10003
|
};
|
|
7795
10004
|
}
|
|
7796
|
-
return
|
|
10005
|
+
return states2;
|
|
7797
10006
|
}, [catalogue, fromToken]);
|
|
7798
10007
|
const toPickerVisible = react.useMemo(
|
|
7799
10008
|
() => destinationStates ? toPickerTokens.filter((t) => !destinationStates[`${Number(t.chainId)}:${String(t.address || "").toLowerCase()}`]?.disabled) : toPickerTokens,
|
|
@@ -7838,7 +10047,7 @@ function ExchangeCard(props) {
|
|
|
7838
10047
|
if (id === balReq.current) setBalances(res);
|
|
7839
10048
|
});
|
|
7840
10049
|
}, [engine, wallet.account, tokens]);
|
|
7841
|
-
const
|
|
10050
|
+
const evmFromBal = from && fromToken ? balances[balanceKey(from.chainId, fromToken.address)] : void 0;
|
|
7842
10051
|
const [prices, setPrices] = react.useState({});
|
|
7843
10052
|
react.useEffect(() => {
|
|
7844
10053
|
if (isPill) return;
|
|
@@ -7852,24 +10061,47 @@ function ExchangeCard(props) {
|
|
|
7852
10061
|
alive = false;
|
|
7853
10062
|
};
|
|
7854
10063
|
}, [engine, from?.symbol, to?.symbol, isPill]);
|
|
7855
|
-
const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${
|
|
10064
|
+
const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${recipient2 ?? ""}`;
|
|
7856
10065
|
const flow = useFlow({
|
|
7857
10066
|
engine,
|
|
7858
10067
|
wallet,
|
|
7859
10068
|
kind: "swap",
|
|
7860
|
-
enabled: quotable && !isPill,
|
|
10069
|
+
enabled: quotable && !isPill && !needsRecipient && !sourceIsSolana,
|
|
7861
10070
|
paramsKey,
|
|
7862
|
-
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient:
|
|
7863
|
-
recipientFor:
|
|
10071
|
+
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: recipient2 }, payer),
|
|
10072
|
+
recipientFor: recipientState.recipientFor,
|
|
7864
10073
|
onQuote: config.onQuote,
|
|
7865
10074
|
onSuccess: config.onSuccess,
|
|
7866
10075
|
onError: config.onError
|
|
7867
10076
|
});
|
|
10077
|
+
const solActive = sourceIsSolana && !isPill && !rampMode;
|
|
10078
|
+
const solFlow = useSolanaSourceFlow({
|
|
10079
|
+
engine,
|
|
10080
|
+
enabled: solActive && quotable && !recipientState.error,
|
|
10081
|
+
fromSymbol: from?.symbol ?? null,
|
|
10082
|
+
fromMint: fromToken?.address ?? null,
|
|
10083
|
+
toChainId: to?.chainId ?? null,
|
|
10084
|
+
toSymbol: to ? toSymbol : null,
|
|
10085
|
+
amount: normalizedAmount,
|
|
10086
|
+
owner: wallet.account,
|
|
10087
|
+
payer: solanaWallet.address,
|
|
10088
|
+
recipient: recipient2,
|
|
10089
|
+
signer: () => {
|
|
10090
|
+
const info = solanaWallet.wallets.find((w) => normalizeSolanaWalletName(w.name) === normalizeSolanaWalletName(solanaWallet.walletName ?? ""));
|
|
10091
|
+
if (!info) throw new Error("Connect a Solana wallet to pay from Solana.");
|
|
10092
|
+
return solanaWalletSigner(info);
|
|
10093
|
+
},
|
|
10094
|
+
chainName: "Solana",
|
|
10095
|
+
fromTicker,
|
|
10096
|
+
toTicker,
|
|
10097
|
+
onError: config.onError
|
|
10098
|
+
});
|
|
10099
|
+
const fromBal = solActive ? solFlow.balanceRaw !== void 0 && fromToken ? { ...evmFromBal, raw: solFlow.balanceRaw.toString(), formatted: formatUnits(solFlow.balanceRaw, assetDecimals(fromToken)) } : void 0 : evmFromBal;
|
|
7868
10100
|
const [preview, setPreview] = react.useState({ status: "idle" });
|
|
7869
10101
|
const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
|
|
7870
10102
|
const prevReq = react.useRef(0);
|
|
7871
10103
|
react.useEffect(() => {
|
|
7872
|
-
if (isPill || wallet.account || !quotable) {
|
|
10104
|
+
if (isPill || sourceIsSolana || wallet.account && !needsRecipient || !quotable) {
|
|
7873
10105
|
prevReq.current += 1;
|
|
7874
10106
|
setPreview({ status: "idle" });
|
|
7875
10107
|
return;
|
|
@@ -7877,23 +10109,24 @@ function ExchangeCard(props) {
|
|
|
7877
10109
|
const id = ++prevReq.current;
|
|
7878
10110
|
setPreview({ status: "loading" });
|
|
7879
10111
|
const timer2 = setTimeout(() => {
|
|
7880
|
-
engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient:
|
|
10112
|
+
engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: recipient2 }, wallet.account ?? void 0).then((data) => {
|
|
7881
10113
|
if (id === prevReq.current) setPreview({ status: "ready", data });
|
|
7882
10114
|
}).catch((e) => {
|
|
7883
10115
|
if (id === prevReq.current) setPreview({ status: "error", error: e instanceof Error ? e.message : String(e), fieldError: amountFieldError(e) });
|
|
7884
10116
|
});
|
|
7885
10117
|
}, 350);
|
|
7886
10118
|
return () => clearTimeout(timer2);
|
|
7887
|
-
}, [engine, wallet.account, quotable, paramsKey, returnedAt2]);
|
|
7888
|
-
const
|
|
7889
|
-
const
|
|
10119
|
+
}, [engine, wallet.account, quotable, paramsKey, returnedAt2, needsRecipient, sourceIsSolana]);
|
|
10120
|
+
const connected2 = Boolean(wallet.account);
|
|
10121
|
+
const addressed = connected2 && !needsRecipient;
|
|
10122
|
+
const submitting = solActive ? solFlow.status === "preparing" || solFlow.status === "submitting" : flow.status === "submitting";
|
|
7890
10123
|
const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
|
|
7891
|
-
const quoting =
|
|
7892
|
-
const quoteError = !quotable ? null :
|
|
7893
|
-
const gatewayAmountError = !quoteError ? null :
|
|
10124
|
+
const quoting = solActive ? solFlow.status === "quoting" : addressed ? flow.status === "loading" : preview.status === "loading";
|
|
10125
|
+
const quoteError = !quotable ? null : solActive ? solFlow.status === "error" || solFlow.status === "failed" ? solFlow.error : null : addressed ? flow.status === "error" ? flow.error : null : preview.status === "error" ? preview.error ?? "No route." : null;
|
|
10126
|
+
const gatewayAmountError = !quoteError || solActive ? null : addressed ? flow.fieldError : preview.fieldError ?? null;
|
|
7894
10127
|
const amountError = overLimit && laneLimit ? laneLimitError(laneLimit, limitSymbol) : gatewayAmountError;
|
|
7895
10128
|
const amountNote = mode === "exchange" ? amountError || (laneLimit ? laneLimitHint(laneLimit, limitSymbol) : null) : null;
|
|
7896
|
-
const receive =
|
|
10129
|
+
const receive = solActive ? solFlow.preview?.receive : addressed ? flow.selected?.receive.amount : preview.data?.receive;
|
|
7897
10130
|
const receiveOutRef = react.useRef(null);
|
|
7898
10131
|
const receiveSideRef = react.useRef(null);
|
|
7899
10132
|
const receiveShown = `${receive ?? ""}|${quoting}|${toTicker}`;
|
|
@@ -7906,17 +10139,17 @@ function ExchangeCard(props) {
|
|
|
7906
10139
|
return void 0;
|
|
7907
10140
|
}
|
|
7908
10141
|
}, [toToken]);
|
|
7909
|
-
const meta =
|
|
10142
|
+
const meta = solActive ? solFlow.preview ? { bridge: solFlow.preview.bridge || "ZeroDelta", feeBps: solFlow.preview.feeBps, duration: solFlow.preview.estimatedDuration } : null : addressed ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
|
|
7910
10143
|
const pct = (p) => {
|
|
7911
10144
|
if (!fromBal || !fromToken) return;
|
|
7912
|
-
const
|
|
7913
|
-
setAmount(formatUnits(p === 100 ?
|
|
10145
|
+
const raw2 = BigInt(fromBal.raw);
|
|
10146
|
+
setAmount(formatUnits(p === 100 ? raw2 : raw2 * BigInt(p) / 100n, assetDecimals(fromToken)));
|
|
7914
10147
|
};
|
|
7915
10148
|
const title = config.title || (mode === "onramp" ? "Buy stablecoins" : mode === "offramp" ? "Cash out" : "Exchange");
|
|
7916
10149
|
const soonLabel = mode === "onramp" ? "On-ramp coming soon" : "Off-ramp coming soon";
|
|
7917
|
-
const quotePaused =
|
|
7918
|
-
const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" :
|
|
7919
|
-
const selected =
|
|
10150
|
+
const quotePaused = solActive ? false : addressed ? flow.quotePaused : idle2 && preview.status === "ready";
|
|
10151
|
+
const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected2 && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
|
|
10152
|
+
const selected = addressed ? flow.selected : null;
|
|
7920
10153
|
const hasQuote = Boolean(quotable && !quoting && !quoteError && receive);
|
|
7921
10154
|
const nativeWei = (() => {
|
|
7922
10155
|
try {
|
|
@@ -7926,7 +10159,7 @@ function ExchangeCard(props) {
|
|
|
7926
10159
|
return 0n;
|
|
7927
10160
|
}
|
|
7928
10161
|
})();
|
|
7929
|
-
const networkFee = nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
|
|
10162
|
+
const networkFee = solActive ? solFlow.cost ? `~${(solFlow.cost.lamports / 1e9).toFixed(6)} SOL` : "Paid in SOL" : nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
|
|
7930
10163
|
const eta = durationLabel(meta?.duration);
|
|
7931
10164
|
const rate = hasQuote && receive && Number(normalizedAmount) > 0 ? (Number(receive) / Number(normalizedAmount)).toFixed(6) : null;
|
|
7932
10165
|
const rateRows = hasQuote ? [{ label: "Network fee", value: networkFee }, ...eta ? [{ label: "Estimated time", value: eta }] : []] : [];
|
|
@@ -7943,8 +10176,8 @@ function ExchangeCard(props) {
|
|
|
7943
10176
|
setTo(from);
|
|
7944
10177
|
};
|
|
7945
10178
|
const walletSlot = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-head-tools", children: [
|
|
7946
|
-
|
|
7947
|
-
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-wallet", "data-connected":
|
|
10179
|
+
connected2 ? /* @__PURE__ */ jsxRuntime.jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }) : null,
|
|
10180
|
+
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-wallet", "data-connected": connected2 || void 0, onClick: connected2 ? void 0 : wallet.connect, disabled: wallet.connecting, children: connected2 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
7948
10181
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
|
|
7949
10182
|
" ",
|
|
7950
10183
|
shortAddress2(wallet.account)
|
|
@@ -7992,7 +10225,7 @@ function ExchangeCard(props) {
|
|
|
7992
10225
|
}
|
|
7993
10226
|
);
|
|
7994
10227
|
const rateBox = (open) => /* @__PURE__ */ jsxRuntime.jsx(RateBox, { rate, fromSymbol: from?.symbol ?? "", fromLogoUrl: fromToken?.logoUrl, toTicker, rows: rateRows, defaultOpen: open, paused: quotePaused });
|
|
7995
|
-
const sheetBody = sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
|
|
10228
|
+
const sheetBody = recipientState.open ? /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: toTicker }) : sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
|
|
7996
10229
|
QuoteSheet,
|
|
7997
10230
|
{
|
|
7998
10231
|
onClose: closeSheet,
|
|
@@ -8009,8 +10242,33 @@ function ExchangeCard(props) {
|
|
|
8009
10242
|
legs: selected && selected.legs.length > 1 ? selected.legs : void 0
|
|
8010
10243
|
}
|
|
8011
10244
|
) : null;
|
|
10245
|
+
const connectPayer = async () => {
|
|
10246
|
+
const result = await solanaWallet.connect();
|
|
10247
|
+
setPayerChooser(Array.isArray(result) && result.length > 1);
|
|
10248
|
+
};
|
|
10249
|
+
const solanaCta = !solanaWallet.address ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
10250
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: () => void connectPayer(), busy: solanaWallet.status === "connecting", children: "Connect Solana wallet" }),
|
|
10251
|
+
payerChooser ? solanaWallet.wallets.map((w) => /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => void solanaWallet.connect(w.name).then(() => setPayerChooser(false)), disabled: solanaWallet.status === "connecting", children: w.name }, w.name)) : null,
|
|
10252
|
+
!solanaWallet.wallets.length ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", children: "No Solana wallet found. Install Phantom, Solflare or Backpack to pay from Solana." }) : null
|
|
10253
|
+
] }) : !connected2 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
10254
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect EVM wallet" }),
|
|
10255
|
+
/* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "8px 0 0" }, children: "Your EVM wallet owns the order and can cancel it." })
|
|
10256
|
+
] }) : recipientState.missing ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.familyWallet.connecting, children: [
|
|
10257
|
+
"Connect ",
|
|
10258
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
10259
|
+
" wallet"
|
|
10260
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsx(
|
|
10261
|
+
Button,
|
|
10262
|
+
{
|
|
10263
|
+
onClick: solFlow.run,
|
|
10264
|
+
busy: submitting,
|
|
10265
|
+
disabled: !quotable || !cryptoReady || !!recipientState.error || !solFlow.plan || solFlow.insufficient || solFlow.solShort || solFlow.status === "quoting",
|
|
10266
|
+
children: solFlow.status === "preparing" ? "Preparing order\u2026" : solFlow.status === "submitting" ? "Submitting\u2026" : solFlow.insufficient ? "Insufficient balance" : solFlow.solShort ? "Not enough SOL for network fees" : solFlow.status === "failed" ? "Try again" : !solFlow.plan ? "Exchange" : solFlow.needsPreparation ? "Continue in wallet" : "Submit"
|
|
10267
|
+
}
|
|
10268
|
+
);
|
|
10269
|
+
const solanaSteps = solActive && solFlow.plan && connected2 && solanaWallet.address ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "0 0 8px" }, "data-testid": "solana-steps", children: solFlow.needsPreparation || solFlow.status === "preparing" ? "Prepare order \xB7 Submit \xB7 Track" : solFlow.status === "prepared" ? "Prepare order \u2713 \xB7 Submit \xB7 Track" : "Submit \xB7 Track" }) : null;
|
|
8012
10270
|
let body;
|
|
8013
|
-
if (hist &&
|
|
10271
|
+
if (hist && connected2) {
|
|
8014
10272
|
body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
|
|
8015
10273
|
} else if (view === "from" || view === "to") {
|
|
8016
10274
|
const isFrom = view === "from";
|
|
@@ -8035,6 +10293,26 @@ function ExchangeCard(props) {
|
|
|
8035
10293
|
);
|
|
8036
10294
|
} else if (sheetBody && !wide) {
|
|
8037
10295
|
body = sheetBody;
|
|
10296
|
+
} else if (solActive && solFlow.status === "sent") {
|
|
10297
|
+
body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
10298
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
10299
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending": "true", children: /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph5, {}) }),
|
|
10300
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-amt sg-mono", children: [
|
|
10301
|
+
solFlow.sent?.receive ?? receive,
|
|
10302
|
+
" ",
|
|
10303
|
+
solFlow.sent?.toTicker ?? toTicker
|
|
10304
|
+
] }),
|
|
10305
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
|
|
10306
|
+
"Submitted on Solana \u2014 ZeroDelta delivers it",
|
|
10307
|
+
solFlow.sent?.recipient ? ` \xB7 ${shortAddress2(solFlow.sent.recipient)}` : ""
|
|
10308
|
+
] })
|
|
10309
|
+
] }),
|
|
10310
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
10311
|
+
solFlow.signature ? /* @__PURE__ */ jsxRuntime.jsx("a", { className: "sg-btn sg-btn-ghost", href: `https://solscan.io/tx/${solFlow.signature}`, target: "_blank", rel: "noopener noreferrer", children: "View on Solscan" }) : null,
|
|
10312
|
+
solFlow.lastTxEntry && connected2 ? /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: solFlow.lastTxEntry }), children: "View transaction" }) : null,
|
|
10313
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: solFlow.reset, children: "Start a new exchange" })
|
|
10314
|
+
] })
|
|
10315
|
+
] });
|
|
8038
10316
|
} else if (flow.status === "success" || flow.status === "pending") {
|
|
8039
10317
|
body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
8040
10318
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
@@ -8046,7 +10324,7 @@ function ExchangeCard(props) {
|
|
|
8046
10324
|
] }),
|
|
8047
10325
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
|
|
8048
10326
|
flow.verdict?.status === "confirmed" ? "Confirmed on-chain" : "Submitted \u2014 awaiting confirmation",
|
|
8049
|
-
props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
10327
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
8050
10328
|
] })
|
|
8051
10329
|
] }),
|
|
8052
10330
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
@@ -8057,8 +10335,19 @@ function ExchangeCard(props) {
|
|
|
8057
10335
|
} else {
|
|
8058
10336
|
const payToken = mode === "onramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You pay", symbol: from?.symbol ?? null, chainId: from?.chainId ?? null, token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") });
|
|
8059
10337
|
const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, token: toToken, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") });
|
|
8060
|
-
const cta = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
8061
|
-
|
|
10338
|
+
const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
10339
|
+
solanaSteps,
|
|
10340
|
+
solanaCta,
|
|
10341
|
+
/* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }),
|
|
10342
|
+
solanaWallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: solanaWallet.error }) : null,
|
|
10343
|
+
wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
|
|
10344
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
10345
|
+
!connected2 && !rampMode ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : recipientState.missing && !rampMode && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
|
|
10346
|
+
"Connect ",
|
|
10347
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
10348
|
+
" wallet"
|
|
10349
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: rampMode ? void 0 : flow.submit, busy: submitting, disabled: needsRecipient || rampMode || !quotable || !cryptoReady || connected2 && (!flow.selected || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading"), children: ctaLabel }),
|
|
10350
|
+
!rampMode ? /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null,
|
|
8062
10351
|
wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
|
|
8063
10352
|
] });
|
|
8064
10353
|
const notices = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
@@ -8204,6 +10493,11 @@ function mount(el, config) {
|
|
|
8204
10493
|
root.render(react.createElement(Comp, variant === "rwa" ? { ...props, product: "rwa" } : props));
|
|
8205
10494
|
return () => root.unmount();
|
|
8206
10495
|
}
|
|
10496
|
+
/*! Bundled license information:
|
|
10497
|
+
|
|
10498
|
+
@noble/ed25519/index.js:
|
|
10499
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
10500
|
+
*/
|
|
8207
10501
|
|
|
8208
10502
|
exports.CompliancePanel = CompliancePanel;
|
|
8209
10503
|
exports.EXECUTABLE_STABLE_ASSETS = EXECUTABLE_STABLE_ASSETS;
|
|
@@ -8222,13 +10516,20 @@ exports.brokenLaneReason = brokenLaneReason;
|
|
|
8222
10516
|
exports.complianceChecks = complianceChecks;
|
|
8223
10517
|
exports.complianceControlsLine = complianceControlsLine;
|
|
8224
10518
|
exports.complianceView = complianceView;
|
|
10519
|
+
exports.connectSolanaWallet = connectSolanaWallet;
|
|
8225
10520
|
exports.counterpartTokens = counterpartTokens;
|
|
8226
10521
|
exports.createEngine = createEngine;
|
|
8227
10522
|
exports.darkTheme = darkTheme;
|
|
8228
10523
|
exports.destinationAvailability = destinationAvailability;
|
|
10524
|
+
exports.disconnectSolanaWallet = disconnectSolanaWallet;
|
|
10525
|
+
exports.discoverSolanaWallets = discoverSolanaWallets;
|
|
8229
10526
|
exports.formatJurisdiction = formatJurisdiction;
|
|
8230
10527
|
exports.humanizeComplianceReason = humanizeComplianceReason;
|
|
8231
10528
|
exports.lightTheme = lightTheme;
|
|
8232
10529
|
exports.mount = mount;
|
|
10530
|
+
exports.onSolanaAccountChange = onSolanaAccountChange;
|
|
8233
10531
|
exports.resolveTheme = resolveTheme;
|
|
10532
|
+
exports.solanaWalletSigner = solanaWalletSigner;
|
|
8234
10533
|
exports.symbolKey = symbolKey;
|
|
10534
|
+
exports.useSolanaWallet = useSolanaWallet;
|
|
10535
|
+
exports.watchSolanaWallets = watchSolanaWallets;
|