@glacislabs/stablegenie-zerodelta 4.12.0 → 4.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-A7ADZJXA.js → chunk-6WFIFKZ4.js} +1427 -227
- package/dist/{chunk-MA2VYFG3.js → chunk-M55J3P64.js} +961 -97
- package/dist/core/index.cjs +2086 -239
- package/dist/core/index.d.cts +449 -40
- package/dist/core/index.d.ts +449 -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 +3085 -450
- package/dist/index.d.cts +96 -4
- package/dist/index.d.ts +96 -4
- package/dist/index.js +2 -2
- package/dist/{mount-hxb3zioQ.d.ts → mount-B6soKC-9.d.ts} +1 -1
- package/dist/{mount-xruGixNZ.d.cts → mount-CEy4Nqky.d.cts} +1 -1
- package/dist/mount.cjs +3076 -448
- 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 +13 -9
- package/dist/{verify-D8tr1yY1.d.cts → verify-Y9jZ83T5.d.cts} +81 -68
- package/dist/{verify-D8tr1yY1.d.ts → verify-Y9jZ83T5.d.ts} +81 -68
- package/package.json +4 -3
package/dist/mount.cjs
CHANGED
|
@@ -4,7 +4,703 @@ var react = require('react');
|
|
|
4
4
|
var client = require('react-dom/client');
|
|
5
5
|
var jsxRuntime = require('react/jsx-runtime');
|
|
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
|
+
});
|
|
576
|
+
|
|
577
|
+
// src/core/delivery.ts
|
|
578
|
+
var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "expired", "failed"]);
|
|
579
|
+
var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim"]);
|
|
580
|
+
var TRACKING = Object.freeze({ phase: "tracking", status: "", steps: [] });
|
|
581
|
+
var word = (v) => typeof v === "string" ? v.trim().toLowerCase() : "";
|
|
582
|
+
function normalizeDelivery(raw2) {
|
|
583
|
+
const row = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2.data ?? raw2 : null;
|
|
584
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) return TRACKING;
|
|
585
|
+
const r = row;
|
|
586
|
+
const chained = r.isChained === true || Array.isArray(r.legs) && r.legs.length > 1;
|
|
587
|
+
const journey = word(r.journeyStatus);
|
|
588
|
+
const own = word(r.status);
|
|
589
|
+
const status = journey || own;
|
|
590
|
+
const rawSteps = Array.isArray(r.steps) ? r.steps : [];
|
|
591
|
+
const steps = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string").sort((a, b) => Number(a.stepNumber ?? 0) - Number(b.stepNumber ?? 0)).slice(0, 8).map((s) => ({ name: String(s.stepName).slice(0, 32), done: s.stepStatus === "completed" }));
|
|
592
|
+
if (!status) return TRACKING;
|
|
593
|
+
if (FAILED.has(status)) return { phase: "failed", status, steps };
|
|
594
|
+
if (ATTENTION.has(status)) return { phase: "attention", status, steps };
|
|
595
|
+
if (status === "delivered" && !(chained && !journey)) return { phase: "delivered", status, steps: steps.map((s) => ({ ...s, done: true })) };
|
|
596
|
+
return { phase: "in-progress", status: status === "delivered" ? "continuing" : status, steps };
|
|
597
|
+
}
|
|
598
|
+
var HASH = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
|
|
599
|
+
function sameOrder(raw2, hash2) {
|
|
600
|
+
const row = raw2 && typeof raw2 === "object" ? raw2.data ?? raw2 : null;
|
|
601
|
+
const got = row && typeof row === "object" ? row.txHash : void 0;
|
|
602
|
+
if (typeof got !== "string" || !got) return false;
|
|
603
|
+
return hash2.startsWith("0x") ? got.toLowerCase() === hash2.toLowerCase() : got === hash2;
|
|
604
|
+
}
|
|
605
|
+
async function fetchDelivery(api, hash2) {
|
|
606
|
+
if (typeof hash2 !== "string" || !HASH.test(hash2)) return TRACKING;
|
|
607
|
+
try {
|
|
608
|
+
const raw2 = await api.apiRequest(`/transactions/${hash2}`, { timeoutMs: 8e3 });
|
|
609
|
+
return sameOrder(raw2, hash2) ? normalizeDelivery(raw2) : TRACKING;
|
|
610
|
+
} catch {
|
|
611
|
+
return TRACKING;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// src/react/hooks/useDelivery.ts
|
|
616
|
+
function deliveryPollDelay(elapsedMs) {
|
|
617
|
+
if (elapsedMs < 6e4) return 5e3;
|
|
618
|
+
if (elapsedMs < 11 * 6e4) return 15e3;
|
|
619
|
+
return 3e4;
|
|
620
|
+
}
|
|
621
|
+
var DELIVERY_GIVE_UP_MS = 2 * 60 * 60 * 1e3;
|
|
622
|
+
var UNANSWERED_LIMIT = 20;
|
|
623
|
+
var UNAVAILABLE = Object.freeze({ phase: "unavailable", status: "", steps: [] });
|
|
624
|
+
var hidden = () => typeof document !== "undefined" && document.visibilityState === "hidden";
|
|
625
|
+
function useDelivery(engine, hash2) {
|
|
626
|
+
const [state, setState] = react.useState({ hash: null, value: TRACKING });
|
|
627
|
+
react.useEffect(() => {
|
|
628
|
+
if (!hash2) return;
|
|
629
|
+
let alive = true;
|
|
630
|
+
let timer2;
|
|
631
|
+
let answered = false;
|
|
632
|
+
let unanswered = 0;
|
|
633
|
+
const started2 = Date.now();
|
|
634
|
+
setState({ hash: hash2, value: TRACKING });
|
|
635
|
+
const schedule = () => {
|
|
636
|
+
if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) return setState({ hash: hash2, value: UNAVAILABLE });
|
|
637
|
+
timer2 = setTimeout(tick, deliveryPollDelay(Date.now() - started2));
|
|
638
|
+
};
|
|
639
|
+
const tick = async () => {
|
|
640
|
+
timer2 = void 0;
|
|
641
|
+
if (hidden()) return schedule();
|
|
642
|
+
const next = await engine.trackDelivery(hash2);
|
|
643
|
+
if (!alive) return;
|
|
644
|
+
if (next.phase === "tracking") {
|
|
645
|
+
if (!answered && ++unanswered >= UNANSWERED_LIMIT) return setState({ hash: hash2, value: UNAVAILABLE });
|
|
646
|
+
return schedule();
|
|
647
|
+
}
|
|
648
|
+
answered = true;
|
|
649
|
+
setState({ hash: hash2, value: next });
|
|
650
|
+
if (next.phase === "delivered" || next.phase === "failed") return;
|
|
651
|
+
schedule();
|
|
652
|
+
};
|
|
653
|
+
const onVisible2 = () => {
|
|
654
|
+
if (!alive || hidden() || !timer2) return;
|
|
655
|
+
clearTimeout(timer2);
|
|
656
|
+
void tick();
|
|
657
|
+
};
|
|
658
|
+
void tick();
|
|
659
|
+
if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisible2);
|
|
660
|
+
return () => {
|
|
661
|
+
alive = false;
|
|
662
|
+
if (timer2) clearTimeout(timer2);
|
|
663
|
+
if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisible2);
|
|
664
|
+
};
|
|
665
|
+
}, [engine, hash2]);
|
|
666
|
+
return state.hash === hash2 ? state.value : TRACKING;
|
|
667
|
+
}
|
|
668
|
+
var STEP_LABEL = {
|
|
669
|
+
submitted: "Submitted",
|
|
670
|
+
arrived: "Arrived",
|
|
671
|
+
filled: "Filled",
|
|
672
|
+
outbound_bridging: "Bridging",
|
|
673
|
+
delivered: "Delivered"
|
|
674
|
+
};
|
|
675
|
+
var label = (name) => STEP_LABEL[name] ?? name.replace(/_/g, " ");
|
|
676
|
+
function deliveryHeadline(delivery, sourceConfirmed, direct = false) {
|
|
677
|
+
if (direct) return sourceConfirmed ? "Delivered" : "Submitted \u2014 awaiting confirmation";
|
|
678
|
+
switch (delivery.phase) {
|
|
679
|
+
case "delivered":
|
|
680
|
+
return "Delivered";
|
|
681
|
+
case "failed":
|
|
682
|
+
return delivery.status === "cancelled" ? "Cancelled \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
|
|
683
|
+
case "attention":
|
|
684
|
+
return delivery.status === "cancel_pending" ? "Being cancelled \u2014 not delivered" : "Waiting to be claimed \u2014 open the transaction";
|
|
685
|
+
case "in-progress": {
|
|
686
|
+
if (delivery.status === "continuing") return "On its way \u2014 final leg next";
|
|
687
|
+
const next = delivery.steps.find((s) => !s.done);
|
|
688
|
+
return next ? `On its way \u2014 ${label(next.name).toLowerCase()} next` : "On its way";
|
|
689
|
+
}
|
|
690
|
+
case "unavailable":
|
|
691
|
+
return sourceConfirmed ? "Sent \u2014 open the transaction to follow delivery" : "Submitted \u2014 awaiting confirmation";
|
|
692
|
+
default:
|
|
693
|
+
return sourceConfirmed ? "Sent \u2014 tracking delivery" : "Submitted \u2014 awaiting confirmation";
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function isDelivered(delivery, sourceConfirmed, direct = false) {
|
|
697
|
+
return direct ? sourceConfirmed : delivery.phase === "delivered";
|
|
698
|
+
}
|
|
699
|
+
function DeliverySteps(props) {
|
|
700
|
+
const { steps, phase } = props.delivery;
|
|
701
|
+
if (!steps.length || phase === "failed") return null;
|
|
702
|
+
return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-steps", "data-testid": "delivery-steps", "data-phase": phase, children: steps.map((s) => `${label(s.name)}${s.done ? " \u2713" : ""}`).join(" \xB7 ") });
|
|
703
|
+
}
|
|
8
704
|
var ConfigContext = react.createContext({});
|
|
9
705
|
function useMergedConfig(local) {
|
|
10
706
|
const ctx = react.useContext(ConfigContext);
|
|
@@ -104,7 +800,10 @@ var CANONICAL_ESCROW = Object.freeze({
|
|
|
104
800
|
// Plume
|
|
105
801
|
});
|
|
106
802
|
var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
|
|
107
|
-
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
|
|
803
|
+
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
|
|
804
|
+
9745: 2500n * 10n ** 18n,
|
|
805
|
+
98866: 5000n * 10n ** 18n
|
|
806
|
+
};
|
|
108
807
|
function maxNativeFeeWei(chainId) {
|
|
109
808
|
return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
|
|
110
809
|
}
|
|
@@ -222,6 +921,247 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
|
|
|
222
921
|
1151111081099710: "Solana"
|
|
223
922
|
});
|
|
224
923
|
|
|
924
|
+
// src/core/solana.ts
|
|
925
|
+
var SOLANA_CHAIN_ID = 1151111081099710;
|
|
926
|
+
function isSolanaChainId(value) {
|
|
927
|
+
return Number(value) === SOLANA_CHAIN_ID;
|
|
928
|
+
}
|
|
929
|
+
var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
930
|
+
function base58Encode(bytes) {
|
|
931
|
+
let zeros = 0;
|
|
932
|
+
while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
|
|
933
|
+
let value = 0n;
|
|
934
|
+
for (const byte of bytes) value = value << 8n | BigInt(byte);
|
|
935
|
+
let out = "";
|
|
936
|
+
while (value > 0n) {
|
|
937
|
+
out = BASE58_ALPHABET[Number(value % 58n)] + out;
|
|
938
|
+
value /= 58n;
|
|
939
|
+
}
|
|
940
|
+
return "1".repeat(zeros) + out;
|
|
941
|
+
}
|
|
942
|
+
function base58Decode(text) {
|
|
943
|
+
let value = 0n;
|
|
944
|
+
for (const char of text) {
|
|
945
|
+
const digit = BASE58_ALPHABET.indexOf(char);
|
|
946
|
+
if (digit < 0) return null;
|
|
947
|
+
value = value * 58n + BigInt(digit);
|
|
948
|
+
}
|
|
949
|
+
const body = [];
|
|
950
|
+
while (value > 0n) {
|
|
951
|
+
body.unshift(Number(value & 0xffn));
|
|
952
|
+
value >>= 8n;
|
|
953
|
+
}
|
|
954
|
+
let zeros = 0;
|
|
955
|
+
while (zeros < text.length && text[zeros] === "1") zeros += 1;
|
|
956
|
+
return new Uint8Array([...new Array(zeros).fill(0), ...body]);
|
|
957
|
+
}
|
|
958
|
+
function isSolanaAddress(value) {
|
|
959
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
960
|
+
return text.length >= 32 && text.length <= 44 && base58Decode(text)?.length === 32;
|
|
961
|
+
}
|
|
962
|
+
function solanaKeyHex(value) {
|
|
963
|
+
if (!isSolanaAddress(value)) return null;
|
|
964
|
+
return `0x${Array.from(base58Decode(value.trim()), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
965
|
+
}
|
|
966
|
+
function hexToSolanaKey(value) {
|
|
967
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(value)) return null;
|
|
968
|
+
return base58Encode(Uint8Array.from(value.slice(2).match(/../g), (byte) => Number.parseInt(byte, 16)));
|
|
969
|
+
}
|
|
970
|
+
var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
971
|
+
var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
|
|
972
|
+
var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
|
|
973
|
+
var pin = (symbol, decimals, bridge, tokenProgram) => Object.freeze({ symbol, decimals, bridge, tokenProgram });
|
|
974
|
+
var SOLANA_DESTINATION_ASSETS = Object.freeze({
|
|
975
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: pin("USDC", 6, "cctp", TOKEN_PROGRAM),
|
|
976
|
+
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": pin("PYUSD", 6, "layerzero", TOKEN_2022_PROGRAM),
|
|
977
|
+
DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT: pin("USDE", 9, "layerzero", TOKEN_PROGRAM),
|
|
978
|
+
"2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": pin("USDG", 6, "layerzero", TOKEN_2022_PROGRAM),
|
|
979
|
+
AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
|
|
980
|
+
});
|
|
981
|
+
function solanaDestinationAsset(mint) {
|
|
982
|
+
const key = typeof mint === "string" ? mint.trim() : "";
|
|
983
|
+
return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
|
|
984
|
+
}
|
|
985
|
+
function solanaBridgeOf(token) {
|
|
986
|
+
const pinned = solanaDestinationAsset(token.address);
|
|
987
|
+
if (!pinned || pinned.symbol !== token.symbol.trim().toUpperCase()) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
988
|
+
return pinned.bridge;
|
|
989
|
+
}
|
|
990
|
+
var K = new Uint32Array([
|
|
991
|
+
1116352408,
|
|
992
|
+
1899447441,
|
|
993
|
+
3049323471,
|
|
994
|
+
3921009573,
|
|
995
|
+
961987163,
|
|
996
|
+
1508970993,
|
|
997
|
+
2453635748,
|
|
998
|
+
2870763221,
|
|
999
|
+
3624381080,
|
|
1000
|
+
310598401,
|
|
1001
|
+
607225278,
|
|
1002
|
+
1426881987,
|
|
1003
|
+
1925078388,
|
|
1004
|
+
2162078206,
|
|
1005
|
+
2614888103,
|
|
1006
|
+
3248222580,
|
|
1007
|
+
3835390401,
|
|
1008
|
+
4022224774,
|
|
1009
|
+
264347078,
|
|
1010
|
+
604807628,
|
|
1011
|
+
770255983,
|
|
1012
|
+
1249150122,
|
|
1013
|
+
1555081692,
|
|
1014
|
+
1996064986,
|
|
1015
|
+
2554220882,
|
|
1016
|
+
2821834349,
|
|
1017
|
+
2952996808,
|
|
1018
|
+
3210313671,
|
|
1019
|
+
3336571891,
|
|
1020
|
+
3584528711,
|
|
1021
|
+
113926993,
|
|
1022
|
+
338241895,
|
|
1023
|
+
666307205,
|
|
1024
|
+
773529912,
|
|
1025
|
+
1294757372,
|
|
1026
|
+
1396182291,
|
|
1027
|
+
1695183700,
|
|
1028
|
+
1986661051,
|
|
1029
|
+
2177026350,
|
|
1030
|
+
2456956037,
|
|
1031
|
+
2730485921,
|
|
1032
|
+
2820302411,
|
|
1033
|
+
3259730800,
|
|
1034
|
+
3345764771,
|
|
1035
|
+
3516065817,
|
|
1036
|
+
3600352804,
|
|
1037
|
+
4094571909,
|
|
1038
|
+
275423344,
|
|
1039
|
+
430227734,
|
|
1040
|
+
506948616,
|
|
1041
|
+
659060556,
|
|
1042
|
+
883997877,
|
|
1043
|
+
958139571,
|
|
1044
|
+
1322822218,
|
|
1045
|
+
1537002063,
|
|
1046
|
+
1747873779,
|
|
1047
|
+
1955562222,
|
|
1048
|
+
2024104815,
|
|
1049
|
+
2227730452,
|
|
1050
|
+
2361852424,
|
|
1051
|
+
2428436474,
|
|
1052
|
+
2756734187,
|
|
1053
|
+
3204031479,
|
|
1054
|
+
3329325298
|
|
1055
|
+
]);
|
|
1056
|
+
function sha256(data) {
|
|
1057
|
+
const bitLen = data.length * 8;
|
|
1058
|
+
const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
|
|
1059
|
+
padded.set(data);
|
|
1060
|
+
padded[data.length] = 128;
|
|
1061
|
+
const view = new DataView(padded.buffer);
|
|
1062
|
+
view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
|
|
1063
|
+
view.setUint32(padded.length - 4, bitLen >>> 0);
|
|
1064
|
+
const h2 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
|
|
1065
|
+
const w = new Uint32Array(64);
|
|
1066
|
+
const rotr = (x, n) => x >>> n | x << 32 - n;
|
|
1067
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
1068
|
+
for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
|
|
1069
|
+
for (let i = 16; i < 64; i += 1) {
|
|
1070
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
|
|
1071
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
|
|
1072
|
+
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
1073
|
+
}
|
|
1074
|
+
let [a, b, c, d, e, f, g, hh] = h2;
|
|
1075
|
+
for (let i = 0; i < 64; i += 1) {
|
|
1076
|
+
const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
|
|
1077
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
1078
|
+
hh = g;
|
|
1079
|
+
g = f;
|
|
1080
|
+
f = e;
|
|
1081
|
+
e = d + t1 >>> 0;
|
|
1082
|
+
d = c;
|
|
1083
|
+
c = b;
|
|
1084
|
+
b = a;
|
|
1085
|
+
a = t1 + t2 >>> 0;
|
|
1086
|
+
}
|
|
1087
|
+
h2[0] = h2[0] + a >>> 0;
|
|
1088
|
+
h2[1] = h2[1] + b >>> 0;
|
|
1089
|
+
h2[2] = h2[2] + c >>> 0;
|
|
1090
|
+
h2[3] = h2[3] + d >>> 0;
|
|
1091
|
+
h2[4] = h2[4] + e >>> 0;
|
|
1092
|
+
h2[5] = h2[5] + f >>> 0;
|
|
1093
|
+
h2[6] = h2[6] + g >>> 0;
|
|
1094
|
+
h2[7] = h2[7] + hh >>> 0;
|
|
1095
|
+
}
|
|
1096
|
+
const out = new Uint8Array(32);
|
|
1097
|
+
const outView = new DataView(out.buffer);
|
|
1098
|
+
for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h2[i]);
|
|
1099
|
+
return out;
|
|
1100
|
+
}
|
|
1101
|
+
var P = 2n ** 255n - 19n;
|
|
1102
|
+
var mod = (a) => (a % P + P) % P;
|
|
1103
|
+
var pow = (base, exp) => {
|
|
1104
|
+
let result = 1n;
|
|
1105
|
+
let b = mod(base);
|
|
1106
|
+
for (let e = exp; e > 0n; e >>= 1n) {
|
|
1107
|
+
if (e & 1n) result = result * b % P;
|
|
1108
|
+
b = b * b % P;
|
|
1109
|
+
}
|
|
1110
|
+
return result;
|
|
1111
|
+
};
|
|
1112
|
+
var D = mod(-121665n * pow(121666n, P - 2n));
|
|
1113
|
+
function isOnEd25519Curve(bytes) {
|
|
1114
|
+
let y = 0n;
|
|
1115
|
+
for (let i = 31; i >= 0; i -= 1) y = y << 8n | BigInt(bytes[i]);
|
|
1116
|
+
y = mod(y & (1n << 255n) - 1n);
|
|
1117
|
+
const yy = y * y % P;
|
|
1118
|
+
const u = mod(yy - 1n);
|
|
1119
|
+
const v = mod(D * yy + 1n);
|
|
1120
|
+
if (v === 0n) return u === 0n;
|
|
1121
|
+
const x2 = u * pow(v, P - 2n) % P;
|
|
1122
|
+
return x2 === 0n || pow(x2, (P - 1n) / 2n) === 1n;
|
|
1123
|
+
}
|
|
1124
|
+
function keyBytes(base58) {
|
|
1125
|
+
const bytes = base58Decode(base58);
|
|
1126
|
+
if (!bytes || bytes.length !== 32) throw new Error("Not a valid Solana address.");
|
|
1127
|
+
return bytes;
|
|
1128
|
+
}
|
|
1129
|
+
function findProgramAddress(seeds, programId) {
|
|
1130
|
+
const program = keyBytes(programId);
|
|
1131
|
+
const marker = new TextEncoder().encode("ProgramDerivedAddress");
|
|
1132
|
+
for (let bump = 255; bump >= 1; bump -= 1) {
|
|
1133
|
+
const parts = [...seeds, Uint8Array.of(bump), program, marker];
|
|
1134
|
+
const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
1135
|
+
let at = 0;
|
|
1136
|
+
for (const part of parts) {
|
|
1137
|
+
buf.set(part, at);
|
|
1138
|
+
at += part.length;
|
|
1139
|
+
}
|
|
1140
|
+
const candidate = sha256(buf);
|
|
1141
|
+
if (!isOnEd25519Curve(candidate)) return candidate;
|
|
1142
|
+
}
|
|
1143
|
+
throw new Error("Could not derive a program address.");
|
|
1144
|
+
}
|
|
1145
|
+
function associatedTokenAddress(owner, mint, tokenProgram) {
|
|
1146
|
+
return base58Encode(findProgramAddress([keyBytes(owner), keyBytes(tokenProgram), keyBytes(mint)], ASSOCIATED_TOKEN_PROGRAM));
|
|
1147
|
+
}
|
|
1148
|
+
function expectedSolanaDelivery(recipient2, mint) {
|
|
1149
|
+
if (!isSolanaAddress(recipient2)) throw new Error("Not a valid Solana address.");
|
|
1150
|
+
const pinned = solanaDestinationAsset(mint);
|
|
1151
|
+
if (!pinned) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
1152
|
+
const target = pinned.bridge === "cctp" ? associatedTokenAddress(recipient2.trim(), mint.trim(), pinned.tokenProgram) : recipient2.trim();
|
|
1153
|
+
return solanaKeyHex(target);
|
|
1154
|
+
}
|
|
1155
|
+
function checkSolanaReceiver(request, intended, mint) {
|
|
1156
|
+
if (!isSolanaAddress(intended)) throw new Error("Not a valid Solana address.");
|
|
1157
|
+
if (request.destinationReceiverOwner !== intended.trim()) throw new Error("The quote was not made out to your Solana recipient; refusing to sign.");
|
|
1158
|
+
const receiver = request.destinationReceiver || "";
|
|
1159
|
+
const display = hexToSolanaKey(receiver);
|
|
1160
|
+
if (!display) throw new Error("The quote carries no Solana delivery account; refusing to sign.");
|
|
1161
|
+
if (request.destinationReceiverBase58 && request.destinationReceiverBase58 !== display) throw new Error("The quote names two different Solana delivery accounts; refusing to sign.");
|
|
1162
|
+
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.");
|
|
1163
|
+
}
|
|
1164
|
+
|
|
225
1165
|
// src/core/address.ts
|
|
226
1166
|
function symbolKey(value) {
|
|
227
1167
|
return String(value || "").trim().toUpperCase();
|
|
@@ -233,71 +1173,31 @@ function normalizeAddress(value) {
|
|
|
233
1173
|
if (!isAddress(value)) return null;
|
|
234
1174
|
return String(value).toLowerCase();
|
|
235
1175
|
}
|
|
236
|
-
function assertAddress(value,
|
|
1176
|
+
function assertAddress(value, label2) {
|
|
237
1177
|
const normalized = normalizeAddress(value);
|
|
238
|
-
if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${
|
|
1178
|
+
if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label2} is not a valid EVM address.`);
|
|
239
1179
|
return normalized;
|
|
240
1180
|
}
|
|
241
|
-
function resolveSwapReceiver(
|
|
1181
|
+
function resolveSwapReceiver(recipient2, payer, destinationChainId) {
|
|
242
1182
|
const payerAddr = assertAddress(payer, "Swap wallet");
|
|
243
|
-
if (
|
|
244
|
-
|
|
1183
|
+
if (isSolanaChainId(destinationChainId)) return assertChainAddress(destinationChainId, recipient2, "Deposit recipient");
|
|
1184
|
+
if (recipient2 === void 0 || recipient2 === null || recipient2 === "") return payerAddr;
|
|
1185
|
+
const normalized = normalizeAddress(recipient2);
|
|
245
1186
|
if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
|
|
246
1187
|
return normalized;
|
|
247
1188
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
function assetDecimals(token) {
|
|
251
|
-
const sym = symbolKey(token?.symbol);
|
|
252
|
-
const registry = Number(token?.decimals);
|
|
253
|
-
const canonical = CANONICAL_DECIMALS[sym];
|
|
254
|
-
if (canonical !== void 0) {
|
|
255
|
-
if (!Number.isInteger(registry)) {
|
|
256
|
-
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
257
|
-
}
|
|
258
|
-
if (registry !== canonical) {
|
|
259
|
-
throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
260
|
-
}
|
|
261
|
-
return canonical;
|
|
262
|
-
}
|
|
263
|
-
if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
|
|
264
|
-
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
265
|
-
}
|
|
266
|
-
return registry;
|
|
267
|
-
}
|
|
268
|
-
function normalizeDecimalText(value) {
|
|
269
|
-
const text = String(value || "").trim().replace(/\s+/g, "");
|
|
270
|
-
if (!text) return "";
|
|
271
|
-
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
272
|
-
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
273
|
-
if (text.includes(",")) return "";
|
|
274
|
-
return text;
|
|
275
|
-
}
|
|
276
|
-
function parseUnitsDecimal(amount, decimals) {
|
|
277
|
-
const text = normalizeDecimalText(amount);
|
|
278
|
-
if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
|
|
279
|
-
const [whole, frac = ""] = text.split(".");
|
|
280
|
-
if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
|
|
281
|
-
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
282
|
-
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
283
|
-
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
284
|
-
return value;
|
|
285
|
-
}
|
|
286
|
-
function scaleDecimals(amount, fromDecimals, toDecimals) {
|
|
287
|
-
if (toDecimals === fromDecimals) return amount;
|
|
288
|
-
if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
|
289
|
-
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
1189
|
+
function isChainAddress(chainId, value) {
|
|
1190
|
+
return isSolanaChainId(chainId) ? isSolanaAddress(value) : isAddress(value);
|
|
290
1191
|
}
|
|
291
|
-
function
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
const whole = value / base;
|
|
295
|
-
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
296
|
-
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
297
|
-
return frac ? `${whole}.${frac}` : whole.toString();
|
|
1192
|
+
function chainAddressKey(chainId, value) {
|
|
1193
|
+
const text = String(value || "");
|
|
1194
|
+
return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
|
|
298
1195
|
}
|
|
299
|
-
function
|
|
300
|
-
|
|
1196
|
+
function assertChainAddress(chainId, value, label2) {
|
|
1197
|
+
if (!isSolanaChainId(chainId)) return assertAddress(value, label2);
|
|
1198
|
+
if (!String(value || "").trim()) throw new Error("Connect a Solana wallet or enter a Solana recipient address.");
|
|
1199
|
+
if (!isSolanaAddress(value)) throw new Error("Not a valid Solana address.");
|
|
1200
|
+
return String(value).trim();
|
|
301
1201
|
}
|
|
302
1202
|
|
|
303
1203
|
// src/core/abi.ts
|
|
@@ -370,14 +1270,12 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
|
|
|
370
1270
|
const tuples = orders.map(encodeOrderTuple);
|
|
371
1271
|
let offset = 32n * BigInt(tuples.length);
|
|
372
1272
|
const offsets = tuples.map((tuple) => {
|
|
373
|
-
const
|
|
1273
|
+
const word2 = uintWord(offset);
|
|
374
1274
|
offset += BigInt(tuple.length / 2);
|
|
375
|
-
return
|
|
1275
|
+
return word2;
|
|
376
1276
|
}).join("");
|
|
377
1277
|
return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
|
|
378
1278
|
}
|
|
379
|
-
var EVM_BYTES_PAYLOAD_BYTES = 64;
|
|
380
|
-
var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
|
|
381
1279
|
var MAX_DECODED_ORDERS = 16;
|
|
382
1280
|
function decodeSubmitOrderCalldata(data) {
|
|
383
1281
|
const hex = strip0x(String(data || "")).toLowerCase();
|
|
@@ -385,56 +1283,61 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
385
1283
|
if (`0x${hex.slice(0, 8)}` !== SUBMIT_ORDER_SELECTOR) return null;
|
|
386
1284
|
const body = hex.slice(8);
|
|
387
1285
|
const totalBytes = body.length / 2;
|
|
388
|
-
const
|
|
1286
|
+
const word2 = (byteOffset) => {
|
|
389
1287
|
if (!Number.isSafeInteger(byteOffset) || byteOffset < 0 || byteOffset + 32 > totalBytes) return null;
|
|
390
1288
|
return BigInt(`0x${body.slice(byteOffset * 2, byteOffset * 2 + 64)}`);
|
|
391
1289
|
};
|
|
392
1290
|
const addressAt = (byteOffset) => {
|
|
393
|
-
const w =
|
|
1291
|
+
const w = word2(byteOffset);
|
|
394
1292
|
if (w === null || w >= 1n << 160n) return null;
|
|
395
1293
|
return `0x${w.toString(16).padStart(40, "0")}`;
|
|
396
1294
|
};
|
|
397
1295
|
const uint64At = (byteOffset) => {
|
|
398
|
-
const w =
|
|
1296
|
+
const w = word2(byteOffset);
|
|
399
1297
|
return w === null || w > MAX_UINT64 ? null : w;
|
|
400
1298
|
};
|
|
401
|
-
const
|
|
402
|
-
const len =
|
|
403
|
-
if (len !== 20n) return null;
|
|
404
|
-
const
|
|
405
|
-
|
|
406
|
-
|
|
1299
|
+
const keyBytesAt = (byteOffset) => {
|
|
1300
|
+
const len = word2(byteOffset);
|
|
1301
|
+
if (len !== 20n && len !== 32n) return null;
|
|
1302
|
+
const length = Number(len);
|
|
1303
|
+
const padded = Math.ceil(length / 32) * 32;
|
|
1304
|
+
const content = body.slice((byteOffset + 32) * 2, (byteOffset + 32 + padded) * 2);
|
|
1305
|
+
if (content.length !== padded * 2 || content.slice(length * 2) !== "0".repeat((padded - length) * 2)) return null;
|
|
1306
|
+
return { value: `0x${content.slice(0, length * 2)}`, size: 32 + padded };
|
|
407
1307
|
};
|
|
408
|
-
if (
|
|
409
|
-
if (
|
|
1308
|
+
if (word2(0) !== 64n) return null;
|
|
1309
|
+
if (word2(32) === null) return null;
|
|
410
1310
|
const partnerId = `0x${body.slice(64, 128)}`;
|
|
411
|
-
const count =
|
|
1311
|
+
const count = word2(64);
|
|
412
1312
|
if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
|
|
413
1313
|
const n = Number(count);
|
|
414
1314
|
const arrayBase = 96;
|
|
415
|
-
|
|
1315
|
+
let next = arrayBase + 32 * n;
|
|
416
1316
|
const orders = [];
|
|
417
1317
|
for (let i = 0; i < n; i += 1) {
|
|
418
|
-
const rel =
|
|
419
|
-
if (rel === null || rel !== BigInt(
|
|
420
|
-
const base =
|
|
1318
|
+
const rel = word2(arrayBase + i * 32);
|
|
1319
|
+
if (rel === null || rel !== BigInt(next - arrayBase)) return null;
|
|
1320
|
+
const base = next;
|
|
421
1321
|
const owner = addressAt(base);
|
|
422
1322
|
const bidToken = addressAt(base + 32);
|
|
423
|
-
const bidTokenAmount =
|
|
424
|
-
const askOffset =
|
|
425
|
-
const askTokenAmount =
|
|
426
|
-
const receiverOffset =
|
|
1323
|
+
const bidTokenAmount = word2(base + 64);
|
|
1324
|
+
const askOffset = word2(base + 96);
|
|
1325
|
+
const askTokenAmount = word2(base + 128);
|
|
1326
|
+
const receiverOffset = word2(base + 160);
|
|
427
1327
|
const destinationChainId = uint64At(base + 192);
|
|
428
1328
|
const executionChainId = uint64At(base + 224);
|
|
429
1329
|
const deadline = uint64At(base + 256);
|
|
430
|
-
if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES
|
|
1330
|
+
if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES) {
|
|
431
1331
|
return null;
|
|
432
1332
|
}
|
|
433
|
-
const askToken =
|
|
434
|
-
|
|
1333
|
+
const askToken = keyBytesAt(base + Number(askOffset));
|
|
1334
|
+
if (!askToken || receiverOffset !== ORDER_HEAD_BYTES + BigInt(askToken.size)) return null;
|
|
1335
|
+
const destinationReceiver = keyBytesAt(base + Number(receiverOffset));
|
|
435
1336
|
if (askToken === null || destinationReceiver === null) return null;
|
|
436
|
-
|
|
1337
|
+
next = base + Number(ORDER_HEAD_BYTES) + askToken.size + destinationReceiver.size;
|
|
1338
|
+
orders.push({ owner, bidToken, bidTokenAmount, askToken: askToken.value, askTokenAmount, destinationReceiver: destinationReceiver.value, destinationChainId, executionChainId, deadline });
|
|
437
1339
|
}
|
|
1340
|
+
if (next !== totalBytes) return null;
|
|
438
1341
|
return { partnerId, orders };
|
|
439
1342
|
}
|
|
440
1343
|
function toHexQuantity(value) {
|
|
@@ -442,47 +1345,343 @@ function toHexQuantity(value) {
|
|
|
442
1345
|
return `0x${n.toString(16)}`;
|
|
443
1346
|
}
|
|
444
1347
|
|
|
445
|
-
// src/core/
|
|
446
|
-
function
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
1348
|
+
// src/core/solana-tx.ts
|
|
1349
|
+
function bytesEqual(a, b) {
|
|
1350
|
+
return a.length === b.length && a.every((v, i) => v === b[i]);
|
|
1351
|
+
}
|
|
1352
|
+
function hexBytes(hex) {
|
|
1353
|
+
const h2 = strip0x(hex);
|
|
1354
|
+
if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
|
|
1355
|
+
return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
|
|
1356
|
+
}
|
|
1357
|
+
function solanaKeyBytes(key) {
|
|
1358
|
+
if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
|
|
1359
|
+
return base58Decode(key);
|
|
1360
|
+
}
|
|
1361
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1362
|
+
function base64Decode(text) {
|
|
1363
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) throw new Error("Invalid base64.");
|
|
1364
|
+
const out = [];
|
|
1365
|
+
let value = 0, bits = 0;
|
|
1366
|
+
for (const ch of text.replace(/=+$/, "")) {
|
|
1367
|
+
value = value << 6 | B64.indexOf(ch);
|
|
1368
|
+
bits += 6;
|
|
1369
|
+
if (bits >= 8) {
|
|
1370
|
+
bits -= 8;
|
|
1371
|
+
out.push(value >> bits & 255);
|
|
1372
|
+
}
|
|
451
1373
|
}
|
|
452
|
-
|
|
453
|
-
|
|
1374
|
+
const bytes = Uint8Array.from(out);
|
|
1375
|
+
if (base64Encode(bytes) !== text) throw new Error("Noncanonical base64.");
|
|
1376
|
+
return bytes;
|
|
1377
|
+
}
|
|
1378
|
+
function base64Encode(bytes) {
|
|
1379
|
+
let out = "";
|
|
1380
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
1381
|
+
const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
|
|
1382
|
+
out += B64[n >>> 18 & 63] + B64[n >>> 12 & 63] + (i + 1 < bytes.length ? B64[n >>> 6 & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
|
|
454
1383
|
}
|
|
455
|
-
|
|
456
|
-
|
|
1384
|
+
return out;
|
|
1385
|
+
}
|
|
1386
|
+
var Reader = class {
|
|
1387
|
+
constructor(bytes) {
|
|
1388
|
+
this.bytes = bytes;
|
|
1389
|
+
}
|
|
1390
|
+
bytes;
|
|
1391
|
+
at = 0;
|
|
1392
|
+
take(n) {
|
|
1393
|
+
if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error("Truncated Solana data.");
|
|
1394
|
+
const v = this.bytes.slice(this.at, this.at + n);
|
|
1395
|
+
this.at += n;
|
|
1396
|
+
return v;
|
|
1397
|
+
}
|
|
1398
|
+
byte() {
|
|
1399
|
+
return this.take(1)[0];
|
|
1400
|
+
}
|
|
1401
|
+
compact() {
|
|
1402
|
+
let n = 0;
|
|
1403
|
+
for (let i = 0; i < 3; i++) {
|
|
1404
|
+
const b = this.byte();
|
|
1405
|
+
if (i === 2 && b > 3) throw new Error("Invalid compact-u16.");
|
|
1406
|
+
n |= (b & 127) << 7 * i;
|
|
1407
|
+
if (!(b & 128)) {
|
|
1408
|
+
if (i && b === 0) throw new Error("Noncanonical compact-u16.");
|
|
1409
|
+
return n;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
throw new Error("Invalid compact-u16.");
|
|
457
1413
|
}
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
1414
|
+
u64() {
|
|
1415
|
+
const b = this.take(8);
|
|
1416
|
+
let n = 0n;
|
|
1417
|
+
for (let i = 7; i >= 0; i--) n = n << 8n | BigInt(b[i]);
|
|
1418
|
+
return n;
|
|
461
1419
|
}
|
|
462
|
-
|
|
1420
|
+
vec() {
|
|
1421
|
+
const b = this.take(4);
|
|
1422
|
+
return this.take(new DataView(b.buffer).getUint32(0, true));
|
|
1423
|
+
}
|
|
1424
|
+
end() {
|
|
1425
|
+
if (this.at !== this.bytes.length) throw new Error("Trailing Solana data.");
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
function parseSolanaTransaction(input) {
|
|
1429
|
+
const bytes = new Uint8Array(input), r = new Reader(bytes);
|
|
1430
|
+
const count = r.compact(), signatureOffset = r.at;
|
|
1431
|
+
if (count < 1 || count > 127) throw new Error("Invalid signature count.");
|
|
1432
|
+
r.take(count * 64);
|
|
1433
|
+
const messageOffset = r.at, first = r.byte();
|
|
1434
|
+
if (first & 128 && first !== 128) throw new Error("Unsupported Solana message version.");
|
|
1435
|
+
const version = first === 128 ? 0 : "legacy";
|
|
1436
|
+
const requiredSignatures = version === 0 ? r.byte() : first;
|
|
1437
|
+
const readonlySigned = r.byte(), readonlyUnsigned = r.byte();
|
|
1438
|
+
const keyCount = r.compact();
|
|
1439
|
+
if (requiredSignatures !== count || requiredSignatures > keyCount || readonlySigned >= count || readonlyUnsigned > keyCount - count || keyCount > 256) throw new Error("Invalid Solana message header.");
|
|
1440
|
+
const staticKeys = Array.from({ length: keyCount }, () => base58Encode(r.take(32)));
|
|
1441
|
+
const blockhashOffset = r.at;
|
|
1442
|
+
r.take(32);
|
|
1443
|
+
const instructions = Array.from({ length: r.compact() }, () => {
|
|
1444
|
+
const programIdIndex = r.byte();
|
|
1445
|
+
const accounts = Array.from(r.take(r.compact()));
|
|
1446
|
+
return { programIdIndex, accounts, data: r.take(r.compact()) };
|
|
1447
|
+
});
|
|
1448
|
+
const lookups = version === 0 ? Array.from({ length: r.compact() }, () => ({
|
|
1449
|
+
address: base58Encode(r.take(32)),
|
|
1450
|
+
writable: Array.from(r.take(r.compact())),
|
|
1451
|
+
readonly: Array.from(r.take(r.compact()))
|
|
1452
|
+
})) : [];
|
|
1453
|
+
r.end();
|
|
1454
|
+
const all = keyCount + lookups.reduce((n, l) => n + l.writable.length + l.readonly.length, 0);
|
|
1455
|
+
if (all > 256 || instructions.some((ix) => ix.programIdIndex >= keyCount || ix.accounts.some((i) => i >= all))) throw new Error("Invalid Solana account index.");
|
|
1456
|
+
return { bytes, messageOffset, blockhashOffset, version, requiredSignatures, signatureOffset, staticKeys, instructions, lookups };
|
|
1457
|
+
}
|
|
1458
|
+
function overwriteBlockhash(input, blockhash) {
|
|
1459
|
+
const tx = parseSolanaTransaction(input), out = new Uint8Array(input);
|
|
1460
|
+
out.set(solanaKeyBytes(blockhash), tx.blockhashOffset);
|
|
1461
|
+
return out;
|
|
463
1462
|
}
|
|
464
|
-
function
|
|
465
|
-
const
|
|
466
|
-
|
|
1463
|
+
function placeSignature(input, publicKey, signature) {
|
|
1464
|
+
const tx = parseSolanaTransaction(input), index = tx.staticKeys.slice(0, tx.requiredSignatures).indexOf(publicKey);
|
|
1465
|
+
if (index < 0 || signature.length !== 64) throw new Error("Missing Solana signer slot.");
|
|
1466
|
+
const out = new Uint8Array(input);
|
|
1467
|
+
out.set(signature, tx.signatureOffset + index * 64);
|
|
1468
|
+
return out;
|
|
467
1469
|
}
|
|
468
|
-
function
|
|
469
|
-
|
|
1470
|
+
function assertWalletMessage(original, signed) {
|
|
1471
|
+
const a = parseSolanaTransaction(original), b = parseSolanaTransaction(signed);
|
|
1472
|
+
if (!bytesEqual(a.bytes.subarray(a.messageOffset), b.bytes.subarray(b.messageOffset))) throw new Error("The wallet modified the transaction message; refusing to send.");
|
|
1473
|
+
for (let i = 1; i < a.requiredSignatures; i++) {
|
|
1474
|
+
const start2 = a.signatureOffset + 64 * i;
|
|
1475
|
+
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.");
|
|
1476
|
+
}
|
|
1477
|
+
if (!b.bytes.subarray(b.signatureOffset, b.signatureOffset + 64).some(Boolean)) throw new Error("The wallet returned no fee-payer signature.");
|
|
1478
|
+
}
|
|
1479
|
+
var SUBMIT_ORDER_DISCRIMINATOR = [230, 150, 200, 53, 92, 208, 109, 108];
|
|
1480
|
+
function isSubmitOrder(data) {
|
|
1481
|
+
return data.length >= 8 && SUBMIT_ORDER_DISCRIMINATOR.every((v, i) => data[i] === v);
|
|
1482
|
+
}
|
|
1483
|
+
function decodeSolanaSubmitOrder(data) {
|
|
1484
|
+
if (!isSubmitOrder(data)) throw new Error("Not a submit_order instruction.");
|
|
1485
|
+
const r = new Reader(data);
|
|
1486
|
+
r.take(8);
|
|
1487
|
+
const owner = r.take(20), askToken = r.vec();
|
|
1488
|
+
let askTokenAmount = 0n;
|
|
1489
|
+
for (const b of r.take(32)) askTokenAmount = askTokenAmount << 8n | BigInt(b);
|
|
1490
|
+
const bidTokenAmount = r.u64(), destinationReceiver = r.vec(), destinationChainId = r.u64(), executionChainId = r.u64(), deadline = r.u64();
|
|
1491
|
+
const tag = r.byte();
|
|
1492
|
+
if (tag !== 0 && tag !== 1) throw new Error("Invalid submit_order partner tag.");
|
|
1493
|
+
const partnerId = tag === 1 ? r.take(32) : null;
|
|
1494
|
+
r.end();
|
|
1495
|
+
return { owner, askToken, askTokenAmount, bidTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline, partnerId };
|
|
1496
|
+
}
|
|
1497
|
+
function verifySolanaSubmit(p, e) {
|
|
1498
|
+
const fail = (field) => {
|
|
1499
|
+
throw new Error(`Solana order mismatch (${field}); refusing to sign.`);
|
|
1500
|
+
};
|
|
1501
|
+
if (hexBytes(e.owner).length !== 20 || !bytesEqual(p.owner, hexBytes(e.owner))) fail("owner");
|
|
1502
|
+
if (!bytesEqual(p.askToken, hexBytes(e.askToken))) fail("ask token");
|
|
1503
|
+
if (p.askTokenAmount <= 0n) fail("non-positive output");
|
|
1504
|
+
if (p.askTokenAmount < BigInt(e.minAskTokenAmount)) fail("minimum received");
|
|
1505
|
+
if (p.askTokenAmount > BigInt(e.maxAskTokenAmount)) fail("maximum received");
|
|
1506
|
+
if (p.bidTokenAmount !== BigInt(e.bidTokenAmount)) fail("amount sent");
|
|
1507
|
+
if (!bytesEqual(p.destinationReceiver, hexBytes(e.destinationReceiver))) fail("receiver");
|
|
1508
|
+
if (p.destinationChainId !== BigInt(e.destinationChainId)) fail("destination chain");
|
|
1509
|
+
if (p.executionChainId !== BigInt(e.executionChainId)) fail("execution chain");
|
|
1510
|
+
if (p.deadline !== BigInt(e.deadline)) fail("deadline");
|
|
1511
|
+
if (p.partnerId !== null !== (e.partnerId !== null)) fail("subsidy marker");
|
|
1512
|
+
}
|
|
1513
|
+
var PREPARATION_INSTRUCTIONS = [
|
|
1514
|
+
{ discriminator: [225, 205, 234, 143, 17, 186, 50, 220], signer: 2 },
|
|
1515
|
+
// create_profile
|
|
1516
|
+
{ discriminator: [223, 99, 118, 101, 213, 29, 215, 137], signer: 3 },
|
|
1517
|
+
// initialize_buffer_data
|
|
1518
|
+
{ discriminator: [105, 254, 33, 182, 188, 80, 204, 204], signer: 3 },
|
|
1519
|
+
// write_buffer_data
|
|
1520
|
+
{ discriminator: [179, 249, 129, 154, 80, 167, 138, 18], signer: 3 },
|
|
1521
|
+
// finalize_buffer_data
|
|
1522
|
+
{ discriminator: [23, 25, 65, 45, 74, 9, 223, 23], signer: 2 }
|
|
1523
|
+
// close_buffer_data
|
|
1524
|
+
];
|
|
1525
|
+
var SUBMIT_SIGNER_ACCOUNT = 11;
|
|
1526
|
+
function preparationInstruction(data) {
|
|
1527
|
+
return data.length >= 8 ? PREPARATION_INSTRUCTIONS.find((p) => p.discriminator.every((byte, i) => data[i] === byte)) : void 0;
|
|
1528
|
+
}
|
|
1529
|
+
function verifySolanaTransaction(tx, expected, keys, mustSubmit) {
|
|
1530
|
+
if (tx.staticKeys[0] !== expected.signer) throw new Error("Wrong Solana fee payer; refusing to sign.");
|
|
1531
|
+
if (!mustSubmit && tx.requiredSignatures !== 1) throw new Error("Unexpected co-signer on a preparation step; refusing to sign.");
|
|
1532
|
+
let submits = 0, buffer = null;
|
|
1533
|
+
for (const ix of tx.instructions) {
|
|
1534
|
+
if (tx.staticKeys[ix.programIdIndex] !== expected.program) throw new Error("Foreign program instruction; refusing to sign.");
|
|
1535
|
+
const preparation = preparationInstruction(ix.data);
|
|
1536
|
+
if (!isSubmitOrder(ix.data) && !preparation) throw new Error("Unexpected ZeroDelta instruction; refusing to sign.");
|
|
1537
|
+
const signerSlot = preparation ? preparation.signer : SUBMIT_SIGNER_ACCOUNT;
|
|
1538
|
+
if (keys[ix.accounts[signerSlot]] !== expected.signer) throw new Error("ZeroDelta instruction names another signer; refusing to sign.");
|
|
1539
|
+
if (!isSubmitOrder(ix.data)) continue;
|
|
1540
|
+
submits++;
|
|
1541
|
+
verifySolanaSubmit(decodeSolanaSubmitOrder(ix.data), expected);
|
|
1542
|
+
if (keys[ix.accounts[1]] !== expected.mint) throw new Error("Wrong source mint; refusing to sign.");
|
|
1543
|
+
buffer = keys[ix.accounts[8]] ?? null;
|
|
1544
|
+
if (!buffer) throw new Error("Missing route buffer; refusing to sign.");
|
|
1545
|
+
}
|
|
1546
|
+
if (submits !== (mustSubmit ? 1 : 0)) throw new Error("Expected exactly one submit_order in submit and none in preparation; refusing to sign.");
|
|
1547
|
+
return buffer;
|
|
1548
|
+
}
|
|
1549
|
+
function parseAddressLookupTable(data) {
|
|
1550
|
+
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.");
|
|
1551
|
+
return Array.from({ length: (data.length - 56) / 32 }, (_, i) => base58Encode(data.subarray(56 + 32 * i, 88 + 32 * i)));
|
|
1552
|
+
}
|
|
1553
|
+
async function resolveSolanaKeys(tx, rpc) {
|
|
1554
|
+
if (!tx.lookups.length) return [...tx.staticKeys];
|
|
1555
|
+
const result = await rpc("getMultipleAccounts", [tx.lookups.map((l) => l.address), { encoding: "base64", commitment: "confirmed" }]);
|
|
1556
|
+
if (!Array.isArray(result.value) || result.value.length !== tx.lookups.length) throw new Error("Missing lookup tables.");
|
|
1557
|
+
const writable = [], readonly = [];
|
|
1558
|
+
tx.lookups.forEach((lookup, i) => {
|
|
1559
|
+
const account = result.value[i];
|
|
1560
|
+
if (account?.owner !== "AddressLookupTab1e1111111111111111111111111" || account.data[1] !== "base64") throw new Error("Invalid lookup table account.");
|
|
1561
|
+
const table = parseAddressLookupTable(base64Decode(account.data[0]));
|
|
1562
|
+
for (const [indexes, into] of [[lookup.writable, writable], [lookup.readonly, readonly]]) for (const index of indexes) {
|
|
1563
|
+
if (!table[index]) throw new Error("Lookup table index out of range.");
|
|
1564
|
+
into.push(table[index]);
|
|
1565
|
+
}
|
|
1566
|
+
});
|
|
1567
|
+
return [...tx.staticKeys, ...writable, ...readonly];
|
|
1568
|
+
}
|
|
1569
|
+
function encodeNextSolanaOrders(legs) {
|
|
1570
|
+
return legs.length ? hexBytes(`0x${uintWord(32)}${encodeSubmitOrder(legs).slice(10 + 128)}`) : new Uint8Array();
|
|
1571
|
+
}
|
|
1572
|
+
function checkSolanaRouteBuffer(account, expected) {
|
|
1573
|
+
if (!account || account.owner !== expected.program || account.data[1] !== "base64") throw new Error("Route buffer is not a ZeroDelta account.");
|
|
1574
|
+
const d = base64Decode(account.data[0]);
|
|
1575
|
+
if (d.length < 53) throw new Error("Route buffer truncated.");
|
|
1576
|
+
if (base58Encode(d.subarray(9, 41)) !== expected.signer) throw new Error("Route buffer signer mismatch.");
|
|
1577
|
+
const len = new DataView(d.buffer, d.byteOffset + 49, 4).getUint32(0, true);
|
|
1578
|
+
if (d.length < 53 + len || !bytesEqual(d.subarray(53, 53 + len), encodeNextSolanaOrders(expected.nextOrders))) throw new Error("Route buffer legs mismatch.");
|
|
1579
|
+
}
|
|
1580
|
+
function checkSolanaProgram(gateway, pinned, registry2) {
|
|
1581
|
+
const program = gateway || registry2 || "";
|
|
1582
|
+
solanaKeyBytes(program);
|
|
1583
|
+
if (pinned ? program !== pinned : gateway && registry2 && gateway !== registry2) throw new Error("Solana program does not match pin or chains registry.");
|
|
1584
|
+
return program;
|
|
1585
|
+
}
|
|
1586
|
+
function checkSolanaPlan(txs) {
|
|
1587
|
+
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.");
|
|
1588
|
+
}
|
|
1589
|
+
async function deriveSolanaEvent(signer, salt) {
|
|
1590
|
+
const s = hexBytes(salt), material = new Uint8Array(32 + s.length);
|
|
1591
|
+
material.set(solanaKeyBytes(signer));
|
|
1592
|
+
material.set(s, 32);
|
|
1593
|
+
const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", material));
|
|
1594
|
+
const { eventPublicKey: eventPublicKey2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
|
|
1595
|
+
return { seed, publicKey: base58Encode(await eventPublicKey2(seed)) };
|
|
1596
|
+
}
|
|
1597
|
+
async function cosignSolanaEvent(bytes, signer, build) {
|
|
1598
|
+
const event = await deriveSolanaEvent(signer, build.salt);
|
|
1599
|
+
if (event.publicKey !== build.messageSentEventData) throw new Error("Event buildData key mismatch; refusing to sign.");
|
|
1600
|
+
const tx = parseSolanaTransaction(bytes);
|
|
1601
|
+
const { eventSignature: eventSignature2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
|
|
1602
|
+
return placeSignature(bytes, event.publicKey, await eventSignature2(tx.bytes.subarray(tx.messageOffset), event.seed));
|
|
1603
|
+
}
|
|
1604
|
+
async function pollSolanaConfirmation(rpc, signature) {
|
|
1605
|
+
const deadline = Date.now() + 9e4;
|
|
1606
|
+
while (Date.now() < deadline) {
|
|
1607
|
+
const { value } = await rpc("getSignatureStatuses", [[signature]]);
|
|
1608
|
+
const status = value?.[0];
|
|
1609
|
+
if (status?.err) throw new Error(`Transaction failed on chain: ${JSON.stringify(status.err)}`);
|
|
1610
|
+
if (["confirmed", "finalized"].includes(status?.confirmationStatus)) return;
|
|
1611
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
1612
|
+
}
|
|
1613
|
+
throw new Error("Transaction confirmation timed out; check the signature before retrying.");
|
|
470
1614
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
1615
|
+
|
|
1616
|
+
// src/core/units.ts
|
|
1617
|
+
function assetDecimals(token) {
|
|
1618
|
+
const sym = symbolKey(token?.symbol);
|
|
1619
|
+
const registry2 = Number(token?.decimals);
|
|
1620
|
+
const canonical = isSolanaChainId(token?.chainId) ? solanaDestinationAsset(token?.address)?.decimals : CANONICAL_DECIMALS[sym];
|
|
1621
|
+
if (canonical !== void 0) {
|
|
1622
|
+
if (!Number.isInteger(registry2)) {
|
|
1623
|
+
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
1624
|
+
}
|
|
1625
|
+
if (registry2 !== canonical) {
|
|
1626
|
+
throw new Error(`ZeroDelta token registry reported ${registry2} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
1627
|
+
}
|
|
1628
|
+
return canonical;
|
|
476
1629
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
1630
|
+
if (!Number.isInteger(registry2) || registry2 < 0 || registry2 > 36) {
|
|
1631
|
+
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
1632
|
+
}
|
|
1633
|
+
return registry2;
|
|
480
1634
|
}
|
|
481
|
-
function
|
|
482
|
-
const
|
|
483
|
-
if (
|
|
484
|
-
if (
|
|
485
|
-
|
|
1635
|
+
function normalizeDecimalText(value) {
|
|
1636
|
+
const text = String(value || "").trim().replace(/\s+/g, "");
|
|
1637
|
+
if (!text) return "";
|
|
1638
|
+
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
1639
|
+
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
1640
|
+
if (text.includes(",")) return "";
|
|
1641
|
+
return text;
|
|
1642
|
+
}
|
|
1643
|
+
function parseUnitsDecimal(amount, decimals) {
|
|
1644
|
+
const text = normalizeDecimalText(amount);
|
|
1645
|
+
if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
|
|
1646
|
+
const [whole, frac = ""] = text.split(".");
|
|
1647
|
+
if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
|
|
1648
|
+
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
1649
|
+
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
1650
|
+
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
1651
|
+
return value;
|
|
1652
|
+
}
|
|
1653
|
+
function scaleDecimals(amount, fromDecimals, toDecimals) {
|
|
1654
|
+
if (toDecimals === fromDecimals) return amount;
|
|
1655
|
+
if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
|
1656
|
+
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
1657
|
+
}
|
|
1658
|
+
function formatUnits(raw2, decimals, maxDecimals = 6) {
|
|
1659
|
+
const value = BigInt(raw2 || "0");
|
|
1660
|
+
const base = 10n ** BigInt(decimals);
|
|
1661
|
+
const whole = value / base;
|
|
1662
|
+
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
1663
|
+
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
1664
|
+
return frac ? `${whole}.${frac}` : whole.toString();
|
|
1665
|
+
}
|
|
1666
|
+
function finalOf(quote) {
|
|
1667
|
+
return BigInt(quote?.finalAmount || quote?.toAmount || "0");
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// src/core/ask-scale.ts
|
|
1671
|
+
function askTokenDecimals(quote, tokens, _from, to) {
|
|
1672
|
+
const requests = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
|
|
1673
|
+
const execution = Number(requests[requests.length - 1]?.executionChainId || quote.executionChainId);
|
|
1674
|
+
if (!Number.isSafeInteger(execution) || execution <= 0) throw new Error("Could not verify the quote amount precision.");
|
|
1675
|
+
if (execution === Number(to.chainId)) return assetDecimals(to);
|
|
1676
|
+
const row = tokens.find((token) => Number(token.chainId) === execution && symbolKey(token.symbol) === symbolKey(to.symbol));
|
|
1677
|
+
if (row) return assetDecimals(row);
|
|
1678
|
+
if (isSolanaChainId(to.chainId)) throw new Error("Could not verify the quote amount precision.");
|
|
1679
|
+
return assetDecimals(to);
|
|
1680
|
+
}
|
|
1681
|
+
function askCovers(ask, final, askDecimals, finalDecimals) {
|
|
1682
|
+
if (![askDecimals, finalDecimals].every((n) => Number.isInteger(n) && n >= 0 && n <= 36)) throw new Error("Could not verify the quote amount precision.");
|
|
1683
|
+
const shift = askDecimals - finalDecimals;
|
|
1684
|
+
return shift >= 0 ? ask >= final * 10n ** BigInt(shift) : ask * 10n ** BigInt(-shift) >= final;
|
|
486
1685
|
}
|
|
487
1686
|
|
|
488
1687
|
// src/core/ticker.ts
|
|
@@ -523,7 +1722,7 @@ function counterpartTokens(tokens, selected) {
|
|
|
523
1722
|
return tokens.filter((token) => assetClassOf(token.symbol) === want);
|
|
524
1723
|
}
|
|
525
1724
|
function tokenKey(chainId, address) {
|
|
526
|
-
return `${Number(chainId)}:${
|
|
1725
|
+
return `${Number(chainId)}:${chainAddressKey(chainId, address)}`;
|
|
527
1726
|
}
|
|
528
1727
|
function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
|
|
529
1728
|
return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
|
|
@@ -559,35 +1758,35 @@ function isSourceToken(token, ctx) {
|
|
|
559
1758
|
if (!ctx.sourceChains.has(chainId)) return false;
|
|
560
1759
|
return ctx.execution.has(chainId) || !isKnownUnbridgeable(token.bridge) && ctx.source.has(tokenKey(chainId, token.address));
|
|
561
1760
|
}
|
|
562
|
-
function directLaneOK(token,
|
|
563
|
-
if (!
|
|
564
|
-
if (symbolKey(
|
|
565
|
-
if (Number(
|
|
566
|
-
return lanes.has(laneKey(
|
|
1761
|
+
function directLaneOK(token, source2, lanes) {
|
|
1762
|
+
if (!source2 || !lanes) return true;
|
|
1763
|
+
if (symbolKey(source2.symbol) !== symbolKey(token.symbol)) return true;
|
|
1764
|
+
if (Number(source2.chainId) === Number(token.chainId)) return true;
|
|
1765
|
+
return lanes.has(laneKey(source2.chainId, source2.address, token.chainId, token.address));
|
|
567
1766
|
}
|
|
568
|
-
function brokenLaneFor(token,
|
|
569
|
-
if (!
|
|
570
|
-
return brokenLanes.get(laneKey(
|
|
1767
|
+
function brokenLaneFor(token, source2, brokenLanes) {
|
|
1768
|
+
if (!source2 || !brokenLanes) return void 0;
|
|
1769
|
+
return brokenLanes.get(laneKey(source2.chainId, source2.address, token.chainId, token.address));
|
|
571
1770
|
}
|
|
572
|
-
function laneLimitFor(token,
|
|
573
|
-
if (!
|
|
574
|
-
return limitedLanes2.get(laneKey(
|
|
1771
|
+
function laneLimitFor(token, source2, limitedLanes2) {
|
|
1772
|
+
if (!source2 || !limitedLanes2) return void 0;
|
|
1773
|
+
return limitedLanes2.get(laneKey(source2.chainId, source2.address, token.chainId, token.address));
|
|
575
1774
|
}
|
|
576
|
-
function destinationAvailability(token, ctx,
|
|
577
|
-
if (brokenLaneFor(token,
|
|
578
|
-
if (directLaneOK(token,
|
|
1775
|
+
function destinationAvailability(token, ctx, source2) {
|
|
1776
|
+
if (brokenLaneFor(token, source2 ?? void 0, ctx.brokenLanes)) return "unreachable";
|
|
1777
|
+
if (directLaneOK(token, source2 ?? void 0, ctx.lanes)) {
|
|
579
1778
|
if (ctx.execution.has(Number(token.chainId))) return "available";
|
|
580
1779
|
if (token.isChainedDestination === true) return "available";
|
|
581
1780
|
if (!isKnownUnbridgeable(token.bridge) && ctx.destination.has(tokenKey(token.chainId, token.address))) return "available";
|
|
582
1781
|
}
|
|
583
1782
|
return ctx.hubSymbols.has(symbolKey(token.symbol)) ? "hub-only" : "unreachable";
|
|
584
1783
|
}
|
|
585
|
-
function hasReachableDestination(
|
|
1784
|
+
function hasReachableDestination(source2, catalogue, ctx) {
|
|
586
1785
|
if (catalogue.length === 0) return true;
|
|
587
|
-
const from = tokenKey(
|
|
1786
|
+
const from = tokenKey(source2.chainId, source2.address);
|
|
588
1787
|
for (const candidate of catalogue) {
|
|
589
1788
|
if (tokenKey(candidate.chainId, candidate.address) === from) continue;
|
|
590
|
-
if (destinationAvailability(candidate, ctx,
|
|
1789
|
+
if (destinationAvailability(candidate, ctx, source2) === "available") return true;
|
|
591
1790
|
}
|
|
592
1791
|
return false;
|
|
593
1792
|
}
|
|
@@ -601,7 +1800,7 @@ function buildCatalogue(input) {
|
|
|
601
1800
|
const sourceChains = new Set([...registryChainIds].filter((id) => supportedChainIds.has(id)));
|
|
602
1801
|
const execution = executionChainIds(enabledChains);
|
|
603
1802
|
const projected = product === "rwa" ? routes.filter((route) => route.isEnabled !== false) : executableRoutes(routes);
|
|
604
|
-
const
|
|
1803
|
+
const source2 = sourceKeys(projected);
|
|
605
1804
|
const destination = destinationKeys(projected);
|
|
606
1805
|
const lanes = laneKeys(projected);
|
|
607
1806
|
const chainIds = new Set(sourceChains);
|
|
@@ -609,19 +1808,19 @@ function buildCatalogue(input) {
|
|
|
609
1808
|
const id = Number(route.toChainId);
|
|
610
1809
|
if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
|
|
611
1810
|
}
|
|
612
|
-
const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
|
|
1811
|
+
const allowed = tokens.filter((token) => token.isEnabled !== false && isChainAddress(token.chainId, token.address) && allowedAssets.has(symbolKey(token.symbol)));
|
|
613
1812
|
const projectedCatalogue = allowed.filter((token) => {
|
|
614
1813
|
if (!chainIds.has(Number(token.chainId))) return false;
|
|
615
1814
|
if (product === "rwa") return true;
|
|
616
1815
|
if (!isExecutableBridge(token)) return false;
|
|
617
1816
|
const key = tokenKey(token.chainId, token.address);
|
|
618
|
-
return
|
|
1817
|
+
return source2.has(key) || destination.has(key) || execution.has(Number(token.chainId));
|
|
619
1818
|
});
|
|
620
1819
|
const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
|
|
621
1820
|
const catalogue = ready ? projectedCatalogue : allowed;
|
|
622
1821
|
const hubSymbols = hubDeliverableSymbols(catalogue, execution);
|
|
623
|
-
const ctx = { source, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
|
|
624
|
-
const
|
|
1822
|
+
const ctx = { source: source2, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
|
|
1823
|
+
const sources2 = ready ? catalogue.filter((token) => isSourceToken(token, ctx) && hasReachableDestination(token, catalogue, ctx)) : (
|
|
625
1824
|
// Unprojected: the only rule we can still apply with confidence is the escrow-chain bound,
|
|
626
1825
|
// which comes from this build's own pins rather than from the registry.
|
|
627
1826
|
catalogue.filter((token) => sourceChains.has(Number(token.chainId)))
|
|
@@ -632,7 +1831,7 @@ function buildCatalogue(input) {
|
|
|
632
1831
|
...ctx,
|
|
633
1832
|
product,
|
|
634
1833
|
tokens: catalogue,
|
|
635
|
-
sources,
|
|
1834
|
+
sources: sources2,
|
|
636
1835
|
chainIds,
|
|
637
1836
|
chains: [...byId.values()],
|
|
638
1837
|
ready,
|
|
@@ -643,19 +1842,19 @@ function buildCatalogue(input) {
|
|
|
643
1842
|
|
|
644
1843
|
// src/core/options.ts
|
|
645
1844
|
function chainNameOf(chainId, chains) {
|
|
646
|
-
const
|
|
647
|
-
return
|
|
1845
|
+
const chain2 = chains.find((item) => Number(item.chainId) === Number(chainId));
|
|
1846
|
+
return chain2?.displayName || chain2?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
|
|
648
1847
|
}
|
|
649
1848
|
function chainById(chains, chainId) {
|
|
650
|
-
return chains.find((
|
|
1849
|
+
return chains.find((chain2) => Number(chain2.chainId) === Number(chainId)) || null;
|
|
651
1850
|
}
|
|
652
|
-
function chainSelectable(
|
|
1851
|
+
function chainSelectable(chain2, chainId) {
|
|
653
1852
|
if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
|
|
654
|
-
if (!
|
|
655
|
-
return
|
|
1853
|
+
if (!chain2) return true;
|
|
1854
|
+
return chain2.isEnabled !== false;
|
|
656
1855
|
}
|
|
657
1856
|
function tokenEnabled(token) {
|
|
658
|
-
return token?.isEnabled !== false &&
|
|
1857
|
+
return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
|
|
659
1858
|
}
|
|
660
1859
|
function findToken(tokens, chainId, symbol) {
|
|
661
1860
|
const key = symbolKey(symbol);
|
|
@@ -691,8 +1890,8 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
691
1890
|
for (const token of universe) {
|
|
692
1891
|
if (!tokenEnabled(token)) continue;
|
|
693
1892
|
const chainId = Number(token.chainId);
|
|
694
|
-
const
|
|
695
|
-
if (!chainSelectable(
|
|
1893
|
+
const chain2 = chainById(chains, chainId);
|
|
1894
|
+
if (!chainSelectable(chain2, chainId)) continue;
|
|
696
1895
|
const key = tokenKey(chainId, token.address);
|
|
697
1896
|
if (seen.has(key)) continue;
|
|
698
1897
|
if (refusal(token)) continue;
|
|
@@ -714,38 +1913,633 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
714
1913
|
direct
|
|
715
1914
|
});
|
|
716
1915
|
}
|
|
717
|
-
options.sort((a, b) => {
|
|
718
|
-
const walletChain = Number(walletChainId || 0);
|
|
719
|
-
if (walletChain) {
|
|
720
|
-
if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
|
|
721
|
-
if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
|
|
722
|
-
}
|
|
723
|
-
if (a.direct !== b.direct) return a.direct ? -1 : 1;
|
|
724
|
-
if (a.symbolKey !== b.symbolKey) {
|
|
725
|
-
if (a.symbolKey === invoiceKey) return -1;
|
|
726
|
-
if (b.symbolKey === invoiceKey) return 1;
|
|
727
|
-
return a.symbolKey.localeCompare(b.symbolKey);
|
|
728
|
-
}
|
|
729
|
-
if (a.sameChain !== b.sameChain) return a.sameChain ? -1 : 1;
|
|
730
|
-
return a.chainId - b.chainId;
|
|
731
|
-
});
|
|
732
|
-
return options;
|
|
1916
|
+
options.sort((a, b) => {
|
|
1917
|
+
const walletChain = Number(walletChainId || 0);
|
|
1918
|
+
if (walletChain) {
|
|
1919
|
+
if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
|
|
1920
|
+
if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
|
|
1921
|
+
}
|
|
1922
|
+
if (a.direct !== b.direct) return a.direct ? -1 : 1;
|
|
1923
|
+
if (a.symbolKey !== b.symbolKey) {
|
|
1924
|
+
if (a.symbolKey === invoiceKey) return -1;
|
|
1925
|
+
if (b.symbolKey === invoiceKey) return 1;
|
|
1926
|
+
return a.symbolKey.localeCompare(b.symbolKey);
|
|
1927
|
+
}
|
|
1928
|
+
if (a.sameChain !== b.sameChain) return a.sameChain ? -1 : 1;
|
|
1929
|
+
return a.chainId - b.chainId;
|
|
1930
|
+
});
|
|
1931
|
+
return options;
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
// src/core/solana-source.ts
|
|
1935
|
+
var CANONICAL_SOLANA_PROGRAM = "zd1E5feCJLNYaPPsBAYkCPMKGVnipYf8God9h917W33";
|
|
1936
|
+
var MAX_ASK_OVER_FINAL_BPS = 200n;
|
|
1937
|
+
var states = /* @__PURE__ */ new WeakMap();
|
|
1938
|
+
var quoteRequests = /* @__PURE__ */ new WeakMap();
|
|
1939
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
1940
|
+
var activeSigners = /* @__PURE__ */ new Set();
|
|
1941
|
+
var clone = (value) => JSON.parse(JSON.stringify(value));
|
|
1942
|
+
function freeze(value) {
|
|
1943
|
+
if (value && typeof value === "object") {
|
|
1944
|
+
for (const v of Object.values(value)) freeze(v);
|
|
1945
|
+
Object.freeze(value);
|
|
1946
|
+
}
|
|
1947
|
+
return value;
|
|
1948
|
+
}
|
|
1949
|
+
function raw(value, label2, positive = false) {
|
|
1950
|
+
if (typeof value !== "string" || !/^\d+$/.test(value) || positive && BigInt(value) <= 0n || BigInt(value) >= 1n << 256n) throw new Error(`Invalid ${label2}.`);
|
|
1951
|
+
return value;
|
|
1952
|
+
}
|
|
1953
|
+
function chain(value) {
|
|
1954
|
+
const text = String(value);
|
|
1955
|
+
if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) >= 1n << 64n) throw new Error("Invalid order chain.");
|
|
1956
|
+
return text;
|
|
1957
|
+
}
|
|
1958
|
+
function same(a, b) {
|
|
1959
|
+
return a.toLowerCase() === b.toLowerCase();
|
|
1960
|
+
}
|
|
1961
|
+
function recipient(input) {
|
|
1962
|
+
const to = input.recipient || (isSolanaChainId(input.toChainId) ? input.sender : input.owner);
|
|
1963
|
+
if (!isChainAddress(input.toChainId, to)) throw new Error("Invalid destination recipient.");
|
|
1964
|
+
return chainAddressKey(input.toChainId, to);
|
|
1965
|
+
}
|
|
1966
|
+
function validateInput(input) {
|
|
1967
|
+
if (input.fromChainId !== void 0 && input.fromChainId !== SOLANA_CHAIN_ID) throw new Error("Solana source chain required.");
|
|
1968
|
+
if (!Number.isSafeInteger(input.toChainId) || input.toChainId <= 0) throw new Error("Invalid destination chain.");
|
|
1969
|
+
if (!SUPPORTED_ASSETS.has(symbolKey(input.fromToken)) || !SUPPORTED_ASSETS.has(symbolKey(input.toToken))) throw new Error("Unsupported Solana source asset.");
|
|
1970
|
+
assertAddress(input.owner, "EVM order owner");
|
|
1971
|
+
solanaKeyBytes(input.sender);
|
|
1972
|
+
recipient(input);
|
|
1973
|
+
const span = input.deadlineSpanSeconds ?? 7200, slip = input.slippageBps ?? 0;
|
|
1974
|
+
if (!Number.isInteger(span) || span < 1 || span > 86400) throw new Error("Invalid Solana deadline span.");
|
|
1975
|
+
if (!Number.isInteger(slip) || slip < 0 || slip > 1e4) throw new Error("Invalid slippage tolerance.");
|
|
1976
|
+
}
|
|
1977
|
+
function selections(input, tokens) {
|
|
1978
|
+
validateInput(input);
|
|
1979
|
+
const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
|
|
1980
|
+
if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
|
|
1981
|
+
solanaKeyBytes(from.address);
|
|
1982
|
+
assertPinnedSolanaSource(from);
|
|
1983
|
+
if (!isChainAddress(input.toChainId, to.address)) throw new Error("Invalid destination token.");
|
|
1984
|
+
const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
|
|
1985
|
+
raw(amount, "input amount", true);
|
|
1986
|
+
if (BigInt(amount) >= 1n << 64n) throw new Error("Solana bid exceeds u64.");
|
|
1987
|
+
return { from, to, amount };
|
|
1988
|
+
}
|
|
1989
|
+
function assertPinnedSolanaSource(token) {
|
|
1990
|
+
const pinned = solanaDestinationAsset(token.address);
|
|
1991
|
+
if (!pinned || pinned.symbol !== symbolKey(token.symbol) || pinned.decimals !== Number(token.decimals)) {
|
|
1992
|
+
throw new Error("This Solana token is not supported for payment; refusing to sign.");
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
function makeRequest(input, from, to, amount) {
|
|
1996
|
+
return {
|
|
1997
|
+
inputChain: SOLANA_CHAIN_ID,
|
|
1998
|
+
outputChain: input.toChainId,
|
|
1999
|
+
inputToken: from.symbol,
|
|
2000
|
+
outputToken: to.symbol,
|
|
2001
|
+
inputAmount: amount,
|
|
2002
|
+
owners: { evm: input.owner },
|
|
2003
|
+
destinationWallet: recipient(input),
|
|
2004
|
+
sender: input.sender,
|
|
2005
|
+
deadline: String(Math.floor(Date.now() / 1e3) + (input.deadlineSpanSeconds ?? 7200))
|
|
2006
|
+
};
|
|
2007
|
+
}
|
|
2008
|
+
function normalizePreview(request, quote, to, amount) {
|
|
2009
|
+
const option = quote?.options?.[0];
|
|
2010
|
+
if (!option) throw new Error("Native quote returned no options.");
|
|
2011
|
+
const receive = raw(option.finalAmount, "quoted output", true);
|
|
2012
|
+
return {
|
|
2013
|
+
receive: formatUnits(receive, assetDecimals(to)),
|
|
2014
|
+
receiveRaw: receive,
|
|
2015
|
+
fromAmount: amount,
|
|
2016
|
+
fromToken: request.inputToken,
|
|
2017
|
+
toToken: request.outputToken,
|
|
2018
|
+
bridge: option.bridge || "",
|
|
2019
|
+
feeBps: Number(option.feeBps || 0),
|
|
2020
|
+
estimatedDuration: Number(option.estimatedTimeSec || 0),
|
|
2021
|
+
via: null,
|
|
2022
|
+
nativeFeeRaw: String(option.gasCostSource || "0"),
|
|
2023
|
+
quote,
|
|
2024
|
+
option,
|
|
2025
|
+
txData: option.txData,
|
|
2026
|
+
request
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
async function quoteSolanaSource(api, input) {
|
|
2030
|
+
const { from, to, amount } = selections(input, await api.fetchTokens());
|
|
2031
|
+
const request = makeRequest(input, from, to, amount);
|
|
2032
|
+
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
2033
|
+
const preview = normalizePreview(request, quote, to, input.amountIn);
|
|
2034
|
+
quoteRequests.set(preview, { api, request: clone(request) });
|
|
2035
|
+
return preview;
|
|
2036
|
+
}
|
|
2037
|
+
async function previewSolanaSource(api, input) {
|
|
2038
|
+
const tokens = await api.fetchTokens();
|
|
2039
|
+
const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
|
|
2040
|
+
if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
|
|
2041
|
+
assertPinnedSolanaSource(from);
|
|
2042
|
+
const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
|
|
2043
|
+
raw(amount, "input amount", true);
|
|
2044
|
+
const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
|
|
2045
|
+
const request = body;
|
|
2046
|
+
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
2047
|
+
const option = quote?.options?.[0];
|
|
2048
|
+
if (!option) throw new Error("Native quote returned no options.");
|
|
2049
|
+
const receive = raw(option.finalAmount, "quoted output", true);
|
|
2050
|
+
return {
|
|
2051
|
+
receive: formatUnits(receive, assetDecimals(to)),
|
|
2052
|
+
receiveRaw: receive,
|
|
2053
|
+
fromAmount: input.amountIn,
|
|
2054
|
+
fromToken: request.inputToken,
|
|
2055
|
+
toToken: request.outputToken,
|
|
2056
|
+
bridge: option.bridge || "",
|
|
2057
|
+
feeBps: Number(option.feeBps || 0),
|
|
2058
|
+
estimatedDuration: Number(option.estimatedTimeSec || 0),
|
|
2059
|
+
via: null,
|
|
2060
|
+
nativeFeeRaw: "0"
|
|
2061
|
+
};
|
|
2062
|
+
}
|
|
2063
|
+
function solanaQuoteCompliance(quote) {
|
|
2064
|
+
for (const value of [quote?.complianceDecision, quote?.compliance]) {
|
|
2065
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value;
|
|
2066
|
+
}
|
|
2067
|
+
return void 0;
|
|
2068
|
+
}
|
|
2069
|
+
function denied(value) {
|
|
2070
|
+
return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
|
|
2071
|
+
}
|
|
2072
|
+
async function checkActiveScreens(api, input) {
|
|
2073
|
+
const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
|
|
2074
|
+
const screens = await Promise.all(addresses.map(async (address) => {
|
|
2075
|
+
try {
|
|
2076
|
+
return await api.screenWallet(address);
|
|
2077
|
+
} catch {
|
|
2078
|
+
return void 0;
|
|
2079
|
+
}
|
|
2080
|
+
}));
|
|
2081
|
+
if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
|
|
2082
|
+
}
|
|
2083
|
+
function jsonGuards(input, preview, tokens, chains) {
|
|
2084
|
+
const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
|
|
2085
|
+
const wanted = makeRequest(input, from, to, amount);
|
|
2086
|
+
for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
|
|
2087
|
+
if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
|
|
2088
|
+
}
|
|
2089
|
+
if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
|
|
2090
|
+
const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
|
|
2091
|
+
if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
|
|
2092
|
+
if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
|
|
2093
|
+
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.");
|
|
2094
|
+
if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
|
|
2095
|
+
if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
|
|
2096
|
+
if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
|
|
2097
|
+
if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
|
|
2098
|
+
checkSolanaPlan(option.txData);
|
|
2099
|
+
const orders = option.orderRequests;
|
|
2100
|
+
if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
|
|
2101
|
+
const first = orders[0], last = orders[orders.length - 1];
|
|
2102
|
+
if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
|
|
2103
|
+
if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
|
|
2104
|
+
const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
|
|
2105
|
+
if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
|
|
2106
|
+
if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
|
|
2107
|
+
for (let i = 0; i < orders.length; i++) {
|
|
2108
|
+
const order = orders[i];
|
|
2109
|
+
if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
|
|
2110
|
+
raw(order.askTokenAmount, "ask amount", true);
|
|
2111
|
+
raw(order.bidTokenAmount, "bid amount", true);
|
|
2112
|
+
chain(order.destinationChainId);
|
|
2113
|
+
chain(order.executionChainId);
|
|
2114
|
+
if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
|
|
2115
|
+
if (isSolanaChainId(order.destinationChainId)) {
|
|
2116
|
+
if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
|
|
2117
|
+
solanaBridgeOf(to);
|
|
2118
|
+
checkSolanaReceiver(order, recipient(input), to.address);
|
|
2119
|
+
} else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
|
|
2120
|
+
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.");
|
|
2121
|
+
if (i) {
|
|
2122
|
+
const previous = orders[i - 1];
|
|
2123
|
+
if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
|
|
2124
|
+
if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
const quoteForScale = { ...option, orderRequests: orders };
|
|
2128
|
+
const execution = Number(last.executionChainId);
|
|
2129
|
+
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.");
|
|
2130
|
+
const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
|
|
2131
|
+
const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
|
|
2132
|
+
const minFinal = final * (10000n - slip) / 10000n;
|
|
2133
|
+
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.");
|
|
2134
|
+
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.");
|
|
2135
|
+
const registry2 = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
|
|
2136
|
+
const contracts = registry2?.contracts;
|
|
2137
|
+
const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry2?.escrowContract);
|
|
2138
|
+
const marker = option.partnerId ?? preview.quote.partnerId;
|
|
2139
|
+
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.");
|
|
2140
|
+
const ask = BigInt(first.askTokenAmount);
|
|
2141
|
+
return {
|
|
2142
|
+
program,
|
|
2143
|
+
signer: input.sender,
|
|
2144
|
+
mint: from.address,
|
|
2145
|
+
owner: input.owner,
|
|
2146
|
+
askToken: first.askToken,
|
|
2147
|
+
minAskTokenAmount: ask.toString(),
|
|
2148
|
+
maxAskTokenAmount: ask.toString(),
|
|
2149
|
+
bidTokenAmount: amount,
|
|
2150
|
+
destinationReceiver: first.destinationReceiver,
|
|
2151
|
+
destinationChainId: String(first.destinationChainId),
|
|
2152
|
+
executionChainId: String(first.executionChainId),
|
|
2153
|
+
deadline: request.deadline,
|
|
2154
|
+
partnerId: marker == null ? null : String(marker),
|
|
2155
|
+
nextOrders: orders.slice(1)
|
|
2156
|
+
};
|
|
2157
|
+
}
|
|
2158
|
+
async function buildSolanaSourcePlan(api, input, quoted) {
|
|
2159
|
+
const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
|
|
2160
|
+
const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
|
|
2161
|
+
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.");
|
|
2162
|
+
const preview = clone(served);
|
|
2163
|
+
const expected = jsonGuards(input, preview, tokens, chains);
|
|
2164
|
+
await checkActiveScreens(api, input);
|
|
2165
|
+
const plan = freeze({ preview, expected, txData: preview.option.txData });
|
|
2166
|
+
const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
|
|
2167
|
+
states.set(plan, {
|
|
2168
|
+
api,
|
|
2169
|
+
input: clone(input),
|
|
2170
|
+
plan,
|
|
2171
|
+
failed: false,
|
|
2172
|
+
busy: false,
|
|
2173
|
+
originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
|
|
2174
|
+
signatures: [],
|
|
2175
|
+
done: 0
|
|
2176
|
+
});
|
|
2177
|
+
return plan;
|
|
2178
|
+
}
|
|
2179
|
+
function createSolanaRpc(api) {
|
|
2180
|
+
return async (method, params) => {
|
|
2181
|
+
const body = await api.apiRequest("/solana-rpc", {
|
|
2182
|
+
method: "POST",
|
|
2183
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
2184
|
+
timeoutMs: 15e3
|
|
2185
|
+
});
|
|
2186
|
+
if (body.error && solanaLamportShortfall(body.error.data?.logs) !== null) throw new Error(SOL_SHORTFALL_MESSAGE);
|
|
2187
|
+
if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
|
|
2188
|
+
return body.result;
|
|
2189
|
+
};
|
|
2190
|
+
}
|
|
2191
|
+
var SolanaSendError = class extends Error {
|
|
2192
|
+
constructor(message, signature, sentAt) {
|
|
2193
|
+
super(message);
|
|
2194
|
+
this.signature = signature;
|
|
2195
|
+
this.sentAt = sentAt;
|
|
2196
|
+
this.name = "SolanaSendError";
|
|
2197
|
+
}
|
|
2198
|
+
signature;
|
|
2199
|
+
sentAt;
|
|
2200
|
+
};
|
|
2201
|
+
async function executeSolanaPlan(input) {
|
|
2202
|
+
const signature = await runSolanaPlan(input, false);
|
|
2203
|
+
if (!signature) throw new Error("Missing final Solana submit.");
|
|
2204
|
+
return signature;
|
|
2205
|
+
}
|
|
2206
|
+
async function executeSolanaPlanStaged(input) {
|
|
2207
|
+
const signature = await runSolanaPlan(input, true);
|
|
2208
|
+
return signature ? { status: "sent", signature } : { status: "prepared" };
|
|
2209
|
+
}
|
|
2210
|
+
function solanaPlanNeedsPreparation(plan) {
|
|
2211
|
+
const state = states.get(plan);
|
|
2212
|
+
const live = state?.plan ?? plan;
|
|
2213
|
+
return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
|
|
2214
|
+
}
|
|
2215
|
+
async function runSolanaPlan(input, stopBeforeSubmit) {
|
|
2216
|
+
const state = states.get(input.plan);
|
|
2217
|
+
if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
|
|
2218
|
+
if (state.sent) return state.sent;
|
|
2219
|
+
if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
|
|
2220
|
+
if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
|
|
2221
|
+
state.busy = true;
|
|
2222
|
+
activeSigners.add(input.signer.publicKey);
|
|
2223
|
+
let index = 0, completedBeforeRun = state.signatures.length;
|
|
2224
|
+
const progress = (stage) => {
|
|
2225
|
+
const pending = inFlight.get(input.signer.publicKey);
|
|
2226
|
+
try {
|
|
2227
|
+
input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
|
|
2228
|
+
} catch {
|
|
2229
|
+
}
|
|
2230
|
+
};
|
|
2231
|
+
try {
|
|
2232
|
+
progress("preparing");
|
|
2233
|
+
const pending = inFlight.get(input.signer.publicKey);
|
|
2234
|
+
if (pending) {
|
|
2235
|
+
const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
|
|
2236
|
+
const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
|
|
2237
|
+
if (status?.err) inFlight.delete(input.signer.publicKey);
|
|
2238
|
+
else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
|
|
2239
|
+
inFlight.delete(input.signer.publicKey);
|
|
2240
|
+
if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
|
|
2241
|
+
if (pending.final) {
|
|
2242
|
+
pending.state.sent = pending.signature;
|
|
2243
|
+
reportSolana(pending.state, pending.signature);
|
|
2244
|
+
if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
|
|
2245
|
+
progress("sent");
|
|
2246
|
+
return pending.signature;
|
|
2247
|
+
}
|
|
2248
|
+
} else {
|
|
2249
|
+
if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
|
|
2250
|
+
throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
|
|
2251
|
+
}
|
|
2252
|
+
inFlight.delete(input.signer.publicKey);
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
if (state.failed) {
|
|
2256
|
+
const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
|
|
2257
|
+
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.");
|
|
2258
|
+
state.plan = retried;
|
|
2259
|
+
state.done = 0;
|
|
2260
|
+
state.failed = false;
|
|
2261
|
+
}
|
|
2262
|
+
const plan = state.plan;
|
|
2263
|
+
checkSolanaPlan(plan.txData);
|
|
2264
|
+
for (const tx of plan.txData) {
|
|
2265
|
+
const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
|
|
2266
|
+
verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
|
|
2267
|
+
}
|
|
2268
|
+
for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
|
|
2269
|
+
completedBeforeRun = state.signatures.length;
|
|
2270
|
+
const startAt = state.done;
|
|
2271
|
+
for (index = startAt; index < plan.txData.length; index++) {
|
|
2272
|
+
if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
|
|
2273
|
+
progress("ready");
|
|
2274
|
+
return null;
|
|
2275
|
+
}
|
|
2276
|
+
if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
|
|
2277
|
+
await checkActiveScreens(state.api, state.input);
|
|
2278
|
+
const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
|
|
2279
|
+
const keys = await resolveSolanaKeys(parsed, input.rpc);
|
|
2280
|
+
const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
|
|
2281
|
+
if (buffer) {
|
|
2282
|
+
const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
|
|
2283
|
+
checkSolanaRouteBuffer(account.value, plan.expected);
|
|
2284
|
+
}
|
|
2285
|
+
const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
|
|
2286
|
+
let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
|
|
2287
|
+
if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
|
|
2288
|
+
verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
|
|
2289
|
+
progress("signing");
|
|
2290
|
+
const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
|
|
2291
|
+
assertWalletMessage(bytes, signed);
|
|
2292
|
+
verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
|
|
2293
|
+
const signedTx = parseSolanaTransaction(signed);
|
|
2294
|
+
const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
|
|
2295
|
+
const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
|
|
2296
|
+
inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
|
|
2297
|
+
progress("sending");
|
|
2298
|
+
try {
|
|
2299
|
+
const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
|
|
2300
|
+
if (returned !== signature) throw new Error("RPC returned a different signature.");
|
|
2301
|
+
if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
|
|
2302
|
+
} catch (error) {
|
|
2303
|
+
throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
|
|
2304
|
+
}
|
|
2305
|
+
inFlight.delete(input.signer.publicKey);
|
|
2306
|
+
state.signatures.push(signature);
|
|
2307
|
+
state.done = index + 1;
|
|
2308
|
+
if (tx.actionType === "submit") {
|
|
2309
|
+
state.sent = signature;
|
|
2310
|
+
reportSolana(state, signature);
|
|
2311
|
+
progress("sent");
|
|
2312
|
+
return signature;
|
|
2313
|
+
}
|
|
2314
|
+
progress("ready");
|
|
2315
|
+
}
|
|
2316
|
+
throw new Error("Missing final Solana submit.");
|
|
2317
|
+
} catch (error) {
|
|
2318
|
+
state.failed = true;
|
|
2319
|
+
progress("failed");
|
|
2320
|
+
throw error;
|
|
2321
|
+
} finally {
|
|
2322
|
+
state.busy = false;
|
|
2323
|
+
activeSigners.delete(input.signer.publicKey);
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
function reportSolana(state, signature) {
|
|
2327
|
+
try {
|
|
2328
|
+
void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
|
|
2329
|
+
});
|
|
2330
|
+
} catch {
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
async function readSolanaBalance(rpc, owner, mint) {
|
|
2334
|
+
try {
|
|
2335
|
+
solanaKeyBytes(owner);
|
|
2336
|
+
solanaKeyBytes(mint);
|
|
2337
|
+
const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
|
|
2338
|
+
if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
|
|
2339
|
+
let total = 0n, decimals;
|
|
2340
|
+
for (const item of result.value) {
|
|
2341
|
+
const amount = item.account?.data?.parsed?.info?.tokenAmount;
|
|
2342
|
+
if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
|
|
2343
|
+
decimals = amount.decimals;
|
|
2344
|
+
total += BigInt(raw(amount.amount, "token balance"));
|
|
2345
|
+
}
|
|
2346
|
+
return total;
|
|
2347
|
+
} catch {
|
|
2348
|
+
return void 0;
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
function solanaLamportShortfall(logs) {
|
|
2352
|
+
if (!Array.isArray(logs)) return null;
|
|
2353
|
+
for (const line of logs) {
|
|
2354
|
+
const m = /insufficient lamports (\d+), need (\d+)/.exec(String(line));
|
|
2355
|
+
if (m) {
|
|
2356
|
+
const need = Number(m[2]);
|
|
2357
|
+
return Number.isSafeInteger(need) && need > 0 ? need : null;
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
return null;
|
|
2361
|
+
}
|
|
2362
|
+
var SOL_SHORTFALL_MESSAGE = "Not enough SOL in this wallet for the Solana network fee and account rent. Add a little SOL and try again.";
|
|
2363
|
+
async function simulateSolanaCost(rpc, plan) {
|
|
2364
|
+
checkSolanaPlan(plan.txData);
|
|
2365
|
+
const signer = plan.expected.signer;
|
|
2366
|
+
const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
|
|
2367
|
+
const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
|
|
2368
|
+
const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
|
|
2369
|
+
if (sim.value?.err) {
|
|
2370
|
+
const need = solanaLamportShortfall(sim.value.logs);
|
|
2371
|
+
if (need !== null && Number.isSafeInteger(balanceLamports)) return { lamports: need, balanceLamports, sufficient: false };
|
|
2372
|
+
throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
|
|
2373
|
+
}
|
|
2374
|
+
if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
|
|
2375
|
+
const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
|
|
2376
|
+
return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
// src/core/history.ts
|
|
2380
|
+
var WALLET_HISTORY_LIMIT = 50;
|
|
2381
|
+
var HASH2 = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
|
|
2382
|
+
var WALLET = /^(?:0x[0-9a-fA-F]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$/;
|
|
2383
|
+
function historyKey(value) {
|
|
2384
|
+
return value.startsWith("0x") ? value.toLowerCase() : value;
|
|
2385
|
+
}
|
|
2386
|
+
var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
|
|
2387
|
+
function tokenAt(tokens, chainId, address) {
|
|
2388
|
+
if (!address) return void 0;
|
|
2389
|
+
const key = historyKey(address);
|
|
2390
|
+
return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key);
|
|
2391
|
+
}
|
|
2392
|
+
function amountOf(raw2, token, rowDecimals, rowAmount) {
|
|
2393
|
+
const decimals = token ? Number(token.decimals) : Number(rowDecimals);
|
|
2394
|
+
if (/^\d{1,78}$/.test(raw2) && Number.isInteger(decimals) && decimals > 0 && decimals <= 36) return formatUnits(raw2, decimals);
|
|
2395
|
+
return Number(rowDecimals) > 0 && /^\d+(?:\.\d+)?$/.test(rowAmount) ? rowAmount.slice(0, 40) : "";
|
|
2396
|
+
}
|
|
2397
|
+
function historyEntryFromOrder(raw2, tokens) {
|
|
2398
|
+
if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return null;
|
|
2399
|
+
const r = raw2;
|
|
2400
|
+
const hash2 = str(r.txHash);
|
|
2401
|
+
if (!HASH2.test(hash2)) return null;
|
|
2402
|
+
const fromChainId = Number(r.sourceChainId) || 0;
|
|
2403
|
+
const toChainId = Number(r.finalDestChainId ?? r.destChainId) || 0;
|
|
2404
|
+
const from = tokenAt(tokens, fromChainId, str(r.fromTokenAddress));
|
|
2405
|
+
const toAddress = str(r.finalToTokenAddress) || str(r.toTokenAddress);
|
|
2406
|
+
const to = tokenAt(tokens, toChainId, toAddress);
|
|
2407
|
+
const fromAsset = (from?.symbol ?? str(r.fromTokenSymbol)).slice(0, 10);
|
|
2408
|
+
const toAsset = (to?.symbol ?? (str(r.finalToTokenSymbol) || str(r.toTokenSymbol))).slice(0, 10);
|
|
2409
|
+
const payAmount = amountOf(str(r.fromTokenRawAmount), from, r.fromTokenDecimals, str(r.fromTokenAmount));
|
|
2410
|
+
const receiveAmount = str(r.finalToTokenRawAmount) ? amountOf(str(r.finalToTokenRawAmount), to, r.finalToTokenDecimals, str(r.finalToTokenAmount)) : amountOf(str(r.toTokenRawAmount), to, r.toTokenDecimals, str(r.toTokenAmount));
|
|
2411
|
+
const delivery = normalizeDelivery(r).phase;
|
|
2412
|
+
const wallet = str(r.wallet);
|
|
2413
|
+
const receiver = str(r.destinationReceiver);
|
|
2414
|
+
const at = str(r.createdAt) || str(r.submittedAt);
|
|
2415
|
+
return {
|
|
2416
|
+
kind: "swap",
|
|
2417
|
+
hash: hash2,
|
|
2418
|
+
txKind: "submitOrder",
|
|
2419
|
+
chainId: fromChainId || null,
|
|
2420
|
+
chainName: "",
|
|
2421
|
+
fromAsset,
|
|
2422
|
+
toAsset,
|
|
2423
|
+
fromTicker: from ? tokenTicker(from).slice(0, 12) : void 0,
|
|
2424
|
+
toTicker: to ? tokenTicker(to).slice(0, 12) : void 0,
|
|
2425
|
+
payAmount,
|
|
2426
|
+
receiveAmount,
|
|
2427
|
+
account: WALLET.test(wallet) ? historyKey(wallet) : "",
|
|
2428
|
+
recipient: WALLET.test(receiver) ? receiver : "",
|
|
2429
|
+
settlement: "escrow",
|
|
2430
|
+
status: "submitted",
|
|
2431
|
+
at: Number.isNaN(Date.parse(at)) ? (/* @__PURE__ */ new Date(0)).toISOString() : new Date(at).toISOString(),
|
|
2432
|
+
delivery: delivery === "tracking" || delivery === "unavailable" ? void 0 : delivery,
|
|
2433
|
+
legs: [
|
|
2434
|
+
{
|
|
2435
|
+
index: 1,
|
|
2436
|
+
fromAsset,
|
|
2437
|
+
fromTicker: from ? tokenTicker(from).slice(0, 12) : void 0,
|
|
2438
|
+
fromChainId,
|
|
2439
|
+
fromChainName: "",
|
|
2440
|
+
fromAmount: payAmount,
|
|
2441
|
+
toAsset,
|
|
2442
|
+
toTicker: to ? tokenTicker(to).slice(0, 12) : void 0,
|
|
2443
|
+
toChainId,
|
|
2444
|
+
toChainName: "",
|
|
2445
|
+
toAmount: receiveAmount,
|
|
2446
|
+
executionChainId: Number(r.executionChainId) || 0,
|
|
2447
|
+
executionChainName: ""
|
|
2448
|
+
}
|
|
2449
|
+
]
|
|
2450
|
+
};
|
|
2451
|
+
}
|
|
2452
|
+
async function fetchWalletHistory(api, wallets) {
|
|
2453
|
+
const asked = [...new Set(wallets.filter((w) => WALLET.test(w)).map(historyKey))];
|
|
2454
|
+
if (!asked.length) return [];
|
|
2455
|
+
const tokens = await api.fetchTokens().catch(() => []);
|
|
2456
|
+
const reads = await Promise.all(
|
|
2457
|
+
asked.map(async (wallet) => {
|
|
2458
|
+
try {
|
|
2459
|
+
const rows = await api.apiRequest(`/transactions?wallet=${encodeURIComponent(wallet)}&limit=${WALLET_HISTORY_LIMIT}`, { timeoutMs: 1e4 });
|
|
2460
|
+
if (!Array.isArray(rows)) return null;
|
|
2461
|
+
return rows.filter((row) => historyKey(str(row?.wallet)) === wallet).map((row) => historyEntryFromOrder(row, tokens));
|
|
2462
|
+
} catch {
|
|
2463
|
+
return null;
|
|
2464
|
+
}
|
|
2465
|
+
})
|
|
2466
|
+
);
|
|
2467
|
+
if (reads.every((read) => read === null)) return null;
|
|
2468
|
+
return reads.flatMap((read) => read ?? []).filter((e) => e !== null);
|
|
2469
|
+
}
|
|
2470
|
+
function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
|
|
2471
|
+
const byHash = /* @__PURE__ */ new Map();
|
|
2472
|
+
for (const entry of remote ?? []) if (!byHash.has(historyKey(entry.hash))) byHash.set(historyKey(entry.hash), entry);
|
|
2473
|
+
const out = [];
|
|
2474
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2475
|
+
for (const entry of local) {
|
|
2476
|
+
const key = historyKey(entry.hash);
|
|
2477
|
+
if (seen.has(key)) continue;
|
|
2478
|
+
seen.add(key);
|
|
2479
|
+
const known = byHash.get(key);
|
|
2480
|
+
out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
|
|
2481
|
+
}
|
|
2482
|
+
for (const [key, entry] of byHash) if (!seen.has(key)) out.push(entry);
|
|
2483
|
+
return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
// src/core/escrow.ts
|
|
2487
|
+
function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
|
|
2488
|
+
const fromQuote = normalizeAddress(quoteEscrow);
|
|
2489
|
+
const fromChains = normalizeAddress(chainsEscrow);
|
|
2490
|
+
if (!fromChains || fromChains === ZERO_ADDRESS) {
|
|
2491
|
+
throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
|
|
2492
|
+
}
|
|
2493
|
+
if (!fromQuote || fromQuote === ZERO_ADDRESS) {
|
|
2494
|
+
throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
|
|
2495
|
+
}
|
|
2496
|
+
if (fromQuote !== fromChains) {
|
|
2497
|
+
throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
|
|
2498
|
+
}
|
|
2499
|
+
const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
|
|
2500
|
+
if (pinned && pinned !== fromChains) {
|
|
2501
|
+
throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
|
|
2502
|
+
}
|
|
2503
|
+
return fromChains;
|
|
2504
|
+
}
|
|
2505
|
+
function isLayerZeroRoute(quote, option = {}) {
|
|
2506
|
+
const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
|
|
2507
|
+
return bridge.includes("layerzero") || bridge.includes("layer zero");
|
|
2508
|
+
}
|
|
2509
|
+
function sourceAssetKey(quote, option = {}) {
|
|
2510
|
+
return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
|
|
2511
|
+
}
|
|
2512
|
+
function requiresNativeBridgeFee(quote, option = {}) {
|
|
2513
|
+
const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
|
|
2514
|
+
const execChainId = Number(quote?.executionChainId);
|
|
2515
|
+
if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
|
|
2516
|
+
return false;
|
|
2517
|
+
}
|
|
2518
|
+
const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
|
|
2519
|
+
if (canonical) return canonical === "layerzero";
|
|
2520
|
+
return isLayerZeroRoute(quote, option);
|
|
2521
|
+
}
|
|
2522
|
+
function applyLayerZeroBuffer(quote, option = {}) {
|
|
2523
|
+
const gas = BigInt(quote?.gasCostSource || "0");
|
|
2524
|
+
if (gas <= 0n) return 0n;
|
|
2525
|
+
if (!requiresNativeBridgeFee(quote, option)) return 0n;
|
|
2526
|
+
return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
|
|
733
2527
|
}
|
|
734
2528
|
|
|
735
2529
|
// src/core/native-fee.ts
|
|
736
2530
|
function routeNativeValue(route) {
|
|
737
2531
|
try {
|
|
738
|
-
const
|
|
739
|
-
if (
|
|
740
|
-
const value = BigInt(
|
|
2532
|
+
const raw2 = route?.quote?.msgValue;
|
|
2533
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
|
|
2534
|
+
const value = BigInt(raw2);
|
|
741
2535
|
return value > 0n ? value : 0n;
|
|
742
2536
|
} catch {
|
|
743
2537
|
return 0n;
|
|
744
2538
|
}
|
|
745
2539
|
}
|
|
746
2540
|
function nativeSymbol(chainId, chains = []) {
|
|
747
|
-
const
|
|
748
|
-
const fromRegistry = typeof
|
|
2541
|
+
const registry2 = chainById(chains, Number(chainId))?.nativeCurrency;
|
|
2542
|
+
const fromRegistry = typeof registry2 === "string" ? registry2.trim() : "";
|
|
749
2543
|
return fromRegistry || BUNDLED_NATIVE_SYMBOL[Number(chainId)] || "ETH";
|
|
750
2544
|
}
|
|
751
2545
|
function formatNative(wei) {
|
|
@@ -772,6 +2566,11 @@ function nativeFeeShortMessage(check2, symbol, chainName3) {
|
|
|
772
2566
|
}
|
|
773
2567
|
|
|
774
2568
|
// src/core/route-health.ts
|
|
2569
|
+
function healthLaneKey(value) {
|
|
2570
|
+
if (typeof value !== "string") return "";
|
|
2571
|
+
const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
|
|
2572
|
+
return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
|
|
2573
|
+
}
|
|
775
2574
|
var EMPTY = /* @__PURE__ */ new Map();
|
|
776
2575
|
var NO_LIMITS = /* @__PURE__ */ new Map();
|
|
777
2576
|
function laneAvailabilityState(lane) {
|
|
@@ -791,7 +2590,7 @@ function suppressedLanes(health) {
|
|
|
791
2590
|
const out = /* @__PURE__ */ new Map();
|
|
792
2591
|
for (const lane of health.lanes) {
|
|
793
2592
|
if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
|
|
794
|
-
const key =
|
|
2593
|
+
const key = healthLaneKey(lane.laneKey);
|
|
795
2594
|
if (!key) continue;
|
|
796
2595
|
const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
|
|
797
2596
|
const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
|
|
@@ -811,7 +2610,7 @@ function limitedLanes(health) {
|
|
|
811
2610
|
const out = /* @__PURE__ */ new Map();
|
|
812
2611
|
for (const lane of health.lanes) {
|
|
813
2612
|
if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
|
|
814
|
-
const key =
|
|
2613
|
+
const key = healthLaneKey(lane.laneKey);
|
|
815
2614
|
const limit = lane.availability?.limit;
|
|
816
2615
|
if (!key || !limit || typeof limit !== "object") continue;
|
|
817
2616
|
const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
|
|
@@ -834,14 +2633,14 @@ function limitedLanes(health) {
|
|
|
834
2633
|
}
|
|
835
2634
|
function exceedsLaneLimit(limit, amount, bidDecimals) {
|
|
836
2635
|
if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
|
|
837
|
-
let
|
|
2636
|
+
let raw2;
|
|
838
2637
|
try {
|
|
839
|
-
|
|
2638
|
+
raw2 = parseUnitsDecimal(amount, bidDecimals);
|
|
840
2639
|
} catch {
|
|
841
2640
|
return false;
|
|
842
2641
|
}
|
|
843
2642
|
const scale = Math.max(bidDecimals, limit.decimals);
|
|
844
|
-
return scaleDecimals(
|
|
2643
|
+
return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
|
|
845
2644
|
}
|
|
846
2645
|
function laneLimitAmount(limit) {
|
|
847
2646
|
return formatUnits(limit.maxAmount, limit.decimals);
|
|
@@ -938,11 +2737,11 @@ function complianceView(compliance, hasQuote = true) {
|
|
|
938
2737
|
};
|
|
939
2738
|
}
|
|
940
2739
|
if (decision === "REVIEW" || decision === "REMEDIATE") {
|
|
941
|
-
const
|
|
2740
|
+
const word2 = decision.toLowerCase();
|
|
942
2741
|
return {
|
|
943
2742
|
tone: "warn",
|
|
944
|
-
label: `Compliance: ${
|
|
945
|
-
headline: `Manual ${
|
|
2743
|
+
label: `Compliance: ${word2} required`,
|
|
2744
|
+
headline: `Manual ${word2} required`,
|
|
946
2745
|
blocked: false,
|
|
947
2746
|
needsAction: true,
|
|
948
2747
|
screened
|
|
@@ -1007,12 +2806,12 @@ function stripBundlePrefix(head) {
|
|
|
1007
2806
|
if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
|
|
1008
2807
|
return { head, source: null };
|
|
1009
2808
|
}
|
|
1010
|
-
function complianceReasonHead(
|
|
1011
|
-
return stripBundlePrefix((
|
|
2809
|
+
function complianceReasonHead(raw2) {
|
|
2810
|
+
return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
|
|
1012
2811
|
}
|
|
1013
|
-
function usd(
|
|
1014
|
-
const n = Number(
|
|
1015
|
-
if (!Number.isFinite(n)) return `$${
|
|
2812
|
+
function usd(raw2) {
|
|
2813
|
+
const n = Number(raw2);
|
|
2814
|
+
if (!Number.isFinite(n)) return `$${raw2}`;
|
|
1016
2815
|
return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
|
|
1017
2816
|
}
|
|
1018
2817
|
function capFromDetail(detail) {
|
|
@@ -1023,11 +2822,11 @@ function categoryPhrase(detail) {
|
|
|
1023
2822
|
const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
|
|
1024
2823
|
return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
|
|
1025
2824
|
}
|
|
1026
|
-
function humanizeComplianceReason(
|
|
1027
|
-
const [headRaw, ...restParts] =
|
|
2825
|
+
function humanizeComplianceReason(raw2) {
|
|
2826
|
+
const [headRaw, ...restParts] = raw2.split(":");
|
|
1028
2827
|
const detail = restParts.join(":").trim();
|
|
1029
|
-
const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
|
|
1030
|
-
const scope =
|
|
2828
|
+
const { head, source: source2 } = stripBundlePrefix((headRaw ?? "").trim());
|
|
2829
|
+
const scope = source2 === "legislation" ? "applicable regulations" : "the applicable policy";
|
|
1031
2830
|
switch (head) {
|
|
1032
2831
|
case "asset_pair_not_allowed": {
|
|
1033
2832
|
const m = detail.match(/^(\S+)->(\S+)\s+in\s+(\S+)/);
|
|
@@ -1101,8 +2900,8 @@ var CHECK_HEADS = {
|
|
|
1101
2900
|
function distinctScreenedWallets(compliance) {
|
|
1102
2901
|
const seen = /* @__PURE__ */ new Set();
|
|
1103
2902
|
const wallets = [];
|
|
1104
|
-
for (const
|
|
1105
|
-
const address =
|
|
2903
|
+
for (const raw2 of compliance?.screenedWallets ?? []) {
|
|
2904
|
+
const address = raw2?.trim();
|
|
1106
2905
|
if (!address) continue;
|
|
1107
2906
|
const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
|
|
1108
2907
|
if (seen.has(key)) continue;
|
|
@@ -1122,11 +2921,11 @@ function screeningLabel(wallets) {
|
|
|
1122
2921
|
function complianceChecks(compliance, cv = complianceView(compliance)) {
|
|
1123
2922
|
if (cv.tone === "neutral") return [];
|
|
1124
2923
|
const byControl = /* @__PURE__ */ new Map();
|
|
1125
|
-
for (const
|
|
1126
|
-
const head = complianceReasonHead(
|
|
2924
|
+
for (const raw2 of compliance?.reasons ?? []) {
|
|
2925
|
+
const head = complianceReasonHead(raw2);
|
|
1127
2926
|
const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
|
|
1128
2927
|
if (!id) continue;
|
|
1129
|
-
byControl.set(id, [...byControl.get(id) ?? [],
|
|
2928
|
+
byControl.set(id, [...byControl.get(id) ?? [], raw2]);
|
|
1130
2929
|
}
|
|
1131
2930
|
const screenedWallets = distinctScreenedWallets(compliance);
|
|
1132
2931
|
const wallets = screenedWallets.length;
|
|
@@ -1175,9 +2974,9 @@ var BLOCK_CATEGORY_LABELS = {
|
|
|
1175
2974
|
};
|
|
1176
2975
|
var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
|
|
1177
2976
|
function blockLabelFor(categories) {
|
|
1178
|
-
for (const
|
|
1179
|
-
const
|
|
1180
|
-
if (
|
|
2977
|
+
for (const raw2 of categories) {
|
|
2978
|
+
const label2 = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
|
|
2979
|
+
if (label2) return label2;
|
|
1181
2980
|
}
|
|
1182
2981
|
return BLOCK_LABEL_DEFAULT;
|
|
1183
2982
|
}
|
|
@@ -1197,8 +2996,8 @@ var REASON_TAGS = {
|
|
|
1197
2996
|
dest_chain_not_allowed: "Chain not allowed",
|
|
1198
2997
|
jurisdiction_out_of_scope: "Out of scope"
|
|
1199
2998
|
};
|
|
1200
|
-
function complianceReasonTag(
|
|
1201
|
-
const head = complianceReasonHead(
|
|
2999
|
+
function complianceReasonTag(raw2) {
|
|
3000
|
+
const head = complianceReasonHead(raw2);
|
|
1202
3001
|
return REASON_TAGS[head] ?? head.replace(/_/g, " ");
|
|
1203
3002
|
}
|
|
1204
3003
|
function complianceTagOf(compliance) {
|
|
@@ -1261,8 +3060,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1261
3060
|
const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
|
|
1262
3061
|
const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
|
|
1263
3062
|
const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
|
|
1264
|
-
const enforcePayCeiling = (
|
|
1265
|
-
if (maxPayRaw > 0n && BigInt(
|
|
3063
|
+
const enforcePayCeiling = (raw2) => {
|
|
3064
|
+
if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
|
|
1266
3065
|
throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
|
|
1267
3066
|
}
|
|
1268
3067
|
};
|
|
@@ -1286,7 +3085,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1286
3085
|
if (BigInt(quote?.fromAmount || "0") !== guessSent) {
|
|
1287
3086
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
1288
3087
|
}
|
|
1289
|
-
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
3088
|
+
const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
|
|
1290
3089
|
const final = finalOf(quote);
|
|
1291
3090
|
if (final > bestFinal) {
|
|
1292
3091
|
bestFinal = final;
|
|
@@ -1323,7 +3122,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1323
3122
|
directTransfer: false,
|
|
1324
3123
|
quote: best,
|
|
1325
3124
|
youPayRaw: bestGuess.toString(),
|
|
1326
|
-
recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
|
|
3125
|
+
recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
|
|
1327
3126
|
targetRaw: targetRaw.toString(),
|
|
1328
3127
|
overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
|
|
1329
3128
|
meetsTarget: bestFinal >= targetRaw,
|
|
@@ -1345,7 +3144,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
1345
3144
|
if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
|
|
1346
3145
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
1347
3146
|
}
|
|
1348
|
-
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
3147
|
+
const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
|
|
1349
3148
|
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
1350
3149
|
return {
|
|
1351
3150
|
directTransfer: false,
|
|
@@ -1376,13 +3175,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
|
|
|
1376
3175
|
const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
|
|
1377
3176
|
const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
|
|
1378
3177
|
if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
|
|
3178
|
+
const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
|
|
3179
|
+
const keyBytes2 = (value, label2) => {
|
|
3180
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label2} is not a valid 32-byte Solana key.`);
|
|
3181
|
+
return String(value).toLowerCase();
|
|
3182
|
+
};
|
|
1379
3183
|
return {
|
|
1380
3184
|
owner: assertAddress(order.owner || payer, "Order owner"),
|
|
1381
3185
|
bidToken: assertAddress(order.bidToken, "Bid token"),
|
|
1382
3186
|
bidTokenAmount: String(order.bidTokenAmount || "0"),
|
|
1383
|
-
askToken: assertAddress(order.askToken, "Ask token"),
|
|
3187
|
+
askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
|
|
1384
3188
|
askTokenAmount: String(order.askTokenAmount || "0"),
|
|
1385
|
-
destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
|
|
3189
|
+
destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
|
|
3190
|
+
...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
|
|
1386
3191
|
destinationChainId: String(order.destinationChainId || destination.chainId),
|
|
1387
3192
|
executionChainId,
|
|
1388
3193
|
deadline
|
|
@@ -1394,17 +3199,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
|
|
|
1394
3199
|
(request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
|
|
1395
3200
|
);
|
|
1396
3201
|
}
|
|
1397
|
-
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
|
|
3202
|
+
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
|
|
1398
3203
|
const list = orders?.length ? orders : [order];
|
|
1399
3204
|
const sourceOrder = list[0];
|
|
1400
3205
|
const finalOrder = list[list.length - 1];
|
|
1401
3206
|
const now = Math.floor(Date.now() / 1e3);
|
|
1402
3207
|
const deadline = Number(sourceOrder.deadline || 0);
|
|
3208
|
+
const solana = isSolanaChainId(destination.chainId);
|
|
3209
|
+
if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
|
|
3210
|
+
throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
3211
|
+
}
|
|
1403
3212
|
for (const current of list) {
|
|
1404
3213
|
if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
|
|
1405
3214
|
throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
|
|
1406
3215
|
}
|
|
1407
|
-
if (
|
|
3216
|
+
if (isSolanaChainId(current.destinationChainId)) {
|
|
3217
|
+
if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
|
|
3218
|
+
checkSolanaReceiver(current, destination.address, destinationToken.address);
|
|
3219
|
+
} else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
|
|
1408
3220
|
throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
|
|
1409
3221
|
}
|
|
1410
3222
|
if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
|
|
@@ -1414,9 +3226,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
1414
3226
|
if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
|
|
1415
3227
|
throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
|
|
1416
3228
|
}
|
|
1417
|
-
if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
3229
|
+
if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
1418
3230
|
throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
|
|
1419
3231
|
}
|
|
3232
|
+
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.");
|
|
1420
3233
|
if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
|
|
1421
3234
|
throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
|
|
1422
3235
|
}
|
|
@@ -1435,10 +3248,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
1435
3248
|
if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
|
|
1436
3249
|
throw new Error("ZeroDelta quote returned a non-positive output amount.");
|
|
1437
3250
|
}
|
|
1438
|
-
|
|
3251
|
+
const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
|
|
3252
|
+
const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
|
|
3253
|
+
if (!covers(result.targetRaw)) {
|
|
1439
3254
|
throw new Error("ZeroDelta quote would not cover the requested destination amount.");
|
|
1440
3255
|
}
|
|
1441
|
-
if (
|
|
3256
|
+
if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
|
|
1442
3257
|
throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
|
|
1443
3258
|
}
|
|
1444
3259
|
const maxDeadline = maxDeadlineSeconds(quote);
|
|
@@ -1470,8 +3285,8 @@ function routeDeltaLabel(result, quote) {
|
|
|
1470
3285
|
return "~0";
|
|
1471
3286
|
}
|
|
1472
3287
|
function quotePartnerId(quote) {
|
|
1473
|
-
const
|
|
1474
|
-
return typeof
|
|
3288
|
+
const raw2 = quote.partnerId;
|
|
3289
|
+
return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
|
|
1475
3290
|
}
|
|
1476
3291
|
function optionTicker(option) {
|
|
1477
3292
|
return option.ticker || option.symbol;
|
|
@@ -1481,15 +3296,16 @@ function routeLabelFor(option, destinationToken, result) {
|
|
|
1481
3296
|
const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
|
|
1482
3297
|
return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
|
|
1483
3298
|
}
|
|
1484
|
-
function
|
|
1485
|
-
const
|
|
3299
|
+
function tokenAt2(tokens, chainId, address) {
|
|
3300
|
+
const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
|
|
3301
|
+
const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
|
|
1486
3302
|
if (!wanted || !tokens?.length) return void 0;
|
|
1487
|
-
return tokens.find((t) => Number(t.chainId) === Number(chainId) &&
|
|
3303
|
+
return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
|
|
1488
3304
|
}
|
|
1489
|
-
function legAmount(
|
|
3305
|
+
function legAmount(raw2, decimals) {
|
|
1490
3306
|
if (decimals === void 0) return "";
|
|
1491
3307
|
try {
|
|
1492
|
-
return formatUnits(
|
|
3308
|
+
return formatUnits(raw2 || "0", decimals);
|
|
1493
3309
|
} catch {
|
|
1494
3310
|
return "";
|
|
1495
3311
|
}
|
|
@@ -1504,7 +3320,7 @@ function buildLegs(orders, ctx) {
|
|
|
1504
3320
|
const order = orders[index];
|
|
1505
3321
|
const isLast = index === orders.length - 1;
|
|
1506
3322
|
const toChainId = Number(order.destinationChainId);
|
|
1507
|
-
const askToken = isLast ? ctx.destinationToken :
|
|
3323
|
+
const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
|
|
1508
3324
|
const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
|
|
1509
3325
|
const toTicker = askToken ? tokenTicker(askToken) : "";
|
|
1510
3326
|
const toDecimals = askToken ? assetDecimals(askToken) : void 0;
|
|
@@ -1520,7 +3336,7 @@ function buildLegs(orders, ctx) {
|
|
|
1520
3336
|
toTicker,
|
|
1521
3337
|
toChainId,
|
|
1522
3338
|
toChainName: chainNameOf(toChainId, ctx.chains),
|
|
1523
|
-
toAmount: legAmount(order.askTokenAmount, toDecimals),
|
|
3339
|
+
toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
|
|
1524
3340
|
executionChainId,
|
|
1525
3341
|
executionChainName: chainNameOf(executionChainId, ctx.chains)
|
|
1526
3342
|
});
|
|
@@ -1624,8 +3440,12 @@ async function buildRoute({
|
|
|
1624
3440
|
const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
|
|
1625
3441
|
const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
|
|
1626
3442
|
const order = orders[0];
|
|
1627
|
-
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
|
|
1628
|
-
const
|
|
3443
|
+
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
|
|
3444
|
+
const echoedExecution = Number(quote.executionChainId || 0);
|
|
3445
|
+
if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
|
|
3446
|
+
throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
|
|
3447
|
+
}
|
|
3448
|
+
const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
|
|
1629
3449
|
if (needsNativeFee) {
|
|
1630
3450
|
let rawFee;
|
|
1631
3451
|
try {
|
|
@@ -1669,7 +3489,7 @@ async function buildRoute({
|
|
|
1669
3489
|
},
|
|
1670
3490
|
routeLabel: routeLabelFor(option, destinationToken, result),
|
|
1671
3491
|
deltaLabel: routeDeltaLabel(result, quote),
|
|
1672
|
-
legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
|
|
3492
|
+
legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
|
|
1673
3493
|
transactions: [
|
|
1674
3494
|
{
|
|
1675
3495
|
id: "approve",
|
|
@@ -1702,6 +3522,7 @@ async function buildRoute({
|
|
|
1702
3522
|
gasCostSource: quote.gasCostSource,
|
|
1703
3523
|
msgValue: valueRaw.toString(),
|
|
1704
3524
|
deadline: order.deadline,
|
|
3525
|
+
...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
|
|
1705
3526
|
partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
|
|
1706
3527
|
iterations: result.iterations,
|
|
1707
3528
|
// Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
|
|
@@ -1717,10 +3538,10 @@ var CHANNEL_HEADER = "x-zd-channel";
|
|
|
1717
3538
|
var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
|
|
1718
3539
|
var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
|
|
1719
3540
|
var WIDGET_CHANNEL = "widget";
|
|
1720
|
-
var WIDGET_VERSION = "4.
|
|
3541
|
+
var WIDGET_VERSION = "4.13.1" ;
|
|
1721
3542
|
var MAX_CHANNEL_VERSION_LEN = 32;
|
|
1722
|
-
function sanitizeVersion(
|
|
1723
|
-
const v = String(
|
|
3543
|
+
function sanitizeVersion(raw2) {
|
|
3544
|
+
const v = String(raw2).trim();
|
|
1724
3545
|
if (!v) return "";
|
|
1725
3546
|
const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
|
|
1726
3547
|
return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
|
|
@@ -1756,9 +3577,9 @@ function isReportableSubmission(report) {
|
|
|
1756
3577
|
|
|
1757
3578
|
// src/core/api.ts
|
|
1758
3579
|
function apiError(message, props = {}) {
|
|
1759
|
-
const
|
|
1760
|
-
Object.assign(
|
|
1761
|
-
return
|
|
3580
|
+
const err2 = new Error(message);
|
|
3581
|
+
Object.assign(err2, props);
|
|
3582
|
+
return err2;
|
|
1762
3583
|
}
|
|
1763
3584
|
function toQuery(params) {
|
|
1764
3585
|
const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== "" && v !== null);
|
|
@@ -1776,14 +3597,14 @@ function sanitizeMessage(value, fallback) {
|
|
|
1776
3597
|
return text.length > MAX_MESSAGE_LEN ? `${text.slice(0, MAX_MESSAGE_LEN - 1)}\u2026` : text;
|
|
1777
3598
|
}
|
|
1778
3599
|
function apiMessage(json, fallback) {
|
|
1779
|
-
const
|
|
1780
|
-
if (
|
|
1781
|
-
if (Array.isArray(
|
|
1782
|
-
const head = sanitizeMessage(
|
|
1783
|
-
const detail = sanitizeMessage(
|
|
3600
|
+
const err2 = json?.error || json;
|
|
3601
|
+
if (err2?.fieldErrors?.[0]?.message) return sanitizeMessage(err2.fieldErrors[0].message, fallback);
|
|
3602
|
+
if (Array.isArray(err2?.reasons) && err2.reasons.length) {
|
|
3603
|
+
const head = sanitizeMessage(err2.message, fallback);
|
|
3604
|
+
const detail = sanitizeMessage(err2.reasons.filter((r) => typeof r === "string").join(", "), "");
|
|
1784
3605
|
return detail ? `${head}: ${detail}` : head;
|
|
1785
3606
|
}
|
|
1786
|
-
return sanitizeMessage(
|
|
3607
|
+
return sanitizeMessage(err2?.message, fallback);
|
|
1787
3608
|
}
|
|
1788
3609
|
function isStructuredComplianceBlock(error) {
|
|
1789
3610
|
const code = String(error?.code || "").toUpperCase();
|
|
@@ -1798,12 +3619,12 @@ function classifyQuoteError(error) {
|
|
|
1798
3619
|
const isBlock = isStructuredComplianceBlock(error) || !!catMatch || error.code === "blocked" || error.code === "compliance_block" || /\b(stolen|sanction(?:s|ed|ing)?|block(?:ed|list)|screen(?:ed|ing)?|compliance|ofac|denylist|blacklist)\b/i.test(haystack);
|
|
1799
3620
|
if (!isBlock) return null;
|
|
1800
3621
|
const category = (catMatch?.[1] || "").toUpperCase() || "COMPLIANCE";
|
|
1801
|
-
const
|
|
3622
|
+
const label2 = blockLabelFor([category]);
|
|
1802
3623
|
return {
|
|
1803
3624
|
blocked: true,
|
|
1804
3625
|
category,
|
|
1805
3626
|
reason: reasons.join(", ") || error.message || "",
|
|
1806
|
-
message: `This payment was blocked by compliance screening \u2014 the recipient is ${
|
|
3627
|
+
message: `This payment was blocked by compliance screening \u2014 the recipient is ${label2}. Choose a different recipient or connect a different wallet.`
|
|
1807
3628
|
};
|
|
1808
3629
|
}
|
|
1809
3630
|
function amountFieldError(error) {
|
|
@@ -1923,9 +3744,9 @@ function createApiClient(cfg) {
|
|
|
1923
3744
|
if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
|
|
1924
3745
|
return once("chains", async () => {
|
|
1925
3746
|
const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
|
|
1926
|
-
const normalized = (Array.isArray(chains) ? chains : []).map((
|
|
1927
|
-
const escrow = normalizeAddress(
|
|
1928
|
-
return escrow ? { ...
|
|
3747
|
+
const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
|
|
3748
|
+
const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
|
|
3749
|
+
return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
|
|
1929
3750
|
});
|
|
1930
3751
|
cache.chains = { at: Date.now(), value: normalized };
|
|
1931
3752
|
return normalized;
|
|
@@ -2028,14 +3849,16 @@ function createApiClient(cfg) {
|
|
|
2028
3849
|
async function screenWallet(address, chainId) {
|
|
2029
3850
|
const addr = String(address || "").trim();
|
|
2030
3851
|
if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
|
|
2031
|
-
const
|
|
3852
|
+
const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
|
|
3853
|
+
if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
|
|
3854
|
+
const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
|
|
2032
3855
|
const hit = screenCache.get(key);
|
|
2033
3856
|
if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
|
|
2034
3857
|
const inflight = screenInflight.get(key);
|
|
2035
3858
|
if (inflight) return inflight;
|
|
2036
3859
|
const request = apiRequest("/screen/wallet", {
|
|
2037
3860
|
method: "POST",
|
|
2038
|
-
body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
|
|
3861
|
+
body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
|
|
2039
3862
|
timeoutMs: 12e3
|
|
2040
3863
|
}).then((screen) => {
|
|
2041
3864
|
if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
|
|
@@ -2075,7 +3898,7 @@ function createApiClient(cfg) {
|
|
|
2075
3898
|
|
|
2076
3899
|
// src/core/plan.ts
|
|
2077
3900
|
function optionBalanceKey(option) {
|
|
2078
|
-
return `${Number(option.chainId)}:${
|
|
3901
|
+
return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
|
|
2079
3902
|
}
|
|
2080
3903
|
function hasPositiveBalance(option, balances) {
|
|
2081
3904
|
try {
|
|
@@ -2085,7 +3908,8 @@ function hasPositiveBalance(option, balances) {
|
|
|
2085
3908
|
}
|
|
2086
3909
|
}
|
|
2087
3910
|
function validateDestination(destination) {
|
|
2088
|
-
|
|
3911
|
+
const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
|
|
3912
|
+
if (isSolanaChainId(destination.chainId)) destination.address = address;
|
|
2089
3913
|
const chainId = Number(destination.chainId);
|
|
2090
3914
|
const asset = symbolKey(destination.asset);
|
|
2091
3915
|
if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
|
|
@@ -2143,8 +3967,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
2143
3967
|
if (directOptions.length) {
|
|
2144
3968
|
const parties = [];
|
|
2145
3969
|
const seenParty = /* @__PURE__ */ new Set();
|
|
2146
|
-
for (const
|
|
2147
|
-
const addr = String(
|
|
3970
|
+
for (const raw2 of [payer, destination.address]) {
|
|
3971
|
+
const addr = String(raw2 || "").trim();
|
|
2148
3972
|
if (!addr) continue;
|
|
2149
3973
|
const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
|
|
2150
3974
|
if (seenParty.has(key)) continue;
|
|
@@ -2252,7 +4076,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
|
|
|
2252
4076
|
if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
|
|
2253
4077
|
const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
|
|
2254
4078
|
const option = buildPayOptions({ invoiceAsset: destination.asset, invoiceChainId: destination.chainId, tokens, routes, chains, walletChainId: wallet.chainId, catalogue }).find(
|
|
2255
|
-
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && o.address
|
|
4079
|
+
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
|
|
2256
4080
|
);
|
|
2257
4081
|
if (!option) throw new Error("That funding option is not available for this payment right now.");
|
|
2258
4082
|
return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
|
|
@@ -2275,8 +4099,10 @@ function viaOf(quote, tokens) {
|
|
|
2275
4099
|
const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
|
|
2276
4100
|
if (orders.length < 2) return null;
|
|
2277
4101
|
const first = orders[0];
|
|
2278
|
-
const
|
|
2279
|
-
const
|
|
4102
|
+
const chainId = Number(first?.destinationChainId);
|
|
4103
|
+
const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
|
|
4104
|
+
const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
|
|
4105
|
+
const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
|
|
2280
4106
|
return token ? tokenTicker(token) : "";
|
|
2281
4107
|
}
|
|
2282
4108
|
async function quoteSwapPreview(api, swap, owner) {
|
|
@@ -2288,7 +4114,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
2288
4114
|
if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
|
|
2289
4115
|
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
2290
4116
|
const account = normalizeAddress(owner) || PREVIEW_OWNER;
|
|
2291
|
-
const previewReceiver = normalizeAddress(swap.recipient) || account;
|
|
4117
|
+
const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
|
|
2292
4118
|
const quote = await api.fetchQuote({
|
|
2293
4119
|
fromChainId: v.fromChainId,
|
|
2294
4120
|
toChainId: v.toChainId,
|
|
@@ -2296,7 +4122,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
2296
4122
|
toToken: destToken.symbol,
|
|
2297
4123
|
fromAmount: amountInRaw.toString(),
|
|
2298
4124
|
owner: account,
|
|
2299
|
-
destinationReceiver: previewReceiver
|
|
4125
|
+
...previewReceiver ? { destinationReceiver: previewReceiver } : {}
|
|
2300
4126
|
});
|
|
2301
4127
|
const final = finalOf(quote);
|
|
2302
4128
|
return {
|
|
@@ -2321,7 +4147,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
2321
4147
|
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
|
|
2322
4148
|
if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
|
|
2323
4149
|
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
2324
|
-
const receiver = resolveSwapReceiver(swap.recipient, account);
|
|
4150
|
+
const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
|
|
2325
4151
|
const option = {
|
|
2326
4152
|
symbol: sourceToken.symbol,
|
|
2327
4153
|
symbolKey: symbolKey(sourceToken.symbol),
|
|
@@ -2371,16 +4197,16 @@ function isHexQuantity(value) {
|
|
|
2371
4197
|
return /^0x[0-9a-fA-F]+$/.test(String(value));
|
|
2372
4198
|
}
|
|
2373
4199
|
function dataWord(data, index) {
|
|
2374
|
-
const
|
|
2375
|
-
return /^[a-fA-F0-9]{64}$/.test(
|
|
4200
|
+
const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
|
|
4201
|
+
return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
|
|
2376
4202
|
}
|
|
2377
4203
|
function dataAddress(data, index) {
|
|
2378
|
-
const
|
|
2379
|
-
return
|
|
4204
|
+
const word2 = dataWord(data, index);
|
|
4205
|
+
return word2 ? `0x${word2.slice(24)}` : "";
|
|
2380
4206
|
}
|
|
2381
4207
|
function dataUint(data, index) {
|
|
2382
|
-
const
|
|
2383
|
-
return
|
|
4208
|
+
const word2 = dataWord(data, index);
|
|
4209
|
+
return word2 ? BigInt(`0x${word2}`) : null;
|
|
2384
4210
|
}
|
|
2385
4211
|
function rawEquals(value, expected) {
|
|
2386
4212
|
try {
|
|
@@ -2391,9 +4217,9 @@ function rawEquals(value, expected) {
|
|
|
2391
4217
|
}
|
|
2392
4218
|
function planMsgValueHex(route) {
|
|
2393
4219
|
try {
|
|
2394
|
-
const
|
|
2395
|
-
if (
|
|
2396
|
-
return "0x" + BigInt(
|
|
4220
|
+
const raw2 = route?.quote?.msgValue;
|
|
4221
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
|
|
4222
|
+
return "0x" + BigInt(raw2).toString(16);
|
|
2397
4223
|
} catch {
|
|
2398
4224
|
return null;
|
|
2399
4225
|
}
|
|
@@ -2420,15 +4246,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
|
2420
4246
|
if (!decoded) return false;
|
|
2421
4247
|
const first = decoded.orders[0];
|
|
2422
4248
|
const last = decoded.orders[decoded.orders.length - 1];
|
|
2423
|
-
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);
|
|
4249
|
+
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));
|
|
2424
4250
|
}
|
|
2425
4251
|
return false;
|
|
2426
4252
|
}
|
|
4253
|
+
function solanaDeliveryMatches(encoded, recipient2, mint) {
|
|
4254
|
+
try {
|
|
4255
|
+
return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
|
|
4256
|
+
} catch {
|
|
4257
|
+
return false;
|
|
4258
|
+
}
|
|
4259
|
+
}
|
|
2427
4260
|
async function allowanceCovers(tx, account, ethCall2) {
|
|
2428
4261
|
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
2429
4262
|
try {
|
|
2430
|
-
const
|
|
2431
|
-
return BigInt(
|
|
4263
|
+
const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
|
|
4264
|
+
return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
2432
4265
|
} catch {
|
|
2433
4266
|
return false;
|
|
2434
4267
|
}
|
|
@@ -2439,9 +4272,9 @@ var TX_VERIFY_ATTEMPTS = 5;
|
|
|
2439
4272
|
var TX_VERIFY_INTERVAL_MS = 2500;
|
|
2440
4273
|
var TX_VERIFY_FETCH_MS = 5e3;
|
|
2441
4274
|
var TX_VERIFY_DEADLINE_MS = 18e3;
|
|
2442
|
-
function registryRpc(
|
|
2443
|
-
if (!
|
|
2444
|
-
const candidates = [
|
|
4275
|
+
function registryRpc(chain2) {
|
|
4276
|
+
if (!chain2) return "";
|
|
4277
|
+
const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
|
|
2445
4278
|
const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
|
|
2446
4279
|
return found || "";
|
|
2447
4280
|
}
|
|
@@ -2522,8 +4355,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2522
4355
|
}
|
|
2523
4356
|
return null;
|
|
2524
4357
|
}
|
|
2525
|
-
async function verifySubmittedTx({ chainId, hash, from, to, data, value, minNonce }) {
|
|
2526
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(String(
|
|
4358
|
+
async function verifySubmittedTx({ chainId, hash: hash2, from, to, data, value, minNonce }) {
|
|
4359
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash2 || ""))) return { status: "mismatch" };
|
|
2527
4360
|
if (!normalizeAddress(from) || typeof minNonce !== "number") return { status: "unconfirmed", reason: "no-binding" };
|
|
2528
4361
|
const rpcUrl = await chainRpcUrl(chainId);
|
|
2529
4362
|
if (!rpcUrl) return { status: "unconfirmed", reason: "no-rpc" };
|
|
@@ -2534,7 +4367,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2534
4367
|
if (!matched) {
|
|
2535
4368
|
let tx = null;
|
|
2536
4369
|
try {
|
|
2537
|
-
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [
|
|
4370
|
+
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash2]);
|
|
2538
4371
|
} catch {
|
|
2539
4372
|
tx = null;
|
|
2540
4373
|
}
|
|
@@ -2546,7 +4379,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2546
4379
|
if (matched) {
|
|
2547
4380
|
let receipt = null;
|
|
2548
4381
|
try {
|
|
2549
|
-
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [
|
|
4382
|
+
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash2]);
|
|
2550
4383
|
} catch {
|
|
2551
4384
|
receipt = null;
|
|
2552
4385
|
}
|
|
@@ -2588,9 +4421,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2588
4421
|
}
|
|
2589
4422
|
function record(target, hex) {
|
|
2590
4423
|
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
|
|
2591
|
-
const
|
|
4424
|
+
const raw2 = BigInt(hex || "0x0").toString();
|
|
2592
4425
|
const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
2593
|
-
out[key] = { raw, formatted: formatUnits(
|
|
4426
|
+
out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
|
|
2594
4427
|
return true;
|
|
2595
4428
|
}
|
|
2596
4429
|
async function readOne(rpcUrl, target) {
|
|
@@ -2656,9 +4489,9 @@ function isSameOriginPath(value) {
|
|
|
2656
4489
|
return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
|
|
2657
4490
|
}
|
|
2658
4491
|
function resolveApiBase(value) {
|
|
2659
|
-
const
|
|
2660
|
-
if (isSameOriginPath(
|
|
2661
|
-
return parseAllowedApiBase(
|
|
4492
|
+
const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
|
|
4493
|
+
if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
|
|
4494
|
+
return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
|
|
2662
4495
|
}
|
|
2663
4496
|
function canAttachApiKey(apiBase, trustedOrigin) {
|
|
2664
4497
|
if (isSameOriginPath(apiBase)) return true;
|
|
@@ -2697,31 +4530,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
|
|
|
2697
4530
|
}
|
|
2698
4531
|
|
|
2699
4532
|
// src/core/index.ts
|
|
4533
|
+
var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
|
|
2700
4534
|
function sanitizeLegs(legs) {
|
|
2701
4535
|
if (!Array.isArray(legs) || !legs.length) return void 0;
|
|
2702
4536
|
const text = (v, max) => String(v ?? "").slice(0, max);
|
|
2703
|
-
const
|
|
4537
|
+
const chain2 = (v) => Number(v) || 0;
|
|
2704
4538
|
const ticker = (value, asset) => safeTicker(value, asset) || void 0;
|
|
2705
4539
|
return legs.slice(0, 8).map((leg, i) => ({
|
|
2706
4540
|
index: Number(leg?.index) || i + 1,
|
|
2707
4541
|
fromAsset: text(leg?.fromAsset, 12),
|
|
2708
4542
|
fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
|
|
2709
|
-
fromChainId:
|
|
4543
|
+
fromChainId: chain2(leg?.fromChainId),
|
|
2710
4544
|
fromChainName: text(leg?.fromChainName, 40),
|
|
2711
4545
|
fromAmount: text(leg?.fromAmount, 40),
|
|
2712
4546
|
toAsset: text(leg?.toAsset, 12),
|
|
2713
4547
|
toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
|
|
2714
|
-
toChainId:
|
|
4548
|
+
toChainId: chain2(leg?.toChainId),
|
|
2715
4549
|
toChainName: text(leg?.toChainName, 40),
|
|
2716
4550
|
toAmount: text(leg?.toAmount, 40),
|
|
2717
|
-
executionChainId:
|
|
4551
|
+
executionChainId: chain2(leg?.executionChainId),
|
|
2718
4552
|
executionChainName: text(leg?.executionChainName, 40)
|
|
2719
4553
|
}));
|
|
2720
4554
|
}
|
|
2721
4555
|
function sanitizeTxEntry(entry) {
|
|
2722
4556
|
return {
|
|
2723
4557
|
kind: entry.kind === "swap" ? "swap" : "payment",
|
|
2724
|
-
|
|
4558
|
+
// A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
|
|
4559
|
+
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) : "",
|
|
2725
4560
|
txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
|
|
2726
4561
|
chainId: Number(entry.chainId) || null,
|
|
2727
4562
|
chainName: String(entry.chainName || "").slice(0, 40),
|
|
@@ -2732,7 +4567,7 @@ function sanitizeTxEntry(entry) {
|
|
|
2732
4567
|
payAmount: String(entry.payAmount || "").slice(0, 40),
|
|
2733
4568
|
receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
|
|
2734
4569
|
account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
|
|
2735
|
-
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
|
|
4570
|
+
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
|
|
2736
4571
|
settlement: entry.settlement === "direct" ? "direct" : "escrow",
|
|
2737
4572
|
status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
|
|
2738
4573
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -2743,6 +4578,7 @@ function createEngine(config = {}) {
|
|
|
2743
4578
|
const resolved = resolveConfig(config);
|
|
2744
4579
|
const api = createApiClient(resolved);
|
|
2745
4580
|
const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
|
|
4581
|
+
const solanaRpc = createSolanaRpc(api);
|
|
2746
4582
|
return {
|
|
2747
4583
|
api,
|
|
2748
4584
|
verifier,
|
|
@@ -2753,7 +4589,7 @@ function createEngine(config = {}) {
|
|
|
2753
4589
|
fetchRouteHealth: api.fetchRouteHealth,
|
|
2754
4590
|
fetchQuote: api.fetchQuote,
|
|
2755
4591
|
fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
|
|
2756
|
-
fetchCatalogue: async (allowedAssets, product) => {
|
|
4592
|
+
fetchCatalogue: async (allowedAssets, product, options) => {
|
|
2757
4593
|
const [chains, registryTokens, routes, health, vaults] = await Promise.all([
|
|
2758
4594
|
api.fetchChains().catch(() => []),
|
|
2759
4595
|
api.fetchTokens().catch(() => []),
|
|
@@ -2770,7 +4606,9 @@ function createEngine(config = {}) {
|
|
|
2770
4606
|
routes,
|
|
2771
4607
|
product,
|
|
2772
4608
|
...allowed ? { allowedAssets: allowed } : {},
|
|
2773
|
-
|
|
4609
|
+
// Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
|
|
4610
|
+
// Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
|
|
4611
|
+
supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
|
|
2774
4612
|
brokenLanes: suppressedLanes(health),
|
|
2775
4613
|
// Same read, same degraded mode: a null health response limits nothing.
|
|
2776
4614
|
limitedLanes: limitedLanes(health),
|
|
@@ -2781,6 +4619,15 @@ function createEngine(config = {}) {
|
|
|
2781
4619
|
quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
|
|
2782
4620
|
quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
|
|
2783
4621
|
buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
|
|
4622
|
+
quoteSolanaSource: (input) => quoteSolanaSource(api, input),
|
|
4623
|
+
buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
|
|
4624
|
+
executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
|
|
4625
|
+
executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
|
|
4626
|
+
previewSolanaSource: (input) => previewSolanaSource(api, input),
|
|
4627
|
+
trackDelivery: (hash2) => fetchDelivery(api, hash2),
|
|
4628
|
+
fetchWalletHistory: (wallets) => fetchWalletHistory(api, wallets),
|
|
4629
|
+
readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
|
|
4630
|
+
simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
|
|
2784
4631
|
payerNonceBaseline: verifier.payerNonceBaseline,
|
|
2785
4632
|
verifySubmittedTx: verifier.verifySubmittedTx,
|
|
2786
4633
|
readBalances: verifier.readBalances,
|
|
@@ -2879,8 +4726,8 @@ function addChainParams(chainId) {
|
|
|
2879
4726
|
rpcUrls: [rpc]
|
|
2880
4727
|
};
|
|
2881
4728
|
}
|
|
2882
|
-
function rpcErrorCode(
|
|
2883
|
-
let cur =
|
|
4729
|
+
function rpcErrorCode(err2) {
|
|
4730
|
+
let cur = err2;
|
|
2884
4731
|
const seen = /* @__PURE__ */ new Set();
|
|
2885
4732
|
while (cur && typeof cur === "object" && !seen.has(cur)) {
|
|
2886
4733
|
seen.add(cur);
|
|
@@ -2894,50 +4741,50 @@ function rpcErrorCode(err) {
|
|
|
2894
4741
|
async function switchChain(provider, chainId) {
|
|
2895
4742
|
try {
|
|
2896
4743
|
await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainHex(chainId) }] });
|
|
2897
|
-
} catch (
|
|
4744
|
+
} catch (err2) {
|
|
2898
4745
|
const params = addChainParams(chainId);
|
|
2899
|
-
if (rpcErrorCode(
|
|
4746
|
+
if (rpcErrorCode(err2) === 4902 && params) {
|
|
2900
4747
|
await provider.request({ method: "wallet_addEthereumChain", params: [params] });
|
|
2901
4748
|
await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainHex(chainId) }] });
|
|
2902
4749
|
return;
|
|
2903
4750
|
}
|
|
2904
|
-
throw
|
|
4751
|
+
throw err2;
|
|
2905
4752
|
}
|
|
2906
4753
|
}
|
|
2907
|
-
function shortWalletMessage(
|
|
2908
|
-
if (
|
|
2909
|
-
const e =
|
|
4754
|
+
function shortWalletMessage(err2) {
|
|
4755
|
+
if (err2 && typeof err2 === "object") {
|
|
4756
|
+
const e = err2;
|
|
2910
4757
|
if (typeof e.shortMessage === "string" && e.shortMessage) return e.shortMessage;
|
|
2911
4758
|
if (typeof e.message === "string" && e.message) return e.message;
|
|
2912
4759
|
}
|
|
2913
4760
|
return void 0;
|
|
2914
4761
|
}
|
|
2915
|
-
function normalizeWalletError(
|
|
2916
|
-
if (!
|
|
2917
|
-
const code = rpcErrorCode(
|
|
2918
|
-
const name =
|
|
4762
|
+
function normalizeWalletError(err2, fallback = "Transaction failed.") {
|
|
4763
|
+
if (!err2) return fallback;
|
|
4764
|
+
const code = rpcErrorCode(err2);
|
|
4765
|
+
const name = err2 && typeof err2 === "object" && "name" in err2 ? err2.name : void 0;
|
|
2919
4766
|
if (code === -32002) return "Open your wallet \u2014 a request is already pending.";
|
|
2920
4767
|
if (code === 4001 || name === "UserRejectedRequestError") return "Request was rejected in your wallet.";
|
|
2921
4768
|
if (code === 4902) return "This chain isn't set up in your wallet. Approve adding it and try again.";
|
|
2922
|
-
if (code === -32603) return shortWalletMessage(
|
|
2923
|
-
return shortWalletMessage(
|
|
4769
|
+
if (code === -32603) return shortWalletMessage(err2) || "Your wallet returned an internal error. Try again.";
|
|
4770
|
+
return shortWalletMessage(err2) || fallback;
|
|
2924
4771
|
}
|
|
2925
4772
|
async function sendTransaction(provider, tx) {
|
|
2926
|
-
const
|
|
4773
|
+
const hash2 = await provider.request({
|
|
2927
4774
|
method: "eth_sendTransaction",
|
|
2928
4775
|
params: [{ from: tx.from, to: tx.to, data: tx.data, value: tx.value || "0x0" }]
|
|
2929
4776
|
});
|
|
2930
|
-
return
|
|
4777
|
+
return hash2;
|
|
2931
4778
|
}
|
|
2932
4779
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2933
|
-
async function waitForReceipt(provider,
|
|
4780
|
+
async function waitForReceipt(provider, hash2, opts = {}) {
|
|
2934
4781
|
const timeoutMs = opts.timeoutMs ?? 9e4;
|
|
2935
4782
|
const pollMs = opts.pollMs ?? 2500;
|
|
2936
4783
|
const deadline = Date.now() + timeoutMs;
|
|
2937
4784
|
for (; ; ) {
|
|
2938
4785
|
let receipt = null;
|
|
2939
4786
|
try {
|
|
2940
|
-
receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [
|
|
4787
|
+
receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash2] });
|
|
2941
4788
|
} catch {
|
|
2942
4789
|
}
|
|
2943
4790
|
if (receipt && receipt.status != null) {
|
|
@@ -2958,9 +4805,9 @@ async function ethCall(provider, to, data) {
|
|
|
2958
4805
|
}
|
|
2959
4806
|
async function nativeBalance(provider, account) {
|
|
2960
4807
|
try {
|
|
2961
|
-
const
|
|
2962
|
-
if (typeof
|
|
2963
|
-
return BigInt(
|
|
4808
|
+
const raw2 = await provider.request({ method: "eth_getBalance", params: [account, "latest"] });
|
|
4809
|
+
if (typeof raw2 !== "string" || !/^0x[0-9a-fA-F]*$/.test(raw2)) return null;
|
|
4810
|
+
return BigInt(raw2 || "0x0");
|
|
2964
4811
|
} catch {
|
|
2965
4812
|
return null;
|
|
2966
4813
|
}
|
|
@@ -3046,9 +4893,9 @@ function isEntry(v) {
|
|
|
3046
4893
|
function readTxHistory(account, storage2 = defaultStorage()) {
|
|
3047
4894
|
if (!storage2 || !validAccount(account)) return [];
|
|
3048
4895
|
try {
|
|
3049
|
-
const
|
|
3050
|
-
if (!
|
|
3051
|
-
const parsed = JSON.parse(
|
|
4896
|
+
const raw2 = storage2.getItem(txHistoryKey(account));
|
|
4897
|
+
if (!raw2) return [];
|
|
4898
|
+
const parsed = JSON.parse(raw2);
|
|
3052
4899
|
return Array.isArray(parsed) ? parsed.filter(isEntry) : [];
|
|
3053
4900
|
} catch {
|
|
3054
4901
|
return [];
|
|
@@ -3267,7 +5114,7 @@ function useFlow(args) {
|
|
|
3267
5114
|
const account = wallet.account;
|
|
3268
5115
|
if (!route || !provider || !account) return;
|
|
3269
5116
|
busyRef.current = true;
|
|
3270
|
-
const
|
|
5117
|
+
const recipient2 = recipientFor(account);
|
|
3271
5118
|
const sourceChainId = route.source.chainId;
|
|
3272
5119
|
const txSteps = route.transactions.map((tx) => ({ id: tx.id, label: tx.label, state: "pending" }));
|
|
3273
5120
|
txSteps.push({ id: "verify", label: "Confirm on-chain", state: "pending" });
|
|
@@ -3275,7 +5122,7 @@ function useFlow(args) {
|
|
|
3275
5122
|
setStatus("submitting");
|
|
3276
5123
|
setError(null);
|
|
3277
5124
|
setVerdict(null);
|
|
3278
|
-
const patch = (id, s,
|
|
5125
|
+
const patch = (id, s, hash2) => setSteps((prev) => prev.map((st) => st.id === id ? { ...st, state: s, ...hash2 ? { hash: hash2 } : {} } : st));
|
|
3279
5126
|
try {
|
|
3280
5127
|
const current = await getChainId(provider);
|
|
3281
5128
|
if (current !== Number(sourceChainId)) {
|
|
@@ -3305,17 +5152,17 @@ function useFlow(args) {
|
|
|
3305
5152
|
patch(tx.id, "done");
|
|
3306
5153
|
continue;
|
|
3307
5154
|
}
|
|
3308
|
-
if (!validatePlannedTransaction(tx, route,
|
|
5155
|
+
if (!validatePlannedTransaction(tx, route, recipient2)) {
|
|
3309
5156
|
throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
|
|
3310
5157
|
}
|
|
3311
5158
|
patch(tx.id, "active");
|
|
3312
|
-
const
|
|
5159
|
+
const hash2 = await sendTransaction(provider, { from: account, to: tx.to, data: tx.data, value: tx.value });
|
|
3313
5160
|
if (!isFinal) {
|
|
3314
|
-
await waitForReceipt(provider,
|
|
5161
|
+
await waitForReceipt(provider, hash2);
|
|
3315
5162
|
}
|
|
3316
|
-
patch(tx.id, "done",
|
|
5163
|
+
patch(tx.id, "done", hash2);
|
|
3317
5164
|
if (tx.kind !== "approve") {
|
|
3318
|
-
settleHash =
|
|
5165
|
+
settleHash = hash2;
|
|
3319
5166
|
settleTx = tx;
|
|
3320
5167
|
}
|
|
3321
5168
|
}
|
|
@@ -3343,7 +5190,7 @@ function useFlow(args) {
|
|
|
3343
5190
|
payAmount: route.source.payAmount,
|
|
3344
5191
|
receiveAmount: route.receive.amount,
|
|
3345
5192
|
account,
|
|
3346
|
-
recipient,
|
|
5193
|
+
recipient: recipient2,
|
|
3347
5194
|
settlement: route.state === "DIRECT" ? "direct" : "escrow",
|
|
3348
5195
|
status: v.status === "confirmed" ? "confirmed" : v.status === "mismatch" || v.status === "reverted" ? "error" : "unconfirmed",
|
|
3349
5196
|
// One signature can be several orders. Record them, or the history of a chained RWA trade
|
|
@@ -3471,18 +5318,18 @@ function groupDecimal(value) {
|
|
|
3471
5318
|
var SIGNIFICANT_DIGITS = 7;
|
|
3472
5319
|
var MIN_FRACTION_DIGITS = 4;
|
|
3473
5320
|
function formatCalculatedAmount(value, decimals) {
|
|
3474
|
-
let
|
|
5321
|
+
let raw2 = typeof value === "number" ? String(value) : value.trim();
|
|
3475
5322
|
if (typeof value === "number") {
|
|
3476
|
-
if (!Number.isFinite(value)) return
|
|
3477
|
-
if (/e/i.test(
|
|
3478
|
-
|
|
5323
|
+
if (!Number.isFinite(value)) return raw2;
|
|
5324
|
+
if (/e/i.test(raw2)) {
|
|
5325
|
+
raw2 = value.toLocaleString("en-US", {
|
|
3479
5326
|
useGrouping: false,
|
|
3480
5327
|
maximumFractionDigits: 20
|
|
3481
5328
|
});
|
|
3482
5329
|
}
|
|
3483
5330
|
}
|
|
3484
|
-
const match =
|
|
3485
|
-
if (!match) return
|
|
5331
|
+
const match = raw2.match(/^([+-]?)(\d*)(?:\.(\d*))?$/);
|
|
5332
|
+
if (!match) return raw2;
|
|
3486
5333
|
const negative = match[1] === "-";
|
|
3487
5334
|
const integer = (match[2] || "0").replace(/^0+(?=\d)/, "");
|
|
3488
5335
|
const fraction = match[3] ?? "";
|
|
@@ -3507,15 +5354,15 @@ function formatCalculatedAmount(value, decimals) {
|
|
|
3507
5354
|
const out = groupDecimal(trimFraction(fixed));
|
|
3508
5355
|
return negative && out !== "0" ? `-${out}` : out;
|
|
3509
5356
|
}
|
|
3510
|
-
function exactAmountTitle(
|
|
3511
|
-
const full = typeof
|
|
5357
|
+
function exactAmountTitle(raw2, shown) {
|
|
5358
|
+
const full = typeof raw2 === "number" ? String(raw2) : raw2.trim();
|
|
3512
5359
|
if (!full || /e/i.test(full)) return void 0;
|
|
3513
5360
|
const normalized = full.includes(".") ? trimFraction(full) : full;
|
|
3514
5361
|
const grouped = groupDecimal(normalized);
|
|
3515
5362
|
return grouped === shown ? void 0 : grouped;
|
|
3516
5363
|
}
|
|
3517
|
-
function sanitizeAmount(
|
|
3518
|
-
const cleaned =
|
|
5364
|
+
function sanitizeAmount(raw2) {
|
|
5365
|
+
const cleaned = raw2.replace(/[^0-9.]/g, "");
|
|
3519
5366
|
const first = cleaned.indexOf(".");
|
|
3520
5367
|
if (first === -1) return cleaned;
|
|
3521
5368
|
return cleaned.slice(0, first + 1) + cleaned.slice(first + 1).replace(/\./g, "");
|
|
@@ -3652,6 +5499,7 @@ var WIDGET_CSS = `
|
|
|
3652
5499
|
.sg-success-check{width:40px;height:40px;border-radius:999px;background:var(--sg-accent);color:var(--sg-accent-text);display:inline-flex;align-items:center;justify-content:center;margin-bottom:8px}
|
|
3653
5500
|
/* Broadcast but not receipt-confirmed: mute the disc so a pending settlement never wears the
|
|
3654
5501
|
accent-coloured "paid" affordance. Mirrors .sg-settle-disc[data-pending] in the island. */
|
|
5502
|
+
.sg-success-steps{font-size:12px;color:var(--sg-text-muted);margin-top:6px;text-align:center}
|
|
3655
5503
|
.sg-success-check[data-pending="true"]{background:var(--sg-surface);color:var(--sg-text-muted);border:1px solid var(--sg-border)}
|
|
3656
5504
|
.sg-success-amt{font-size:20px;font-weight:700;font-variant-numeric:tabular-nums}
|
|
3657
5505
|
.sg-success-sub{font-size:12px;color:var(--sg-text-muted);margin-top:2px}
|
|
@@ -4428,9 +6276,9 @@ function useGroupedAmountInput(amount, onAmount) {
|
|
|
4428
6276
|
});
|
|
4429
6277
|
const onChange = (e) => {
|
|
4430
6278
|
const input = e.target;
|
|
4431
|
-
const
|
|
4432
|
-
caret.current = { input, kept: sanitizeAmount(
|
|
4433
|
-
onAmount(sanitizeAmount(
|
|
6279
|
+
const raw2 = input.value;
|
|
6280
|
+
caret.current = { input, kept: sanitizeAmount(raw2.slice(0, input.selectionEnd ?? raw2.length)).length };
|
|
6281
|
+
onAmount(sanitizeAmount(raw2));
|
|
4434
6282
|
rerender();
|
|
4435
6283
|
};
|
|
4436
6284
|
const onKeyDown = (e) => {
|
|
@@ -4542,7 +6390,7 @@ function StepList(props) {
|
|
|
4542
6390
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: s.state === "done" ? "sg-muted" : "", children: s.label }),
|
|
4543
6391
|
rich ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: ` \u2014 ${STEP_STATE_WORD[s.state]}` }) : null
|
|
4544
6392
|
] }, s.id)) }),
|
|
4545
|
-
rich && props.verdict && verifyDone ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-step-verdict", children: props.verdict.status === "confirmed" ? "Confirmed on-chain \u2014
|
|
6393
|
+
rich && props.verdict && verifyDone ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-step-verdict", children: props.verdict.status === "confirmed" ? "Confirmed on-chain \u2014 on its way to the merchant." : props.verdict.status === "mismatch" ? "The submitted transaction did not match the reviewed plan." : "Payment sent \u2014 confirmation is still pending." }) : null
|
|
4546
6394
|
] });
|
|
4547
6395
|
}
|
|
4548
6396
|
var SHOW_ROADMAP_METHODS = true;
|
|
@@ -4554,11 +6402,11 @@ var METHODS = [
|
|
|
4554
6402
|
function isLiveMethod(m) {
|
|
4555
6403
|
return m === "stablecoin";
|
|
4556
6404
|
}
|
|
4557
|
-
function balanceRank(
|
|
4558
|
-
if (
|
|
6405
|
+
function balanceRank(raw2, decimals) {
|
|
6406
|
+
if (raw2 == null) return 0n;
|
|
4559
6407
|
try {
|
|
4560
6408
|
const d = Number.isFinite(Number(decimals)) ? Math.max(0, Math.trunc(Number(decimals))) : 18;
|
|
4561
|
-
const v = BigInt(
|
|
6409
|
+
const v = BigInt(raw2);
|
|
4562
6410
|
return d <= 18 ? v * 10n ** BigInt(18 - d) : v / 10n ** BigInt(d - 18);
|
|
4563
6411
|
} catch {
|
|
4564
6412
|
return 0n;
|
|
@@ -4598,7 +6446,7 @@ function RouteList(props) {
|
|
|
4598
6446
|
visible.map((r) => {
|
|
4599
6447
|
const selected = props.selectedId === r.id;
|
|
4600
6448
|
const bal = props.balances?.[routeBalanceKey(r)];
|
|
4601
|
-
const
|
|
6449
|
+
const short2 = props.shortIds?.has(r.id) ?? false;
|
|
4602
6450
|
const held = props.heldIds?.has(r.id) ?? false;
|
|
4603
6451
|
return (
|
|
4604
6452
|
// a11y note: a native radio cannot contain the rich
|
|
@@ -4610,7 +6458,7 @@ function RouteList(props) {
|
|
|
4610
6458
|
{
|
|
4611
6459
|
className: "sg-route-item",
|
|
4612
6460
|
"data-selected": selected,
|
|
4613
|
-
"data-short":
|
|
6461
|
+
"data-short": short2 || void 0,
|
|
4614
6462
|
"data-held": held || void 0,
|
|
4615
6463
|
role: "radio",
|
|
4616
6464
|
"aria-checked": selected,
|
|
@@ -4645,7 +6493,7 @@ function RouteList(props) {
|
|
|
4645
6493
|
"bal ",
|
|
4646
6494
|
bal.formatted
|
|
4647
6495
|
] }) : null,
|
|
4648
|
-
|
|
6496
|
+
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,
|
|
4649
6497
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-radio", "aria-hidden": "true" })
|
|
4650
6498
|
] })
|
|
4651
6499
|
]
|
|
@@ -4882,8 +6730,8 @@ var CHAIN_ALIASES = {
|
|
|
4882
6730
|
137: ["matic"],
|
|
4883
6731
|
43114: ["avax"]
|
|
4884
6732
|
};
|
|
4885
|
-
function labelForms(
|
|
4886
|
-
const lower2 =
|
|
6733
|
+
function labelForms(label2) {
|
|
6734
|
+
const lower2 = label2.trim().toLowerCase();
|
|
4887
6735
|
if (!lower2) return [];
|
|
4888
6736
|
const compact = lower2.replace(/[^a-z0-9]/g, "");
|
|
4889
6737
|
return compact && compact !== lower2 ? [lower2, compact] : [lower2];
|
|
@@ -4892,10 +6740,10 @@ function buildChainSearchTerms(chains) {
|
|
|
4892
6740
|
const byId = /* @__PURE__ */ new Map();
|
|
4893
6741
|
const ids = /* @__PURE__ */ new Set([...chains.map((c) => Number(c.chainId)), ...Object.keys(CHAIN_LABELS).map(Number)]);
|
|
4894
6742
|
for (const id of ids) {
|
|
4895
|
-
const
|
|
6743
|
+
const chain2 = chains.find((c) => Number(c.chainId) === id);
|
|
4896
6744
|
const terms = /* @__PURE__ */ new Set();
|
|
4897
|
-
for (const
|
|
4898
|
-
if (
|
|
6745
|
+
for (const label2 of [chain2?.displayName, chain2?.name, typeof chain2?.slug === "string" ? chain2.slug : void 0, CHAIN_LABELS[id]]) {
|
|
6746
|
+
if (label2) for (const form of labelForms(label2)) terms.add(form);
|
|
4899
6747
|
}
|
|
4900
6748
|
for (const alias of CHAIN_ALIASES[id] ?? []) terms.add(alias);
|
|
4901
6749
|
byId.set(id, [...terms]);
|
|
@@ -5267,7 +7115,7 @@ function TokenSelect(props) {
|
|
|
5267
7115
|
const members = g.deployments;
|
|
5268
7116
|
const multi = members.length > 1;
|
|
5269
7117
|
const single = members[0];
|
|
5270
|
-
const
|
|
7118
|
+
const label2 = multi ? g.symbol : tokenTicker(single.token);
|
|
5271
7119
|
const blocked = !!g.unavailable;
|
|
5272
7120
|
const opensNetworks = multi || blocked;
|
|
5273
7121
|
const zero = showBalances && g.amount === 0 || blocked;
|
|
@@ -5291,7 +7139,7 @@ function TokenSelect(props) {
|
|
|
5291
7139
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-pk-left", children: [
|
|
5292
7140
|
/* @__PURE__ */ jsxRuntime.jsx(TokenPlate, { symbol: g.symbol, logoUrl: g.logoUrl }),
|
|
5293
7141
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-pk-text", children: [
|
|
5294
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-pk-label", children:
|
|
7142
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-pk-label", children: label2 }),
|
|
5295
7143
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-pk-line", children: [
|
|
5296
7144
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-pk-sub", children: multi ? showBalances ? "Total across" : "Available on" : `On ${chainName3(Number(single.token.chainId))}` }),
|
|
5297
7145
|
/* @__PURE__ */ jsxRuntime.jsx(ChainMarks, { chainIds: members.map((m) => Number(m.token.chainId)), chainById: chainById2, decorative: !multi }),
|
|
@@ -5300,7 +7148,7 @@ function TokenSelect(props) {
|
|
|
5300
7148
|
!multi && single.hint ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-pk-note", "data-testid": "lane-limit", children: single.hint }) : null
|
|
5301
7149
|
] })
|
|
5302
7150
|
] }),
|
|
5303
|
-
showBalances ? /* @__PURE__ */ jsxRuntime.jsx(BalanceColumn, { amount: g.amount, usd: g.usd, symbol:
|
|
7151
|
+
showBalances ? /* @__PURE__ */ jsxRuntime.jsx(BalanceColumn, { amount: g.amount, usd: g.usd, symbol: label2 }) : opensNetworks ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-pk-chev", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx(ChevronGlyph, {}) }) : null
|
|
5304
7152
|
]
|
|
5305
7153
|
},
|
|
5306
7154
|
g.key
|
|
@@ -5384,7 +7232,7 @@ function durationLabel(seconds) {
|
|
|
5384
7232
|
}
|
|
5385
7233
|
function TokenButton(props) {
|
|
5386
7234
|
const shown = props.token ? tokenTicker(props.token) : props.symbol ?? "";
|
|
5387
|
-
const
|
|
7235
|
+
const chain2 = props.chainId ? CHAIN_LABELS[props.chainId] || `Chain ${props.chainId}` : "";
|
|
5388
7236
|
return /* @__PURE__ */ jsxRuntime.jsxs(
|
|
5389
7237
|
"button",
|
|
5390
7238
|
{
|
|
@@ -5393,13 +7241,13 @@ function TokenButton(props) {
|
|
|
5393
7241
|
className: "sg-tokbtn",
|
|
5394
7242
|
disabled: props.disabled,
|
|
5395
7243
|
onClick: props.onClick,
|
|
5396
|
-
"aria-label": `${props.label}: ${props.symbol ? `${shown} on ${
|
|
7244
|
+
"aria-label": `${props.label}: ${props.symbol ? `${shown} on ${chain2}` : "select token"}`,
|
|
5397
7245
|
children: [
|
|
5398
7246
|
props.symbol && props.chainId ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
5399
7247
|
/* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: props.symbol, logoUrl: props.token?.logoUrl, chainId: props.chainId, size: "xs" }),
|
|
5400
7248
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-tokbtn-text", children: [
|
|
5401
7249
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-sym", children: shown }),
|
|
5402
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chain", children:
|
|
7250
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chain", children: chain2 })
|
|
5403
7251
|
] })
|
|
5404
7252
|
] }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-text", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-sym", children: "Select" }) }),
|
|
5405
7253
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chev", children: /* @__PURE__ */ jsxRuntime.jsx(ChevronRight, {}) })
|
|
@@ -5586,12 +7434,12 @@ function TriggerGlyph({ cv }) {
|
|
|
5586
7434
|
return /* @__PURE__ */ jsxRuntime.jsx(ShieldTick, {});
|
|
5587
7435
|
}
|
|
5588
7436
|
function CheckRow({ check: check2, onViewPolicy }) {
|
|
5589
|
-
const
|
|
7437
|
+
const label2 = check2.id === "risk" ? check2.ok ? "Risk screening passed" : "Risk screening failed" : check2.label;
|
|
5590
7438
|
return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: "sg-cp-check", "data-ok": check2.ok, children: [
|
|
5591
7439
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-check-head", children: [
|
|
5592
7440
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cp-check-label", children: [
|
|
5593
7441
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-mark", "data-ok": check2.ok, children: check2.ok ? /* @__PURE__ */ jsxRuntime.jsx(Tick, {}) : /* @__PURE__ */ jsxRuntime.jsx(Cross, {}) }),
|
|
5594
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { children:
|
|
7442
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { children: label2 }),
|
|
5595
7443
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: check2.ok ? " \u2014 passed" : " \u2014 failed" })
|
|
5596
7444
|
] }),
|
|
5597
7445
|
check2.id === "risk" ? /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-cp-link", onClick: onViewPolicy, children: [
|
|
@@ -5659,9 +7507,9 @@ function QuoteChecks({
|
|
|
5659
7507
|
] }) : null
|
|
5660
7508
|
] });
|
|
5661
7509
|
}
|
|
5662
|
-
function Fact({ label, value, title, mono = false }) {
|
|
7510
|
+
function Fact({ label: label2, value, title, mono = false }) {
|
|
5663
7511
|
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-fact", children: [
|
|
5664
|
-
/* @__PURE__ */ jsxRuntime.jsx("dt", { children:
|
|
7512
|
+
/* @__PURE__ */ jsxRuntime.jsx("dt", { children: label2 }),
|
|
5665
7513
|
/* @__PURE__ */ jsxRuntime.jsx("dd", { title, className: mono ? "sg-mono" : void 0, children: value })
|
|
5666
7514
|
] });
|
|
5667
7515
|
}
|
|
@@ -5790,6 +7638,39 @@ function useTxHistory(account) {
|
|
|
5790
7638
|
}, [account]);
|
|
5791
7639
|
return entries;
|
|
5792
7640
|
}
|
|
7641
|
+
var WALLET_HISTORY_REFRESH_MS = 3e4;
|
|
7642
|
+
var hidden2 = () => typeof document !== "undefined" && document.visibilityState === "hidden";
|
|
7643
|
+
var travelling = (entries) => !!entries?.some((e) => e.delivery === "in-progress" || e.delivery === "attention");
|
|
7644
|
+
function useWalletHistory(engine, wallets) {
|
|
7645
|
+
const [entries, setEntries] = react.useState(null);
|
|
7646
|
+
const key = wallets.filter((w) => !!w).join("|");
|
|
7647
|
+
react.useEffect(() => {
|
|
7648
|
+
setEntries(null);
|
|
7649
|
+
if (!engine || !key) return;
|
|
7650
|
+
let alive = true;
|
|
7651
|
+
let timer2;
|
|
7652
|
+
const read = async () => {
|
|
7653
|
+
if (timer2) clearTimeout(timer2);
|
|
7654
|
+
timer2 = void 0;
|
|
7655
|
+
if (!hidden2()) {
|
|
7656
|
+
const next = await engine.fetchWalletHistory(key.split("|"));
|
|
7657
|
+
if (!alive) return;
|
|
7658
|
+
if (next) setEntries(next);
|
|
7659
|
+
if (!travelling(next)) return;
|
|
7660
|
+
}
|
|
7661
|
+
timer2 = setTimeout(read, WALLET_HISTORY_REFRESH_MS);
|
|
7662
|
+
};
|
|
7663
|
+
void read();
|
|
7664
|
+
const onRecorded = () => void read();
|
|
7665
|
+
if (typeof window !== "undefined") window.addEventListener(TX_HISTORY_EVENT, onRecorded);
|
|
7666
|
+
return () => {
|
|
7667
|
+
alive = false;
|
|
7668
|
+
if (timer2) clearTimeout(timer2);
|
|
7669
|
+
if (typeof window !== "undefined") window.removeEventListener(TX_HISTORY_EVENT, onRecorded);
|
|
7670
|
+
};
|
|
7671
|
+
}, [engine, key]);
|
|
7672
|
+
return entries;
|
|
7673
|
+
}
|
|
5793
7674
|
function BackGlyph() {
|
|
5794
7675
|
return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "17", height: "17", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
|
|
5795
7676
|
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M19 12H5" }),
|
|
@@ -5873,7 +7754,15 @@ function TxLegs(props) {
|
|
|
5873
7754
|
] }, `${leg.index}:${leg.fromChainId}:${leg.toChainId}`)) })
|
|
5874
7755
|
] });
|
|
5875
7756
|
}
|
|
5876
|
-
function statusBadge(
|
|
7757
|
+
function statusBadge(entry) {
|
|
7758
|
+
if (entry.delivery === "delivered")
|
|
7759
|
+
return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Delivered" });
|
|
7760
|
+
if (entry.delivery === "failed")
|
|
7761
|
+
return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Not delivered" });
|
|
7762
|
+
if (entry.delivery === "attention")
|
|
7763
|
+
return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Needs action" });
|
|
7764
|
+
if (entry.delivery === "in-progress") return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", children: "On its way" });
|
|
7765
|
+
const status = entry.status;
|
|
5877
7766
|
if (status === "confirmed")
|
|
5878
7767
|
return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Confirmed" });
|
|
5879
7768
|
if (status === "error")
|
|
@@ -5945,7 +7834,7 @@ function TxHistoryList(props) {
|
|
|
5945
7834
|
] }),
|
|
5946
7835
|
whenLabel(e.at) ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-txrow-time", children: whenLabel(e.at) }) : null
|
|
5947
7836
|
] }),
|
|
5948
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-txrow-end", children: statusBadge(e
|
|
7837
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-txrow-end", children: statusBadge(e) })
|
|
5949
7838
|
] })
|
|
5950
7839
|
] }, `${e.hash}:${e.at}`)
|
|
5951
7840
|
)) });
|
|
@@ -5985,7 +7874,7 @@ function TxDetail(props) {
|
|
|
5985
7874
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta", children: [
|
|
5986
7875
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
|
|
5987
7876
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Status" }),
|
|
5988
|
-
statusBadge(e
|
|
7877
|
+
statusBadge(e)
|
|
5989
7878
|
] }),
|
|
5990
7879
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
|
|
5991
7880
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "You sent" }),
|
|
@@ -6021,18 +7910,21 @@ function displayableHistory(entries, account) {
|
|
|
6021
7910
|
}
|
|
6022
7911
|
function TxHistoryPanel(props) {
|
|
6023
7912
|
const account = props.account;
|
|
6024
|
-
const
|
|
6025
|
-
const
|
|
6026
|
-
const
|
|
7913
|
+
const stored = useTxHistory(account);
|
|
7914
|
+
const remote = useWalletHistory(props.engine, [account, props.solanaAccount]);
|
|
7915
|
+
const entries = react.useMemo(() => mergeHistory(displayableHistory(stored, account), remote), [stored, account, remote]);
|
|
7916
|
+
const linked = props.initialEntry && displayableHistory([props.initialEntry], account).length ? props.initialEntry : null;
|
|
7917
|
+
const [selectedHash, setSelectedHash] = react.useState(linked?.hash ?? null);
|
|
7918
|
+
const selected = selectedHash ? entries.find((e) => e.hash === selectedHash) ?? (linked?.hash === selectedHash ? linked : null) : null;
|
|
6027
7919
|
const backRef = react.useRef(null);
|
|
6028
|
-
react.useEffect(() =>
|
|
7920
|
+
react.useEffect(() => setSelectedHash(linked?.hash ?? null), [linked?.hash]);
|
|
6029
7921
|
const pick = (entry) => {
|
|
6030
|
-
|
|
7922
|
+
setSelectedHash(entry.hash);
|
|
6031
7923
|
requestAnimationFrame(() => backRef.current?.focus());
|
|
6032
7924
|
};
|
|
6033
7925
|
return /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
|
|
6034
7926
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-head", children: [
|
|
6035
|
-
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", autoFocus: true, ref: backRef, className: "sg-back", onClick: selected ? () =>
|
|
7927
|
+
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", autoFocus: true, ref: backRef, className: "sg-back", onClick: selected ? () => setSelectedHash(null) : props.onBack, "aria-label": "Back", children: /* @__PURE__ */ jsxRuntime.jsx(BackGlyph, {}) }),
|
|
6036
7928
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-title", children: [
|
|
6037
7929
|
selected ? "Transaction" : "Transaction history",
|
|
6038
7930
|
account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress2(account) }) : null
|
|
@@ -6041,6 +7933,444 @@ function TxHistoryPanel(props) {
|
|
|
6041
7933
|
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 })
|
|
6042
7934
|
] });
|
|
6043
7935
|
}
|
|
7936
|
+
|
|
7937
|
+
// src/provider/solana-wallet.ts
|
|
7938
|
+
var sources = /* @__PURE__ */ new WeakMap();
|
|
7939
|
+
var infos = /* @__PURE__ */ new WeakMap();
|
|
7940
|
+
var connected = /* @__PURE__ */ new WeakMap();
|
|
7941
|
+
var registries = /* @__PURE__ */ new WeakMap();
|
|
7942
|
+
var EMPTY2 = Object.freeze([]);
|
|
7943
|
+
function normalizeSolanaWalletName(name) {
|
|
7944
|
+
return name.trim().toLowerCase().replace(/\s+(wallet|evm|solana)$/i, "");
|
|
7945
|
+
}
|
|
7946
|
+
function solanaWalletInfo(provider) {
|
|
7947
|
+
const standard = "features" in provider;
|
|
7948
|
+
if (standard ? !provider.chains?.some((chain2) => chain2.startsWith("solana:")) || typeof provider.features?.["standard:connect"]?.connect !== "function" : typeof provider.connect !== "function") return null;
|
|
7949
|
+
let info = infos.get(provider);
|
|
7950
|
+
if (!info) {
|
|
7951
|
+
const name = provider.name || (!standard && provider.isPhantom ? "Phantom" : !standard && provider.isSolflare ? "Solflare" : "Solana wallet");
|
|
7952
|
+
info = Object.freeze({ name, icon: standard ? provider.icon : void 0, kind: standard ? "standard" : "legacy" });
|
|
7953
|
+
infos.set(provider, info);
|
|
7954
|
+
sources.set(info, provider);
|
|
7955
|
+
}
|
|
7956
|
+
return info;
|
|
7957
|
+
}
|
|
7958
|
+
function targetWindow(win) {
|
|
7959
|
+
return win ?? (typeof window === "undefined" ? void 0 : window);
|
|
7960
|
+
}
|
|
7961
|
+
function registry(win) {
|
|
7962
|
+
const existing = registries.get(win);
|
|
7963
|
+
if (existing) return existing;
|
|
7964
|
+
const standard = /* @__PURE__ */ new Set();
|
|
7965
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7966
|
+
let snapshot = EMPTY2;
|
|
7967
|
+
const read = () => {
|
|
7968
|
+
const candidates = [...standard].map(solanaWalletInfo);
|
|
7969
|
+
for (const [provider, name] of [[win.phantom?.solana, "Phantom"], [win.solflare, "Solflare"], [win.solana, void 0]]) {
|
|
7970
|
+
if (!provider || typeof provider.connect !== "function") continue;
|
|
7971
|
+
let info = solanaWalletInfo(provider);
|
|
7972
|
+
if (info && name && info.name === "Solana wallet") {
|
|
7973
|
+
info = Object.freeze({ ...info, name });
|
|
7974
|
+
infos.set(provider, info);
|
|
7975
|
+
sources.set(info, provider);
|
|
7976
|
+
}
|
|
7977
|
+
candidates.push(info);
|
|
7978
|
+
}
|
|
7979
|
+
const names = /* @__PURE__ */ new Set();
|
|
7980
|
+
const providers = /* @__PURE__ */ new Set();
|
|
7981
|
+
const next = candidates.filter((info) => {
|
|
7982
|
+
if (!info) return false;
|
|
7983
|
+
const name = normalizeSolanaWalletName(info.name);
|
|
7984
|
+
const provider = sources.get(info);
|
|
7985
|
+
if (names.has(name) || providers.has(provider)) return false;
|
|
7986
|
+
names.add(name);
|
|
7987
|
+
providers.add(provider);
|
|
7988
|
+
return true;
|
|
7989
|
+
});
|
|
7990
|
+
if (next.length !== snapshot.length || next.some((info) => !snapshot.includes(info))) snapshot = Object.freeze(next);
|
|
7991
|
+
return snapshot;
|
|
7992
|
+
};
|
|
7993
|
+
const refresh = () => {
|
|
7994
|
+
const previous = snapshot;
|
|
7995
|
+
read();
|
|
7996
|
+
if (previous !== snapshot) for (const cb of listeners) cb();
|
|
7997
|
+
};
|
|
7998
|
+
const api = {
|
|
7999
|
+
register(...wallets) {
|
|
8000
|
+
const added = wallets.filter((wallet) => !standard.has(wallet));
|
|
8001
|
+
for (const wallet of added) standard.add(wallet);
|
|
8002
|
+
refresh();
|
|
8003
|
+
return () => {
|
|
8004
|
+
for (const wallet of added) standard.delete(wallet);
|
|
8005
|
+
refresh();
|
|
8006
|
+
};
|
|
8007
|
+
}
|
|
8008
|
+
};
|
|
8009
|
+
const result = { read, watch: (cb) => {
|
|
8010
|
+
listeners.add(cb);
|
|
8011
|
+
return () => {
|
|
8012
|
+
listeners.delete(cb);
|
|
8013
|
+
};
|
|
8014
|
+
} };
|
|
8015
|
+
registries.set(win, result);
|
|
8016
|
+
win.addEventListener("wallet-standard:register-wallet", (event) => {
|
|
8017
|
+
const callback = event.detail;
|
|
8018
|
+
if (typeof callback === "function") callback(api);
|
|
8019
|
+
});
|
|
8020
|
+
win.addEventListener("focus", refresh);
|
|
8021
|
+
const EventClass = win.CustomEvent;
|
|
8022
|
+
win.dispatchEvent(new EventClass("wallet-standard:app-ready", { detail: api }));
|
|
8023
|
+
read();
|
|
8024
|
+
return result;
|
|
8025
|
+
}
|
|
8026
|
+
function discoverSolanaWallets(win) {
|
|
8027
|
+
const target = targetWindow(win);
|
|
8028
|
+
return target ? registry(target).read() : EMPTY2;
|
|
8029
|
+
}
|
|
8030
|
+
function watchSolanaWallets(cb, win) {
|
|
8031
|
+
const target = targetWindow(win);
|
|
8032
|
+
if (!target) return () => {
|
|
8033
|
+
};
|
|
8034
|
+
const store = registry(target);
|
|
8035
|
+
const unsubscribe = store.watch(() => cb(store.read()));
|
|
8036
|
+
cb(store.read());
|
|
8037
|
+
return unsubscribe;
|
|
8038
|
+
}
|
|
8039
|
+
function source(info) {
|
|
8040
|
+
const provider = sources.get(info);
|
|
8041
|
+
if (!provider) throw new Error("Solana wallet is no longer available. Discover it before connecting.");
|
|
8042
|
+
return provider;
|
|
8043
|
+
}
|
|
8044
|
+
function validAddress(value) {
|
|
8045
|
+
const address = value?.toString().trim();
|
|
8046
|
+
return address && isSolanaAddress(address) ? address : null;
|
|
8047
|
+
}
|
|
8048
|
+
function accountAddress(accounts) {
|
|
8049
|
+
const account = accounts?.find((item) => !item.chains?.length || item.chains.some((chain2) => chain2.startsWith("solana:")));
|
|
8050
|
+
return validAddress(account?.address);
|
|
8051
|
+
}
|
|
8052
|
+
function connectedSolanaAddress(info) {
|
|
8053
|
+
const provider = source(info);
|
|
8054
|
+
return "features" in provider ? accountAddress(provider.accounts) : validAddress(provider.publicKey);
|
|
8055
|
+
}
|
|
8056
|
+
async function connectSolanaWallet(info, options = {}) {
|
|
8057
|
+
const provider = source(info);
|
|
8058
|
+
let address;
|
|
8059
|
+
if ("features" in provider) {
|
|
8060
|
+
const result = await provider.features["standard:connect"].connect(options.silent ? { silent: true } : void 0);
|
|
8061
|
+
const accounts = result?.accounts ?? provider.accounts;
|
|
8062
|
+
connected.set(provider, accounts ?? []);
|
|
8063
|
+
address = accountAddress(accounts);
|
|
8064
|
+
} else {
|
|
8065
|
+
const result = await provider.connect(options.silent ? { onlyIfTrusted: true } : void 0);
|
|
8066
|
+
address = validAddress(result?.publicKey ?? provider.publicKey);
|
|
8067
|
+
connected.set(provider, address ? [{ address }] : []);
|
|
8068
|
+
}
|
|
8069
|
+
if (!address) throw new Error("The wallet did not return a valid Solana address.");
|
|
8070
|
+
return address;
|
|
8071
|
+
}
|
|
8072
|
+
async function disconnectSolanaWallet(info) {
|
|
8073
|
+
const provider = source(info);
|
|
8074
|
+
if ("features" in provider) await provider.features["standard:disconnect"]?.disconnect();
|
|
8075
|
+
else await provider.disconnect?.();
|
|
8076
|
+
connected.delete(provider);
|
|
8077
|
+
}
|
|
8078
|
+
var CANNOT_PAY = "This wallet cannot pay from Solana here; use a Wallet Standard wallet (Phantom, Solflare, Backpack).";
|
|
8079
|
+
function solanaWalletSigner(info) {
|
|
8080
|
+
const provider = source(info);
|
|
8081
|
+
const accounts = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
|
|
8082
|
+
const address = accountAddress(accounts);
|
|
8083
|
+
if (!connected.has(provider) || !address) throw new Error("Connect a Solana wallet before paying.");
|
|
8084
|
+
if ("features" in provider ? typeof provider.features["solana:signTransaction"]?.signTransaction !== "function" : typeof provider.signTransactionBytes !== "function") throw new Error(CANNOT_PAY);
|
|
8085
|
+
return {
|
|
8086
|
+
publicKey: address,
|
|
8087
|
+
async signTransaction(bytes) {
|
|
8088
|
+
const current = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
|
|
8089
|
+
const account = current?.find((a) => a.address === address);
|
|
8090
|
+
if (!connected.has(provider) || !account || accountAddress(current) !== address) throw new Error("Solana wallet account changed; reconnect before paying.");
|
|
8091
|
+
let signed;
|
|
8092
|
+
if ("features" in provider) {
|
|
8093
|
+
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.");
|
|
8094
|
+
const result = await provider.features["solana:signTransaction"].signTransaction({ account, chain: "solana:mainnet", transaction: new Uint8Array(bytes) });
|
|
8095
|
+
if (result.length !== 1) throw new Error("Wallet returned an invalid Solana signing result.");
|
|
8096
|
+
signed = result[0]?.signedTransaction;
|
|
8097
|
+
} else signed = await provider.signTransactionBytes(new Uint8Array(bytes));
|
|
8098
|
+
if (!(signed instanceof Uint8Array)) throw new Error("Wallet did not return signed transaction bytes.");
|
|
8099
|
+
return new Uint8Array(signed);
|
|
8100
|
+
}
|
|
8101
|
+
};
|
|
8102
|
+
}
|
|
8103
|
+
function onSolanaAccountChange(info, cb) {
|
|
8104
|
+
const provider = source(info);
|
|
8105
|
+
if ("features" in provider) return provider.features["standard:events"]?.on("change", (change) => {
|
|
8106
|
+
if (change.accounts !== void 0) {
|
|
8107
|
+
connected.set(provider, change.accounts);
|
|
8108
|
+
cb(accountAddress(change.accounts));
|
|
8109
|
+
}
|
|
8110
|
+
}) ?? (() => {
|
|
8111
|
+
});
|
|
8112
|
+
const changed = (key) => {
|
|
8113
|
+
const address = validAddress(key);
|
|
8114
|
+
connected.set(provider, address ? [{ address }] : []);
|
|
8115
|
+
cb(address);
|
|
8116
|
+
};
|
|
8117
|
+
const disconnected = () => {
|
|
8118
|
+
connected.delete(provider);
|
|
8119
|
+
cb(null);
|
|
8120
|
+
};
|
|
8121
|
+
provider.on?.("accountChanged", changed);
|
|
8122
|
+
provider.on?.("connect", changed);
|
|
8123
|
+
provider.on?.("disconnect", disconnected);
|
|
8124
|
+
return () => {
|
|
8125
|
+
const off = provider.off ?? provider.removeListener;
|
|
8126
|
+
off?.call(provider, "accountChanged", changed);
|
|
8127
|
+
off?.call(provider, "connect", changed);
|
|
8128
|
+
off?.call(provider, "disconnect", disconnected);
|
|
8129
|
+
};
|
|
8130
|
+
}
|
|
8131
|
+
|
|
8132
|
+
// src/react/hooks/useSolanaWallet.ts
|
|
8133
|
+
var STORAGE_KEY = "sg-solana-wallet";
|
|
8134
|
+
function remember(name) {
|
|
8135
|
+
try {
|
|
8136
|
+
if (name) window.localStorage.setItem(STORAGE_KEY, name);
|
|
8137
|
+
else window.localStorage.removeItem(STORAGE_KEY);
|
|
8138
|
+
} catch {
|
|
8139
|
+
}
|
|
8140
|
+
}
|
|
8141
|
+
function remembered() {
|
|
8142
|
+
try {
|
|
8143
|
+
return window.localStorage.getItem(STORAGE_KEY);
|
|
8144
|
+
} catch {
|
|
8145
|
+
return null;
|
|
8146
|
+
}
|
|
8147
|
+
}
|
|
8148
|
+
var INITIAL = { address: null, walletName: null, status: "idle", error: null };
|
|
8149
|
+
function useSolanaWallet(provider) {
|
|
8150
|
+
const override = react.useMemo(() => null, [provider]);
|
|
8151
|
+
const [discovered, setDiscovered] = react.useState(discoverSolanaWallets);
|
|
8152
|
+
const wallets = react.useMemo(() => discovered, [provider, override, discovered]);
|
|
8153
|
+
const [state, setState] = react.useState(INITIAL);
|
|
8154
|
+
const active = react.useRef(null);
|
|
8155
|
+
const unsubscribe = react.useRef(() => {
|
|
8156
|
+
});
|
|
8157
|
+
const generation = react.useRef(0);
|
|
8158
|
+
const attempted = react.useRef(false);
|
|
8159
|
+
react.useEffect(() => {
|
|
8160
|
+
attempted.current = false;
|
|
8161
|
+
setState(INITIAL);
|
|
8162
|
+
return () => {
|
|
8163
|
+
generation.current += 1;
|
|
8164
|
+
unsubscribe.current();
|
|
8165
|
+
active.current = null;
|
|
8166
|
+
};
|
|
8167
|
+
}, [provider]);
|
|
8168
|
+
react.useEffect(() => watchSolanaWallets(setDiscovered), [provider]);
|
|
8169
|
+
const runConnect = react.useCallback(async (info, silent = false) => {
|
|
8170
|
+
const request = ++generation.current;
|
|
8171
|
+
unsubscribe.current();
|
|
8172
|
+
active.current = null;
|
|
8173
|
+
setState({ ...INITIAL, status: "connecting" });
|
|
8174
|
+
try {
|
|
8175
|
+
const address = await connectSolanaWallet(info, { silent });
|
|
8176
|
+
if (request !== generation.current) return;
|
|
8177
|
+
active.current = info;
|
|
8178
|
+
unsubscribe.current = onSolanaAccountChange(info, (next) => {
|
|
8179
|
+
if (request !== generation.current) return;
|
|
8180
|
+
setState({ address: next, walletName: next ? info.name : null, status: next ? "connected" : "idle", error: null });
|
|
8181
|
+
if (!next) {
|
|
8182
|
+
generation.current += 1;
|
|
8183
|
+
unsubscribe.current();
|
|
8184
|
+
active.current = null;
|
|
8185
|
+
remember(null);
|
|
8186
|
+
}
|
|
8187
|
+
});
|
|
8188
|
+
setState({ address, walletName: info.name, status: "connected", error: null });
|
|
8189
|
+
remember(info.name);
|
|
8190
|
+
return address;
|
|
8191
|
+
} catch (error) {
|
|
8192
|
+
if (request === generation.current) setState(silent ? INITIAL : {
|
|
8193
|
+
...INITIAL,
|
|
8194
|
+
status: "error",
|
|
8195
|
+
error: error instanceof Error ? error.message : "Could not connect a Solana wallet."
|
|
8196
|
+
});
|
|
8197
|
+
}
|
|
8198
|
+
}, []);
|
|
8199
|
+
react.useEffect(() => {
|
|
8200
|
+
if (attempted.current || active.current) return;
|
|
8201
|
+
const name = remembered();
|
|
8202
|
+
const info = wallets.find((wallet) => connectedSolanaAddress(wallet)) ?? (name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : void 0);
|
|
8203
|
+
if (!info) return;
|
|
8204
|
+
attempted.current = true;
|
|
8205
|
+
void runConnect(info, true);
|
|
8206
|
+
}, [wallets, runConnect]);
|
|
8207
|
+
const connect = react.useCallback(async (name) => {
|
|
8208
|
+
if (!name && wallets.length > 1) return wallets;
|
|
8209
|
+
attempted.current = true;
|
|
8210
|
+
const info = name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : wallets[0];
|
|
8211
|
+
if (!info) {
|
|
8212
|
+
setState({ ...INITIAL, status: "error", error: name ? "Solana wallet is not available." : "No Solana wallet found." });
|
|
8213
|
+
return;
|
|
8214
|
+
}
|
|
8215
|
+
return runConnect(info);
|
|
8216
|
+
}, [wallets, runConnect]);
|
|
8217
|
+
const disconnect = react.useCallback(async () => {
|
|
8218
|
+
attempted.current = true;
|
|
8219
|
+
generation.current += 1;
|
|
8220
|
+
unsubscribe.current();
|
|
8221
|
+
const info = active.current;
|
|
8222
|
+
active.current = null;
|
|
8223
|
+
setState(INITIAL);
|
|
8224
|
+
remember(null);
|
|
8225
|
+
if (info) {
|
|
8226
|
+
try {
|
|
8227
|
+
await disconnectSolanaWallet(info);
|
|
8228
|
+
} catch {
|
|
8229
|
+
}
|
|
8230
|
+
}
|
|
8231
|
+
}, []);
|
|
8232
|
+
return { ...state, wallets, connect, disconnect };
|
|
8233
|
+
}
|
|
8234
|
+
|
|
8235
|
+
// src/react/hooks/useRecipient.ts
|
|
8236
|
+
function useRecipient(destinationChainId, hostRecipient, opts = {}) {
|
|
8237
|
+
const recipientFamily = isSolanaChainId(destinationChainId) ? "solana" : "evm";
|
|
8238
|
+
const own = useSolanaWallet();
|
|
8239
|
+
const wallet = opts.solanaWallet ?? own;
|
|
8240
|
+
const [custom, setCustom] = react.useState({});
|
|
8241
|
+
const [open, setOpen] = react.useState(false);
|
|
8242
|
+
const triggerRef = react.useRef(null);
|
|
8243
|
+
const evmManaged = recipientFamily === "evm" && Boolean(opts.sourceIsSolana);
|
|
8244
|
+
const managed = hostRecipient === void 0 && (recipientFamily === "solana" || evmManaged);
|
|
8245
|
+
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;
|
|
8246
|
+
const recipient2 = hostRecipient !== void 0 ? hostRecipient : recipientFamily === "solana" ? custom.solana || wallet.address || void 0 : evmManaged ? custom.evm || opts.evm?.account || void 0 : void 0;
|
|
8247
|
+
const missing = managed && !recipient2;
|
|
8248
|
+
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 };
|
|
8249
|
+
const close = () => {
|
|
8250
|
+
setOpen(false);
|
|
8251
|
+
requestAnimationFrame(() => triggerRef.current?.focus());
|
|
8252
|
+
};
|
|
8253
|
+
const selectAddress = (address) => {
|
|
8254
|
+
setCustom((prev) => ({ ...prev, [recipientFamily]: address }));
|
|
8255
|
+
close();
|
|
8256
|
+
};
|
|
8257
|
+
const connect = async (name) => {
|
|
8258
|
+
if (recipientFamily === "evm") {
|
|
8259
|
+
if (opts.evm?.account) selectAddress("");
|
|
8260
|
+
else opts.evm?.connect();
|
|
8261
|
+
return;
|
|
8262
|
+
}
|
|
8263
|
+
if (wallet.address && !name) {
|
|
8264
|
+
selectAddress("");
|
|
8265
|
+
return;
|
|
8266
|
+
}
|
|
8267
|
+
if (!name && wallet.wallets.length !== 1) {
|
|
8268
|
+
setOpen(true);
|
|
8269
|
+
return;
|
|
8270
|
+
}
|
|
8271
|
+
const address = await wallet.connect(name);
|
|
8272
|
+
if (typeof address === "string") selectAddress("");
|
|
8273
|
+
else setOpen(true);
|
|
8274
|
+
};
|
|
8275
|
+
const recipientFor = (account) => recipientFamily === "solana" || evmManaged ? recipient2 || "" : hostRecipient || account;
|
|
8276
|
+
return { recipientFamily, recipient: recipient2, recipientFor, managed, missing, error, wallet, familyWallet, open: open && managed, show: () => setOpen(true), close, selectAddress, connect, triggerRef };
|
|
8277
|
+
}
|
|
8278
|
+
var short = (address) => `${address.slice(0, 4)}\u2026${address.slice(-4)}`;
|
|
8279
|
+
function RecipientNote({ state, disabled }) {
|
|
8280
|
+
if (state.error) return /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: state.error });
|
|
8281
|
+
if (!state.managed) return null;
|
|
8282
|
+
const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
|
|
8283
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", justifyContent: "center", gap: 6, marginTop: 10, fontSize: 13, color: "var(--sg-text-muted)", flexWrap: "wrap" }, children: [
|
|
8284
|
+
state.recipient ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
8285
|
+
"To ",
|
|
8286
|
+
/* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", title: state.recipient, style: { color: "var(--sg-text)" }, children: short(state.recipient) }),
|
|
8287
|
+
" on ",
|
|
8288
|
+
family,
|
|
8289
|
+
" \xB7 "
|
|
8290
|
+
] }) : null,
|
|
8291
|
+
/* @__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" })
|
|
8292
|
+
] });
|
|
8293
|
+
}
|
|
8294
|
+
function RecipientSheet({ state, symbol }) {
|
|
8295
|
+
const [draft, setDraft] = react.useState(state.recipient ?? "");
|
|
8296
|
+
const id = react.useId();
|
|
8297
|
+
const inputRef = react.useRef(null);
|
|
8298
|
+
const sheetRef = react.useRef(null);
|
|
8299
|
+
const closeRef = react.useRef(state.close);
|
|
8300
|
+
closeRef.current = state.close;
|
|
8301
|
+
const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
|
|
8302
|
+
const valid = state.recipientFamily === "solana" ? isSolanaAddress(draft) : /^0x[0-9a-fA-F]{40}$/.test(draft.trim());
|
|
8303
|
+
const invalid = Boolean(draft.trim()) && !valid;
|
|
8304
|
+
const noWallet = state.recipientFamily === "solana" && !state.familyWallet.address && !state.familyWallet.wallets.length;
|
|
8305
|
+
react.useEffect(() => {
|
|
8306
|
+
(noWallet ? inputRef : sheetRef).current?.focus();
|
|
8307
|
+
const onKey = (event) => {
|
|
8308
|
+
if (event.key === "Escape") {
|
|
8309
|
+
event.stopPropagation();
|
|
8310
|
+
closeRef.current();
|
|
8311
|
+
}
|
|
8312
|
+
};
|
|
8313
|
+
document.addEventListener("keydown", onKey, true);
|
|
8314
|
+
return () => document.removeEventListener("keydown", onKey, true);
|
|
8315
|
+
}, [noWallet]);
|
|
8316
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet", role: "dialog", "aria-modal": "true", "aria-label": `${family} recipient`, ref: sheetRef, tabIndex: -1, children: [
|
|
8317
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet-head", children: [
|
|
8318
|
+
/* @__PURE__ */ jsxRuntime.jsxs("h4", { className: "sg-cp-sheet-title", children: [
|
|
8319
|
+
family,
|
|
8320
|
+
" recipient"
|
|
8321
|
+
] }),
|
|
8322
|
+
/* @__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" }) }) })
|
|
8323
|
+
] }),
|
|
8324
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet-body", children: [
|
|
8325
|
+
/* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cp-card", children: [
|
|
8326
|
+
/* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", style: { margin: "0 0 12px" }, children: [
|
|
8327
|
+
symbol,
|
|
8328
|
+
" is delivered to a ",
|
|
8329
|
+
family,
|
|
8330
|
+
" wallet. Your EVM wallet stays the owner of the order and can cancel it."
|
|
8331
|
+
] }),
|
|
8332
|
+
/* @__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` }),
|
|
8333
|
+
!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,
|
|
8334
|
+
noWallet ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", children: [
|
|
8335
|
+
"No ",
|
|
8336
|
+
family,
|
|
8337
|
+
" wallet found. Enter a ",
|
|
8338
|
+
family,
|
|
8339
|
+
" address instead."
|
|
8340
|
+
] }) : null,
|
|
8341
|
+
state.familyWallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: state.familyWallet.error }) : null
|
|
8342
|
+
] }),
|
|
8343
|
+
/* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cp-card", children: [
|
|
8344
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-field", style: { margin: 0 }, children: [
|
|
8345
|
+
/* @__PURE__ */ jsxRuntime.jsx("label", { className: "sg-label", htmlFor: id, children: "Send to a different address" }),
|
|
8346
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
|
8347
|
+
"input",
|
|
8348
|
+
{
|
|
8349
|
+
ref: inputRef,
|
|
8350
|
+
id,
|
|
8351
|
+
className: "sg-input sg-mono",
|
|
8352
|
+
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)" },
|
|
8353
|
+
placeholder: `${family} recipient address`,
|
|
8354
|
+
"aria-label": `${family} recipient address`,
|
|
8355
|
+
"aria-invalid": invalid || void 0,
|
|
8356
|
+
"aria-describedby": `${id}-help${invalid ? ` ${id}-error` : ""}`,
|
|
8357
|
+
value: draft,
|
|
8358
|
+
onChange: (event) => setDraft(event.target.value),
|
|
8359
|
+
spellCheck: false
|
|
8360
|
+
}
|
|
8361
|
+
)
|
|
8362
|
+
] }),
|
|
8363
|
+
invalid ? /* @__PURE__ */ jsxRuntime.jsx("div", { id: `${id}-error`, children: /* @__PURE__ */ jsxRuntime.jsxs(StatusPanel, { tone: "error", children: [
|
|
8364
|
+
"Not a valid ",
|
|
8365
|
+
family,
|
|
8366
|
+
" address."
|
|
8367
|
+
] }) }) : null,
|
|
8368
|
+
/* @__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." }),
|
|
8369
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { disabled: !valid, onClick: () => state.selectAddress(draft.trim()), children: "Use this address" })
|
|
8370
|
+
] })
|
|
8371
|
+
] })
|
|
8372
|
+
] });
|
|
8373
|
+
}
|
|
6044
8374
|
var IDENTITY_KEY_PREFIX = "sg:link:v1:";
|
|
6045
8375
|
var LEGACY_IDENTITY_KEY = "zd-link-identity";
|
|
6046
8376
|
var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
@@ -6055,10 +8385,10 @@ function storage() {
|
|
|
6055
8385
|
return null;
|
|
6056
8386
|
}
|
|
6057
8387
|
}
|
|
6058
|
-
function parseIdentity(
|
|
6059
|
-
if (!
|
|
8388
|
+
function parseIdentity(raw2) {
|
|
8389
|
+
if (!raw2) return null;
|
|
6060
8390
|
try {
|
|
6061
|
-
const p = JSON.parse(
|
|
8391
|
+
const p = JSON.parse(raw2);
|
|
6062
8392
|
if (!p || typeof p !== "object") return null;
|
|
6063
8393
|
const walletAddress = typeof p.walletAddress === "string" ? p.walletAddress : "";
|
|
6064
8394
|
if (!ADDRESS_RE.test(walletAddress)) return null;
|
|
@@ -6398,14 +8728,17 @@ function PaymentIsland(props) {
|
|
|
6398
8728
|
const exQuotable = !rampMode && exAmountValid && !exOverLimit && Boolean(exFromChainId && exFromAsset && exToChainId && exToAsset);
|
|
6399
8729
|
const payFundingAssets = props.fundingAssets?.length ? props.fundingAssets : ["USDC", "USDT", "USDE"];
|
|
6400
8730
|
const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${payFundingAssets.join(",")}`;
|
|
6401
|
-
const
|
|
8731
|
+
const recipientState = useRecipient(isPay ? null : exToChainId ?? null, props.recipient);
|
|
8732
|
+
const recipient2 = recipientState.recipient;
|
|
8733
|
+
const needsRecipient = !isPay && (recipientState.missing || !!recipientState.error);
|
|
8734
|
+
const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${recipient2 ?? ""}`;
|
|
6402
8735
|
const flow = useFlow({
|
|
6403
8736
|
engine,
|
|
6404
8737
|
wallet,
|
|
6405
8738
|
kind: isPay ? "payment" : "swap",
|
|
6406
8739
|
// Bank settlement parks the card, so gate the network work off too — otherwise the island would
|
|
6407
8740
|
// quote (and fire onQuote) for a payment whose CTA it never shows.
|
|
6408
|
-
enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable,
|
|
8741
|
+
enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable && !needsRecipient,
|
|
6409
8742
|
paramsKey: isPay ? payParamsKey : exParamsKey,
|
|
6410
8743
|
loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
|
|
6411
8744
|
chainId,
|
|
@@ -6417,11 +8750,11 @@ function PaymentIsland(props) {
|
|
|
6417
8750
|
fromToken: exFromAsset,
|
|
6418
8751
|
toToken: exToAsset,
|
|
6419
8752
|
amountIn: normEx,
|
|
6420
|
-
recipient:
|
|
8753
|
+
recipient: recipient2
|
|
6421
8754
|
},
|
|
6422
8755
|
payer
|
|
6423
8756
|
),
|
|
6424
|
-
recipientFor: (account) => isPay ? props.recipient :
|
|
8757
|
+
recipientFor: (account) => isPay ? props.recipient : recipientState.recipientFor(account),
|
|
6425
8758
|
onQuote: config.onQuote,
|
|
6426
8759
|
onSuccess: config.onSuccess,
|
|
6427
8760
|
onError: config.onError
|
|
@@ -6513,27 +8846,27 @@ function PaymentIsland(props) {
|
|
|
6513
8846
|
}, [isPay, exProduct, catalogue, exSourceTokens, exchangeTokens, props.defaultFromAsset, props.defaultToAsset]);
|
|
6514
8847
|
const exDestinationStates = react.useMemo(() => {
|
|
6515
8848
|
if (!catalogue?.ready) return void 0;
|
|
6516
|
-
const
|
|
8849
|
+
const states2 = {};
|
|
6517
8850
|
for (const token of catalogue.tokens) {
|
|
6518
8851
|
const key = balanceKey(Number(token.chainId), token.address);
|
|
6519
8852
|
const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
|
|
6520
8853
|
if (measured) {
|
|
6521
|
-
|
|
8854
|
+
states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
6522
8855
|
continue;
|
|
6523
8856
|
}
|
|
6524
8857
|
const verdict = destinationAvailability(token, catalogue, exFromToken);
|
|
6525
8858
|
if (verdict === "available") {
|
|
6526
8859
|
const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
|
|
6527
|
-
if (limit)
|
|
8860
|
+
if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
|
|
6528
8861
|
continue;
|
|
6529
8862
|
}
|
|
6530
|
-
|
|
8863
|
+
states2[key] = {
|
|
6531
8864
|
disabled: true,
|
|
6532
8865
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
6533
8866
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
6534
8867
|
};
|
|
6535
8868
|
}
|
|
6536
|
-
return
|
|
8869
|
+
return states2;
|
|
6537
8870
|
}, [catalogue, exFromToken]);
|
|
6538
8871
|
const exFromBal = exFrom && exFromToken ? exBalances[balanceKey(exFrom.chainId, exFromToken.address)] : void 0;
|
|
6539
8872
|
const fundingTokens = react.useMemo(() => {
|
|
@@ -6680,6 +9013,9 @@ function PaymentIsland(props) {
|
|
|
6680
9013
|
const selectedVisible = Boolean(sel && visibleRoutes.some((r) => r.id === sel.id));
|
|
6681
9014
|
const selBal = sel ? holdings.balances[balanceKey(sel.source.chainId, sel.source.tokenAddress)] : void 0;
|
|
6682
9015
|
const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
|
|
9016
|
+
const evmDirect = flow.lastTxEntry?.settlement === "direct";
|
|
9017
|
+
const evmConfirmed = flow.verdict?.status === "confirmed";
|
|
9018
|
+
const evmDelivery = useDelivery(engine, (flow.status === "success" || flow.status === "pending") && !evmDirect ? flow.txHash : null);
|
|
6683
9019
|
const mismatch = flow.status === "error" && flow.verdict?.status === "mismatch";
|
|
6684
9020
|
const destTicker = isPay ? tickerOn(registryTokens, props.toChainId, props.toAsset ?? "") : exToToken ? tokenTicker(exToToken) : exToAsset ?? "";
|
|
6685
9021
|
const exFromTicker = exFromToken ? tokenTicker(exFromToken) : exFromAsset ?? "";
|
|
@@ -6737,14 +9073,18 @@ function PaymentIsland(props) {
|
|
|
6737
9073
|
linkMenu
|
|
6738
9074
|
] }) : void 0;
|
|
6739
9075
|
const activeStep = flow.steps.find((s) => s.state === "active");
|
|
6740
|
-
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" ?
|
|
9076
|
+
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" ? (
|
|
9077
|
+
// Announces what the receipt shows: delivery from the tracker, never settlement on the
|
|
9078
|
+
// source receipt alone (review 2026-10-28).
|
|
9079
|
+
`${isPay ? "Payment" : verb.past}: ${deliveryHeadline(evmDelivery, evmConfirmed, evmDirect)}.`
|
|
9080
|
+
) : "";
|
|
6741
9081
|
const loading = flow.status === "loading";
|
|
6742
|
-
const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel);
|
|
9082
|
+
const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel) && !needsRecipient;
|
|
6743
9083
|
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";
|
|
6744
9084
|
const exPct = (p) => {
|
|
6745
9085
|
if (!exFromBal || !exFromToken) return;
|
|
6746
|
-
const
|
|
6747
|
-
setExAmount(formatUnits(p === 100 ?
|
|
9086
|
+
const raw2 = BigInt(exFromBal.raw);
|
|
9087
|
+
setExAmount(formatUnits(p === 100 ? raw2 : raw2 * BigInt(p) / 100n, assetDecimals(exFromToken)));
|
|
6748
9088
|
};
|
|
6749
9089
|
const exGatewayAmountError = !isPay && exQuotable && flow.status === "error" && flow.steps.length === 0 ? flow.fieldError : null;
|
|
6750
9090
|
const exAmountError = exOverLimit && exLaneLimit ? laneLimitError(exLaneLimit, exLimitSymbol) : exGatewayAmountError;
|
|
@@ -6782,7 +9122,7 @@ function PaymentIsland(props) {
|
|
|
6782
9122
|
] });
|
|
6783
9123
|
let body;
|
|
6784
9124
|
if (hist && wallet.account) {
|
|
6785
|
-
body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
|
|
9125
|
+
body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
|
|
6786
9126
|
} else if (isPay && view === "select" && wallet.account) {
|
|
6787
9127
|
body = /* @__PURE__ */ jsxRuntime.jsx(
|
|
6788
9128
|
TokenSelect,
|
|
@@ -6821,6 +9161,8 @@ function PaymentIsland(props) {
|
|
|
6821
9161
|
}
|
|
6822
9162
|
}
|
|
6823
9163
|
);
|
|
9164
|
+
} else if (recipientState.open && !isPay) {
|
|
9165
|
+
body = /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: destTicker });
|
|
6824
9166
|
} else if (rampMode) {
|
|
6825
9167
|
body = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-soonpanel", children: [
|
|
6826
9168
|
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-soonpanel-title", children: mode === "onramp" ? "Buying with fiat is coming soon" : "Cashing out to fiat is coming soon" }),
|
|
@@ -6858,7 +9200,7 @@ function PaymentIsland(props) {
|
|
|
6858
9200
|
] })
|
|
6859
9201
|
] });
|
|
6860
9202
|
} else if (paid || settling) {
|
|
6861
|
-
const confirmed =
|
|
9203
|
+
const confirmed = isDelivered(evmDelivery, evmConfirmed, evmDirect);
|
|
6862
9204
|
body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
6863
9205
|
/* @__PURE__ */ jsxRuntime.jsx(IdentityLine, { account: wallet.account, email: identity?.email }),
|
|
6864
9206
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt", children: [
|
|
@@ -6870,9 +9212,10 @@ function PaymentIsland(props) {
|
|
|
6870
9212
|
destTicker
|
|
6871
9213
|
] }),
|
|
6872
9214
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
|
|
6873
|
-
|
|
6874
|
-
|
|
6875
|
-
] })
|
|
9215
|
+
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
9216
|
+
(flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : ""
|
|
9217
|
+
] }),
|
|
9218
|
+
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
6876
9219
|
] }),
|
|
6877
9220
|
!identityMatchesWallet ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-remember", children: [
|
|
6878
9221
|
/* @__PURE__ */ jsxRuntime.jsxs("label", { className: "sg-remember-top", children: [
|
|
@@ -6987,16 +9330,23 @@ function PaymentIsland(props) {
|
|
|
6987
9330
|
quoteError ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: flow.error || "Couldn't get a price right now." }) : null,
|
|
6988
9331
|
walletError ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: flow.error || "The wallet could not complete this payment." }) : null,
|
|
6989
9332
|
submitting || walletError ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { variant: "rich", steps: flow.steps, verdict: flow.verdict }) : null,
|
|
6990
|
-
/* @__PURE__ */ jsxRuntime.
|
|
6991
|
-
Button,
|
|
6992
|
-
|
|
6993
|
-
|
|
6994
|
-
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
9333
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
9334
|
+
recipientState.missing && !isPay && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
|
|
9335
|
+
"Connect ",
|
|
9336
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
9337
|
+
" wallet"
|
|
9338
|
+
] }) : 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(
|
|
9339
|
+
Button,
|
|
9340
|
+
{
|
|
9341
|
+
onClick: payReady && !submitting && !flow.insufficient && !flow.nativeShortfall && !loading ? flow.submit : void 0,
|
|
9342
|
+
busy: submitting || loading,
|
|
9343
|
+
softDisabled: submitting,
|
|
9344
|
+
disabled: !submitting && (!payReady || flow.insufficient || !!flow.nativeShortfall || loading),
|
|
9345
|
+
children: ctaLabel
|
|
9346
|
+
}
|
|
9347
|
+
),
|
|
9348
|
+
!isPay ? /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null
|
|
9349
|
+
] })
|
|
7000
9350
|
] })
|
|
7001
9351
|
] });
|
|
7002
9352
|
}
|
|
@@ -7290,6 +9640,9 @@ function PayCard(props) {
|
|
|
7290
9640
|
};
|
|
7291
9641
|
react.useEffect(() => setHist(null), [wallet.account]);
|
|
7292
9642
|
const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
|
|
9643
|
+
const evmDirect = flow.lastTxEntry?.settlement === "direct";
|
|
9644
|
+
const evmConfirmed = flow.verdict?.status === "confirmed";
|
|
9645
|
+
const evmDelivery = useDelivery(engine, (flow.status === "success" || flow.status === "pending") && !evmDirect ? flow.txHash : null);
|
|
7293
9646
|
const pickFunding = (pick) => {
|
|
7294
9647
|
setPickError(null);
|
|
7295
9648
|
const r = visibleRoutes.find((x) => x.source.chainId === pick.chainId && symbolKey(x.source.asset) === symbolKey(pick.symbol));
|
|
@@ -7349,7 +9702,7 @@ function PayCard(props) {
|
|
|
7349
9702
|
...durationLabel(sel.quote.estimatedDuration) ? [{ label: "Estimated time", value: durationLabel(sel.quote.estimatedDuration) }] : []
|
|
7350
9703
|
] : [];
|
|
7351
9704
|
const loadingPlan = flow.status === "loading" || holdings.loading && !sel || pricing !== null;
|
|
7352
|
-
return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Complete payment", theme: config.theme, heightPx: props.heightPx, walletSlot, onClose: props.onClose, children: hist && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) : view === "select" && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(
|
|
9705
|
+
return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Complete payment", theme: config.theme, heightPx: props.heightPx, walletSlot, onClose: props.onClose, children: hist && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) : view === "select" && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(
|
|
7353
9706
|
TokenSelect,
|
|
7354
9707
|
{
|
|
7355
9708
|
title: "Pay with",
|
|
@@ -7371,17 +9724,18 @@ function PayCard(props) {
|
|
|
7371
9724
|
] })
|
|
7372
9725
|
] }) : flow.status === "success" || flow.status === "pending" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
7373
9726
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
7374
|
-
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending":
|
|
9727
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending": !isDelivered(evmDelivery, evmConfirmed, evmDirect), children: /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph3, {}) }),
|
|
7375
9728
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-amt sg-mono", children: [
|
|
7376
9729
|
props.amount,
|
|
7377
9730
|
" ",
|
|
7378
9731
|
tickerOn(registryTokens, props.toChainId, props.toAsset)
|
|
7379
9732
|
] }),
|
|
7380
|
-
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
|
|
7381
|
-
|
|
9733
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
9734
|
+
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
7382
9735
|
" \xB7 ",
|
|
7383
9736
|
shortAddress2(props.recipient)
|
|
7384
|
-
] })
|
|
9737
|
+
] }),
|
|
9738
|
+
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
7385
9739
|
] }),
|
|
7386
9740
|
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
|
|
7387
9741
|
] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
@@ -7458,6 +9812,9 @@ function StableGenieSwap(props) {
|
|
|
7458
9812
|
const [toChainId, setToChainId] = react.useState(props.defaultToChainId ?? 8453);
|
|
7459
9813
|
const [toAsset, setToAsset] = react.useState(props.defaultToAsset ?? "USDC");
|
|
7460
9814
|
const [amount, setAmount] = react.useState(props.defaultAmount ?? "");
|
|
9815
|
+
const recipientState = useRecipient(toChainId, props.recipient);
|
|
9816
|
+
const recipient2 = recipientState.recipient;
|
|
9817
|
+
const needsRecipient = recipientState.missing || !!recipientState.error;
|
|
7461
9818
|
const [catalogue, setCatalogue] = react.useState(null);
|
|
7462
9819
|
react.useEffect(() => {
|
|
7463
9820
|
if (props.variant === "pill") return;
|
|
@@ -7487,15 +9844,15 @@ function StableGenieSwap(props) {
|
|
|
7487
9844
|
}, [catalogue]);
|
|
7488
9845
|
const amountValid = /^\d+(\.\d+)?$/.test(amount.replace(",", ".")) && Number(amount.replace(",", ".")) > 0;
|
|
7489
9846
|
const enabled = amountValid && props.variant !== "pill";
|
|
7490
|
-
const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${
|
|
9847
|
+
const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${recipient2 ?? ""}`;
|
|
7491
9848
|
const flow = useFlow({
|
|
7492
9849
|
engine,
|
|
7493
9850
|
wallet,
|
|
7494
9851
|
kind: "swap",
|
|
7495
|
-
enabled,
|
|
9852
|
+
enabled: enabled && !needsRecipient,
|
|
7496
9853
|
paramsKey,
|
|
7497
|
-
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient:
|
|
7498
|
-
recipientFor:
|
|
9854
|
+
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient: recipient2 }, payer),
|
|
9855
|
+
recipientFor: recipientState.recipientFor,
|
|
7499
9856
|
onQuote: config.onQuote,
|
|
7500
9857
|
onSuccess: config.onSuccess,
|
|
7501
9858
|
onError: config.onError
|
|
@@ -7530,27 +9887,32 @@ function StableGenieSwap(props) {
|
|
|
7530
9887
|
};
|
|
7531
9888
|
}, [engine, props.variant, hist]);
|
|
7532
9889
|
const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
|
|
9890
|
+
const evmDirect = flow.lastTxEntry?.settlement === "direct";
|
|
9891
|
+
const evmConfirmed = flow.verdict?.status === "confirmed";
|
|
9892
|
+
const evmDelivery = useDelivery(engine, (flow.status === "success" || flow.status === "pending") && !evmDirect ? flow.txHash : null);
|
|
7533
9893
|
if (props.variant === "pill") return /* @__PURE__ */ jsxRuntime.jsx(PaymentIsland, { kind: "swap", ...props });
|
|
7534
9894
|
const walletSlot = wallet.account ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-head-tools", children: [
|
|
7535
9895
|
/* @__PURE__ */ jsxRuntime.jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }),
|
|
7536
9896
|
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-brand", children: "ZeroDelta" })
|
|
7537
9897
|
] }) : void 0;
|
|
7538
9898
|
if (hist && wallet.account) {
|
|
7539
|
-
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 }) });
|
|
9899
|
+
return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) });
|
|
7540
9900
|
}
|
|
9901
|
+
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 }) });
|
|
7541
9902
|
if (flow.status === "success" || flow.status === "pending") {
|
|
7542
9903
|
return /* @__PURE__ */ jsxRuntime.jsxs(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: [
|
|
7543
9904
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
7544
|
-
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending":
|
|
9905
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending": !isDelivered(evmDelivery, evmConfirmed, evmDirect), children: /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph4, {}) }),
|
|
7545
9906
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-amt sg-mono", children: [
|
|
7546
9907
|
receive,
|
|
7547
9908
|
" ",
|
|
7548
9909
|
tickerOn(registryTokens, toChainId, toAsset)
|
|
7549
9910
|
] }),
|
|
7550
|
-
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
|
|
7551
|
-
|
|
7552
|
-
props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
7553
|
-
] })
|
|
9911
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
9912
|
+
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
9913
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
9914
|
+
] }),
|
|
9915
|
+
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
7554
9916
|
] }),
|
|
7555
9917
|
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
|
|
7556
9918
|
] });
|
|
@@ -7578,11 +9940,169 @@ function StableGenieSwap(props) {
|
|
|
7578
9940
|
flow.selected && flow.status !== "loading" ? /* @__PURE__ */ jsxRuntime.jsx(CompliancePanel, { compliance: flow.selected.quote.compliance, direct: flow.selected.state === "DIRECT" }) : null,
|
|
7579
9941
|
submitting ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { steps: flow.steps }) : null,
|
|
7580
9942
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
7581
|
-
!wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : /* @__PURE__ */ jsxRuntime.
|
|
9943
|
+
!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: [
|
|
9944
|
+
"Connect ",
|
|
9945
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
9946
|
+
" wallet"
|
|
9947
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.submit, busy: submitting, disabled: needsRecipient || !flow.selected || flow.insufficient || !!flow.nativeShortfall || !enabled || flow.status === "loading", children: swapLabel }),
|
|
9948
|
+
/* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }),
|
|
7582
9949
|
wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
|
|
7583
9950
|
] })
|
|
7584
9951
|
] });
|
|
7585
9952
|
}
|
|
9953
|
+
function keyOf(a) {
|
|
9954
|
+
return `${a.fromSymbol}|${a.toChainId}|${a.toSymbol}|${a.amount}|${a.owner ?? ""}|${a.payer ?? ""}|${a.recipient ?? ""}`;
|
|
9955
|
+
}
|
|
9956
|
+
function useSolanaSourceFlow(args) {
|
|
9957
|
+
const { engine, enabled, fromSymbol, fromMint, toChainId, toSymbol, amount, owner, payer, recipient: recipient2 } = args;
|
|
9958
|
+
const [status, setStatus] = react.useState("idle");
|
|
9959
|
+
const [preview, setPreview] = react.useState(null);
|
|
9960
|
+
const [plan, setPlan] = react.useState(null);
|
|
9961
|
+
const [error, setError] = react.useState(null);
|
|
9962
|
+
const [balanceRaw, setBalanceRaw] = react.useState(void 0);
|
|
9963
|
+
const [cost, setCost] = react.useState(null);
|
|
9964
|
+
const [progress, setProgress] = react.useState(null);
|
|
9965
|
+
const [signature, setSignature] = react.useState(null);
|
|
9966
|
+
const [lastTxEntry, setLastTxEntry] = react.useState(null);
|
|
9967
|
+
const [sent, setSent] = react.useState(null);
|
|
9968
|
+
const [nonce, setNonce] = react.useState(0);
|
|
9969
|
+
const req = react.useRef(0);
|
|
9970
|
+
const busy = react.useRef(false);
|
|
9971
|
+
const latest = react.useRef(args);
|
|
9972
|
+
latest.current = args;
|
|
9973
|
+
const planKey = react.useRef(null);
|
|
9974
|
+
const planArgs = react.useRef(null);
|
|
9975
|
+
const changedWhileBusy = react.useRef(false);
|
|
9976
|
+
const addressed = Boolean(owner && payer && recipient2);
|
|
9977
|
+
const key = keyOf(args);
|
|
9978
|
+
react.useEffect(() => {
|
|
9979
|
+
const id = ++req.current;
|
|
9980
|
+
if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
|
|
9981
|
+
setStatus("idle");
|
|
9982
|
+
setPreview(null);
|
|
9983
|
+
setPlan(null);
|
|
9984
|
+
setError(null);
|
|
9985
|
+
setCost(null);
|
|
9986
|
+
return;
|
|
9987
|
+
}
|
|
9988
|
+
if (busy.current) {
|
|
9989
|
+
changedWhileBusy.current = true;
|
|
9990
|
+
return;
|
|
9991
|
+
}
|
|
9992
|
+
setStatus("quoting");
|
|
9993
|
+
planKey.current = null;
|
|
9994
|
+
planArgs.current = null;
|
|
9995
|
+
setError(null);
|
|
9996
|
+
setPlan(null);
|
|
9997
|
+
setCost(null);
|
|
9998
|
+
const timer2 = setTimeout(async () => {
|
|
9999
|
+
try {
|
|
10000
|
+
if (!addressed) {
|
|
10001
|
+
const next = await engine.previewSolanaSource({ toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount });
|
|
10002
|
+
if (id !== req.current) return;
|
|
10003
|
+
setPreview(next);
|
|
10004
|
+
setStatus("ready");
|
|
10005
|
+
return;
|
|
10006
|
+
}
|
|
10007
|
+
const input = { toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount, owner, sender: payer, recipient: recipient2 };
|
|
10008
|
+
const quoted = await engine.quoteSolanaSource(input);
|
|
10009
|
+
const built = await engine.buildSolanaSourcePlan(input, quoted);
|
|
10010
|
+
if (id !== req.current) return;
|
|
10011
|
+
planKey.current = key;
|
|
10012
|
+
planArgs.current = { ...latest.current };
|
|
10013
|
+
setPreview(quoted);
|
|
10014
|
+
setPlan(built);
|
|
10015
|
+
setStatus("ready");
|
|
10016
|
+
engine.simulateSolanaCost(built).then(
|
|
10017
|
+
(c) => id === req.current && setCost(c),
|
|
10018
|
+
() => id === req.current && setCost(null)
|
|
10019
|
+
);
|
|
10020
|
+
} catch (e) {
|
|
10021
|
+
if (id !== req.current) return;
|
|
10022
|
+
setStatus("error");
|
|
10023
|
+
setError(e instanceof Error ? e.message : String(e));
|
|
10024
|
+
}
|
|
10025
|
+
}, 350);
|
|
10026
|
+
return () => clearTimeout(timer2);
|
|
10027
|
+
}, [engine, enabled, key, addressed, nonce]);
|
|
10028
|
+
react.useEffect(() => {
|
|
10029
|
+
let alive = true;
|
|
10030
|
+
setBalanceRaw(void 0);
|
|
10031
|
+
if (!enabled || !payer || !fromMint) return;
|
|
10032
|
+
engine.readSolanaBalance(payer, fromMint).then((b) => {
|
|
10033
|
+
if (alive) setBalanceRaw(b);
|
|
10034
|
+
});
|
|
10035
|
+
return () => {
|
|
10036
|
+
alive = false;
|
|
10037
|
+
};
|
|
10038
|
+
}, [engine, enabled, payer, fromMint]);
|
|
10039
|
+
const needsPreparation = plan ? solanaPlanNeedsPreparation(plan) : false;
|
|
10040
|
+
const run = react.useCallback(async () => {
|
|
10041
|
+
const current = plan;
|
|
10042
|
+
if (!current || busy.current) return;
|
|
10043
|
+
if (planKey.current !== keyOf(latest.current)) {
|
|
10044
|
+
setError("The order changed; review the new quote before signing.");
|
|
10045
|
+
setNonce((n) => n + 1);
|
|
10046
|
+
return;
|
|
10047
|
+
}
|
|
10048
|
+
busy.current = true;
|
|
10049
|
+
let broadcast = false;
|
|
10050
|
+
setError(null);
|
|
10051
|
+
setStatus(needsPreparation ? "preparing" : "submitting");
|
|
10052
|
+
try {
|
|
10053
|
+
const result = await engine.executeSolanaPlanStaged({ plan: current, signer: latest.current.signer(), onProgress: setProgress });
|
|
10054
|
+
if (result.status === "prepared") {
|
|
10055
|
+
setStatus("prepared");
|
|
10056
|
+
return;
|
|
10057
|
+
}
|
|
10058
|
+
const a = planArgs.current ?? latest.current;
|
|
10059
|
+
broadcast = true;
|
|
10060
|
+
setSent({ receive: current.preview.receive, toTicker: a.toTicker, recipient: a.recipient ?? "" });
|
|
10061
|
+
setSignature(result.signature);
|
|
10062
|
+
setStatus("sent");
|
|
10063
|
+
const entry = engine.recordTransaction({
|
|
10064
|
+
kind: "swap",
|
|
10065
|
+
hash: result.signature,
|
|
10066
|
+
txKind: "submitOrder",
|
|
10067
|
+
chainId: SOLANA_CHAIN_ID,
|
|
10068
|
+
chainName: a.chainName,
|
|
10069
|
+
fromAsset: a.fromSymbol ?? "",
|
|
10070
|
+
toAsset: a.toSymbol ?? "",
|
|
10071
|
+
fromTicker: a.fromTicker,
|
|
10072
|
+
toTicker: a.toTicker,
|
|
10073
|
+
payAmount: a.amount,
|
|
10074
|
+
receiveAmount: current.preview.receive,
|
|
10075
|
+
account: a.owner ?? "",
|
|
10076
|
+
recipient: a.recipient ?? "",
|
|
10077
|
+
settlement: "escrow",
|
|
10078
|
+
status: "submitted"
|
|
10079
|
+
});
|
|
10080
|
+
setLastTxEntry(entry.hash ? entry : null);
|
|
10081
|
+
appendTxHistory(a.owner, entry);
|
|
10082
|
+
} catch (e) {
|
|
10083
|
+
const err2 = e instanceof Error ? e : new Error(String(e));
|
|
10084
|
+
setStatus("failed");
|
|
10085
|
+
setError(err2.message);
|
|
10086
|
+
latest.current.onError?.(err2);
|
|
10087
|
+
} finally {
|
|
10088
|
+
busy.current = false;
|
|
10089
|
+
if (changedWhileBusy.current) {
|
|
10090
|
+
changedWhileBusy.current = false;
|
|
10091
|
+
if (!broadcast && planKey.current !== keyOf(latest.current)) setNonce((n) => n + 1);
|
|
10092
|
+
}
|
|
10093
|
+
}
|
|
10094
|
+
}, [engine, plan, needsPreparation]);
|
|
10095
|
+
const insufficient = balanceRaw !== void 0 && plan ? balanceRaw < BigInt(plan.expected.bidTokenAmount) : false;
|
|
10096
|
+
const solShort = cost ? !cost.sufficient : false;
|
|
10097
|
+
const reset = react.useCallback(() => {
|
|
10098
|
+
setSignature(null);
|
|
10099
|
+
setLastTxEntry(null);
|
|
10100
|
+
setSent(null);
|
|
10101
|
+
setProgress(null);
|
|
10102
|
+
setNonce((n) => n + 1);
|
|
10103
|
+
}, []);
|
|
10104
|
+
return { status, preview, plan, error, balanceRaw, cost, progress, signature, lastTxEntry, sent, addressed, needsPreparation, insufficient, solShort, run, reset };
|
|
10105
|
+
}
|
|
7586
10106
|
function QuoteSheet(props) {
|
|
7587
10107
|
const sheetRef = react.useRef(null);
|
|
7588
10108
|
const onCloseRef = react.useRef(props.onClose);
|
|
@@ -7691,7 +10211,7 @@ function ExchangeCard(props) {
|
|
|
7691
10211
|
react.useEffect(() => {
|
|
7692
10212
|
if (isPill) return;
|
|
7693
10213
|
let alive = true;
|
|
7694
|
-
engine.fetchCatalogue(allowed, product).then((next) => {
|
|
10214
|
+
engine.fetchCatalogue(allowed, product, { solanaSources: true }).then((next) => {
|
|
7695
10215
|
if (alive) setCatalogue(next);
|
|
7696
10216
|
});
|
|
7697
10217
|
return () => {
|
|
@@ -7724,6 +10244,16 @@ function ExchangeCard(props) {
|
|
|
7724
10244
|
() => props.defaultToChainId && props.defaultToAsset ? { chainId: props.defaultToChainId, symbol: symbolKey(props.defaultToAsset) } : null
|
|
7725
10245
|
);
|
|
7726
10246
|
const [amount, setAmount] = react.useState(props.defaultAmount ?? "");
|
|
10247
|
+
const solanaWallet = useSolanaWallet();
|
|
10248
|
+
const [payerChooser, setPayerChooser] = react.useState(false);
|
|
10249
|
+
const sourceIsSolana = isSolanaChainId(from?.chainId);
|
|
10250
|
+
const recipientState = useRecipient(to?.chainId ?? null, props.recipient, {
|
|
10251
|
+
solanaWallet,
|
|
10252
|
+
sourceIsSolana,
|
|
10253
|
+
evm: { account: wallet.account, connect: wallet.connect, connecting: wallet.connecting }
|
|
10254
|
+
});
|
|
10255
|
+
const recipient2 = recipientState.recipient;
|
|
10256
|
+
const needsRecipient = recipientState.missing || !!recipientState.error;
|
|
7727
10257
|
const onInputChange = react.useRef(props.onInputChange);
|
|
7728
10258
|
onInputChange.current = props.onInputChange;
|
|
7729
10259
|
const fromChainId = from?.chainId ?? null;
|
|
@@ -7754,27 +10284,27 @@ function ExchangeCard(props) {
|
|
|
7754
10284
|
}, [product, catalogue, sourceTokens, tokens, props.defaultFromAsset, props.defaultToAsset]);
|
|
7755
10285
|
const destinationStates = react.useMemo(() => {
|
|
7756
10286
|
if (!catalogue?.ready) return void 0;
|
|
7757
|
-
const
|
|
10287
|
+
const states2 = {};
|
|
7758
10288
|
for (const token of catalogue.tokens) {
|
|
7759
10289
|
const key = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
|
|
7760
10290
|
const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
|
|
7761
10291
|
if (measured) {
|
|
7762
|
-
|
|
10292
|
+
states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
7763
10293
|
continue;
|
|
7764
10294
|
}
|
|
7765
10295
|
const verdict = destinationAvailability(token, catalogue, fromToken);
|
|
7766
10296
|
if (verdict === "available") {
|
|
7767
10297
|
const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
|
|
7768
|
-
if (limit)
|
|
10298
|
+
if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
|
|
7769
10299
|
continue;
|
|
7770
10300
|
}
|
|
7771
|
-
|
|
10301
|
+
states2[key] = {
|
|
7772
10302
|
disabled: true,
|
|
7773
10303
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
7774
10304
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
7775
10305
|
};
|
|
7776
10306
|
}
|
|
7777
|
-
return
|
|
10307
|
+
return states2;
|
|
7778
10308
|
}, [catalogue, fromToken]);
|
|
7779
10309
|
const toPickerVisible = react.useMemo(
|
|
7780
10310
|
() => destinationStates ? toPickerTokens.filter((t) => !destinationStates[`${Number(t.chainId)}:${String(t.address || "").toLowerCase()}`]?.disabled) : toPickerTokens,
|
|
@@ -7819,7 +10349,7 @@ function ExchangeCard(props) {
|
|
|
7819
10349
|
if (id === balReq.current) setBalances(res);
|
|
7820
10350
|
});
|
|
7821
10351
|
}, [engine, wallet.account, tokens]);
|
|
7822
|
-
const
|
|
10352
|
+
const evmFromBal = from && fromToken ? balances[balanceKey(from.chainId, fromToken.address)] : void 0;
|
|
7823
10353
|
const [prices, setPrices] = react.useState({});
|
|
7824
10354
|
react.useEffect(() => {
|
|
7825
10355
|
if (isPill) return;
|
|
@@ -7833,24 +10363,47 @@ function ExchangeCard(props) {
|
|
|
7833
10363
|
alive = false;
|
|
7834
10364
|
};
|
|
7835
10365
|
}, [engine, from?.symbol, to?.symbol, isPill]);
|
|
7836
|
-
const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${
|
|
10366
|
+
const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${recipient2 ?? ""}`;
|
|
7837
10367
|
const flow = useFlow({
|
|
7838
10368
|
engine,
|
|
7839
10369
|
wallet,
|
|
7840
10370
|
kind: "swap",
|
|
7841
|
-
enabled: quotable && !isPill,
|
|
10371
|
+
enabled: quotable && !isPill && !needsRecipient && !sourceIsSolana,
|
|
7842
10372
|
paramsKey,
|
|
7843
|
-
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient:
|
|
7844
|
-
recipientFor:
|
|
10373
|
+
loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: recipient2 }, payer),
|
|
10374
|
+
recipientFor: recipientState.recipientFor,
|
|
7845
10375
|
onQuote: config.onQuote,
|
|
7846
10376
|
onSuccess: config.onSuccess,
|
|
7847
10377
|
onError: config.onError
|
|
7848
10378
|
});
|
|
10379
|
+
const solActive = sourceIsSolana && !isPill && !rampMode;
|
|
10380
|
+
const solFlow = useSolanaSourceFlow({
|
|
10381
|
+
engine,
|
|
10382
|
+
enabled: solActive && quotable && !recipientState.error,
|
|
10383
|
+
fromSymbol: from?.symbol ?? null,
|
|
10384
|
+
fromMint: fromToken?.address ?? null,
|
|
10385
|
+
toChainId: to?.chainId ?? null,
|
|
10386
|
+
toSymbol: to ? toSymbol : null,
|
|
10387
|
+
amount: normalizedAmount,
|
|
10388
|
+
owner: wallet.account,
|
|
10389
|
+
payer: solanaWallet.address,
|
|
10390
|
+
recipient: recipient2,
|
|
10391
|
+
signer: () => {
|
|
10392
|
+
const info = solanaWallet.wallets.find((w) => normalizeSolanaWalletName(w.name) === normalizeSolanaWalletName(solanaWallet.walletName ?? ""));
|
|
10393
|
+
if (!info) throw new Error("Connect a Solana wallet to pay from Solana.");
|
|
10394
|
+
return solanaWalletSigner(info);
|
|
10395
|
+
},
|
|
10396
|
+
chainName: "Solana",
|
|
10397
|
+
fromTicker,
|
|
10398
|
+
toTicker,
|
|
10399
|
+
onError: config.onError
|
|
10400
|
+
});
|
|
10401
|
+
const fromBal = solActive ? solFlow.balanceRaw !== void 0 && fromToken ? { ...evmFromBal, raw: solFlow.balanceRaw.toString(), formatted: formatUnits(solFlow.balanceRaw, assetDecimals(fromToken)) } : void 0 : evmFromBal;
|
|
7849
10402
|
const [preview, setPreview] = react.useState({ status: "idle" });
|
|
7850
10403
|
const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
|
|
7851
10404
|
const prevReq = react.useRef(0);
|
|
7852
10405
|
react.useEffect(() => {
|
|
7853
|
-
if (isPill || wallet.account || !quotable) {
|
|
10406
|
+
if (isPill || sourceIsSolana || wallet.account && !needsRecipient || !quotable) {
|
|
7854
10407
|
prevReq.current += 1;
|
|
7855
10408
|
setPreview({ status: "idle" });
|
|
7856
10409
|
return;
|
|
@@ -7858,23 +10411,28 @@ function ExchangeCard(props) {
|
|
|
7858
10411
|
const id = ++prevReq.current;
|
|
7859
10412
|
setPreview({ status: "loading" });
|
|
7860
10413
|
const timer2 = setTimeout(() => {
|
|
7861
|
-
engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient:
|
|
10414
|
+
engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: recipient2 }, wallet.account ?? void 0).then((data) => {
|
|
7862
10415
|
if (id === prevReq.current) setPreview({ status: "ready", data });
|
|
7863
10416
|
}).catch((e) => {
|
|
7864
10417
|
if (id === prevReq.current) setPreview({ status: "error", error: e instanceof Error ? e.message : String(e), fieldError: amountFieldError(e) });
|
|
7865
10418
|
});
|
|
7866
10419
|
}, 350);
|
|
7867
10420
|
return () => clearTimeout(timer2);
|
|
7868
|
-
}, [engine, wallet.account, quotable, paramsKey, returnedAt2]);
|
|
7869
|
-
const
|
|
7870
|
-
const
|
|
10421
|
+
}, [engine, wallet.account, quotable, paramsKey, returnedAt2, needsRecipient, sourceIsSolana]);
|
|
10422
|
+
const connected2 = Boolean(wallet.account);
|
|
10423
|
+
const addressed = connected2 && !needsRecipient;
|
|
10424
|
+
const submitting = solActive ? solFlow.status === "preparing" || solFlow.status === "submitting" : flow.status === "submitting";
|
|
7871
10425
|
const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
|
|
7872
|
-
const
|
|
7873
|
-
const
|
|
7874
|
-
const
|
|
10426
|
+
const evmDirect = flow.lastTxEntry?.settlement === "direct";
|
|
10427
|
+
const evmConfirmed = flow.verdict?.status === "confirmed";
|
|
10428
|
+
const evmDelivery = useDelivery(engine, (flow.status === "success" || flow.status === "pending") && !evmDirect ? flow.txHash : null);
|
|
10429
|
+
const solDelivery = useDelivery(engine, solActive && solFlow.status === "sent" ? solFlow.signature : null);
|
|
10430
|
+
const quoting = solActive ? solFlow.status === "quoting" : addressed ? flow.status === "loading" : preview.status === "loading";
|
|
10431
|
+
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;
|
|
10432
|
+
const gatewayAmountError = !quoteError || solActive ? null : addressed ? flow.fieldError : preview.fieldError ?? null;
|
|
7875
10433
|
const amountError = overLimit && laneLimit ? laneLimitError(laneLimit, limitSymbol) : gatewayAmountError;
|
|
7876
10434
|
const amountNote = mode === "exchange" ? amountError || (laneLimit ? laneLimitHint(laneLimit, limitSymbol) : null) : null;
|
|
7877
|
-
const receive =
|
|
10435
|
+
const receive = solActive ? solFlow.preview?.receive : addressed ? flow.selected?.receive.amount : preview.data?.receive;
|
|
7878
10436
|
const receiveOutRef = react.useRef(null);
|
|
7879
10437
|
const receiveSideRef = react.useRef(null);
|
|
7880
10438
|
const receiveShown = `${receive ?? ""}|${quoting}|${toTicker}`;
|
|
@@ -7887,17 +10445,17 @@ function ExchangeCard(props) {
|
|
|
7887
10445
|
return void 0;
|
|
7888
10446
|
}
|
|
7889
10447
|
}, [toToken]);
|
|
7890
|
-
const meta =
|
|
10448
|
+
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;
|
|
7891
10449
|
const pct = (p) => {
|
|
7892
10450
|
if (!fromBal || !fromToken) return;
|
|
7893
|
-
const
|
|
7894
|
-
setAmount(formatUnits(p === 100 ?
|
|
10451
|
+
const raw2 = BigInt(fromBal.raw);
|
|
10452
|
+
setAmount(formatUnits(p === 100 ? raw2 : raw2 * BigInt(p) / 100n, assetDecimals(fromToken)));
|
|
7895
10453
|
};
|
|
7896
10454
|
const title = config.title || (mode === "onramp" ? "Buy stablecoins" : mode === "offramp" ? "Cash out" : "Exchange");
|
|
7897
10455
|
const soonLabel = mode === "onramp" ? "On-ramp coming soon" : "Off-ramp coming soon";
|
|
7898
|
-
const quotePaused =
|
|
7899
|
-
const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" :
|
|
7900
|
-
const selected =
|
|
10456
|
+
const quotePaused = solActive ? false : addressed ? flow.quotePaused : idle2 && preview.status === "ready";
|
|
10457
|
+
const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected2 && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
|
|
10458
|
+
const selected = addressed ? flow.selected : null;
|
|
7901
10459
|
const hasQuote = Boolean(quotable && !quoting && !quoteError && receive);
|
|
7902
10460
|
const nativeWei = (() => {
|
|
7903
10461
|
try {
|
|
@@ -7907,14 +10465,14 @@ function ExchangeCard(props) {
|
|
|
7907
10465
|
return 0n;
|
|
7908
10466
|
}
|
|
7909
10467
|
})();
|
|
7910
|
-
const networkFee = nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
|
|
10468
|
+
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";
|
|
7911
10469
|
const eta = durationLabel(meta?.duration);
|
|
7912
10470
|
const rate = hasQuote && receive && Number(normalizedAmount) > 0 ? (Number(receive) / Number(normalizedAmount)).toFixed(6) : null;
|
|
7913
10471
|
const rateRows = hasQuote ? [{ label: "Network fee", value: networkFee }, ...eta ? [{ label: "Estimated time", value: eta }] : []] : [];
|
|
7914
10472
|
const via = selected ? selected.legs.length > 1 ? selected.legs[0]?.toTicker || selected.legs[0]?.toAsset || "" : null : preview.data?.via ?? null;
|
|
7915
10473
|
const routeShape = via === null ? "Direct" : via ? `Via ${via}` : "Two steps";
|
|
7916
|
-
const compliance = selected?.quote.compliance;
|
|
7917
|
-
const complianceHasQuote = Boolean(selected && flow.status !== "loading");
|
|
10474
|
+
const compliance = solActive ? solanaQuoteCompliance(solFlow.plan?.preview.quote) : selected?.quote.compliance;
|
|
10475
|
+
const complianceHasQuote = solActive ? Boolean(solFlow.plan && solFlow.status !== "quoting") : Boolean(selected && flow.status !== "loading");
|
|
7918
10476
|
const fromUsd = usdOf2(normalizedAmount, prices[from?.symbol ?? ""]);
|
|
7919
10477
|
const toUsd = usdOf2(receive, prices[to?.symbol ?? ""]);
|
|
7920
10478
|
const flippable = !rampMode && !submitting && Boolean(to && sourceTokens.some((t) => Number(t.chainId) === to.chainId && symbolKey(t.symbol) === to.symbol));
|
|
@@ -7924,8 +10482,8 @@ function ExchangeCard(props) {
|
|
|
7924
10482
|
setTo(from);
|
|
7925
10483
|
};
|
|
7926
10484
|
const walletSlot = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-head-tools", children: [
|
|
7927
|
-
|
|
7928
|
-
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-wallet", "data-connected":
|
|
10485
|
+
connected2 ? /* @__PURE__ */ jsxRuntime.jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }) : null,
|
|
10486
|
+
/* @__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: [
|
|
7929
10487
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
|
|
7930
10488
|
" ",
|
|
7931
10489
|
shortAddress2(wallet.account)
|
|
@@ -7973,7 +10531,7 @@ function ExchangeCard(props) {
|
|
|
7973
10531
|
}
|
|
7974
10532
|
);
|
|
7975
10533
|
const rateBox = (open) => /* @__PURE__ */ jsxRuntime.jsx(RateBox, { rate, fromSymbol: from?.symbol ?? "", fromLogoUrl: fromToken?.logoUrl, toTicker, rows: rateRows, defaultOpen: open, paused: quotePaused });
|
|
7976
|
-
const sheetBody = sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
|
|
10534
|
+
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(
|
|
7977
10535
|
QuoteSheet,
|
|
7978
10536
|
{
|
|
7979
10537
|
onClose: closeSheet,
|
|
@@ -7990,9 +10548,41 @@ function ExchangeCard(props) {
|
|
|
7990
10548
|
legs: selected && selected.legs.length > 1 ? selected.legs : void 0
|
|
7991
10549
|
}
|
|
7992
10550
|
) : null;
|
|
10551
|
+
const connectPayer = async () => {
|
|
10552
|
+
const result = await solanaWallet.connect();
|
|
10553
|
+
setPayerChooser(Array.isArray(result) && result.length > 1);
|
|
10554
|
+
};
|
|
10555
|
+
const solanaCta = !solanaWallet.address ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
10556
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: () => void connectPayer(), busy: solanaWallet.status === "connecting", children: "Connect Solana wallet" }),
|
|
10557
|
+
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,
|
|
10558
|
+
!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
|
|
10559
|
+
] }) : !connected2 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
10560
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect EVM wallet" }),
|
|
10561
|
+
/* @__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." })
|
|
10562
|
+
] }) : recipientState.missing ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.familyWallet.connecting, children: [
|
|
10563
|
+
"Connect ",
|
|
10564
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
10565
|
+
" wallet"
|
|
10566
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsx(
|
|
10567
|
+
Button,
|
|
10568
|
+
{
|
|
10569
|
+
onClick: solFlow.run,
|
|
10570
|
+
busy: submitting,
|
|
10571
|
+
disabled: !quotable || !cryptoReady || !!recipientState.error || !solFlow.plan || solFlow.insufficient || solFlow.solShort || solFlow.status === "quoting",
|
|
10572
|
+
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"
|
|
10573
|
+
}
|
|
10574
|
+
);
|
|
10575
|
+
const solanaSteps = solActive && solFlow.plan && connected2 && solanaWallet.address && solFlow.solShort && solFlow.cost ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "0 0 8px" }, "data-testid": "sol-shortfall", children: [
|
|
10576
|
+
"This order needs about ",
|
|
10577
|
+
(solFlow.cost.lamports / 1e9).toFixed(4),
|
|
10578
|
+
" SOL for network fees and rent; the wallet holds",
|
|
10579
|
+
" ",
|
|
10580
|
+
(solFlow.cost.balanceLamports / 1e9).toFixed(4),
|
|
10581
|
+
" SOL."
|
|
10582
|
+
] }) : null;
|
|
7993
10583
|
let body;
|
|
7994
|
-
if (hist &&
|
|
7995
|
-
body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
|
|
10584
|
+
if (hist && connected2) {
|
|
10585
|
+
body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, solanaAccount: solanaWallet.address, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
|
|
7996
10586
|
} else if (view === "from" || view === "to") {
|
|
7997
10587
|
const isFrom = view === "from";
|
|
7998
10588
|
body = /* @__PURE__ */ jsxRuntime.jsx(
|
|
@@ -8016,19 +10606,41 @@ function ExchangeCard(props) {
|
|
|
8016
10606
|
);
|
|
8017
10607
|
} else if (sheetBody && !wide) {
|
|
8018
10608
|
body = sheetBody;
|
|
10609
|
+
} else if (solActive && solFlow.status === "sent") {
|
|
10610
|
+
body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
10611
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
10612
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending": !isDelivered(solDelivery, false), children: /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph5, {}) }),
|
|
10613
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-amt sg-mono", children: [
|
|
10614
|
+
solFlow.sent?.receive ?? receive,
|
|
10615
|
+
" ",
|
|
10616
|
+
solFlow.sent?.toTicker ?? toTicker
|
|
10617
|
+
] }),
|
|
10618
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
10619
|
+
solDelivery.phase === "tracking" ? "Submitted on Solana \u2014 tracking delivery" : deliveryHeadline(solDelivery, true),
|
|
10620
|
+
solFlow.sent?.recipient ? ` \xB7 ${shortAddress2(solFlow.sent.recipient)}` : ""
|
|
10621
|
+
] }),
|
|
10622
|
+
/* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: solDelivery })
|
|
10623
|
+
] }),
|
|
10624
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
10625
|
+
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,
|
|
10626
|
+
solFlow.lastTxEntry && connected2 ? /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: solFlow.lastTxEntry }), children: "View transaction" }) : null,
|
|
10627
|
+
/* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: solFlow.reset, children: "Start a new exchange" })
|
|
10628
|
+
] })
|
|
10629
|
+
] });
|
|
8019
10630
|
} else if (flow.status === "success" || flow.status === "pending") {
|
|
8020
10631
|
body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
8021
10632
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
|
|
8022
|
-
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending":
|
|
10633
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending": !isDelivered(evmDelivery, evmConfirmed, evmDirect), children: /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph5, {}) }),
|
|
8023
10634
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-amt sg-mono", children: [
|
|
8024
10635
|
receive,
|
|
8025
10636
|
" ",
|
|
8026
10637
|
toTicker
|
|
8027
10638
|
] }),
|
|
8028
|
-
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
|
|
8029
|
-
|
|
8030
|
-
props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
8031
|
-
] })
|
|
10639
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
10640
|
+
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
10641
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
|
|
10642
|
+
] }),
|
|
10643
|
+
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
8032
10644
|
] }),
|
|
8033
10645
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
8034
10646
|
lastTxOwned ? /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: flow.lastTxEntry }), children: "View transaction" }) : null,
|
|
@@ -8038,8 +10650,19 @@ function ExchangeCard(props) {
|
|
|
8038
10650
|
} else {
|
|
8039
10651
|
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") });
|
|
8040
10652
|
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") });
|
|
8041
|
-
const cta = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
8042
|
-
|
|
10653
|
+
const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
10654
|
+
solanaSteps,
|
|
10655
|
+
solanaCta,
|
|
10656
|
+
/* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }),
|
|
10657
|
+
solanaWallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: solanaWallet.error }) : null,
|
|
10658
|
+
wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
|
|
10659
|
+
] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
10660
|
+
!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: [
|
|
10661
|
+
"Connect ",
|
|
10662
|
+
recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
|
|
10663
|
+
" wallet"
|
|
10664
|
+
] }) : /* @__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 }),
|
|
10665
|
+
!rampMode ? /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null,
|
|
8043
10666
|
wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
|
|
8044
10667
|
] });
|
|
8045
10668
|
const notices = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
@@ -8184,5 +10807,10 @@ function mount(el, config) {
|
|
|
8184
10807
|
root.render(react.createElement(Comp, variant === "rwa" ? { ...props, product: "rwa" } : props));
|
|
8185
10808
|
return () => root.unmount();
|
|
8186
10809
|
}
|
|
10810
|
+
/*! Bundled license information:
|
|
10811
|
+
|
|
10812
|
+
@noble/ed25519/index.js:
|
|
10813
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
10814
|
+
*/
|
|
8187
10815
|
|
|
8188
10816
|
exports.mount = mount;
|