@glacislabs/stablegenie-zerodelta 4.12.0 → 4.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +223 -223
- package/dist/{chunk-A7ADZJXA.js → chunk-52MY5D3D.js} +1232 -202
- package/dist/{chunk-MA2VYFG3.js → chunk-BYAKXZ5E.js} +756 -54
- package/dist/core/index.cjs +1880 -214
- package/dist/core/index.d.cts +367 -40
- package/dist/core/index.d.ts +367 -40
- package/dist/core/index.js +1 -1
- package/dist/ed25519-FZW4JEOV.js +526 -0
- package/dist/ed25519-GAMEXARB.js +11 -0
- package/dist/index.cjs +2678 -377
- package/dist/index.d.cts +96 -4
- package/dist/index.d.ts +96 -4
- package/dist/index.js +2 -2
- package/dist/{mount-xruGixNZ.d.cts → mount-BR3wWmjt.d.cts} +1 -1
- package/dist/{mount-hxb3zioQ.d.ts → mount-bKSKIGmW.d.ts} +1 -1
- package/dist/mount.cjs +2669 -375
- package/dist/mount.d.cts +2 -2
- package/dist/mount.d.ts +2 -2
- package/dist/mount.js +2 -2
- package/dist/standalone.global.js +12 -9
- package/dist/{verify-D8tr1yY1.d.cts → verify-DdSA23GJ.d.cts} +78 -68
- package/dist/{verify-D8tr1yY1.d.ts → verify-DdSA23GJ.d.ts} +78 -68
- package/package.json +134 -133
package/dist/core/index.cjs
CHANGED
|
@@ -1,5 +1,575 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __esm = (fn, res) => function __init() {
|
|
6
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
7
|
+
};
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// node_modules/@noble/ed25519/index.js
|
|
14
|
+
var ed25519_exports = {};
|
|
15
|
+
__export(ed25519_exports, {
|
|
16
|
+
Point: () => Point,
|
|
17
|
+
etc: () => etc,
|
|
18
|
+
getPublicKey: () => getPublicKey,
|
|
19
|
+
getPublicKeyAsync: () => getPublicKeyAsync,
|
|
20
|
+
hash: () => hash,
|
|
21
|
+
hashes: () => hashes,
|
|
22
|
+
keygen: () => keygen,
|
|
23
|
+
keygenAsync: () => keygenAsync,
|
|
24
|
+
sign: () => sign,
|
|
25
|
+
signAsync: () => signAsync,
|
|
26
|
+
utils: () => utils,
|
|
27
|
+
verify: () => verify,
|
|
28
|
+
verifyAsync: () => verifyAsync
|
|
29
|
+
});
|
|
30
|
+
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;
|
|
31
|
+
var init_ed25519 = __esm({
|
|
32
|
+
"node_modules/@noble/ed25519/index.js"() {
|
|
33
|
+
ed25519_CURVE = {
|
|
34
|
+
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
|
|
35
|
+
n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
|
|
36
|
+
h: 8n,
|
|
37
|
+
a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
|
|
38
|
+
d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
|
|
39
|
+
Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
|
|
40
|
+
Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
|
|
41
|
+
};
|
|
42
|
+
({ p: P2, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE);
|
|
43
|
+
L = 32;
|
|
44
|
+
L2 = 64;
|
|
45
|
+
captureTrace = (...args) => {
|
|
46
|
+
if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
|
|
47
|
+
Error.captureStackTrace(...args);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
err = (message = "") => {
|
|
51
|
+
const e = new Error(message);
|
|
52
|
+
captureTrace(e, err);
|
|
53
|
+
throw e;
|
|
54
|
+
};
|
|
55
|
+
isBig = (n) => typeof n === "bigint";
|
|
56
|
+
isStr = (s) => typeof s === "string";
|
|
57
|
+
isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
58
|
+
abytes = (value, length, title = "") => {
|
|
59
|
+
const bytes = isBytes(value);
|
|
60
|
+
const len = value?.length;
|
|
61
|
+
const needsLen = length !== void 0;
|
|
62
|
+
if (!bytes || needsLen && len !== length) {
|
|
63
|
+
const prefix = title && `"${title}" `;
|
|
64
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
65
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
66
|
+
err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
67
|
+
}
|
|
68
|
+
return value;
|
|
69
|
+
};
|
|
70
|
+
u8n = (len) => new Uint8Array(len);
|
|
71
|
+
u8fr = (buf) => Uint8Array.from(buf);
|
|
72
|
+
padh = (n, pad) => n.toString(16).padStart(pad, "0");
|
|
73
|
+
bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
|
|
74
|
+
C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
75
|
+
_ch = (ch) => {
|
|
76
|
+
if (ch >= C._0 && ch <= C._9)
|
|
77
|
+
return ch - C._0;
|
|
78
|
+
if (ch >= C.A && ch <= C.F)
|
|
79
|
+
return ch - (C.A - 10);
|
|
80
|
+
if (ch >= C.a && ch <= C.f)
|
|
81
|
+
return ch - (C.a - 10);
|
|
82
|
+
return;
|
|
83
|
+
};
|
|
84
|
+
hexToBytes = (hex) => {
|
|
85
|
+
const e = "hex invalid";
|
|
86
|
+
if (!isStr(hex))
|
|
87
|
+
return err(e);
|
|
88
|
+
const hl = hex.length;
|
|
89
|
+
const al = hl / 2;
|
|
90
|
+
if (hl % 2)
|
|
91
|
+
return err(e);
|
|
92
|
+
const array = u8n(al);
|
|
93
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
94
|
+
const n1 = _ch(hex.charCodeAt(hi));
|
|
95
|
+
const n2 = _ch(hex.charCodeAt(hi + 1));
|
|
96
|
+
if (n1 === void 0 || n2 === void 0)
|
|
97
|
+
return err(e);
|
|
98
|
+
array[ai] = n1 * 16 + n2;
|
|
99
|
+
}
|
|
100
|
+
return array;
|
|
101
|
+
};
|
|
102
|
+
cr = () => globalThis?.crypto;
|
|
103
|
+
subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
|
|
104
|
+
concatBytes = (...arrs) => {
|
|
105
|
+
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
|
|
106
|
+
let pad = 0;
|
|
107
|
+
arrs.forEach((a) => {
|
|
108
|
+
r.set(a, pad);
|
|
109
|
+
pad += a.length;
|
|
110
|
+
});
|
|
111
|
+
return r;
|
|
112
|
+
};
|
|
113
|
+
randomBytes = (len = L) => {
|
|
114
|
+
const c = cr();
|
|
115
|
+
return c.getRandomValues(u8n(len));
|
|
116
|
+
};
|
|
117
|
+
big = BigInt;
|
|
118
|
+
assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
|
|
119
|
+
M = (a, b = P2) => {
|
|
120
|
+
const r = a % b;
|
|
121
|
+
return r >= 0n ? r : b + r;
|
|
122
|
+
};
|
|
123
|
+
modN = (a) => M(a, N);
|
|
124
|
+
invert = (num, md) => {
|
|
125
|
+
if (num === 0n || md <= 0n)
|
|
126
|
+
err("no inverse n=" + num + " mod=" + md);
|
|
127
|
+
let a = M(num, md), b = md, x = 0n, u = 1n;
|
|
128
|
+
while (a !== 0n) {
|
|
129
|
+
const q = b / a, r = b % a;
|
|
130
|
+
const m = x - u * q;
|
|
131
|
+
b = a, a = r, x = u, u = m;
|
|
132
|
+
}
|
|
133
|
+
return b === 1n ? M(x, md) : err("no inverse");
|
|
134
|
+
};
|
|
135
|
+
callHash = (name) => {
|
|
136
|
+
const fn = hashes[name];
|
|
137
|
+
if (typeof fn !== "function")
|
|
138
|
+
err("hashes." + name + " not set");
|
|
139
|
+
return fn;
|
|
140
|
+
};
|
|
141
|
+
hash = (msg) => callHash("sha512")(msg);
|
|
142
|
+
apoint = (p) => p instanceof Point ? p : err("Point expected");
|
|
143
|
+
B256 = 2n ** 256n;
|
|
144
|
+
Point = class _Point {
|
|
145
|
+
static BASE;
|
|
146
|
+
static ZERO;
|
|
147
|
+
X;
|
|
148
|
+
Y;
|
|
149
|
+
Z;
|
|
150
|
+
T;
|
|
151
|
+
constructor(X, Y, Z, T) {
|
|
152
|
+
const max = B256;
|
|
153
|
+
this.X = assertRange(X, 0n, max);
|
|
154
|
+
this.Y = assertRange(Y, 0n, max);
|
|
155
|
+
this.Z = assertRange(Z, 1n, max);
|
|
156
|
+
this.T = assertRange(T, 0n, max);
|
|
157
|
+
Object.freeze(this);
|
|
158
|
+
}
|
|
159
|
+
static CURVE() {
|
|
160
|
+
return ed25519_CURVE;
|
|
161
|
+
}
|
|
162
|
+
static fromAffine(p) {
|
|
163
|
+
return new _Point(p.x, p.y, 1n, M(p.x * p.y));
|
|
164
|
+
}
|
|
165
|
+
/** RFC8032 5.1.3: Uint8Array to Point. */
|
|
166
|
+
static fromBytes(hex, zip215 = false) {
|
|
167
|
+
const d = _d;
|
|
168
|
+
const normed = u8fr(abytes(hex, L));
|
|
169
|
+
const lastByte = hex[31];
|
|
170
|
+
normed[31] = lastByte & -129;
|
|
171
|
+
const y = bytesToNumLE(normed);
|
|
172
|
+
const max = zip215 ? B256 : P2;
|
|
173
|
+
assertRange(y, 0n, max);
|
|
174
|
+
const y2 = M(y * y);
|
|
175
|
+
const u = M(y2 - 1n);
|
|
176
|
+
const v = M(d * y2 + 1n);
|
|
177
|
+
let { isValid, value: x } = uvRatio(u, v);
|
|
178
|
+
if (!isValid)
|
|
179
|
+
err("bad point: y not sqrt");
|
|
180
|
+
const isXOdd = (x & 1n) === 1n;
|
|
181
|
+
const isLastByteOdd = (lastByte & 128) !== 0;
|
|
182
|
+
if (!zip215 && x === 0n && isLastByteOdd)
|
|
183
|
+
err("bad point: x==0, isLastByteOdd");
|
|
184
|
+
if (isLastByteOdd !== isXOdd)
|
|
185
|
+
x = M(-x);
|
|
186
|
+
return new _Point(x, y, 1n, M(x * y));
|
|
187
|
+
}
|
|
188
|
+
static fromHex(hex, zip215) {
|
|
189
|
+
return _Point.fromBytes(hexToBytes(hex), zip215);
|
|
190
|
+
}
|
|
191
|
+
get x() {
|
|
192
|
+
return this.toAffine().x;
|
|
193
|
+
}
|
|
194
|
+
get y() {
|
|
195
|
+
return this.toAffine().y;
|
|
196
|
+
}
|
|
197
|
+
/** Checks if the point is valid and on-curve. */
|
|
198
|
+
assertValidity() {
|
|
199
|
+
const a = _a;
|
|
200
|
+
const d = _d;
|
|
201
|
+
const p = this;
|
|
202
|
+
if (p.is0())
|
|
203
|
+
return err("bad point: ZERO");
|
|
204
|
+
const { X, Y, Z, T } = p;
|
|
205
|
+
const X2 = M(X * X);
|
|
206
|
+
const Y2 = M(Y * Y);
|
|
207
|
+
const Z2 = M(Z * Z);
|
|
208
|
+
const Z4 = M(Z2 * Z2);
|
|
209
|
+
const aX2 = M(X2 * a);
|
|
210
|
+
const left = M(Z2 * M(aX2 + Y2));
|
|
211
|
+
const right = M(Z4 + M(d * M(X2 * Y2)));
|
|
212
|
+
if (left !== right)
|
|
213
|
+
return err("bad point: equation left != right (1)");
|
|
214
|
+
const XY = M(X * Y);
|
|
215
|
+
const ZT = M(Z * T);
|
|
216
|
+
if (XY !== ZT)
|
|
217
|
+
return err("bad point: equation left != right (2)");
|
|
218
|
+
return this;
|
|
219
|
+
}
|
|
220
|
+
/** Equality check: compare points P&Q. */
|
|
221
|
+
equals(other) {
|
|
222
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
223
|
+
const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
|
|
224
|
+
const X1Z2 = M(X1 * Z2);
|
|
225
|
+
const X2Z1 = M(X2 * Z1);
|
|
226
|
+
const Y1Z2 = M(Y1 * Z2);
|
|
227
|
+
const Y2Z1 = M(Y2 * Z1);
|
|
228
|
+
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
|
229
|
+
}
|
|
230
|
+
is0() {
|
|
231
|
+
return this.equals(I);
|
|
232
|
+
}
|
|
233
|
+
/** Flip point over y coordinate. */
|
|
234
|
+
negate() {
|
|
235
|
+
return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
|
|
236
|
+
}
|
|
237
|
+
/** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
|
|
238
|
+
double() {
|
|
239
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
240
|
+
const a = _a;
|
|
241
|
+
const A = M(X1 * X1);
|
|
242
|
+
const B = M(Y1 * Y1);
|
|
243
|
+
const C2 = M(2n * M(Z1 * Z1));
|
|
244
|
+
const D2 = M(a * A);
|
|
245
|
+
const x1y1 = X1 + Y1;
|
|
246
|
+
const E = M(M(x1y1 * x1y1) - A - B);
|
|
247
|
+
const G2 = D2 + B;
|
|
248
|
+
const F = G2 - C2;
|
|
249
|
+
const H = D2 - B;
|
|
250
|
+
const X3 = M(E * F);
|
|
251
|
+
const Y3 = M(G2 * H);
|
|
252
|
+
const T3 = M(E * H);
|
|
253
|
+
const Z3 = M(F * G2);
|
|
254
|
+
return new _Point(X3, Y3, Z3, T3);
|
|
255
|
+
}
|
|
256
|
+
/** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
|
|
257
|
+
add(other) {
|
|
258
|
+
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
|
259
|
+
const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
|
|
260
|
+
const a = _a;
|
|
261
|
+
const d = _d;
|
|
262
|
+
const A = M(X1 * X2);
|
|
263
|
+
const B = M(Y1 * Y2);
|
|
264
|
+
const C2 = M(T1 * d * T2);
|
|
265
|
+
const D2 = M(Z1 * Z2);
|
|
266
|
+
const E = M((X1 + Y1) * (X2 + Y2) - A - B);
|
|
267
|
+
const F = M(D2 - C2);
|
|
268
|
+
const G2 = M(D2 + C2);
|
|
269
|
+
const H = M(B - a * A);
|
|
270
|
+
const X3 = M(E * F);
|
|
271
|
+
const Y3 = M(G2 * H);
|
|
272
|
+
const T3 = M(E * H);
|
|
273
|
+
const Z3 = M(F * G2);
|
|
274
|
+
return new _Point(X3, Y3, Z3, T3);
|
|
275
|
+
}
|
|
276
|
+
subtract(other) {
|
|
277
|
+
return this.add(apoint(other).negate());
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
|
|
281
|
+
* Uses {@link wNAF} for base point.
|
|
282
|
+
* Uses fake point to mitigate side-channel leakage.
|
|
283
|
+
* @param n scalar by which point is multiplied
|
|
284
|
+
* @param safe safe mode guards against timing attacks; unsafe mode is faster
|
|
285
|
+
*/
|
|
286
|
+
multiply(n, safe = true) {
|
|
287
|
+
if (!safe && (n === 0n || this.is0()))
|
|
288
|
+
return I;
|
|
289
|
+
assertRange(n, 1n, N);
|
|
290
|
+
if (n === 1n)
|
|
291
|
+
return this;
|
|
292
|
+
if (this.equals(G))
|
|
293
|
+
return wNAF(n).p;
|
|
294
|
+
let p = I;
|
|
295
|
+
let f = G;
|
|
296
|
+
for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
|
|
297
|
+
if (n & 1n)
|
|
298
|
+
p = p.add(d);
|
|
299
|
+
else if (safe)
|
|
300
|
+
f = f.add(d);
|
|
301
|
+
}
|
|
302
|
+
return p;
|
|
303
|
+
}
|
|
304
|
+
multiplyUnsafe(scalar) {
|
|
305
|
+
return this.multiply(scalar, false);
|
|
306
|
+
}
|
|
307
|
+
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
|
|
308
|
+
toAffine() {
|
|
309
|
+
const { X, Y, Z } = this;
|
|
310
|
+
if (this.equals(I))
|
|
311
|
+
return { x: 0n, y: 1n };
|
|
312
|
+
const iz = invert(Z, P2);
|
|
313
|
+
if (M(Z * iz) !== 1n)
|
|
314
|
+
err("invalid inverse");
|
|
315
|
+
const x = M(X * iz);
|
|
316
|
+
const y = M(Y * iz);
|
|
317
|
+
return { x, y };
|
|
318
|
+
}
|
|
319
|
+
toBytes() {
|
|
320
|
+
const { x, y } = this.assertValidity().toAffine();
|
|
321
|
+
const b = numTo32bLE(y);
|
|
322
|
+
b[31] |= x & 1n ? 128 : 0;
|
|
323
|
+
return b;
|
|
324
|
+
}
|
|
325
|
+
toHex() {
|
|
326
|
+
return bytesToHex(this.toBytes());
|
|
327
|
+
}
|
|
328
|
+
clearCofactor() {
|
|
329
|
+
return this.multiply(big(h), false);
|
|
330
|
+
}
|
|
331
|
+
isSmallOrder() {
|
|
332
|
+
return this.clearCofactor().is0();
|
|
333
|
+
}
|
|
334
|
+
isTorsionFree() {
|
|
335
|
+
let p = this.multiply(N / 2n, false).double();
|
|
336
|
+
if (N % 2n)
|
|
337
|
+
p = p.add(this);
|
|
338
|
+
return p.is0();
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
G = new Point(Gx, Gy, 1n, M(Gx * Gy));
|
|
342
|
+
I = new Point(0n, 1n, 1n, 0n);
|
|
343
|
+
Point.BASE = G;
|
|
344
|
+
Point.ZERO = I;
|
|
345
|
+
numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
|
|
346
|
+
bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
|
|
347
|
+
pow2 = (x, power) => {
|
|
348
|
+
let r = x;
|
|
349
|
+
while (power-- > 0n) {
|
|
350
|
+
r *= r;
|
|
351
|
+
r %= P2;
|
|
352
|
+
}
|
|
353
|
+
return r;
|
|
354
|
+
};
|
|
355
|
+
pow_2_252_3 = (x) => {
|
|
356
|
+
const x2 = x * x % P2;
|
|
357
|
+
const b2 = x2 * x % P2;
|
|
358
|
+
const b4 = pow2(b2, 2n) * b2 % P2;
|
|
359
|
+
const b5 = pow2(b4, 1n) * x % P2;
|
|
360
|
+
const b10 = pow2(b5, 5n) * b5 % P2;
|
|
361
|
+
const b20 = pow2(b10, 10n) * b10 % P2;
|
|
362
|
+
const b40 = pow2(b20, 20n) * b20 % P2;
|
|
363
|
+
const b80 = pow2(b40, 40n) * b40 % P2;
|
|
364
|
+
const b160 = pow2(b80, 80n) * b80 % P2;
|
|
365
|
+
const b240 = pow2(b160, 80n) * b80 % P2;
|
|
366
|
+
const b250 = pow2(b240, 10n) * b10 % P2;
|
|
367
|
+
const pow_p_5_8 = pow2(b250, 2n) * x % P2;
|
|
368
|
+
return { pow_p_5_8, b2 };
|
|
369
|
+
};
|
|
370
|
+
RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
|
|
371
|
+
uvRatio = (u, v) => {
|
|
372
|
+
const v3 = M(v * v * v);
|
|
373
|
+
const v7 = M(v3 * v3 * v);
|
|
374
|
+
const pow3 = pow_2_252_3(u * v7).pow_p_5_8;
|
|
375
|
+
let x = M(u * v3 * pow3);
|
|
376
|
+
const vx2 = M(v * x * x);
|
|
377
|
+
const root1 = x;
|
|
378
|
+
const root2 = M(x * RM1);
|
|
379
|
+
const useRoot1 = vx2 === u;
|
|
380
|
+
const useRoot2 = vx2 === M(-u);
|
|
381
|
+
const noRoot = vx2 === M(-u * RM1);
|
|
382
|
+
if (useRoot1)
|
|
383
|
+
x = root1;
|
|
384
|
+
if (useRoot2 || noRoot)
|
|
385
|
+
x = root2;
|
|
386
|
+
if ((M(x) & 1n) === 1n)
|
|
387
|
+
x = M(-x);
|
|
388
|
+
return { isValid: useRoot1 || useRoot2, value: x };
|
|
389
|
+
};
|
|
390
|
+
modL_LE = (hash2) => modN(bytesToNumLE(hash2));
|
|
391
|
+
sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
|
|
392
|
+
sha512s = (...m) => callHash("sha512")(concatBytes(...m));
|
|
393
|
+
hash2extK = (hashed) => {
|
|
394
|
+
const head = hashed.slice(0, L);
|
|
395
|
+
head[0] &= 248;
|
|
396
|
+
head[31] &= 127;
|
|
397
|
+
head[31] |= 64;
|
|
398
|
+
const prefix = hashed.slice(L, L2);
|
|
399
|
+
const scalar = modL_LE(head);
|
|
400
|
+
const point = G.multiply(scalar);
|
|
401
|
+
const pointBytes = point.toBytes();
|
|
402
|
+
return { head, prefix, scalar, point, pointBytes };
|
|
403
|
+
};
|
|
404
|
+
getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
|
|
405
|
+
getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
|
|
406
|
+
getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
|
|
407
|
+
getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
|
|
408
|
+
hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
|
|
409
|
+
hashFinishS = (res) => res.finish(sha512s(res.hashable));
|
|
410
|
+
_sign = (e, rBytes, msg) => {
|
|
411
|
+
const { pointBytes: P3, scalar: s } = e;
|
|
412
|
+
const r = modL_LE(rBytes);
|
|
413
|
+
const R = G.multiply(r).toBytes();
|
|
414
|
+
const hashable = concatBytes(R, P3, msg);
|
|
415
|
+
const finish = (hashed) => {
|
|
416
|
+
const S = modN(r + modL_LE(hashed) * s);
|
|
417
|
+
return abytes(concatBytes(R, numTo32bLE(S)), L2);
|
|
418
|
+
};
|
|
419
|
+
return { hashable, finish };
|
|
420
|
+
};
|
|
421
|
+
signAsync = async (message, secretKey) => {
|
|
422
|
+
const m = abytes(message);
|
|
423
|
+
const e = await getExtendedPublicKeyAsync(secretKey);
|
|
424
|
+
const rBytes = await sha512a(e.prefix, m);
|
|
425
|
+
return hashFinishA(_sign(e, rBytes, m));
|
|
426
|
+
};
|
|
427
|
+
sign = (message, secretKey) => {
|
|
428
|
+
const m = abytes(message);
|
|
429
|
+
const e = getExtendedPublicKey(secretKey);
|
|
430
|
+
const rBytes = sha512s(e.prefix, m);
|
|
431
|
+
return hashFinishS(_sign(e, rBytes, m));
|
|
432
|
+
};
|
|
433
|
+
defaultVerifyOpts = { zip215: true };
|
|
434
|
+
_verify = (sig, msg, pub, opts = defaultVerifyOpts) => {
|
|
435
|
+
sig = abytes(sig, L2);
|
|
436
|
+
msg = abytes(msg);
|
|
437
|
+
pub = abytes(pub, L);
|
|
438
|
+
const { zip215 } = opts;
|
|
439
|
+
let A;
|
|
440
|
+
let R;
|
|
441
|
+
let s;
|
|
442
|
+
let SB;
|
|
443
|
+
let hashable = Uint8Array.of();
|
|
444
|
+
try {
|
|
445
|
+
A = Point.fromBytes(pub, zip215);
|
|
446
|
+
R = Point.fromBytes(sig.slice(0, L), zip215);
|
|
447
|
+
s = bytesToNumLE(sig.slice(L, L2));
|
|
448
|
+
SB = G.multiply(s, false);
|
|
449
|
+
hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
|
|
450
|
+
} catch (error) {
|
|
451
|
+
}
|
|
452
|
+
const finish = (hashed) => {
|
|
453
|
+
if (SB == null)
|
|
454
|
+
return false;
|
|
455
|
+
if (!zip215 && A.isSmallOrder())
|
|
456
|
+
return false;
|
|
457
|
+
const k = modL_LE(hashed);
|
|
458
|
+
const RkA = R.add(A.multiply(k, false));
|
|
459
|
+
return RkA.add(SB.negate()).clearCofactor().is0();
|
|
460
|
+
};
|
|
461
|
+
return { hashable, finish };
|
|
462
|
+
};
|
|
463
|
+
verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
|
|
464
|
+
verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));
|
|
465
|
+
etc = {
|
|
466
|
+
bytesToHex,
|
|
467
|
+
hexToBytes,
|
|
468
|
+
concatBytes,
|
|
469
|
+
mod: M,
|
|
470
|
+
invert,
|
|
471
|
+
randomBytes
|
|
472
|
+
};
|
|
473
|
+
hashes = {
|
|
474
|
+
sha512Async: async (message) => {
|
|
475
|
+
const s = subtle();
|
|
476
|
+
const m = concatBytes(message);
|
|
477
|
+
return u8n(await s.digest("SHA-512", m.buffer));
|
|
478
|
+
},
|
|
479
|
+
sha512: void 0
|
|
480
|
+
};
|
|
481
|
+
randomSecretKey = (seed = randomBytes(L)) => seed;
|
|
482
|
+
keygen = (seed) => {
|
|
483
|
+
const secretKey = randomSecretKey(seed);
|
|
484
|
+
const publicKey = getPublicKey(secretKey);
|
|
485
|
+
return { secretKey, publicKey };
|
|
486
|
+
};
|
|
487
|
+
keygenAsync = async (seed) => {
|
|
488
|
+
const secretKey = randomSecretKey(seed);
|
|
489
|
+
const publicKey = await getPublicKeyAsync(secretKey);
|
|
490
|
+
return { secretKey, publicKey };
|
|
491
|
+
};
|
|
492
|
+
utils = {
|
|
493
|
+
getExtendedPublicKeyAsync,
|
|
494
|
+
getExtendedPublicKey,
|
|
495
|
+
randomSecretKey
|
|
496
|
+
};
|
|
497
|
+
W = 8;
|
|
498
|
+
scalarBits = 256;
|
|
499
|
+
pwindows = Math.ceil(scalarBits / W) + 1;
|
|
500
|
+
pwindowSize = 2 ** (W - 1);
|
|
501
|
+
precompute = () => {
|
|
502
|
+
const points = [];
|
|
503
|
+
let p = G;
|
|
504
|
+
let b = p;
|
|
505
|
+
for (let w = 0; w < pwindows; w++) {
|
|
506
|
+
b = p;
|
|
507
|
+
points.push(b);
|
|
508
|
+
for (let i = 1; i < pwindowSize; i++) {
|
|
509
|
+
b = b.add(p);
|
|
510
|
+
points.push(b);
|
|
511
|
+
}
|
|
512
|
+
p = b.double();
|
|
513
|
+
}
|
|
514
|
+
return points;
|
|
515
|
+
};
|
|
516
|
+
Gpows = void 0;
|
|
517
|
+
ctneg = (cnd, p) => {
|
|
518
|
+
const n = p.negate();
|
|
519
|
+
return cnd ? n : p;
|
|
520
|
+
};
|
|
521
|
+
wNAF = (n) => {
|
|
522
|
+
const comp = Gpows || (Gpows = precompute());
|
|
523
|
+
let p = I;
|
|
524
|
+
let f = G;
|
|
525
|
+
const pow_2_w = 2 ** W;
|
|
526
|
+
const maxNum = pow_2_w;
|
|
527
|
+
const mask = big(pow_2_w - 1);
|
|
528
|
+
const shiftBy = big(W);
|
|
529
|
+
for (let w = 0; w < pwindows; w++) {
|
|
530
|
+
let wbits = Number(n & mask);
|
|
531
|
+
n >>= shiftBy;
|
|
532
|
+
if (wbits > pwindowSize) {
|
|
533
|
+
wbits -= maxNum;
|
|
534
|
+
n += 1n;
|
|
535
|
+
}
|
|
536
|
+
const off = w * pwindowSize;
|
|
537
|
+
const offF = off;
|
|
538
|
+
const offP = off + Math.abs(wbits) - 1;
|
|
539
|
+
const isEven = w % 2 !== 0;
|
|
540
|
+
const isNeg = wbits < 0;
|
|
541
|
+
if (wbits === 0) {
|
|
542
|
+
f = f.add(ctneg(isEven, comp[offF]));
|
|
543
|
+
} else {
|
|
544
|
+
p = p.add(ctneg(isNeg, comp[offP]));
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (n !== 0n)
|
|
548
|
+
err("invalid wnaf");
|
|
549
|
+
return { p, f };
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
// src/core/ed25519.ts
|
|
555
|
+
var ed25519_exports2 = {};
|
|
556
|
+
__export(ed25519_exports2, {
|
|
557
|
+
eventPublicKey: () => eventPublicKey,
|
|
558
|
+
eventSignature: () => eventSignature
|
|
559
|
+
});
|
|
560
|
+
async function eventPublicKey(seed) {
|
|
561
|
+
const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
|
|
562
|
+
return ed.getPublicKeyAsync(seed);
|
|
563
|
+
}
|
|
564
|
+
async function eventSignature(message, seed) {
|
|
565
|
+
const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
|
|
566
|
+
return ed.signAsync(message, seed);
|
|
567
|
+
}
|
|
568
|
+
var init_ed255192 = __esm({
|
|
569
|
+
"src/core/ed25519.ts"() {
|
|
570
|
+
}
|
|
571
|
+
});
|
|
572
|
+
|
|
3
573
|
// src/core/constants.ts
|
|
4
574
|
var DEFAULT_WIDGET_API_BASE = "/api/widget/v1";
|
|
5
575
|
var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146, 98866]);
|
|
@@ -93,7 +663,10 @@ var CANONICAL_ESCROW = Object.freeze({
|
|
|
93
663
|
// Plume
|
|
94
664
|
});
|
|
95
665
|
var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
|
|
96
|
-
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
|
|
666
|
+
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
|
|
667
|
+
9745: 2500n * 10n ** 18n,
|
|
668
|
+
98866: 5000n * 10n ** 18n
|
|
669
|
+
};
|
|
97
670
|
function maxNativeFeeWei(chainId) {
|
|
98
671
|
return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
|
|
99
672
|
}
|
|
@@ -211,6 +784,247 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
|
|
|
211
784
|
1151111081099710: "Solana"
|
|
212
785
|
});
|
|
213
786
|
|
|
787
|
+
// src/core/solana.ts
|
|
788
|
+
var SOLANA_CHAIN_ID = 1151111081099710;
|
|
789
|
+
function isSolanaChainId(value) {
|
|
790
|
+
return Number(value) === SOLANA_CHAIN_ID;
|
|
791
|
+
}
|
|
792
|
+
var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
793
|
+
function base58Encode(bytes) {
|
|
794
|
+
let zeros = 0;
|
|
795
|
+
while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
|
|
796
|
+
let value = 0n;
|
|
797
|
+
for (const byte of bytes) value = value << 8n | BigInt(byte);
|
|
798
|
+
let out = "";
|
|
799
|
+
while (value > 0n) {
|
|
800
|
+
out = BASE58_ALPHABET[Number(value % 58n)] + out;
|
|
801
|
+
value /= 58n;
|
|
802
|
+
}
|
|
803
|
+
return "1".repeat(zeros) + out;
|
|
804
|
+
}
|
|
805
|
+
function base58Decode(text) {
|
|
806
|
+
let value = 0n;
|
|
807
|
+
for (const char of text) {
|
|
808
|
+
const digit = BASE58_ALPHABET.indexOf(char);
|
|
809
|
+
if (digit < 0) return null;
|
|
810
|
+
value = value * 58n + BigInt(digit);
|
|
811
|
+
}
|
|
812
|
+
const body = [];
|
|
813
|
+
while (value > 0n) {
|
|
814
|
+
body.unshift(Number(value & 0xffn));
|
|
815
|
+
value >>= 8n;
|
|
816
|
+
}
|
|
817
|
+
let zeros = 0;
|
|
818
|
+
while (zeros < text.length && text[zeros] === "1") zeros += 1;
|
|
819
|
+
return new Uint8Array([...new Array(zeros).fill(0), ...body]);
|
|
820
|
+
}
|
|
821
|
+
function isSolanaAddress(value) {
|
|
822
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
823
|
+
return text.length >= 32 && text.length <= 44 && base58Decode(text)?.length === 32;
|
|
824
|
+
}
|
|
825
|
+
function solanaKeyHex(value) {
|
|
826
|
+
if (!isSolanaAddress(value)) return null;
|
|
827
|
+
return `0x${Array.from(base58Decode(value.trim()), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
828
|
+
}
|
|
829
|
+
function hexToSolanaKey(value) {
|
|
830
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(value)) return null;
|
|
831
|
+
return base58Encode(Uint8Array.from(value.slice(2).match(/../g), (byte) => Number.parseInt(byte, 16)));
|
|
832
|
+
}
|
|
833
|
+
var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
834
|
+
var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
|
|
835
|
+
var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
|
|
836
|
+
var pin = (symbol, decimals, bridge, tokenProgram) => Object.freeze({ symbol, decimals, bridge, tokenProgram });
|
|
837
|
+
var SOLANA_DESTINATION_ASSETS = Object.freeze({
|
|
838
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: pin("USDC", 6, "cctp", TOKEN_PROGRAM),
|
|
839
|
+
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": pin("PYUSD", 6, "layerzero", TOKEN_2022_PROGRAM),
|
|
840
|
+
DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT: pin("USDE", 9, "layerzero", TOKEN_PROGRAM),
|
|
841
|
+
"2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": pin("USDG", 6, "layerzero", TOKEN_2022_PROGRAM),
|
|
842
|
+
AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
|
|
843
|
+
});
|
|
844
|
+
function solanaDestinationAsset(mint) {
|
|
845
|
+
const key = typeof mint === "string" ? mint.trim() : "";
|
|
846
|
+
return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
|
|
847
|
+
}
|
|
848
|
+
function solanaBridgeOf(token) {
|
|
849
|
+
const pinned = solanaDestinationAsset(token.address);
|
|
850
|
+
if (!pinned || pinned.symbol !== token.symbol.trim().toUpperCase()) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
851
|
+
return pinned.bridge;
|
|
852
|
+
}
|
|
853
|
+
var K = new Uint32Array([
|
|
854
|
+
1116352408,
|
|
855
|
+
1899447441,
|
|
856
|
+
3049323471,
|
|
857
|
+
3921009573,
|
|
858
|
+
961987163,
|
|
859
|
+
1508970993,
|
|
860
|
+
2453635748,
|
|
861
|
+
2870763221,
|
|
862
|
+
3624381080,
|
|
863
|
+
310598401,
|
|
864
|
+
607225278,
|
|
865
|
+
1426881987,
|
|
866
|
+
1925078388,
|
|
867
|
+
2162078206,
|
|
868
|
+
2614888103,
|
|
869
|
+
3248222580,
|
|
870
|
+
3835390401,
|
|
871
|
+
4022224774,
|
|
872
|
+
264347078,
|
|
873
|
+
604807628,
|
|
874
|
+
770255983,
|
|
875
|
+
1249150122,
|
|
876
|
+
1555081692,
|
|
877
|
+
1996064986,
|
|
878
|
+
2554220882,
|
|
879
|
+
2821834349,
|
|
880
|
+
2952996808,
|
|
881
|
+
3210313671,
|
|
882
|
+
3336571891,
|
|
883
|
+
3584528711,
|
|
884
|
+
113926993,
|
|
885
|
+
338241895,
|
|
886
|
+
666307205,
|
|
887
|
+
773529912,
|
|
888
|
+
1294757372,
|
|
889
|
+
1396182291,
|
|
890
|
+
1695183700,
|
|
891
|
+
1986661051,
|
|
892
|
+
2177026350,
|
|
893
|
+
2456956037,
|
|
894
|
+
2730485921,
|
|
895
|
+
2820302411,
|
|
896
|
+
3259730800,
|
|
897
|
+
3345764771,
|
|
898
|
+
3516065817,
|
|
899
|
+
3600352804,
|
|
900
|
+
4094571909,
|
|
901
|
+
275423344,
|
|
902
|
+
430227734,
|
|
903
|
+
506948616,
|
|
904
|
+
659060556,
|
|
905
|
+
883997877,
|
|
906
|
+
958139571,
|
|
907
|
+
1322822218,
|
|
908
|
+
1537002063,
|
|
909
|
+
1747873779,
|
|
910
|
+
1955562222,
|
|
911
|
+
2024104815,
|
|
912
|
+
2227730452,
|
|
913
|
+
2361852424,
|
|
914
|
+
2428436474,
|
|
915
|
+
2756734187,
|
|
916
|
+
3204031479,
|
|
917
|
+
3329325298
|
|
918
|
+
]);
|
|
919
|
+
function sha256(data) {
|
|
920
|
+
const bitLen = data.length * 8;
|
|
921
|
+
const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
|
|
922
|
+
padded.set(data);
|
|
923
|
+
padded[data.length] = 128;
|
|
924
|
+
const view = new DataView(padded.buffer);
|
|
925
|
+
view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
|
|
926
|
+
view.setUint32(padded.length - 4, bitLen >>> 0);
|
|
927
|
+
const h2 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
|
|
928
|
+
const w = new Uint32Array(64);
|
|
929
|
+
const rotr = (x, n) => x >>> n | x << 32 - n;
|
|
930
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
931
|
+
for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
|
|
932
|
+
for (let i = 16; i < 64; i += 1) {
|
|
933
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
|
|
934
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
|
|
935
|
+
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
936
|
+
}
|
|
937
|
+
let [a, b, c, d, e, f, g, hh] = h2;
|
|
938
|
+
for (let i = 0; i < 64; i += 1) {
|
|
939
|
+
const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
|
|
940
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
941
|
+
hh = g;
|
|
942
|
+
g = f;
|
|
943
|
+
f = e;
|
|
944
|
+
e = d + t1 >>> 0;
|
|
945
|
+
d = c;
|
|
946
|
+
c = b;
|
|
947
|
+
b = a;
|
|
948
|
+
a = t1 + t2 >>> 0;
|
|
949
|
+
}
|
|
950
|
+
h2[0] = h2[0] + a >>> 0;
|
|
951
|
+
h2[1] = h2[1] + b >>> 0;
|
|
952
|
+
h2[2] = h2[2] + c >>> 0;
|
|
953
|
+
h2[3] = h2[3] + d >>> 0;
|
|
954
|
+
h2[4] = h2[4] + e >>> 0;
|
|
955
|
+
h2[5] = h2[5] + f >>> 0;
|
|
956
|
+
h2[6] = h2[6] + g >>> 0;
|
|
957
|
+
h2[7] = h2[7] + hh >>> 0;
|
|
958
|
+
}
|
|
959
|
+
const out = new Uint8Array(32);
|
|
960
|
+
const outView = new DataView(out.buffer);
|
|
961
|
+
for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h2[i]);
|
|
962
|
+
return out;
|
|
963
|
+
}
|
|
964
|
+
var P = 2n ** 255n - 19n;
|
|
965
|
+
var mod = (a) => (a % P + P) % P;
|
|
966
|
+
var pow = (base, exp) => {
|
|
967
|
+
let result = 1n;
|
|
968
|
+
let b = mod(base);
|
|
969
|
+
for (let e = exp; e > 0n; e >>= 1n) {
|
|
970
|
+
if (e & 1n) result = result * b % P;
|
|
971
|
+
b = b * b % P;
|
|
972
|
+
}
|
|
973
|
+
return result;
|
|
974
|
+
};
|
|
975
|
+
var D = mod(-121665n * pow(121666n, P - 2n));
|
|
976
|
+
function isOnEd25519Curve(bytes) {
|
|
977
|
+
let y = 0n;
|
|
978
|
+
for (let i = 31; i >= 0; i -= 1) y = y << 8n | BigInt(bytes[i]);
|
|
979
|
+
y = mod(y & (1n << 255n) - 1n);
|
|
980
|
+
const yy = y * y % P;
|
|
981
|
+
const u = mod(yy - 1n);
|
|
982
|
+
const v = mod(D * yy + 1n);
|
|
983
|
+
if (v === 0n) return u === 0n;
|
|
984
|
+
const x2 = u * pow(v, P - 2n) % P;
|
|
985
|
+
return x2 === 0n || pow(x2, (P - 1n) / 2n) === 1n;
|
|
986
|
+
}
|
|
987
|
+
function keyBytes(base58) {
|
|
988
|
+
const bytes = base58Decode(base58);
|
|
989
|
+
if (!bytes || bytes.length !== 32) throw new Error("Not a valid Solana address.");
|
|
990
|
+
return bytes;
|
|
991
|
+
}
|
|
992
|
+
function findProgramAddress(seeds, programId) {
|
|
993
|
+
const program = keyBytes(programId);
|
|
994
|
+
const marker = new TextEncoder().encode("ProgramDerivedAddress");
|
|
995
|
+
for (let bump = 255; bump >= 1; bump -= 1) {
|
|
996
|
+
const parts = [...seeds, Uint8Array.of(bump), program, marker];
|
|
997
|
+
const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
998
|
+
let at = 0;
|
|
999
|
+
for (const part of parts) {
|
|
1000
|
+
buf.set(part, at);
|
|
1001
|
+
at += part.length;
|
|
1002
|
+
}
|
|
1003
|
+
const candidate = sha256(buf);
|
|
1004
|
+
if (!isOnEd25519Curve(candidate)) return candidate;
|
|
1005
|
+
}
|
|
1006
|
+
throw new Error("Could not derive a program address.");
|
|
1007
|
+
}
|
|
1008
|
+
function associatedTokenAddress(owner, mint, tokenProgram) {
|
|
1009
|
+
return base58Encode(findProgramAddress([keyBytes(owner), keyBytes(tokenProgram), keyBytes(mint)], ASSOCIATED_TOKEN_PROGRAM));
|
|
1010
|
+
}
|
|
1011
|
+
function expectedSolanaDelivery(recipient2, mint) {
|
|
1012
|
+
if (!isSolanaAddress(recipient2)) throw new Error("Not a valid Solana address.");
|
|
1013
|
+
const pinned = solanaDestinationAsset(mint);
|
|
1014
|
+
if (!pinned) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
1015
|
+
const target = pinned.bridge === "cctp" ? associatedTokenAddress(recipient2.trim(), mint.trim(), pinned.tokenProgram) : recipient2.trim();
|
|
1016
|
+
return solanaKeyHex(target);
|
|
1017
|
+
}
|
|
1018
|
+
function checkSolanaReceiver(request, intended, mint) {
|
|
1019
|
+
if (!isSolanaAddress(intended)) throw new Error("Not a valid Solana address.");
|
|
1020
|
+
if (request.destinationReceiverOwner !== intended.trim()) throw new Error("The quote was not made out to your Solana recipient; refusing to sign.");
|
|
1021
|
+
const receiver = request.destinationReceiver || "";
|
|
1022
|
+
const display = hexToSolanaKey(receiver);
|
|
1023
|
+
if (!display) throw new Error("The quote carries no Solana delivery account; refusing to sign.");
|
|
1024
|
+
if (request.destinationReceiverBase58 && request.destinationReceiverBase58 !== display) throw new Error("The quote names two different Solana delivery accounts; refusing to sign.");
|
|
1025
|
+
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.");
|
|
1026
|
+
}
|
|
1027
|
+
|
|
214
1028
|
// src/core/address.ts
|
|
215
1029
|
function symbolKey(value) {
|
|
216
1030
|
return String(value || "").trim().toUpperCase();
|
|
@@ -227,66 +1041,26 @@ function assertAddress(value, label) {
|
|
|
227
1041
|
if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label} is not a valid EVM address.`);
|
|
228
1042
|
return normalized;
|
|
229
1043
|
}
|
|
230
|
-
function resolveSwapReceiver(
|
|
1044
|
+
function resolveSwapReceiver(recipient2, payer, destinationChainId) {
|
|
231
1045
|
const payerAddr = assertAddress(payer, "Swap wallet");
|
|
232
|
-
if (
|
|
233
|
-
|
|
1046
|
+
if (isSolanaChainId(destinationChainId)) return assertChainAddress(destinationChainId, recipient2, "Deposit recipient");
|
|
1047
|
+
if (recipient2 === void 0 || recipient2 === null || recipient2 === "") return payerAddr;
|
|
1048
|
+
const normalized = normalizeAddress(recipient2);
|
|
234
1049
|
if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
|
|
235
1050
|
return normalized;
|
|
236
1051
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
function assetDecimals(token) {
|
|
240
|
-
const sym = symbolKey(token?.symbol);
|
|
241
|
-
const registry = Number(token?.decimals);
|
|
242
|
-
const canonical = CANONICAL_DECIMALS[sym];
|
|
243
|
-
if (canonical !== void 0) {
|
|
244
|
-
if (!Number.isInteger(registry)) {
|
|
245
|
-
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
246
|
-
}
|
|
247
|
-
if (registry !== canonical) {
|
|
248
|
-
throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
249
|
-
}
|
|
250
|
-
return canonical;
|
|
251
|
-
}
|
|
252
|
-
if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
|
|
253
|
-
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
254
|
-
}
|
|
255
|
-
return registry;
|
|
256
|
-
}
|
|
257
|
-
function normalizeDecimalText(value) {
|
|
258
|
-
const text = String(value || "").trim().replace(/\s+/g, "");
|
|
259
|
-
if (!text) return "";
|
|
260
|
-
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
261
|
-
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
262
|
-
if (text.includes(",")) return "";
|
|
263
|
-
return text;
|
|
1052
|
+
function isChainAddress(chainId, value) {
|
|
1053
|
+
return isSolanaChainId(chainId) ? isSolanaAddress(value) : isAddress(value);
|
|
264
1054
|
}
|
|
265
|
-
function
|
|
266
|
-
const text =
|
|
267
|
-
|
|
268
|
-
const [whole, frac = ""] = text.split(".");
|
|
269
|
-
if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
|
|
270
|
-
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
271
|
-
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
272
|
-
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
273
|
-
return value;
|
|
1055
|
+
function chainAddressKey(chainId, value) {
|
|
1056
|
+
const text = String(value || "");
|
|
1057
|
+
return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
|
|
274
1058
|
}
|
|
275
|
-
function
|
|
276
|
-
if (
|
|
277
|
-
if (
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
function formatUnits(raw, decimals, maxDecimals = 6) {
|
|
281
|
-
const value = BigInt(raw || "0");
|
|
282
|
-
const base = 10n ** BigInt(decimals);
|
|
283
|
-
const whole = value / base;
|
|
284
|
-
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
285
|
-
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
286
|
-
return frac ? `${whole}.${frac}` : whole.toString();
|
|
287
|
-
}
|
|
288
|
-
function finalOf(quote) {
|
|
289
|
-
return BigInt(quote?.finalAmount || quote?.toAmount || "0");
|
|
1059
|
+
function assertChainAddress(chainId, value, label) {
|
|
1060
|
+
if (!isSolanaChainId(chainId)) return assertAddress(value, label);
|
|
1061
|
+
if (!String(value || "").trim()) throw new Error("Connect a Solana wallet or enter a Solana recipient address.");
|
|
1062
|
+
if (!isSolanaAddress(value)) throw new Error("Not a valid Solana address.");
|
|
1063
|
+
return String(value).trim();
|
|
290
1064
|
}
|
|
291
1065
|
|
|
292
1066
|
// src/core/abi.ts
|
|
@@ -365,8 +1139,6 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
|
|
|
365
1139
|
}).join("");
|
|
366
1140
|
return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
|
|
367
1141
|
}
|
|
368
|
-
var EVM_BYTES_PAYLOAD_BYTES = 64;
|
|
369
|
-
var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
|
|
370
1142
|
var MAX_DECODED_ORDERS = 16;
|
|
371
1143
|
function decodeSubmitOrderCalldata(data) {
|
|
372
1144
|
const hex = strip0x(String(data || "")).toLowerCase();
|
|
@@ -387,12 +1159,14 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
387
1159
|
const w = word(byteOffset);
|
|
388
1160
|
return w === null || w > MAX_UINT64 ? null : w;
|
|
389
1161
|
};
|
|
390
|
-
const
|
|
1162
|
+
const keyBytesAt = (byteOffset) => {
|
|
391
1163
|
const len = word(byteOffset);
|
|
392
|
-
if (len !== 20n) return null;
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
1164
|
+
if (len !== 20n && len !== 32n) return null;
|
|
1165
|
+
const length = Number(len);
|
|
1166
|
+
const padded = Math.ceil(length / 32) * 32;
|
|
1167
|
+
const content = body.slice((byteOffset + 32) * 2, (byteOffset + 32 + padded) * 2);
|
|
1168
|
+
if (content.length !== padded * 2 || content.slice(length * 2) !== "0".repeat((padded - length) * 2)) return null;
|
|
1169
|
+
return { value: `0x${content.slice(0, length * 2)}`, size: 32 + padded };
|
|
396
1170
|
};
|
|
397
1171
|
if (word(0) !== 64n) return null;
|
|
398
1172
|
if (word(32) === null) return null;
|
|
@@ -401,12 +1175,12 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
401
1175
|
if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
|
|
402
1176
|
const n = Number(count);
|
|
403
1177
|
const arrayBase = 96;
|
|
404
|
-
|
|
1178
|
+
let next = arrayBase + 32 * n;
|
|
405
1179
|
const orders = [];
|
|
406
1180
|
for (let i = 0; i < n; i += 1) {
|
|
407
1181
|
const rel = word(arrayBase + i * 32);
|
|
408
|
-
if (rel === null || rel !== BigInt(
|
|
409
|
-
const base =
|
|
1182
|
+
if (rel === null || rel !== BigInt(next - arrayBase)) return null;
|
|
1183
|
+
const base = next;
|
|
410
1184
|
const owner = addressAt(base);
|
|
411
1185
|
const bidToken = addressAt(base + 32);
|
|
412
1186
|
const bidTokenAmount = word(base + 64);
|
|
@@ -416,14 +1190,17 @@ function decodeSubmitOrderCalldata(data) {
|
|
|
416
1190
|
const destinationChainId = uint64At(base + 192);
|
|
417
1191
|
const executionChainId = uint64At(base + 224);
|
|
418
1192
|
const deadline = uint64At(base + 256);
|
|
419
|
-
if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES
|
|
1193
|
+
if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES) {
|
|
420
1194
|
return null;
|
|
421
1195
|
}
|
|
422
|
-
const askToken =
|
|
423
|
-
|
|
1196
|
+
const askToken = keyBytesAt(base + Number(askOffset));
|
|
1197
|
+
if (!askToken || receiverOffset !== ORDER_HEAD_BYTES + BigInt(askToken.size)) return null;
|
|
1198
|
+
const destinationReceiver = keyBytesAt(base + Number(receiverOffset));
|
|
424
1199
|
if (askToken === null || destinationReceiver === null) return null;
|
|
425
|
-
|
|
1200
|
+
next = base + Number(ORDER_HEAD_BYTES) + askToken.size + destinationReceiver.size;
|
|
1201
|
+
orders.push({ owner, bidToken, bidTokenAmount, askToken: askToken.value, askTokenAmount, destinationReceiver: destinationReceiver.value, destinationChainId, executionChainId, deadline });
|
|
426
1202
|
}
|
|
1203
|
+
if (next !== totalBytes) return null;
|
|
427
1204
|
return { partnerId, orders };
|
|
428
1205
|
}
|
|
429
1206
|
function toHexQuantity(value) {
|
|
@@ -431,47 +1208,349 @@ function toHexQuantity(value) {
|
|
|
431
1208
|
return `0x${n.toString(16)}`;
|
|
432
1209
|
}
|
|
433
1210
|
|
|
434
|
-
// src/core/
|
|
435
|
-
function
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
1211
|
+
// src/core/solana-tx.ts
|
|
1212
|
+
function bytesEqual(a, b) {
|
|
1213
|
+
return a.length === b.length && a.every((v, i) => v === b[i]);
|
|
1214
|
+
}
|
|
1215
|
+
function hexBytes(hex) {
|
|
1216
|
+
const h2 = strip0x(hex);
|
|
1217
|
+
if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
|
|
1218
|
+
return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
|
|
1219
|
+
}
|
|
1220
|
+
function solanaKeyBytes(key) {
|
|
1221
|
+
if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
|
|
1222
|
+
return base58Decode(key);
|
|
1223
|
+
}
|
|
1224
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1225
|
+
function base64Decode(text) {
|
|
1226
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) throw new Error("Invalid base64.");
|
|
1227
|
+
const out = [];
|
|
1228
|
+
let value = 0, bits = 0;
|
|
1229
|
+
for (const ch of text.replace(/=+$/, "")) {
|
|
1230
|
+
value = value << 6 | B64.indexOf(ch);
|
|
1231
|
+
bits += 6;
|
|
1232
|
+
if (bits >= 8) {
|
|
1233
|
+
bits -= 8;
|
|
1234
|
+
out.push(value >> bits & 255);
|
|
1235
|
+
}
|
|
440
1236
|
}
|
|
441
|
-
|
|
442
|
-
|
|
1237
|
+
const bytes = Uint8Array.from(out);
|
|
1238
|
+
if (base64Encode(bytes) !== text) throw new Error("Noncanonical base64.");
|
|
1239
|
+
return bytes;
|
|
1240
|
+
}
|
|
1241
|
+
function base64Encode(bytes) {
|
|
1242
|
+
let out = "";
|
|
1243
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
1244
|
+
const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
|
|
1245
|
+
out += B64[n >>> 18 & 63] + B64[n >>> 12 & 63] + (i + 1 < bytes.length ? B64[n >>> 6 & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
|
|
443
1246
|
}
|
|
444
|
-
|
|
445
|
-
|
|
1247
|
+
return out;
|
|
1248
|
+
}
|
|
1249
|
+
var Reader = class {
|
|
1250
|
+
constructor(bytes) {
|
|
1251
|
+
this.bytes = bytes;
|
|
446
1252
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
1253
|
+
bytes;
|
|
1254
|
+
at = 0;
|
|
1255
|
+
take(n) {
|
|
1256
|
+
if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error("Truncated Solana data.");
|
|
1257
|
+
const v = this.bytes.slice(this.at, this.at + n);
|
|
1258
|
+
this.at += n;
|
|
1259
|
+
return v;
|
|
450
1260
|
}
|
|
451
|
-
|
|
1261
|
+
byte() {
|
|
1262
|
+
return this.take(1)[0];
|
|
1263
|
+
}
|
|
1264
|
+
compact() {
|
|
1265
|
+
let n = 0;
|
|
1266
|
+
for (let i = 0; i < 3; i++) {
|
|
1267
|
+
const b = this.byte();
|
|
1268
|
+
if (i === 2 && b > 3) throw new Error("Invalid compact-u16.");
|
|
1269
|
+
n |= (b & 127) << 7 * i;
|
|
1270
|
+
if (!(b & 128)) {
|
|
1271
|
+
if (i && b === 0) throw new Error("Noncanonical compact-u16.");
|
|
1272
|
+
return n;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
throw new Error("Invalid compact-u16.");
|
|
1276
|
+
}
|
|
1277
|
+
u64() {
|
|
1278
|
+
const b = this.take(8);
|
|
1279
|
+
let n = 0n;
|
|
1280
|
+
for (let i = 7; i >= 0; i--) n = n << 8n | BigInt(b[i]);
|
|
1281
|
+
return n;
|
|
1282
|
+
}
|
|
1283
|
+
vec() {
|
|
1284
|
+
const b = this.take(4);
|
|
1285
|
+
return this.take(new DataView(b.buffer).getUint32(0, true));
|
|
1286
|
+
}
|
|
1287
|
+
end() {
|
|
1288
|
+
if (this.at !== this.bytes.length) throw new Error("Trailing Solana data.");
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
function parseSolanaTransaction(input) {
|
|
1292
|
+
const bytes = new Uint8Array(input), r = new Reader(bytes);
|
|
1293
|
+
const count = r.compact(), signatureOffset = r.at;
|
|
1294
|
+
if (count < 1 || count > 127) throw new Error("Invalid signature count.");
|
|
1295
|
+
r.take(count * 64);
|
|
1296
|
+
const messageOffset = r.at, first = r.byte();
|
|
1297
|
+
if (first & 128 && first !== 128) throw new Error("Unsupported Solana message version.");
|
|
1298
|
+
const version = first === 128 ? 0 : "legacy";
|
|
1299
|
+
const requiredSignatures = version === 0 ? r.byte() : first;
|
|
1300
|
+
const readonlySigned = r.byte(), readonlyUnsigned = r.byte();
|
|
1301
|
+
const keyCount = r.compact();
|
|
1302
|
+
if (requiredSignatures !== count || requiredSignatures > keyCount || readonlySigned >= count || readonlyUnsigned > keyCount - count || keyCount > 256) throw new Error("Invalid Solana message header.");
|
|
1303
|
+
const staticKeys = Array.from({ length: keyCount }, () => base58Encode(r.take(32)));
|
|
1304
|
+
const blockhashOffset = r.at;
|
|
1305
|
+
r.take(32);
|
|
1306
|
+
const instructions = Array.from({ length: r.compact() }, () => {
|
|
1307
|
+
const programIdIndex = r.byte();
|
|
1308
|
+
const accounts = Array.from(r.take(r.compact()));
|
|
1309
|
+
return { programIdIndex, accounts, data: r.take(r.compact()) };
|
|
1310
|
+
});
|
|
1311
|
+
const lookups = version === 0 ? Array.from({ length: r.compact() }, () => ({
|
|
1312
|
+
address: base58Encode(r.take(32)),
|
|
1313
|
+
writable: Array.from(r.take(r.compact())),
|
|
1314
|
+
readonly: Array.from(r.take(r.compact()))
|
|
1315
|
+
})) : [];
|
|
1316
|
+
r.end();
|
|
1317
|
+
const all = keyCount + lookups.reduce((n, l) => n + l.writable.length + l.readonly.length, 0);
|
|
1318
|
+
if (all > 256 || instructions.some((ix) => ix.programIdIndex >= keyCount || ix.accounts.some((i) => i >= all))) throw new Error("Invalid Solana account index.");
|
|
1319
|
+
return { bytes, messageOffset, blockhashOffset, version, requiredSignatures, signatureOffset, staticKeys, instructions, lookups };
|
|
1320
|
+
}
|
|
1321
|
+
function serializeSolanaTransaction(tx) {
|
|
1322
|
+
return new Uint8Array(tx.bytes);
|
|
1323
|
+
}
|
|
1324
|
+
function overwriteBlockhash(input, blockhash) {
|
|
1325
|
+
const tx = parseSolanaTransaction(input), out = new Uint8Array(input);
|
|
1326
|
+
out.set(solanaKeyBytes(blockhash), tx.blockhashOffset);
|
|
1327
|
+
return out;
|
|
452
1328
|
}
|
|
453
|
-
function
|
|
454
|
-
const
|
|
455
|
-
|
|
1329
|
+
function placeSignature(input, publicKey, signature) {
|
|
1330
|
+
const tx = parseSolanaTransaction(input), index = tx.staticKeys.slice(0, tx.requiredSignatures).indexOf(publicKey);
|
|
1331
|
+
if (index < 0 || signature.length !== 64) throw new Error("Missing Solana signer slot.");
|
|
1332
|
+
const out = new Uint8Array(input);
|
|
1333
|
+
out.set(signature, tx.signatureOffset + index * 64);
|
|
1334
|
+
return out;
|
|
456
1335
|
}
|
|
457
|
-
function
|
|
458
|
-
|
|
1336
|
+
function assertWalletMessage(original, signed) {
|
|
1337
|
+
const a = parseSolanaTransaction(original), b = parseSolanaTransaction(signed);
|
|
1338
|
+
if (!bytesEqual(a.bytes.subarray(a.messageOffset), b.bytes.subarray(b.messageOffset))) throw new Error("The wallet modified the transaction message; refusing to send.");
|
|
1339
|
+
for (let i = 1; i < a.requiredSignatures; i++) {
|
|
1340
|
+
const start = a.signatureOffset + 64 * i;
|
|
1341
|
+
if (!bytesEqual(a.bytes.subarray(start, start + 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.");
|
|
1342
|
+
}
|
|
1343
|
+
if (!b.bytes.subarray(b.signatureOffset, b.signatureOffset + 64).some(Boolean)) throw new Error("The wallet returned no fee-payer signature.");
|
|
1344
|
+
}
|
|
1345
|
+
var SUBMIT_ORDER_DISCRIMINATOR = [230, 150, 200, 53, 92, 208, 109, 108];
|
|
1346
|
+
function isSubmitOrder(data) {
|
|
1347
|
+
return data.length >= 8 && SUBMIT_ORDER_DISCRIMINATOR.every((v, i) => data[i] === v);
|
|
1348
|
+
}
|
|
1349
|
+
function decodeSolanaSubmitOrder(data) {
|
|
1350
|
+
if (!isSubmitOrder(data)) throw new Error("Not a submit_order instruction.");
|
|
1351
|
+
const r = new Reader(data);
|
|
1352
|
+
r.take(8);
|
|
1353
|
+
const owner = r.take(20), askToken = r.vec();
|
|
1354
|
+
let askTokenAmount = 0n;
|
|
1355
|
+
for (const b of r.take(32)) askTokenAmount = askTokenAmount << 8n | BigInt(b);
|
|
1356
|
+
const bidTokenAmount = r.u64(), destinationReceiver = r.vec(), destinationChainId = r.u64(), executionChainId = r.u64(), deadline = r.u64();
|
|
1357
|
+
const tag = r.byte();
|
|
1358
|
+
if (tag !== 0 && tag !== 1) throw new Error("Invalid submit_order partner tag.");
|
|
1359
|
+
const partnerId = tag === 1 ? r.take(32) : null;
|
|
1360
|
+
r.end();
|
|
1361
|
+
return { owner, askToken, askTokenAmount, bidTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline, partnerId };
|
|
1362
|
+
}
|
|
1363
|
+
function verifySolanaSubmit(p, e) {
|
|
1364
|
+
const fail = (field) => {
|
|
1365
|
+
throw new Error(`Solana order mismatch (${field}); refusing to sign.`);
|
|
1366
|
+
};
|
|
1367
|
+
if (hexBytes(e.owner).length !== 20 || !bytesEqual(p.owner, hexBytes(e.owner))) fail("owner");
|
|
1368
|
+
if (!bytesEqual(p.askToken, hexBytes(e.askToken))) fail("ask token");
|
|
1369
|
+
if (p.askTokenAmount <= 0n) fail("non-positive output");
|
|
1370
|
+
if (p.askTokenAmount < BigInt(e.minAskTokenAmount)) fail("minimum received");
|
|
1371
|
+
if (p.askTokenAmount > BigInt(e.maxAskTokenAmount)) fail("maximum received");
|
|
1372
|
+
if (p.bidTokenAmount !== BigInt(e.bidTokenAmount)) fail("amount sent");
|
|
1373
|
+
if (!bytesEqual(p.destinationReceiver, hexBytes(e.destinationReceiver))) fail("receiver");
|
|
1374
|
+
if (p.destinationChainId !== BigInt(e.destinationChainId)) fail("destination chain");
|
|
1375
|
+
if (p.executionChainId !== BigInt(e.executionChainId)) fail("execution chain");
|
|
1376
|
+
if (p.deadline !== BigInt(e.deadline)) fail("deadline");
|
|
1377
|
+
if (p.partnerId !== null !== (e.partnerId !== null)) fail("subsidy marker");
|
|
1378
|
+
}
|
|
1379
|
+
var PREPARATION_INSTRUCTIONS = [
|
|
1380
|
+
{ discriminator: [225, 205, 234, 143, 17, 186, 50, 220], signer: 2 },
|
|
1381
|
+
// create_profile
|
|
1382
|
+
{ discriminator: [223, 99, 118, 101, 213, 29, 215, 137], signer: 3 },
|
|
1383
|
+
// initialize_buffer_data
|
|
1384
|
+
{ discriminator: [105, 254, 33, 182, 188, 80, 204, 204], signer: 3 },
|
|
1385
|
+
// write_buffer_data
|
|
1386
|
+
{ discriminator: [179, 249, 129, 154, 80, 167, 138, 18], signer: 3 },
|
|
1387
|
+
// finalize_buffer_data
|
|
1388
|
+
{ discriminator: [23, 25, 65, 45, 74, 9, 223, 23], signer: 2 }
|
|
1389
|
+
// close_buffer_data
|
|
1390
|
+
];
|
|
1391
|
+
var SUBMIT_SIGNER_ACCOUNT = 11;
|
|
1392
|
+
function preparationInstruction(data) {
|
|
1393
|
+
return data.length >= 8 ? PREPARATION_INSTRUCTIONS.find((p) => p.discriminator.every((byte, i) => data[i] === byte)) : void 0;
|
|
1394
|
+
}
|
|
1395
|
+
function isPreparationInstruction(data) {
|
|
1396
|
+
return preparationInstruction(data) !== void 0;
|
|
1397
|
+
}
|
|
1398
|
+
function verifySolanaTransaction(tx, expected, keys, mustSubmit) {
|
|
1399
|
+
if (tx.staticKeys[0] !== expected.signer) throw new Error("Wrong Solana fee payer; refusing to sign.");
|
|
1400
|
+
if (!mustSubmit && tx.requiredSignatures !== 1) throw new Error("Unexpected co-signer on a preparation step; refusing to sign.");
|
|
1401
|
+
let submits = 0, buffer = null;
|
|
1402
|
+
for (const ix of tx.instructions) {
|
|
1403
|
+
if (tx.staticKeys[ix.programIdIndex] !== expected.program) throw new Error("Foreign program instruction; refusing to sign.");
|
|
1404
|
+
const preparation = preparationInstruction(ix.data);
|
|
1405
|
+
if (!isSubmitOrder(ix.data) && !preparation) throw new Error("Unexpected ZeroDelta instruction; refusing to sign.");
|
|
1406
|
+
const signerSlot = preparation ? preparation.signer : SUBMIT_SIGNER_ACCOUNT;
|
|
1407
|
+
if (keys[ix.accounts[signerSlot]] !== expected.signer) throw new Error("ZeroDelta instruction names another signer; refusing to sign.");
|
|
1408
|
+
if (!isSubmitOrder(ix.data)) continue;
|
|
1409
|
+
submits++;
|
|
1410
|
+
verifySolanaSubmit(decodeSolanaSubmitOrder(ix.data), expected);
|
|
1411
|
+
if (keys[ix.accounts[1]] !== expected.mint) throw new Error("Wrong source mint; refusing to sign.");
|
|
1412
|
+
buffer = keys[ix.accounts[8]] ?? null;
|
|
1413
|
+
if (!buffer) throw new Error("Missing route buffer; refusing to sign.");
|
|
1414
|
+
}
|
|
1415
|
+
if (submits !== (mustSubmit ? 1 : 0)) throw new Error("Expected exactly one submit_order in submit and none in preparation; refusing to sign.");
|
|
1416
|
+
return buffer;
|
|
1417
|
+
}
|
|
1418
|
+
function parseAddressLookupTable(data) {
|
|
1419
|
+
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.");
|
|
1420
|
+
return Array.from({ length: (data.length - 56) / 32 }, (_, i) => base58Encode(data.subarray(56 + 32 * i, 88 + 32 * i)));
|
|
1421
|
+
}
|
|
1422
|
+
async function resolveSolanaKeys(tx, rpc) {
|
|
1423
|
+
if (!tx.lookups.length) return [...tx.staticKeys];
|
|
1424
|
+
const result = await rpc("getMultipleAccounts", [tx.lookups.map((l) => l.address), { encoding: "base64", commitment: "confirmed" }]);
|
|
1425
|
+
if (!Array.isArray(result.value) || result.value.length !== tx.lookups.length) throw new Error("Missing lookup tables.");
|
|
1426
|
+
const writable = [], readonly = [];
|
|
1427
|
+
tx.lookups.forEach((lookup, i) => {
|
|
1428
|
+
const account = result.value[i];
|
|
1429
|
+
if (account?.owner !== "AddressLookupTab1e1111111111111111111111111" || account.data[1] !== "base64") throw new Error("Invalid lookup table account.");
|
|
1430
|
+
const table = parseAddressLookupTable(base64Decode(account.data[0]));
|
|
1431
|
+
for (const [indexes, into] of [[lookup.writable, writable], [lookup.readonly, readonly]]) for (const index of indexes) {
|
|
1432
|
+
if (!table[index]) throw new Error("Lookup table index out of range.");
|
|
1433
|
+
into.push(table[index]);
|
|
1434
|
+
}
|
|
1435
|
+
});
|
|
1436
|
+
return [...tx.staticKeys, ...writable, ...readonly];
|
|
1437
|
+
}
|
|
1438
|
+
function encodeNextSolanaOrders(legs) {
|
|
1439
|
+
return legs.length ? hexBytes(`0x${uintWord(32)}${encodeSubmitOrder(legs).slice(10 + 128)}`) : new Uint8Array();
|
|
1440
|
+
}
|
|
1441
|
+
function checkSolanaRouteBuffer(account, expected) {
|
|
1442
|
+
if (!account || account.owner !== expected.program || account.data[1] !== "base64") throw new Error("Route buffer is not a ZeroDelta account.");
|
|
1443
|
+
const d = base64Decode(account.data[0]);
|
|
1444
|
+
if (d.length < 53) throw new Error("Route buffer truncated.");
|
|
1445
|
+
if (base58Encode(d.subarray(9, 41)) !== expected.signer) throw new Error("Route buffer signer mismatch.");
|
|
1446
|
+
const len = new DataView(d.buffer, d.byteOffset + 49, 4).getUint32(0, true);
|
|
1447
|
+
if (d.length < 53 + len || !bytesEqual(d.subarray(53, 53 + len), encodeNextSolanaOrders(expected.nextOrders))) throw new Error("Route buffer legs mismatch.");
|
|
1448
|
+
}
|
|
1449
|
+
function checkSolanaProgram(gateway, pinned, registry) {
|
|
1450
|
+
const program = gateway || registry || "";
|
|
1451
|
+
solanaKeyBytes(program);
|
|
1452
|
+
if (pinned ? program !== pinned : gateway && registry && gateway !== registry) throw new Error("Solana program does not match pin or chains registry.");
|
|
1453
|
+
return program;
|
|
1454
|
+
}
|
|
1455
|
+
function checkSolanaPlan(txs) {
|
|
1456
|
+
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.");
|
|
1457
|
+
}
|
|
1458
|
+
async function deriveSolanaEvent(signer, salt) {
|
|
1459
|
+
const s = hexBytes(salt), material = new Uint8Array(32 + s.length);
|
|
1460
|
+
material.set(solanaKeyBytes(signer));
|
|
1461
|
+
material.set(s, 32);
|
|
1462
|
+
const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", material));
|
|
1463
|
+
const { eventPublicKey: eventPublicKey2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
|
|
1464
|
+
return { seed, publicKey: base58Encode(await eventPublicKey2(seed)) };
|
|
1465
|
+
}
|
|
1466
|
+
async function cosignSolanaEvent(bytes, signer, build) {
|
|
1467
|
+
const event = await deriveSolanaEvent(signer, build.salt);
|
|
1468
|
+
if (event.publicKey !== build.messageSentEventData) throw new Error("Event buildData key mismatch; refusing to sign.");
|
|
1469
|
+
const tx = parseSolanaTransaction(bytes);
|
|
1470
|
+
const { eventSignature: eventSignature2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
|
|
1471
|
+
return placeSignature(bytes, event.publicKey, await eventSignature2(tx.bytes.subarray(tx.messageOffset), event.seed));
|
|
1472
|
+
}
|
|
1473
|
+
async function pollSolanaConfirmation(rpc, signature) {
|
|
1474
|
+
const deadline = Date.now() + 9e4;
|
|
1475
|
+
while (Date.now() < deadline) {
|
|
1476
|
+
const { value } = await rpc("getSignatureStatuses", [[signature]]);
|
|
1477
|
+
const status = value?.[0];
|
|
1478
|
+
if (status?.err) throw new Error(`Transaction failed on chain: ${JSON.stringify(status.err)}`);
|
|
1479
|
+
if (["confirmed", "finalized"].includes(status?.confirmationStatus)) return;
|
|
1480
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
1481
|
+
}
|
|
1482
|
+
throw new Error("Transaction confirmation timed out; check the signature before retrying.");
|
|
459
1483
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
1484
|
+
|
|
1485
|
+
// src/core/units.ts
|
|
1486
|
+
function assetDecimals(token) {
|
|
1487
|
+
const sym = symbolKey(token?.symbol);
|
|
1488
|
+
const registry = Number(token?.decimals);
|
|
1489
|
+
const canonical = isSolanaChainId(token?.chainId) ? solanaDestinationAsset(token?.address)?.decimals : CANONICAL_DECIMALS[sym];
|
|
1490
|
+
if (canonical !== void 0) {
|
|
1491
|
+
if (!Number.isInteger(registry)) {
|
|
1492
|
+
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
1493
|
+
}
|
|
1494
|
+
if (registry !== canonical) {
|
|
1495
|
+
throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
1496
|
+
}
|
|
1497
|
+
return canonical;
|
|
465
1498
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
1499
|
+
if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
|
|
1500
|
+
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
1501
|
+
}
|
|
1502
|
+
return registry;
|
|
469
1503
|
}
|
|
470
|
-
function
|
|
471
|
-
const
|
|
472
|
-
if (
|
|
473
|
-
if (
|
|
474
|
-
|
|
1504
|
+
function normalizeDecimalText(value) {
|
|
1505
|
+
const text = String(value || "").trim().replace(/\s+/g, "");
|
|
1506
|
+
if (!text) return "";
|
|
1507
|
+
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
1508
|
+
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
1509
|
+
if (text.includes(",")) return "";
|
|
1510
|
+
return text;
|
|
1511
|
+
}
|
|
1512
|
+
function parseUnitsDecimal(amount, decimals) {
|
|
1513
|
+
const text = normalizeDecimalText(amount);
|
|
1514
|
+
if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
|
|
1515
|
+
const [whole, frac = ""] = text.split(".");
|
|
1516
|
+
if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
|
|
1517
|
+
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
1518
|
+
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
1519
|
+
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
1520
|
+
return value;
|
|
1521
|
+
}
|
|
1522
|
+
function scaleDecimals(amount, fromDecimals, toDecimals) {
|
|
1523
|
+
if (toDecimals === fromDecimals) return amount;
|
|
1524
|
+
if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
|
1525
|
+
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
1526
|
+
}
|
|
1527
|
+
function formatUnits(raw2, decimals, maxDecimals = 6) {
|
|
1528
|
+
const value = BigInt(raw2 || "0");
|
|
1529
|
+
const base = 10n ** BigInt(decimals);
|
|
1530
|
+
const whole = value / base;
|
|
1531
|
+
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
1532
|
+
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
1533
|
+
return frac ? `${whole}.${frac}` : whole.toString();
|
|
1534
|
+
}
|
|
1535
|
+
function finalOf(quote) {
|
|
1536
|
+
return BigInt(quote?.finalAmount || quote?.toAmount || "0");
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
// src/core/ask-scale.ts
|
|
1540
|
+
function askTokenDecimals(quote, tokens, _from, to) {
|
|
1541
|
+
const requests = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
|
|
1542
|
+
const execution = Number(requests[requests.length - 1]?.executionChainId || quote.executionChainId);
|
|
1543
|
+
if (!Number.isSafeInteger(execution) || execution <= 0) throw new Error("Could not verify the quote amount precision.");
|
|
1544
|
+
if (execution === Number(to.chainId)) return assetDecimals(to);
|
|
1545
|
+
const row = tokens.find((token) => Number(token.chainId) === execution && symbolKey(token.symbol) === symbolKey(to.symbol));
|
|
1546
|
+
if (row) return assetDecimals(row);
|
|
1547
|
+
if (isSolanaChainId(to.chainId)) throw new Error("Could not verify the quote amount precision.");
|
|
1548
|
+
return assetDecimals(to);
|
|
1549
|
+
}
|
|
1550
|
+
function askCovers(ask, final, askDecimals, finalDecimals) {
|
|
1551
|
+
if (![askDecimals, finalDecimals].every((n) => Number.isInteger(n) && n >= 0 && n <= 36)) throw new Error("Could not verify the quote amount precision.");
|
|
1552
|
+
const shift = askDecimals - finalDecimals;
|
|
1553
|
+
return shift >= 0 ? ask >= final * 10n ** BigInt(shift) : ask * 10n ** BigInt(-shift) >= final;
|
|
475
1554
|
}
|
|
476
1555
|
|
|
477
1556
|
// src/core/ticker.ts
|
|
@@ -512,7 +1591,7 @@ function counterpartTokens(tokens, selected) {
|
|
|
512
1591
|
return tokens.filter((token) => assetClassOf(token.symbol) === want);
|
|
513
1592
|
}
|
|
514
1593
|
function tokenKey(chainId, address) {
|
|
515
|
-
return `${Number(chainId)}:${
|
|
1594
|
+
return `${Number(chainId)}:${chainAddressKey(chainId, address)}`;
|
|
516
1595
|
}
|
|
517
1596
|
function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
|
|
518
1597
|
return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
|
|
@@ -598,7 +1677,7 @@ function buildCatalogue(input) {
|
|
|
598
1677
|
const id = Number(route.toChainId);
|
|
599
1678
|
if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
|
|
600
1679
|
}
|
|
601
|
-
const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
|
|
1680
|
+
const allowed = tokens.filter((token) => token.isEnabled !== false && isChainAddress(token.chainId, token.address) && allowedAssets.has(symbolKey(token.symbol)));
|
|
602
1681
|
const projectedCatalogue = allowed.filter((token) => {
|
|
603
1682
|
if (!chainIds.has(Number(token.chainId))) return false;
|
|
604
1683
|
if (product === "rwa") return true;
|
|
@@ -632,23 +1711,23 @@ function buildCatalogue(input) {
|
|
|
632
1711
|
|
|
633
1712
|
// src/core/options.ts
|
|
634
1713
|
function chainNameOf(chainId, chains) {
|
|
635
|
-
const
|
|
636
|
-
return
|
|
1714
|
+
const chain2 = chains.find((item) => Number(item.chainId) === Number(chainId));
|
|
1715
|
+
return chain2?.displayName || chain2?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
|
|
637
1716
|
}
|
|
638
1717
|
function chainById(chains, chainId) {
|
|
639
|
-
return chains.find((
|
|
1718
|
+
return chains.find((chain2) => Number(chain2.chainId) === Number(chainId)) || null;
|
|
640
1719
|
}
|
|
641
1720
|
function isDeliverable(symbol, chainId) {
|
|
642
1721
|
if (Number(chainId) === 8453 && symbolKey(symbol) === "USDT") return false;
|
|
643
1722
|
return true;
|
|
644
1723
|
}
|
|
645
|
-
function chainSelectable(
|
|
1724
|
+
function chainSelectable(chain2, chainId) {
|
|
646
1725
|
if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
|
|
647
|
-
if (!
|
|
648
|
-
return
|
|
1726
|
+
if (!chain2) return true;
|
|
1727
|
+
return chain2.isEnabled !== false;
|
|
649
1728
|
}
|
|
650
1729
|
function tokenEnabled(token) {
|
|
651
|
-
return token?.isEnabled !== false &&
|
|
1730
|
+
return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
|
|
652
1731
|
}
|
|
653
1732
|
function findToken(tokens, chainId, symbol) {
|
|
654
1733
|
const key = symbolKey(symbol);
|
|
@@ -684,8 +1763,8 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
684
1763
|
for (const token of universe) {
|
|
685
1764
|
if (!tokenEnabled(token)) continue;
|
|
686
1765
|
const chainId = Number(token.chainId);
|
|
687
|
-
const
|
|
688
|
-
if (!chainSelectable(
|
|
1766
|
+
const chain2 = chainById(chains, chainId);
|
|
1767
|
+
if (!chainSelectable(chain2, chainId)) continue;
|
|
689
1768
|
const key = tokenKey(chainId, token.address);
|
|
690
1769
|
if (seen.has(key)) continue;
|
|
691
1770
|
if (refusal(token)) continue;
|
|
@@ -725,12 +1804,477 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
725
1804
|
return options;
|
|
726
1805
|
}
|
|
727
1806
|
|
|
1807
|
+
// src/core/solana-source.ts
|
|
1808
|
+
var CANONICAL_SOLANA_PROGRAM = "zd1E5feCJLNYaPPsBAYkCPMKGVnipYf8God9h917W33";
|
|
1809
|
+
var MAX_ASK_OVER_FINAL_BPS = 200n;
|
|
1810
|
+
var states = /* @__PURE__ */ new WeakMap();
|
|
1811
|
+
var quoteRequests = /* @__PURE__ */ new WeakMap();
|
|
1812
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
1813
|
+
var activeSigners = /* @__PURE__ */ new Set();
|
|
1814
|
+
var clone = (value) => JSON.parse(JSON.stringify(value));
|
|
1815
|
+
function freeze(value) {
|
|
1816
|
+
if (value && typeof value === "object") {
|
|
1817
|
+
for (const v of Object.values(value)) freeze(v);
|
|
1818
|
+
Object.freeze(value);
|
|
1819
|
+
}
|
|
1820
|
+
return value;
|
|
1821
|
+
}
|
|
1822
|
+
function raw(value, label, positive = false) {
|
|
1823
|
+
if (typeof value !== "string" || !/^\d+$/.test(value) || positive && BigInt(value) <= 0n || BigInt(value) >= 1n << 256n) throw new Error(`Invalid ${label}.`);
|
|
1824
|
+
return value;
|
|
1825
|
+
}
|
|
1826
|
+
function chain(value) {
|
|
1827
|
+
const text = String(value);
|
|
1828
|
+
if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) >= 1n << 64n) throw new Error("Invalid order chain.");
|
|
1829
|
+
return text;
|
|
1830
|
+
}
|
|
1831
|
+
function same(a, b) {
|
|
1832
|
+
return a.toLowerCase() === b.toLowerCase();
|
|
1833
|
+
}
|
|
1834
|
+
function recipient(input) {
|
|
1835
|
+
const to = input.recipient || (isSolanaChainId(input.toChainId) ? input.sender : input.owner);
|
|
1836
|
+
if (!isChainAddress(input.toChainId, to)) throw new Error("Invalid destination recipient.");
|
|
1837
|
+
return chainAddressKey(input.toChainId, to);
|
|
1838
|
+
}
|
|
1839
|
+
function validateInput(input) {
|
|
1840
|
+
if (input.fromChainId !== void 0 && input.fromChainId !== SOLANA_CHAIN_ID) throw new Error("Solana source chain required.");
|
|
1841
|
+
if (!Number.isSafeInteger(input.toChainId) || input.toChainId <= 0) throw new Error("Invalid destination chain.");
|
|
1842
|
+
if (!SUPPORTED_ASSETS.has(symbolKey(input.fromToken)) || !SUPPORTED_ASSETS.has(symbolKey(input.toToken))) throw new Error("Unsupported Solana source asset.");
|
|
1843
|
+
assertAddress(input.owner, "EVM order owner");
|
|
1844
|
+
solanaKeyBytes(input.sender);
|
|
1845
|
+
recipient(input);
|
|
1846
|
+
const span = input.deadlineSpanSeconds ?? 7200, slip = input.slippageBps ?? 0;
|
|
1847
|
+
if (!Number.isInteger(span) || span < 1 || span > 86400) throw new Error("Invalid Solana deadline span.");
|
|
1848
|
+
if (!Number.isInteger(slip) || slip < 0 || slip > 1e4) throw new Error("Invalid slippage tolerance.");
|
|
1849
|
+
}
|
|
1850
|
+
function selections(input, tokens) {
|
|
1851
|
+
validateInput(input);
|
|
1852
|
+
const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
|
|
1853
|
+
if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
|
|
1854
|
+
solanaKeyBytes(from.address);
|
|
1855
|
+
assertPinnedSolanaSource(from);
|
|
1856
|
+
if (!isChainAddress(input.toChainId, to.address)) throw new Error("Invalid destination token.");
|
|
1857
|
+
const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
|
|
1858
|
+
raw(amount, "input amount", true);
|
|
1859
|
+
if (BigInt(amount) >= 1n << 64n) throw new Error("Solana bid exceeds u64.");
|
|
1860
|
+
return { from, to, amount };
|
|
1861
|
+
}
|
|
1862
|
+
function assertPinnedSolanaSource(token) {
|
|
1863
|
+
const pinned = solanaDestinationAsset(token.address);
|
|
1864
|
+
if (!pinned || pinned.symbol !== symbolKey(token.symbol) || pinned.decimals !== Number(token.decimals)) {
|
|
1865
|
+
throw new Error("This Solana token is not supported for payment; refusing to sign.");
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
function makeRequest(input, from, to, amount) {
|
|
1869
|
+
return {
|
|
1870
|
+
inputChain: SOLANA_CHAIN_ID,
|
|
1871
|
+
outputChain: input.toChainId,
|
|
1872
|
+
inputToken: from.symbol,
|
|
1873
|
+
outputToken: to.symbol,
|
|
1874
|
+
inputAmount: amount,
|
|
1875
|
+
owners: { evm: input.owner },
|
|
1876
|
+
destinationWallet: recipient(input),
|
|
1877
|
+
sender: input.sender,
|
|
1878
|
+
deadline: String(Math.floor(Date.now() / 1e3) + (input.deadlineSpanSeconds ?? 7200))
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
function normalizePreview(request, quote, to, amount) {
|
|
1882
|
+
const option = quote?.options?.[0];
|
|
1883
|
+
if (!option) throw new Error("Native quote returned no options.");
|
|
1884
|
+
const receive = raw(option.finalAmount, "quoted output", true);
|
|
1885
|
+
return {
|
|
1886
|
+
receive: formatUnits(receive, assetDecimals(to)),
|
|
1887
|
+
receiveRaw: receive,
|
|
1888
|
+
fromAmount: amount,
|
|
1889
|
+
fromToken: request.inputToken,
|
|
1890
|
+
toToken: request.outputToken,
|
|
1891
|
+
bridge: option.bridge || "",
|
|
1892
|
+
feeBps: Number(option.feeBps || 0),
|
|
1893
|
+
estimatedDuration: Number(option.estimatedTimeSec || 0),
|
|
1894
|
+
via: null,
|
|
1895
|
+
nativeFeeRaw: String(option.gasCostSource || "0"),
|
|
1896
|
+
quote,
|
|
1897
|
+
option,
|
|
1898
|
+
txData: option.txData,
|
|
1899
|
+
request
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
async function quoteSolanaSource(api, input) {
|
|
1903
|
+
const { from, to, amount } = selections(input, await api.fetchTokens());
|
|
1904
|
+
const request = makeRequest(input, from, to, amount);
|
|
1905
|
+
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
1906
|
+
const preview = normalizePreview(request, quote, to, input.amountIn);
|
|
1907
|
+
quoteRequests.set(preview, { api, request: clone(request) });
|
|
1908
|
+
return preview;
|
|
1909
|
+
}
|
|
1910
|
+
async function previewSolanaSource(api, input) {
|
|
1911
|
+
const tokens = await api.fetchTokens();
|
|
1912
|
+
const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
|
|
1913
|
+
if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
|
|
1914
|
+
assertPinnedSolanaSource(from);
|
|
1915
|
+
const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
|
|
1916
|
+
raw(amount, "input amount", true);
|
|
1917
|
+
const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
|
|
1918
|
+
const request = body;
|
|
1919
|
+
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
1920
|
+
const option = quote?.options?.[0];
|
|
1921
|
+
if (!option) throw new Error("Native quote returned no options.");
|
|
1922
|
+
const receive = raw(option.finalAmount, "quoted output", true);
|
|
1923
|
+
return {
|
|
1924
|
+
receive: formatUnits(receive, assetDecimals(to)),
|
|
1925
|
+
receiveRaw: receive,
|
|
1926
|
+
fromAmount: input.amountIn,
|
|
1927
|
+
fromToken: request.inputToken,
|
|
1928
|
+
toToken: request.outputToken,
|
|
1929
|
+
bridge: option.bridge || "",
|
|
1930
|
+
feeBps: Number(option.feeBps || 0),
|
|
1931
|
+
estimatedDuration: Number(option.estimatedTimeSec || 0),
|
|
1932
|
+
via: null,
|
|
1933
|
+
nativeFeeRaw: "0"
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
function denied(value) {
|
|
1937
|
+
return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
|
|
1938
|
+
}
|
|
1939
|
+
async function checkActiveScreens(api, input) {
|
|
1940
|
+
const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
|
|
1941
|
+
const screens = await Promise.all(addresses.map(async (address) => {
|
|
1942
|
+
try {
|
|
1943
|
+
return await api.screenWallet(address);
|
|
1944
|
+
} catch {
|
|
1945
|
+
return void 0;
|
|
1946
|
+
}
|
|
1947
|
+
}));
|
|
1948
|
+
if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
|
|
1949
|
+
}
|
|
1950
|
+
function jsonGuards(input, preview, tokens, chains) {
|
|
1951
|
+
const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
|
|
1952
|
+
const wanted = makeRequest(input, from, to, amount);
|
|
1953
|
+
for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
|
|
1954
|
+
if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
|
|
1955
|
+
}
|
|
1956
|
+
if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
|
|
1957
|
+
const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
|
|
1958
|
+
if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
|
|
1959
|
+
if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
|
|
1960
|
+
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.");
|
|
1961
|
+
if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
|
|
1962
|
+
if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
|
|
1963
|
+
if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
|
|
1964
|
+
if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
|
|
1965
|
+
checkSolanaPlan(option.txData);
|
|
1966
|
+
const orders = option.orderRequests;
|
|
1967
|
+
if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
|
|
1968
|
+
const first = orders[0], last = orders[orders.length - 1];
|
|
1969
|
+
if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
|
|
1970
|
+
if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
|
|
1971
|
+
const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
|
|
1972
|
+
if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
|
|
1973
|
+
if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
|
|
1974
|
+
for (let i = 0; i < orders.length; i++) {
|
|
1975
|
+
const order = orders[i];
|
|
1976
|
+
if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
|
|
1977
|
+
raw(order.askTokenAmount, "ask amount", true);
|
|
1978
|
+
raw(order.bidTokenAmount, "bid amount", true);
|
|
1979
|
+
chain(order.destinationChainId);
|
|
1980
|
+
chain(order.executionChainId);
|
|
1981
|
+
if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
|
|
1982
|
+
if (isSolanaChainId(order.destinationChainId)) {
|
|
1983
|
+
if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
|
|
1984
|
+
solanaBridgeOf(to);
|
|
1985
|
+
checkSolanaReceiver(order, recipient(input), to.address);
|
|
1986
|
+
} else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
|
|
1987
|
+
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.");
|
|
1988
|
+
if (i) {
|
|
1989
|
+
const previous = orders[i - 1];
|
|
1990
|
+
if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
|
|
1991
|
+
if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
const quoteForScale = { ...option, orderRequests: orders };
|
|
1995
|
+
const execution = Number(last.executionChainId);
|
|
1996
|
+
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.");
|
|
1997
|
+
const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
|
|
1998
|
+
const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
|
|
1999
|
+
const minFinal = final * (10000n - slip) / 10000n;
|
|
2000
|
+
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.");
|
|
2001
|
+
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.");
|
|
2002
|
+
const registry = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
|
|
2003
|
+
const contracts = registry?.contracts;
|
|
2004
|
+
const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry?.escrowContract);
|
|
2005
|
+
const marker = option.partnerId ?? preview.quote.partnerId;
|
|
2006
|
+
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.");
|
|
2007
|
+
const ask = BigInt(first.askTokenAmount);
|
|
2008
|
+
return {
|
|
2009
|
+
program,
|
|
2010
|
+
signer: input.sender,
|
|
2011
|
+
mint: from.address,
|
|
2012
|
+
owner: input.owner,
|
|
2013
|
+
askToken: first.askToken,
|
|
2014
|
+
minAskTokenAmount: ask.toString(),
|
|
2015
|
+
maxAskTokenAmount: ask.toString(),
|
|
2016
|
+
bidTokenAmount: amount,
|
|
2017
|
+
destinationReceiver: first.destinationReceiver,
|
|
2018
|
+
destinationChainId: String(first.destinationChainId),
|
|
2019
|
+
executionChainId: String(first.executionChainId),
|
|
2020
|
+
deadline: request.deadline,
|
|
2021
|
+
partnerId: marker == null ? null : String(marker),
|
|
2022
|
+
nextOrders: orders.slice(1)
|
|
2023
|
+
};
|
|
2024
|
+
}
|
|
2025
|
+
async function buildSolanaSourcePlan(api, input, quoted) {
|
|
2026
|
+
const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
|
|
2027
|
+
const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
|
|
2028
|
+
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.");
|
|
2029
|
+
const preview = clone(served);
|
|
2030
|
+
const expected = jsonGuards(input, preview, tokens, chains);
|
|
2031
|
+
await checkActiveScreens(api, input);
|
|
2032
|
+
const plan = freeze({ preview, expected, txData: preview.option.txData });
|
|
2033
|
+
const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
|
|
2034
|
+
states.set(plan, {
|
|
2035
|
+
api,
|
|
2036
|
+
input: clone(input),
|
|
2037
|
+
plan,
|
|
2038
|
+
failed: false,
|
|
2039
|
+
busy: false,
|
|
2040
|
+
originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
|
|
2041
|
+
signatures: [],
|
|
2042
|
+
done: 0
|
|
2043
|
+
});
|
|
2044
|
+
return plan;
|
|
2045
|
+
}
|
|
2046
|
+
function createSolanaRpc(api) {
|
|
2047
|
+
return async (method, params) => {
|
|
2048
|
+
const body = await api.apiRequest("/solana-rpc", {
|
|
2049
|
+
method: "POST",
|
|
2050
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
2051
|
+
timeoutMs: 15e3
|
|
2052
|
+
});
|
|
2053
|
+
if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
|
|
2054
|
+
return body.result;
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
var SolanaSendError = class extends Error {
|
|
2058
|
+
constructor(message, signature, sentAt) {
|
|
2059
|
+
super(message);
|
|
2060
|
+
this.signature = signature;
|
|
2061
|
+
this.sentAt = sentAt;
|
|
2062
|
+
this.name = "SolanaSendError";
|
|
2063
|
+
}
|
|
2064
|
+
signature;
|
|
2065
|
+
sentAt;
|
|
2066
|
+
};
|
|
2067
|
+
async function executeSolanaPlan(input) {
|
|
2068
|
+
const signature = await runSolanaPlan(input, false);
|
|
2069
|
+
if (!signature) throw new Error("Missing final Solana submit.");
|
|
2070
|
+
return signature;
|
|
2071
|
+
}
|
|
2072
|
+
async function executeSolanaPlanStaged(input) {
|
|
2073
|
+
const signature = await runSolanaPlan(input, true);
|
|
2074
|
+
return signature ? { status: "sent", signature } : { status: "prepared" };
|
|
2075
|
+
}
|
|
2076
|
+
function solanaPlanNeedsPreparation(plan) {
|
|
2077
|
+
const state = states.get(plan);
|
|
2078
|
+
const live = state?.plan ?? plan;
|
|
2079
|
+
return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
|
|
2080
|
+
}
|
|
2081
|
+
async function runSolanaPlan(input, stopBeforeSubmit) {
|
|
2082
|
+
const state = states.get(input.plan);
|
|
2083
|
+
if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
|
|
2084
|
+
if (state.sent) return state.sent;
|
|
2085
|
+
if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
|
|
2086
|
+
if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
|
|
2087
|
+
state.busy = true;
|
|
2088
|
+
activeSigners.add(input.signer.publicKey);
|
|
2089
|
+
let index = 0, completedBeforeRun = state.signatures.length;
|
|
2090
|
+
const progress = (stage) => {
|
|
2091
|
+
const pending = inFlight.get(input.signer.publicKey);
|
|
2092
|
+
try {
|
|
2093
|
+
input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
|
|
2094
|
+
} catch {
|
|
2095
|
+
}
|
|
2096
|
+
};
|
|
2097
|
+
try {
|
|
2098
|
+
progress("preparing");
|
|
2099
|
+
const pending = inFlight.get(input.signer.publicKey);
|
|
2100
|
+
if (pending) {
|
|
2101
|
+
const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
|
|
2102
|
+
const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
|
|
2103
|
+
if (status?.err) inFlight.delete(input.signer.publicKey);
|
|
2104
|
+
else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
|
|
2105
|
+
inFlight.delete(input.signer.publicKey);
|
|
2106
|
+
if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
|
|
2107
|
+
if (pending.final) {
|
|
2108
|
+
pending.state.sent = pending.signature;
|
|
2109
|
+
reportSolana(pending.state, pending.signature);
|
|
2110
|
+
if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
|
|
2111
|
+
progress("sent");
|
|
2112
|
+
return pending.signature;
|
|
2113
|
+
}
|
|
2114
|
+
} else {
|
|
2115
|
+
if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
|
|
2116
|
+
throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
|
|
2117
|
+
}
|
|
2118
|
+
inFlight.delete(input.signer.publicKey);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
if (state.failed) {
|
|
2122
|
+
const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
|
|
2123
|
+
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.");
|
|
2124
|
+
state.plan = retried;
|
|
2125
|
+
state.done = 0;
|
|
2126
|
+
state.failed = false;
|
|
2127
|
+
}
|
|
2128
|
+
const plan = state.plan;
|
|
2129
|
+
checkSolanaPlan(plan.txData);
|
|
2130
|
+
for (const tx of plan.txData) {
|
|
2131
|
+
const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
|
|
2132
|
+
verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
|
|
2133
|
+
}
|
|
2134
|
+
for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
|
|
2135
|
+
completedBeforeRun = state.signatures.length;
|
|
2136
|
+
const startAt = state.done;
|
|
2137
|
+
for (index = startAt; index < plan.txData.length; index++) {
|
|
2138
|
+
if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
|
|
2139
|
+
progress("ready");
|
|
2140
|
+
return null;
|
|
2141
|
+
}
|
|
2142
|
+
if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
|
|
2143
|
+
await checkActiveScreens(state.api, state.input);
|
|
2144
|
+
const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
|
|
2145
|
+
const keys = await resolveSolanaKeys(parsed, input.rpc);
|
|
2146
|
+
const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
|
|
2147
|
+
if (buffer) {
|
|
2148
|
+
const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
|
|
2149
|
+
checkSolanaRouteBuffer(account.value, plan.expected);
|
|
2150
|
+
}
|
|
2151
|
+
const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
|
|
2152
|
+
let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
|
|
2153
|
+
if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
|
|
2154
|
+
verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
|
|
2155
|
+
progress("signing");
|
|
2156
|
+
const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
|
|
2157
|
+
assertWalletMessage(bytes, signed);
|
|
2158
|
+
verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
|
|
2159
|
+
const signedTx = parseSolanaTransaction(signed);
|
|
2160
|
+
const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
|
|
2161
|
+
const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
|
|
2162
|
+
inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
|
|
2163
|
+
progress("sending");
|
|
2164
|
+
try {
|
|
2165
|
+
const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
|
|
2166
|
+
if (returned !== signature) throw new Error("RPC returned a different signature.");
|
|
2167
|
+
if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
|
|
2168
|
+
} catch (error) {
|
|
2169
|
+
throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
|
|
2170
|
+
}
|
|
2171
|
+
inFlight.delete(input.signer.publicKey);
|
|
2172
|
+
state.signatures.push(signature);
|
|
2173
|
+
state.done = index + 1;
|
|
2174
|
+
if (tx.actionType === "submit") {
|
|
2175
|
+
state.sent = signature;
|
|
2176
|
+
reportSolana(state, signature);
|
|
2177
|
+
progress("sent");
|
|
2178
|
+
return signature;
|
|
2179
|
+
}
|
|
2180
|
+
progress("ready");
|
|
2181
|
+
}
|
|
2182
|
+
throw new Error("Missing final Solana submit.");
|
|
2183
|
+
} catch (error) {
|
|
2184
|
+
state.failed = true;
|
|
2185
|
+
progress("failed");
|
|
2186
|
+
throw error;
|
|
2187
|
+
} finally {
|
|
2188
|
+
state.busy = false;
|
|
2189
|
+
activeSigners.delete(input.signer.publicKey);
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
function reportSolana(state, signature) {
|
|
2193
|
+
try {
|
|
2194
|
+
void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
|
|
2195
|
+
});
|
|
2196
|
+
} catch {
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
async function readSolanaBalance(rpc, owner, mint) {
|
|
2200
|
+
try {
|
|
2201
|
+
solanaKeyBytes(owner);
|
|
2202
|
+
solanaKeyBytes(mint);
|
|
2203
|
+
const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
|
|
2204
|
+
if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
|
|
2205
|
+
let total = 0n, decimals;
|
|
2206
|
+
for (const item of result.value) {
|
|
2207
|
+
const amount = item.account?.data?.parsed?.info?.tokenAmount;
|
|
2208
|
+
if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
|
|
2209
|
+
decimals = amount.decimals;
|
|
2210
|
+
total += BigInt(raw(amount.amount, "token balance"));
|
|
2211
|
+
}
|
|
2212
|
+
return total;
|
|
2213
|
+
} catch {
|
|
2214
|
+
return void 0;
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
async function simulateSolanaCost(rpc, plan) {
|
|
2218
|
+
checkSolanaPlan(plan.txData);
|
|
2219
|
+
const signer = plan.expected.signer;
|
|
2220
|
+
const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
|
|
2221
|
+
const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
|
|
2222
|
+
if (sim.value?.err) throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
|
|
2223
|
+
const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
|
|
2224
|
+
if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
|
|
2225
|
+
const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
|
|
2226
|
+
return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
|
|
2227
|
+
}
|
|
2228
|
+
|
|
2229
|
+
// src/core/escrow.ts
|
|
2230
|
+
function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
|
|
2231
|
+
const fromQuote = normalizeAddress(quoteEscrow);
|
|
2232
|
+
const fromChains = normalizeAddress(chainsEscrow);
|
|
2233
|
+
if (!fromChains || fromChains === ZERO_ADDRESS) {
|
|
2234
|
+
throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
|
|
2235
|
+
}
|
|
2236
|
+
if (!fromQuote || fromQuote === ZERO_ADDRESS) {
|
|
2237
|
+
throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
|
|
2238
|
+
}
|
|
2239
|
+
if (fromQuote !== fromChains) {
|
|
2240
|
+
throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
|
|
2241
|
+
}
|
|
2242
|
+
const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
|
|
2243
|
+
if (pinned && pinned !== fromChains) {
|
|
2244
|
+
throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
|
|
2245
|
+
}
|
|
2246
|
+
return fromChains;
|
|
2247
|
+
}
|
|
2248
|
+
function isLayerZeroRoute(quote, option = {}) {
|
|
2249
|
+
const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
|
|
2250
|
+
return bridge.includes("layerzero") || bridge.includes("layer zero");
|
|
2251
|
+
}
|
|
2252
|
+
function sourceAssetKey(quote, option = {}) {
|
|
2253
|
+
return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
|
|
2254
|
+
}
|
|
2255
|
+
function requiresNativeBridgeFee(quote, option = {}) {
|
|
2256
|
+
const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
|
|
2257
|
+
const execChainId = Number(quote?.executionChainId);
|
|
2258
|
+
if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
|
|
2259
|
+
return false;
|
|
2260
|
+
}
|
|
2261
|
+
const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
|
|
2262
|
+
if (canonical) return canonical === "layerzero";
|
|
2263
|
+
return isLayerZeroRoute(quote, option);
|
|
2264
|
+
}
|
|
2265
|
+
function applyLayerZeroBuffer(quote, option = {}) {
|
|
2266
|
+
const gas = BigInt(quote?.gasCostSource || "0");
|
|
2267
|
+
if (gas <= 0n) return 0n;
|
|
2268
|
+
if (!requiresNativeBridgeFee(quote, option)) return 0n;
|
|
2269
|
+
return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
|
|
2270
|
+
}
|
|
2271
|
+
|
|
728
2272
|
// src/core/native-fee.ts
|
|
729
2273
|
function routeNativeValue(route) {
|
|
730
2274
|
try {
|
|
731
|
-
const
|
|
732
|
-
if (
|
|
733
|
-
const value = BigInt(
|
|
2275
|
+
const raw2 = route?.quote?.msgValue;
|
|
2276
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
|
|
2277
|
+
const value = BigInt(raw2);
|
|
734
2278
|
return value > 0n ? value : 0n;
|
|
735
2279
|
} catch {
|
|
736
2280
|
return 0n;
|
|
@@ -765,6 +2309,11 @@ function nativeFeeShortMessage(check, symbol, chainName) {
|
|
|
765
2309
|
}
|
|
766
2310
|
|
|
767
2311
|
// src/core/route-health.ts
|
|
2312
|
+
function healthLaneKey(value) {
|
|
2313
|
+
if (typeof value !== "string") return "";
|
|
2314
|
+
const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
|
|
2315
|
+
return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
|
|
2316
|
+
}
|
|
768
2317
|
var EMPTY = /* @__PURE__ */ new Map();
|
|
769
2318
|
var NO_LIMITS = /* @__PURE__ */ new Map();
|
|
770
2319
|
function laneAvailabilityState(lane) {
|
|
@@ -784,7 +2333,7 @@ function suppressedLanes(health) {
|
|
|
784
2333
|
const out = /* @__PURE__ */ new Map();
|
|
785
2334
|
for (const lane of health.lanes) {
|
|
786
2335
|
if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
|
|
787
|
-
const key =
|
|
2336
|
+
const key = healthLaneKey(lane.laneKey);
|
|
788
2337
|
if (!key) continue;
|
|
789
2338
|
const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
|
|
790
2339
|
const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
|
|
@@ -804,7 +2353,7 @@ function limitedLanes(health) {
|
|
|
804
2353
|
const out = /* @__PURE__ */ new Map();
|
|
805
2354
|
for (const lane of health.lanes) {
|
|
806
2355
|
if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
|
|
807
|
-
const key =
|
|
2356
|
+
const key = healthLaneKey(lane.laneKey);
|
|
808
2357
|
const limit = lane.availability?.limit;
|
|
809
2358
|
if (!key || !limit || typeof limit !== "object") continue;
|
|
810
2359
|
const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
|
|
@@ -827,14 +2376,14 @@ function limitedLanes(health) {
|
|
|
827
2376
|
}
|
|
828
2377
|
function exceedsLaneLimit(limit, amount, bidDecimals) {
|
|
829
2378
|
if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
|
|
830
|
-
let
|
|
2379
|
+
let raw2;
|
|
831
2380
|
try {
|
|
832
|
-
|
|
2381
|
+
raw2 = parseUnitsDecimal(amount, bidDecimals);
|
|
833
2382
|
} catch {
|
|
834
2383
|
return false;
|
|
835
2384
|
}
|
|
836
2385
|
const scale = Math.max(bidDecimals, limit.decimals);
|
|
837
|
-
return scaleDecimals(
|
|
2386
|
+
return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
|
|
838
2387
|
}
|
|
839
2388
|
function laneLimitAmount(limit) {
|
|
840
2389
|
return formatUnits(limit.maxAmount, limit.decimals);
|
|
@@ -1000,12 +2549,12 @@ function stripBundlePrefix(head) {
|
|
|
1000
2549
|
if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
|
|
1001
2550
|
return { head, source: null };
|
|
1002
2551
|
}
|
|
1003
|
-
function complianceReasonHead(
|
|
1004
|
-
return stripBundlePrefix((
|
|
2552
|
+
function complianceReasonHead(raw2) {
|
|
2553
|
+
return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
|
|
1005
2554
|
}
|
|
1006
|
-
function usd(
|
|
1007
|
-
const n = Number(
|
|
1008
|
-
if (!Number.isFinite(n)) return `$${
|
|
2555
|
+
function usd(raw2) {
|
|
2556
|
+
const n = Number(raw2);
|
|
2557
|
+
if (!Number.isFinite(n)) return `$${raw2}`;
|
|
1009
2558
|
return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
|
|
1010
2559
|
}
|
|
1011
2560
|
function capFromDetail(detail) {
|
|
@@ -1016,8 +2565,8 @@ function categoryPhrase(detail) {
|
|
|
1016
2565
|
const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
|
|
1017
2566
|
return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
|
|
1018
2567
|
}
|
|
1019
|
-
function humanizeComplianceReason(
|
|
1020
|
-
const [headRaw, ...restParts] =
|
|
2568
|
+
function humanizeComplianceReason(raw2) {
|
|
2569
|
+
const [headRaw, ...restParts] = raw2.split(":");
|
|
1021
2570
|
const detail = restParts.join(":").trim();
|
|
1022
2571
|
const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
|
|
1023
2572
|
const scope = source === "legislation" ? "applicable regulations" : "the applicable policy";
|
|
@@ -1094,8 +2643,8 @@ var CHECK_HEADS = {
|
|
|
1094
2643
|
function distinctScreenedWallets(compliance) {
|
|
1095
2644
|
const seen = /* @__PURE__ */ new Set();
|
|
1096
2645
|
const wallets = [];
|
|
1097
|
-
for (const
|
|
1098
|
-
const address =
|
|
2646
|
+
for (const raw2 of compliance?.screenedWallets ?? []) {
|
|
2647
|
+
const address = raw2?.trim();
|
|
1099
2648
|
if (!address) continue;
|
|
1100
2649
|
const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
|
|
1101
2650
|
if (seen.has(key)) continue;
|
|
@@ -1115,11 +2664,11 @@ function screeningLabel(wallets) {
|
|
|
1115
2664
|
function complianceChecks(compliance, cv = complianceView(compliance)) {
|
|
1116
2665
|
if (cv.tone === "neutral") return [];
|
|
1117
2666
|
const byControl = /* @__PURE__ */ new Map();
|
|
1118
|
-
for (const
|
|
1119
|
-
const head = complianceReasonHead(
|
|
2667
|
+
for (const raw2 of compliance?.reasons ?? []) {
|
|
2668
|
+
const head = complianceReasonHead(raw2);
|
|
1120
2669
|
const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
|
|
1121
2670
|
if (!id) continue;
|
|
1122
|
-
byControl.set(id, [...byControl.get(id) ?? [],
|
|
2671
|
+
byControl.set(id, [...byControl.get(id) ?? [], raw2]);
|
|
1123
2672
|
}
|
|
1124
2673
|
const screenedWallets = distinctScreenedWallets(compliance);
|
|
1125
2674
|
const wallets = screenedWallets.length;
|
|
@@ -1143,8 +2692,8 @@ function complianceControlsEvaluated(compliance, cv = complianceView(compliance)
|
|
|
1143
2692
|
const checks = complianceChecks(compliance, cv);
|
|
1144
2693
|
if (checks.length === 0) return 0;
|
|
1145
2694
|
const named = /* @__PURE__ */ new Set();
|
|
1146
|
-
for (const
|
|
1147
|
-
const name =
|
|
2695
|
+
for (const raw2 of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
|
|
2696
|
+
const name = raw2?.trim();
|
|
1148
2697
|
if (name) named.add(name.toLowerCase());
|
|
1149
2698
|
}
|
|
1150
2699
|
return checks.length + named.size;
|
|
@@ -1184,8 +2733,8 @@ var BLOCK_CATEGORY_LABELS = {
|
|
|
1184
2733
|
};
|
|
1185
2734
|
var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
|
|
1186
2735
|
function blockLabelFor(categories) {
|
|
1187
|
-
for (const
|
|
1188
|
-
const label = BLOCK_CATEGORY_LABELS[String(
|
|
2736
|
+
for (const raw2 of categories) {
|
|
2737
|
+
const label = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
|
|
1189
2738
|
if (label) return label;
|
|
1190
2739
|
}
|
|
1191
2740
|
return BLOCK_LABEL_DEFAULT;
|
|
@@ -1206,8 +2755,8 @@ var REASON_TAGS = {
|
|
|
1206
2755
|
dest_chain_not_allowed: "Chain not allowed",
|
|
1207
2756
|
jurisdiction_out_of_scope: "Out of scope"
|
|
1208
2757
|
};
|
|
1209
|
-
function complianceReasonTag(
|
|
1210
|
-
const head = complianceReasonHead(
|
|
2758
|
+
function complianceReasonTag(raw2) {
|
|
2759
|
+
const head = complianceReasonHead(raw2);
|
|
1211
2760
|
return REASON_TAGS[head] ?? head.replace(/_/g, " ");
|
|
1212
2761
|
}
|
|
1213
2762
|
function complianceTagOf(compliance) {
|
|
@@ -1270,8 +2819,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1270
2819
|
const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
|
|
1271
2820
|
const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
|
|
1272
2821
|
const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
|
|
1273
|
-
const enforcePayCeiling = (
|
|
1274
|
-
if (maxPayRaw > 0n && BigInt(
|
|
2822
|
+
const enforcePayCeiling = (raw2) => {
|
|
2823
|
+
if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
|
|
1275
2824
|
throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
|
|
1276
2825
|
}
|
|
1277
2826
|
};
|
|
@@ -1295,7 +2844,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1295
2844
|
if (BigInt(quote?.fromAmount || "0") !== guessSent) {
|
|
1296
2845
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
1297
2846
|
}
|
|
1298
|
-
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
2847
|
+
const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
|
|
1299
2848
|
const final = finalOf(quote);
|
|
1300
2849
|
if (final > bestFinal) {
|
|
1301
2850
|
bestFinal = final;
|
|
@@ -1332,7 +2881,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
1332
2881
|
directTransfer: false,
|
|
1333
2882
|
quote: best,
|
|
1334
2883
|
youPayRaw: bestGuess.toString(),
|
|
1335
|
-
recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
|
|
2884
|
+
recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
|
|
1336
2885
|
targetRaw: targetRaw.toString(),
|
|
1337
2886
|
overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
|
|
1338
2887
|
meetsTarget: bestFinal >= targetRaw,
|
|
@@ -1354,7 +2903,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
1354
2903
|
if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
|
|
1355
2904
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
1356
2905
|
}
|
|
1357
|
-
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
2906
|
+
const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
|
|
1358
2907
|
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
1359
2908
|
return {
|
|
1360
2909
|
directTransfer: false,
|
|
@@ -1385,13 +2934,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
|
|
|
1385
2934
|
const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
|
|
1386
2935
|
const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
|
|
1387
2936
|
if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
|
|
2937
|
+
const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
|
|
2938
|
+
const keyBytes2 = (value, label) => {
|
|
2939
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label} is not a valid 32-byte Solana key.`);
|
|
2940
|
+
return String(value).toLowerCase();
|
|
2941
|
+
};
|
|
1388
2942
|
return {
|
|
1389
2943
|
owner: assertAddress(order.owner || payer, "Order owner"),
|
|
1390
2944
|
bidToken: assertAddress(order.bidToken, "Bid token"),
|
|
1391
2945
|
bidTokenAmount: String(order.bidTokenAmount || "0"),
|
|
1392
|
-
askToken: assertAddress(order.askToken, "Ask token"),
|
|
2946
|
+
askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
|
|
1393
2947
|
askTokenAmount: String(order.askTokenAmount || "0"),
|
|
1394
|
-
destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
|
|
2948
|
+
destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
|
|
2949
|
+
...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
|
|
1395
2950
|
destinationChainId: String(order.destinationChainId || destination.chainId),
|
|
1396
2951
|
executionChainId,
|
|
1397
2952
|
deadline
|
|
@@ -1403,17 +2958,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
|
|
|
1403
2958
|
(request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
|
|
1404
2959
|
);
|
|
1405
2960
|
}
|
|
1406
|
-
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
|
|
2961
|
+
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
|
|
1407
2962
|
const list = orders?.length ? orders : [order];
|
|
1408
2963
|
const sourceOrder = list[0];
|
|
1409
2964
|
const finalOrder = list[list.length - 1];
|
|
1410
2965
|
const now = Math.floor(Date.now() / 1e3);
|
|
1411
2966
|
const deadline = Number(sourceOrder.deadline || 0);
|
|
2967
|
+
const solana = isSolanaChainId(destination.chainId);
|
|
2968
|
+
if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
|
|
2969
|
+
throw new Error("This Solana token is not supported for delivery; refusing to sign.");
|
|
2970
|
+
}
|
|
1412
2971
|
for (const current of list) {
|
|
1413
2972
|
if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
|
|
1414
2973
|
throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
|
|
1415
2974
|
}
|
|
1416
|
-
if (
|
|
2975
|
+
if (isSolanaChainId(current.destinationChainId)) {
|
|
2976
|
+
if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
|
|
2977
|
+
checkSolanaReceiver(current, destination.address, destinationToken.address);
|
|
2978
|
+
} else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
|
|
1417
2979
|
throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
|
|
1418
2980
|
}
|
|
1419
2981
|
if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
|
|
@@ -1423,9 +2985,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
1423
2985
|
if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
|
|
1424
2986
|
throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
|
|
1425
2987
|
}
|
|
1426
|
-
if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
2988
|
+
if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
1427
2989
|
throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
|
|
1428
2990
|
}
|
|
2991
|
+
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.");
|
|
1429
2992
|
if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
|
|
1430
2993
|
throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
|
|
1431
2994
|
}
|
|
@@ -1444,10 +3007,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
1444
3007
|
if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
|
|
1445
3008
|
throw new Error("ZeroDelta quote returned a non-positive output amount.");
|
|
1446
3009
|
}
|
|
1447
|
-
|
|
3010
|
+
const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
|
|
3011
|
+
const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
|
|
3012
|
+
if (!covers(result.targetRaw)) {
|
|
1448
3013
|
throw new Error("ZeroDelta quote would not cover the requested destination amount.");
|
|
1449
3014
|
}
|
|
1450
|
-
if (
|
|
3015
|
+
if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
|
|
1451
3016
|
throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
|
|
1452
3017
|
}
|
|
1453
3018
|
const maxDeadline = maxDeadlineSeconds(quote);
|
|
@@ -1479,8 +3044,8 @@ function routeDeltaLabel(result, quote) {
|
|
|
1479
3044
|
return "~0";
|
|
1480
3045
|
}
|
|
1481
3046
|
function quotePartnerId(quote) {
|
|
1482
|
-
const
|
|
1483
|
-
return typeof
|
|
3047
|
+
const raw2 = quote.partnerId;
|
|
3048
|
+
return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
|
|
1484
3049
|
}
|
|
1485
3050
|
function optionTicker(option) {
|
|
1486
3051
|
return option.ticker || option.symbol;
|
|
@@ -1491,14 +3056,15 @@ function routeLabelFor(option, destinationToken, result) {
|
|
|
1491
3056
|
return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
|
|
1492
3057
|
}
|
|
1493
3058
|
function tokenAt(tokens, chainId, address) {
|
|
1494
|
-
const
|
|
3059
|
+
const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
|
|
3060
|
+
const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
|
|
1495
3061
|
if (!wanted || !tokens?.length) return void 0;
|
|
1496
|
-
return tokens.find((t) => Number(t.chainId) === Number(chainId) &&
|
|
3062
|
+
return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
|
|
1497
3063
|
}
|
|
1498
|
-
function legAmount(
|
|
3064
|
+
function legAmount(raw2, decimals) {
|
|
1499
3065
|
if (decimals === void 0) return "";
|
|
1500
3066
|
try {
|
|
1501
|
-
return formatUnits(
|
|
3067
|
+
return formatUnits(raw2 || "0", decimals);
|
|
1502
3068
|
} catch {
|
|
1503
3069
|
return "";
|
|
1504
3070
|
}
|
|
@@ -1529,7 +3095,7 @@ function buildLegs(orders, ctx) {
|
|
|
1529
3095
|
toTicker,
|
|
1530
3096
|
toChainId,
|
|
1531
3097
|
toChainName: chainNameOf(toChainId, ctx.chains),
|
|
1532
|
-
toAmount: legAmount(order.askTokenAmount, toDecimals),
|
|
3098
|
+
toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
|
|
1533
3099
|
executionChainId,
|
|
1534
3100
|
executionChainName: chainNameOf(executionChainId, ctx.chains)
|
|
1535
3101
|
});
|
|
@@ -1633,8 +3199,12 @@ async function buildRoute({
|
|
|
1633
3199
|
const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
|
|
1634
3200
|
const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
|
|
1635
3201
|
const order = orders[0];
|
|
1636
|
-
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
|
|
1637
|
-
const
|
|
3202
|
+
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
|
|
3203
|
+
const echoedExecution = Number(quote.executionChainId || 0);
|
|
3204
|
+
if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
|
|
3205
|
+
throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
|
|
3206
|
+
}
|
|
3207
|
+
const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
|
|
1638
3208
|
if (needsNativeFee) {
|
|
1639
3209
|
let rawFee;
|
|
1640
3210
|
try {
|
|
@@ -1678,7 +3248,7 @@ async function buildRoute({
|
|
|
1678
3248
|
},
|
|
1679
3249
|
routeLabel: routeLabelFor(option, destinationToken, result),
|
|
1680
3250
|
deltaLabel: routeDeltaLabel(result, quote),
|
|
1681
|
-
legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
|
|
3251
|
+
legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
|
|
1682
3252
|
transactions: [
|
|
1683
3253
|
{
|
|
1684
3254
|
id: "approve",
|
|
@@ -1711,6 +3281,7 @@ async function buildRoute({
|
|
|
1711
3281
|
gasCostSource: quote.gasCostSource,
|
|
1712
3282
|
msgValue: valueRaw.toString(),
|
|
1713
3283
|
deadline: order.deadline,
|
|
3284
|
+
...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
|
|
1714
3285
|
partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
|
|
1715
3286
|
iterations: result.iterations,
|
|
1716
3287
|
// Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
|
|
@@ -1726,10 +3297,10 @@ var CHANNEL_HEADER = "x-zd-channel";
|
|
|
1726
3297
|
var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
|
|
1727
3298
|
var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
|
|
1728
3299
|
var WIDGET_CHANNEL = "widget";
|
|
1729
|
-
var WIDGET_VERSION = "4.
|
|
3300
|
+
var WIDGET_VERSION = "4.13.0" ;
|
|
1730
3301
|
var MAX_CHANNEL_VERSION_LEN = 32;
|
|
1731
|
-
function sanitizeVersion(
|
|
1732
|
-
const v = String(
|
|
3302
|
+
function sanitizeVersion(raw2) {
|
|
3303
|
+
const v = String(raw2).trim();
|
|
1733
3304
|
if (!v) return "";
|
|
1734
3305
|
const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
|
|
1735
3306
|
return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
|
|
@@ -1765,9 +3336,9 @@ function isReportableSubmission(report) {
|
|
|
1765
3336
|
|
|
1766
3337
|
// src/core/api.ts
|
|
1767
3338
|
function apiError(message, props = {}) {
|
|
1768
|
-
const
|
|
1769
|
-
Object.assign(
|
|
1770
|
-
return
|
|
3339
|
+
const err2 = new Error(message);
|
|
3340
|
+
Object.assign(err2, props);
|
|
3341
|
+
return err2;
|
|
1771
3342
|
}
|
|
1772
3343
|
function toQuery(params) {
|
|
1773
3344
|
const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== "" && v !== null);
|
|
@@ -1785,14 +3356,14 @@ function sanitizeMessage(value, fallback) {
|
|
|
1785
3356
|
return text.length > MAX_MESSAGE_LEN ? `${text.slice(0, MAX_MESSAGE_LEN - 1)}\u2026` : text;
|
|
1786
3357
|
}
|
|
1787
3358
|
function apiMessage(json, fallback) {
|
|
1788
|
-
const
|
|
1789
|
-
if (
|
|
1790
|
-
if (Array.isArray(
|
|
1791
|
-
const head = sanitizeMessage(
|
|
1792
|
-
const detail = sanitizeMessage(
|
|
3359
|
+
const err2 = json?.error || json;
|
|
3360
|
+
if (err2?.fieldErrors?.[0]?.message) return sanitizeMessage(err2.fieldErrors[0].message, fallback);
|
|
3361
|
+
if (Array.isArray(err2?.reasons) && err2.reasons.length) {
|
|
3362
|
+
const head = sanitizeMessage(err2.message, fallback);
|
|
3363
|
+
const detail = sanitizeMessage(err2.reasons.filter((r) => typeof r === "string").join(", "), "");
|
|
1793
3364
|
return detail ? `${head}: ${detail}` : head;
|
|
1794
3365
|
}
|
|
1795
|
-
return sanitizeMessage(
|
|
3366
|
+
return sanitizeMessage(err2?.message, fallback);
|
|
1796
3367
|
}
|
|
1797
3368
|
function isStructuredComplianceBlock(error) {
|
|
1798
3369
|
const code = String(error?.code || "").toUpperCase();
|
|
@@ -1932,9 +3503,9 @@ function createApiClient(cfg) {
|
|
|
1932
3503
|
if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
|
|
1933
3504
|
return once("chains", async () => {
|
|
1934
3505
|
const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
|
|
1935
|
-
const normalized = (Array.isArray(chains) ? chains : []).map((
|
|
1936
|
-
const escrow = normalizeAddress(
|
|
1937
|
-
return escrow ? { ...
|
|
3506
|
+
const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
|
|
3507
|
+
const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
|
|
3508
|
+
return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
|
|
1938
3509
|
});
|
|
1939
3510
|
cache.chains = { at: Date.now(), value: normalized };
|
|
1940
3511
|
return normalized;
|
|
@@ -2037,14 +3608,16 @@ function createApiClient(cfg) {
|
|
|
2037
3608
|
async function screenWallet(address, chainId) {
|
|
2038
3609
|
const addr = String(address || "").trim();
|
|
2039
3610
|
if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
|
|
2040
|
-
const
|
|
3611
|
+
const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
|
|
3612
|
+
if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
|
|
3613
|
+
const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
|
|
2041
3614
|
const hit = screenCache.get(key);
|
|
2042
3615
|
if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
|
|
2043
3616
|
const inflight = screenInflight.get(key);
|
|
2044
3617
|
if (inflight) return inflight;
|
|
2045
3618
|
const request = apiRequest("/screen/wallet", {
|
|
2046
3619
|
method: "POST",
|
|
2047
|
-
body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
|
|
3620
|
+
body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
|
|
2048
3621
|
timeoutMs: 12e3
|
|
2049
3622
|
}).then((screen) => {
|
|
2050
3623
|
if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
|
|
@@ -2084,7 +3657,7 @@ function createApiClient(cfg) {
|
|
|
2084
3657
|
|
|
2085
3658
|
// src/core/plan.ts
|
|
2086
3659
|
function optionBalanceKey(option) {
|
|
2087
|
-
return `${Number(option.chainId)}:${
|
|
3660
|
+
return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
|
|
2088
3661
|
}
|
|
2089
3662
|
function hasPositiveBalance(option, balances) {
|
|
2090
3663
|
try {
|
|
@@ -2094,7 +3667,8 @@ function hasPositiveBalance(option, balances) {
|
|
|
2094
3667
|
}
|
|
2095
3668
|
}
|
|
2096
3669
|
function validateDestination(destination) {
|
|
2097
|
-
|
|
3670
|
+
const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
|
|
3671
|
+
if (isSolanaChainId(destination.chainId)) destination.address = address;
|
|
2098
3672
|
const chainId = Number(destination.chainId);
|
|
2099
3673
|
const asset = symbolKey(destination.asset);
|
|
2100
3674
|
if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
|
|
@@ -2152,8 +3726,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
2152
3726
|
if (directOptions.length) {
|
|
2153
3727
|
const parties = [];
|
|
2154
3728
|
const seenParty = /* @__PURE__ */ new Set();
|
|
2155
|
-
for (const
|
|
2156
|
-
const addr = String(
|
|
3729
|
+
for (const raw2 of [payer, destination.address]) {
|
|
3730
|
+
const addr = String(raw2 || "").trim();
|
|
2157
3731
|
if (!addr) continue;
|
|
2158
3732
|
const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
|
|
2159
3733
|
if (seenParty.has(key)) continue;
|
|
@@ -2261,7 +3835,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
|
|
|
2261
3835
|
if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
|
|
2262
3836
|
const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
|
|
2263
3837
|
const option = buildPayOptions({ invoiceAsset: destination.asset, invoiceChainId: destination.chainId, tokens, routes, chains, walletChainId: wallet.chainId, catalogue }).find(
|
|
2264
|
-
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && o.address
|
|
3838
|
+
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
|
|
2265
3839
|
);
|
|
2266
3840
|
if (!option) throw new Error("That funding option is not available for this payment right now.");
|
|
2267
3841
|
return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
|
|
@@ -2284,8 +3858,10 @@ function viaOf(quote, tokens) {
|
|
|
2284
3858
|
const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
|
|
2285
3859
|
if (orders.length < 2) return null;
|
|
2286
3860
|
const first = orders[0];
|
|
2287
|
-
const
|
|
2288
|
-
const
|
|
3861
|
+
const chainId = Number(first?.destinationChainId);
|
|
3862
|
+
const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
|
|
3863
|
+
const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
|
|
3864
|
+
const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
|
|
2289
3865
|
return token ? tokenTicker(token) : "";
|
|
2290
3866
|
}
|
|
2291
3867
|
async function quoteSwapPreview(api, swap, owner) {
|
|
@@ -2297,7 +3873,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
2297
3873
|
if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
|
|
2298
3874
|
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
2299
3875
|
const account = normalizeAddress(owner) || PREVIEW_OWNER;
|
|
2300
|
-
const previewReceiver = normalizeAddress(swap.recipient) || account;
|
|
3876
|
+
const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
|
|
2301
3877
|
const quote = await api.fetchQuote({
|
|
2302
3878
|
fromChainId: v.fromChainId,
|
|
2303
3879
|
toChainId: v.toChainId,
|
|
@@ -2305,7 +3881,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
2305
3881
|
toToken: destToken.symbol,
|
|
2306
3882
|
fromAmount: amountInRaw.toString(),
|
|
2307
3883
|
owner: account,
|
|
2308
|
-
destinationReceiver: previewReceiver
|
|
3884
|
+
...previewReceiver ? { destinationReceiver: previewReceiver } : {}
|
|
2309
3885
|
});
|
|
2310
3886
|
const final = finalOf(quote);
|
|
2311
3887
|
return {
|
|
@@ -2330,7 +3906,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
2330
3906
|
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
|
|
2331
3907
|
if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
|
|
2332
3908
|
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
2333
|
-
const receiver = resolveSwapReceiver(swap.recipient, account);
|
|
3909
|
+
const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
|
|
2334
3910
|
const option = {
|
|
2335
3911
|
symbol: sourceToken.symbol,
|
|
2336
3912
|
symbolKey: symbolKey(sourceToken.symbol),
|
|
@@ -2400,9 +3976,9 @@ function rawEquals(value, expected) {
|
|
|
2400
3976
|
}
|
|
2401
3977
|
function planMsgValueHex(route) {
|
|
2402
3978
|
try {
|
|
2403
|
-
const
|
|
2404
|
-
if (
|
|
2405
|
-
return "0x" + BigInt(
|
|
3979
|
+
const raw2 = route?.quote?.msgValue;
|
|
3980
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
|
|
3981
|
+
return "0x" + BigInt(raw2).toString(16);
|
|
2406
3982
|
} catch {
|
|
2407
3983
|
return null;
|
|
2408
3984
|
}
|
|
@@ -2429,15 +4005,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
|
2429
4005
|
if (!decoded) return false;
|
|
2430
4006
|
const first = decoded.orders[0];
|
|
2431
4007
|
const last = decoded.orders[decoded.orders.length - 1];
|
|
2432
|
-
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);
|
|
4008
|
+
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));
|
|
2433
4009
|
}
|
|
2434
4010
|
return false;
|
|
2435
4011
|
}
|
|
4012
|
+
function solanaDeliveryMatches(encoded, recipient2, mint) {
|
|
4013
|
+
try {
|
|
4014
|
+
return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
|
|
4015
|
+
} catch {
|
|
4016
|
+
return false;
|
|
4017
|
+
}
|
|
4018
|
+
}
|
|
2436
4019
|
async function allowanceCovers(tx, account, ethCall) {
|
|
2437
4020
|
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
2438
4021
|
try {
|
|
2439
|
-
const
|
|
2440
|
-
return BigInt(
|
|
4022
|
+
const raw2 = await ethCall(tx.token, encodeAllowance(account, tx.spender));
|
|
4023
|
+
return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
2441
4024
|
} catch {
|
|
2442
4025
|
return false;
|
|
2443
4026
|
}
|
|
@@ -2475,8 +4058,13 @@ var stableGenieIntentSchema = {
|
|
|
2475
4058
|
type: "object",
|
|
2476
4059
|
additionalProperties: false,
|
|
2477
4060
|
required: ["address", "chainId", "asset", "amount"],
|
|
4061
|
+
// The engine performs the decoded 32-byte check; the schema filters the address alphabet.
|
|
4062
|
+
oneOf: [
|
|
4063
|
+
{ properties: { chainId: { const: SOLANA_CHAIN_ID }, address: { pattern: "^[1-9A-HJ-NP-Za-km-z]{32,44}$" } } },
|
|
4064
|
+
{ properties: { chainId: { not: { const: SOLANA_CHAIN_ID } }, address: { pattern: "^0x[a-fA-F0-9]{40}$" } } }
|
|
4065
|
+
],
|
|
2478
4066
|
properties: {
|
|
2479
|
-
address: { type: "string"
|
|
4067
|
+
address: { type: "string" },
|
|
2480
4068
|
// A DESTINATION chain, so it is bounded by shape, not by the escrow-chain list: a payment may
|
|
2481
4069
|
// be delivered on any chain the gateway publishes a route to (~31 of them), while only the
|
|
2482
4070
|
// nine escrow chains can SEND one. See validateDestination in plan.ts.
|
|
@@ -2503,9 +4091,9 @@ var TX_VERIFY_ATTEMPTS = 5;
|
|
|
2503
4091
|
var TX_VERIFY_INTERVAL_MS = 2500;
|
|
2504
4092
|
var TX_VERIFY_FETCH_MS = 5e3;
|
|
2505
4093
|
var TX_VERIFY_DEADLINE_MS = 18e3;
|
|
2506
|
-
function registryRpc(
|
|
2507
|
-
if (!
|
|
2508
|
-
const candidates = [
|
|
4094
|
+
function registryRpc(chain2) {
|
|
4095
|
+
if (!chain2) return "";
|
|
4096
|
+
const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
|
|
2509
4097
|
const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
|
|
2510
4098
|
return found || "";
|
|
2511
4099
|
}
|
|
@@ -2586,8 +4174,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2586
4174
|
}
|
|
2587
4175
|
return null;
|
|
2588
4176
|
}
|
|
2589
|
-
async function verifySubmittedTx({ chainId, hash, from, to, data, value, minNonce }) {
|
|
2590
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(String(
|
|
4177
|
+
async function verifySubmittedTx({ chainId, hash: hash2, from, to, data, value, minNonce }) {
|
|
4178
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash2 || ""))) return { status: "mismatch" };
|
|
2591
4179
|
if (!normalizeAddress(from) || typeof minNonce !== "number") return { status: "unconfirmed", reason: "no-binding" };
|
|
2592
4180
|
const rpcUrl = await chainRpcUrl(chainId);
|
|
2593
4181
|
if (!rpcUrl) return { status: "unconfirmed", reason: "no-rpc" };
|
|
@@ -2598,7 +4186,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2598
4186
|
if (!matched) {
|
|
2599
4187
|
let tx = null;
|
|
2600
4188
|
try {
|
|
2601
|
-
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [
|
|
4189
|
+
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash2]);
|
|
2602
4190
|
} catch {
|
|
2603
4191
|
tx = null;
|
|
2604
4192
|
}
|
|
@@ -2610,7 +4198,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2610
4198
|
if (matched) {
|
|
2611
4199
|
let receipt = null;
|
|
2612
4200
|
try {
|
|
2613
|
-
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [
|
|
4201
|
+
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash2]);
|
|
2614
4202
|
} catch {
|
|
2615
4203
|
receipt = null;
|
|
2616
4204
|
}
|
|
@@ -2652,9 +4240,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
2652
4240
|
}
|
|
2653
4241
|
function record(target, hex) {
|
|
2654
4242
|
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
|
|
2655
|
-
const
|
|
4243
|
+
const raw2 = BigInt(hex || "0x0").toString();
|
|
2656
4244
|
const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
2657
|
-
out[key] = { raw, formatted: formatUnits(
|
|
4245
|
+
out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
|
|
2658
4246
|
return true;
|
|
2659
4247
|
}
|
|
2660
4248
|
async function readOne(rpcUrl, target) {
|
|
@@ -2720,9 +4308,9 @@ function isSameOriginPath(value) {
|
|
|
2720
4308
|
return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
|
|
2721
4309
|
}
|
|
2722
4310
|
function resolveApiBase(value) {
|
|
2723
|
-
const
|
|
2724
|
-
if (isSameOriginPath(
|
|
2725
|
-
return parseAllowedApiBase(
|
|
4311
|
+
const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
|
|
4312
|
+
if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
|
|
4313
|
+
return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
|
|
2726
4314
|
}
|
|
2727
4315
|
function canAttachApiKey(apiBase, trustedOrigin) {
|
|
2728
4316
|
if (isSameOriginPath(apiBase)) return true;
|
|
@@ -2761,31 +4349,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
|
|
|
2761
4349
|
}
|
|
2762
4350
|
|
|
2763
4351
|
// src/core/index.ts
|
|
4352
|
+
var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
|
|
2764
4353
|
function sanitizeLegs(legs) {
|
|
2765
4354
|
if (!Array.isArray(legs) || !legs.length) return void 0;
|
|
2766
4355
|
const text = (v, max) => String(v ?? "").slice(0, max);
|
|
2767
|
-
const
|
|
4356
|
+
const chain2 = (v) => Number(v) || 0;
|
|
2768
4357
|
const ticker = (value, asset) => safeTicker(value, asset) || void 0;
|
|
2769
4358
|
return legs.slice(0, 8).map((leg, i) => ({
|
|
2770
4359
|
index: Number(leg?.index) || i + 1,
|
|
2771
4360
|
fromAsset: text(leg?.fromAsset, 12),
|
|
2772
4361
|
fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
|
|
2773
|
-
fromChainId:
|
|
4362
|
+
fromChainId: chain2(leg?.fromChainId),
|
|
2774
4363
|
fromChainName: text(leg?.fromChainName, 40),
|
|
2775
4364
|
fromAmount: text(leg?.fromAmount, 40),
|
|
2776
4365
|
toAsset: text(leg?.toAsset, 12),
|
|
2777
4366
|
toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
|
|
2778
|
-
toChainId:
|
|
4367
|
+
toChainId: chain2(leg?.toChainId),
|
|
2779
4368
|
toChainName: text(leg?.toChainName, 40),
|
|
2780
4369
|
toAmount: text(leg?.toAmount, 40),
|
|
2781
|
-
executionChainId:
|
|
4370
|
+
executionChainId: chain2(leg?.executionChainId),
|
|
2782
4371
|
executionChainName: text(leg?.executionChainName, 40)
|
|
2783
4372
|
}));
|
|
2784
4373
|
}
|
|
2785
4374
|
function sanitizeTxEntry(entry) {
|
|
2786
4375
|
return {
|
|
2787
4376
|
kind: entry.kind === "swap" ? "swap" : "payment",
|
|
2788
|
-
|
|
4377
|
+
// A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
|
|
4378
|
+
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) : "",
|
|
2789
4379
|
txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
|
|
2790
4380
|
chainId: Number(entry.chainId) || null,
|
|
2791
4381
|
chainName: String(entry.chainName || "").slice(0, 40),
|
|
@@ -2796,7 +4386,7 @@ function sanitizeTxEntry(entry) {
|
|
|
2796
4386
|
payAmount: String(entry.payAmount || "").slice(0, 40),
|
|
2797
4387
|
receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
|
|
2798
4388
|
account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
|
|
2799
|
-
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
|
|
4389
|
+
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
|
|
2800
4390
|
settlement: entry.settlement === "direct" ? "direct" : "escrow",
|
|
2801
4391
|
status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
|
|
2802
4392
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -2807,6 +4397,7 @@ function createEngine(config = {}) {
|
|
|
2807
4397
|
const resolved = resolveConfig(config);
|
|
2808
4398
|
const api = createApiClient(resolved);
|
|
2809
4399
|
const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
|
|
4400
|
+
const solanaRpc = createSolanaRpc(api);
|
|
2810
4401
|
return {
|
|
2811
4402
|
api,
|
|
2812
4403
|
verifier,
|
|
@@ -2817,7 +4408,7 @@ function createEngine(config = {}) {
|
|
|
2817
4408
|
fetchRouteHealth: api.fetchRouteHealth,
|
|
2818
4409
|
fetchQuote: api.fetchQuote,
|
|
2819
4410
|
fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
|
|
2820
|
-
fetchCatalogue: async (allowedAssets, product) => {
|
|
4411
|
+
fetchCatalogue: async (allowedAssets, product, options) => {
|
|
2821
4412
|
const [chains, registryTokens, routes, health, vaults] = await Promise.all([
|
|
2822
4413
|
api.fetchChains().catch(() => []),
|
|
2823
4414
|
api.fetchTokens().catch(() => []),
|
|
@@ -2834,7 +4425,9 @@ function createEngine(config = {}) {
|
|
|
2834
4425
|
routes,
|
|
2835
4426
|
product,
|
|
2836
4427
|
...allowed ? { allowedAssets: allowed } : {},
|
|
2837
|
-
|
|
4428
|
+
// Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
|
|
4429
|
+
// Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
|
|
4430
|
+
supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
|
|
2838
4431
|
brokenLanes: suppressedLanes(health),
|
|
2839
4432
|
// Same read, same degraded mode: a null health response limits nothing.
|
|
2840
4433
|
limitedLanes: limitedLanes(health),
|
|
@@ -2845,6 +4438,13 @@ function createEngine(config = {}) {
|
|
|
2845
4438
|
quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
|
|
2846
4439
|
quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
|
|
2847
4440
|
buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
|
|
4441
|
+
quoteSolanaSource: (input) => quoteSolanaSource(api, input),
|
|
4442
|
+
buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
|
|
4443
|
+
executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
|
|
4444
|
+
executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
|
|
4445
|
+
previewSolanaSource: (input) => previewSolanaSource(api, input),
|
|
4446
|
+
readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
|
|
4447
|
+
simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
|
|
2848
4448
|
payerNonceBaseline: verifier.payerNonceBaseline,
|
|
2849
4449
|
verifySubmittedTx: verifier.verifySubmittedTx,
|
|
2850
4450
|
readBalances: verifier.readBalances,
|
|
@@ -2860,6 +4460,11 @@ function createEngine(config = {}) {
|
|
|
2860
4460
|
}
|
|
2861
4461
|
};
|
|
2862
4462
|
}
|
|
4463
|
+
/*! Bundled license information:
|
|
4464
|
+
|
|
4465
|
+
@noble/ed25519/index.js:
|
|
4466
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
4467
|
+
*/
|
|
2863
4468
|
|
|
2864
4469
|
exports.API_CACHE_TTL_MS = API_CACHE_TTL_MS;
|
|
2865
4470
|
exports.BLOCK_LABEL_DEFAULT = BLOCK_LABEL_DEFAULT;
|
|
@@ -2868,6 +4473,7 @@ exports.BUNDLED_RPC = BUNDLED_RPC;
|
|
|
2868
4473
|
exports.CANONICAL_DECIMALS = CANONICAL_DECIMALS;
|
|
2869
4474
|
exports.CANONICAL_ESCROW = CANONICAL_ESCROW;
|
|
2870
4475
|
exports.CANONICAL_INBOUND_BRIDGE = CANONICAL_INBOUND_BRIDGE;
|
|
4476
|
+
exports.CANONICAL_SOLANA_PROGRAM = CANONICAL_SOLANA_PROGRAM;
|
|
2871
4477
|
exports.CHAIN_DISPLAY_NAMES = CHAIN_DISPLAY_NAMES;
|
|
2872
4478
|
exports.COMPLIANCE_CHECK_ORDER = COMPLIANCE_CHECK_ORDER;
|
|
2873
4479
|
exports.COMPLIANCE_DENY_LABEL = COMPLIANCE_DENY_LABEL;
|
|
@@ -2892,14 +4498,18 @@ exports.QUOTE_BUFFER_BPS = QUOTE_BUFFER_BPS;
|
|
|
2892
4498
|
exports.SAME_CLASS_STABLE = SAME_CLASS_STABLE;
|
|
2893
4499
|
exports.SCREENING_BUCKETS = SCREENING_BUCKETS;
|
|
2894
4500
|
exports.SCREEN_CACHE_TTL_MS = SCREEN_CACHE_TTL_MS;
|
|
4501
|
+
exports.SOLANA_CHAIN_ID = SOLANA_CHAIN_ID;
|
|
4502
|
+
exports.SOLANA_DESTINATION_ASSETS = SOLANA_DESTINATION_ASSETS;
|
|
2895
4503
|
exports.STABLEGENIE_INTENT_TTL_MS = STABLEGENIE_INTENT_TTL_MS;
|
|
2896
4504
|
exports.STABLEGENIE_INTENT_VERSION = STABLEGENIE_INTENT_VERSION;
|
|
2897
4505
|
exports.STABLEGENIE_SUPPORTED_ASSETS = STABLEGENIE_SUPPORTED_ASSETS;
|
|
2898
4506
|
exports.STABLEGENIE_SUPPORTED_CHAIN_IDS = STABLEGENIE_SUPPORTED_CHAIN_IDS;
|
|
2899
4507
|
exports.STABLE_ASSETS = STABLE_ASSETS;
|
|
4508
|
+
exports.SUBMIT_ORDER_DISCRIMINATOR = SUBMIT_ORDER_DISCRIMINATOR;
|
|
2900
4509
|
exports.SUBMIT_ORDER_SELECTOR = SUBMIT_ORDER_SELECTOR;
|
|
2901
4510
|
exports.SUPPORTED_ASSETS = SUPPORTED_ASSETS;
|
|
2902
4511
|
exports.SUPPORTED_CHAIN_IDS = SUPPORTED_CHAIN_IDS;
|
|
4512
|
+
exports.SolanaSendError = SolanaSendError;
|
|
2903
4513
|
exports.TRADEABLE_RWA_ASSETS = TRADEABLE_RWA_ASSETS;
|
|
2904
4514
|
exports.TUNABLE_CATEGORIES = TUNABLE_CATEGORIES;
|
|
2905
4515
|
exports.ZERO_ADDRESS = ZERO_ADDRESS;
|
|
@@ -2908,26 +4518,43 @@ exports.allowanceCovers = allowanceCovers;
|
|
|
2908
4518
|
exports.amountFieldError = amountFieldError;
|
|
2909
4519
|
exports.apiError = apiError;
|
|
2910
4520
|
exports.applyLayerZeroBuffer = applyLayerZeroBuffer;
|
|
4521
|
+
exports.askCovers = askCovers;
|
|
4522
|
+
exports.askTokenDecimals = askTokenDecimals;
|
|
2911
4523
|
exports.assertAddress = assertAddress;
|
|
4524
|
+
exports.assertChainAddress = assertChainAddress;
|
|
2912
4525
|
exports.assertQuoteMatchesSelection = assertQuoteMatchesSelection;
|
|
4526
|
+
exports.assertWalletMessage = assertWalletMessage;
|
|
2913
4527
|
exports.assetClassOf = assetClassOf;
|
|
2914
4528
|
exports.assetDecimals = assetDecimals;
|
|
4529
|
+
exports.associatedTokenAddress = associatedTokenAddress;
|
|
4530
|
+
exports.base58Decode = base58Decode;
|
|
4531
|
+
exports.base58Encode = base58Encode;
|
|
4532
|
+
exports.base64Decode = base64Decode;
|
|
4533
|
+
exports.base64Encode = base64Encode;
|
|
2915
4534
|
exports.blockLabelFor = blockLabelFor;
|
|
2916
4535
|
exports.brokenLaneFor = brokenLaneFor;
|
|
2917
4536
|
exports.brokenLaneReason = brokenLaneReason;
|
|
2918
4537
|
exports.buildCatalogue = buildCatalogue;
|
|
2919
4538
|
exports.buildPayOptions = buildPayOptions;
|
|
2920
4539
|
exports.buildRoute = buildRoute;
|
|
4540
|
+
exports.buildSolanaSourcePlan = buildSolanaSourcePlan;
|
|
2921
4541
|
exports.buildSwapPlan = buildSwapPlan;
|
|
2922
4542
|
exports.bytes32Word = bytes32Word;
|
|
4543
|
+
exports.bytesEqual = bytesEqual;
|
|
2923
4544
|
exports.bytesPayload = bytesPayload;
|
|
2924
4545
|
exports.canAttachApiKey = canAttachApiKey;
|
|
2925
4546
|
exports.categoryLabel = categoryLabel;
|
|
4547
|
+
exports.chainAddressKey = chainAddressKey;
|
|
2926
4548
|
exports.chainById = chainById;
|
|
2927
4549
|
exports.chainNameOf = chainNameOf;
|
|
2928
4550
|
exports.chainSelectable = chainSelectable;
|
|
2929
4551
|
exports.checkEscrow = checkEscrow;
|
|
2930
4552
|
exports.checkNativeFee = checkNativeFee;
|
|
4553
|
+
exports.checkPlan = checkSolanaPlan;
|
|
4554
|
+
exports.checkSolanaPlan = checkSolanaPlan;
|
|
4555
|
+
exports.checkSolanaProgram = checkSolanaProgram;
|
|
4556
|
+
exports.checkSolanaReceiver = checkSolanaReceiver;
|
|
4557
|
+
exports.checkSolanaRouteBuffer = checkSolanaRouteBuffer;
|
|
2931
4558
|
exports.classifyQuoteError = classifyQuoteError;
|
|
2932
4559
|
exports.complianceChecks = complianceChecks;
|
|
2933
4560
|
exports.complianceControlsEvaluated = complianceControlsEvaluated;
|
|
@@ -2936,11 +4563,16 @@ exports.complianceReasonHead = complianceReasonHead;
|
|
|
2936
4563
|
exports.complianceReasonTag = complianceReasonTag;
|
|
2937
4564
|
exports.complianceTagOf = complianceTagOf;
|
|
2938
4565
|
exports.complianceView = complianceView;
|
|
4566
|
+
exports.cosignSolanaEvent = cosignSolanaEvent;
|
|
2939
4567
|
exports.counterpartTokens = counterpartTokens;
|
|
2940
4568
|
exports.createApiClient = createApiClient;
|
|
2941
4569
|
exports.createEngine = createEngine;
|
|
4570
|
+
exports.createSolanaRpc = createSolanaRpc;
|
|
2942
4571
|
exports.createVerifier = createVerifier;
|
|
4572
|
+
exports.decodeSolanaSubmitOrder = decodeSolanaSubmitOrder;
|
|
4573
|
+
exports.decodeSubmitOrder = decodeSolanaSubmitOrder;
|
|
2943
4574
|
exports.decodeSubmitOrderCalldata = decodeSubmitOrderCalldata;
|
|
4575
|
+
exports.deriveSolanaEvent = deriveSolanaEvent;
|
|
2944
4576
|
exports.destinationAvailability = destinationAvailability;
|
|
2945
4577
|
exports.destinationKeys = destinationKeys;
|
|
2946
4578
|
exports.directComplianceFromScreens = directComplianceFromScreens;
|
|
@@ -2948,22 +4580,30 @@ exports.distinctScreenedWallets = distinctScreenedWallets;
|
|
|
2948
4580
|
exports.encodeAllowance = encodeAllowance;
|
|
2949
4581
|
exports.encodeApprove = encodeApprove;
|
|
2950
4582
|
exports.encodeBalanceOf = encodeBalanceOf;
|
|
4583
|
+
exports.encodeNextSolanaOrders = encodeNextSolanaOrders;
|
|
2951
4584
|
exports.encodeSubmitOrder = encodeSubmitOrder;
|
|
2952
4585
|
exports.encodeTransfer = encodeTransfer;
|
|
2953
4586
|
exports.exceedsLaneLimit = exceedsLaneLimit;
|
|
2954
4587
|
exports.executableRoutes = executableRoutes;
|
|
4588
|
+
exports.executeSolanaPlan = executeSolanaPlan;
|
|
4589
|
+
exports.executeSolanaPlanStaged = executeSolanaPlanStaged;
|
|
2955
4590
|
exports.executionChainIds = executionChainIds;
|
|
4591
|
+
exports.expectedSolanaDelivery = expectedSolanaDelivery;
|
|
2956
4592
|
exports.fetchPaymentPlan = fetchPaymentPlan;
|
|
2957
4593
|
exports.finalOf = finalOf;
|
|
4594
|
+
exports.findProgramAddress = findProgramAddress;
|
|
2958
4595
|
exports.findToken = findToken;
|
|
2959
4596
|
exports.foldTicker = foldTicker;
|
|
2960
4597
|
exports.formatJurisdiction = formatJurisdiction;
|
|
2961
4598
|
exports.formatNative = formatNative;
|
|
2962
4599
|
exports.formatUnits = formatUnits;
|
|
2963
4600
|
exports.hasReachableDestination = hasReachableDestination;
|
|
4601
|
+
exports.hexBytes = hexBytes;
|
|
4602
|
+
exports.hexToSolanaKey = hexToSolanaKey;
|
|
2964
4603
|
exports.hubDeliverableSymbols = hubDeliverableSymbols;
|
|
2965
4604
|
exports.humanizeComplianceReason = humanizeComplianceReason;
|
|
2966
4605
|
exports.isAddress = isAddress;
|
|
4606
|
+
exports.isChainAddress = isChainAddress;
|
|
2967
4607
|
exports.isDeliverable = isDeliverable;
|
|
2968
4608
|
exports.isExecutableBridge = isExecutableBridge;
|
|
2969
4609
|
exports.isHexAddress = isHexAddress;
|
|
@@ -2971,7 +4611,12 @@ exports.isHexData = isHexData;
|
|
|
2971
4611
|
exports.isHexQuantity = isHexQuantity;
|
|
2972
4612
|
exports.isKnownUnbridgeable = isKnownUnbridgeable;
|
|
2973
4613
|
exports.isLayerZeroRoute = isLayerZeroRoute;
|
|
4614
|
+
exports.isOnEd25519Curve = isOnEd25519Curve;
|
|
4615
|
+
exports.isPreparationInstruction = isPreparationInstruction;
|
|
4616
|
+
exports.isSolanaAddress = isSolanaAddress;
|
|
4617
|
+
exports.isSolanaChainId = isSolanaChainId;
|
|
2974
4618
|
exports.isSourceToken = isSourceToken;
|
|
4619
|
+
exports.isSubmitOrder = isSubmitOrder;
|
|
2975
4620
|
exports.laneAvailabilityState = laneAvailabilityState;
|
|
2976
4621
|
exports.laneKey = laneKey;
|
|
2977
4622
|
exports.laneKeys = laneKeys;
|
|
@@ -2990,25 +4635,42 @@ exports.normalizeAddress = normalizeAddress;
|
|
|
2990
4635
|
exports.normalizeDecimalText = normalizeDecimalText;
|
|
2991
4636
|
exports.normalizeOrderRequest = normalizeOrderRequest;
|
|
2992
4637
|
exports.normalizeOrderRequests = normalizeOrderRequests;
|
|
4638
|
+
exports.overwriteBlockhash = overwriteBlockhash;
|
|
4639
|
+
exports.parseAddressLookupTable = parseAddressLookupTable;
|
|
2993
4640
|
exports.parseAllowedApiBase = parseAllowedApiBase;
|
|
4641
|
+
exports.parseSolanaTransaction = parseSolanaTransaction;
|
|
2994
4642
|
exports.parseUnitsDecimal = parseUnitsDecimal;
|
|
4643
|
+
exports.placeSignature = placeSignature;
|
|
2995
4644
|
exports.planErrorSummary = planErrorSummary;
|
|
2996
4645
|
exports.planMsgValueHex = planMsgValueHex;
|
|
4646
|
+
exports.pollSolanaConfirmation = pollSolanaConfirmation;
|
|
4647
|
+
exports.previewSolanaSource = previewSolanaSource;
|
|
2997
4648
|
exports.productAssets = productAssets;
|
|
2998
4649
|
exports.quotePartnerId = quotePartnerId;
|
|
2999
4650
|
exports.quotePayOption = quotePayOption;
|
|
4651
|
+
exports.quoteSolanaSource = quoteSolanaSource;
|
|
3000
4652
|
exports.quoteSwapPreview = quoteSwapPreview;
|
|
4653
|
+
exports.readSolanaBalance = readSolanaBalance;
|
|
3001
4654
|
exports.recommendedDeadlineSeconds = recommendedDeadlineSeconds;
|
|
3002
4655
|
exports.registryRpc = registryRpc;
|
|
3003
4656
|
exports.requiresNativeBridgeFee = requiresNativeBridgeFee;
|
|
3004
4657
|
exports.resolveApiBase = resolveApiBase;
|
|
3005
4658
|
exports.resolveConfig = resolveConfig;
|
|
4659
|
+
exports.resolveSolanaKeys = resolveSolanaKeys;
|
|
3006
4660
|
exports.resolveSwapReceiver = resolveSwapReceiver;
|
|
3007
4661
|
exports.resolveVaultIcon = resolveVaultIcon;
|
|
3008
4662
|
exports.routeNativeValue = routeNativeValue;
|
|
3009
4663
|
exports.safeTicker = safeTicker;
|
|
3010
4664
|
exports.scaleDecimals = scaleDecimals;
|
|
3011
4665
|
exports.screeningOutcomeOf = screeningOutcomeOf;
|
|
4666
|
+
exports.serializeSolanaTransaction = serializeSolanaTransaction;
|
|
4667
|
+
exports.sha256 = sha256;
|
|
4668
|
+
exports.simulateSolanaCost = simulateSolanaCost;
|
|
4669
|
+
exports.solanaBridgeOf = solanaBridgeOf;
|
|
4670
|
+
exports.solanaDestinationAsset = solanaDestinationAsset;
|
|
4671
|
+
exports.solanaKeyBytes = solanaKeyBytes;
|
|
4672
|
+
exports.solanaKeyHex = solanaKeyHex;
|
|
4673
|
+
exports.solanaPlanNeedsPreparation = solanaPlanNeedsPreparation;
|
|
3012
4674
|
exports.solveExactIn = solveExactIn;
|
|
3013
4675
|
exports.solveExactOut = solveExactOut;
|
|
3014
4676
|
exports.sourceKeys = sourceKeys;
|
|
@@ -3029,4 +4691,8 @@ exports.validateDestination = validateDestination;
|
|
|
3029
4691
|
exports.validatePlannedTransaction = validatePlannedTransaction;
|
|
3030
4692
|
exports.validateSwap = validateSwap;
|
|
3031
4693
|
exports.vaultIconsBySymbol = vaultIconsBySymbol;
|
|
4694
|
+
exports.verifySolanaSubmit = verifySolanaSubmit;
|
|
4695
|
+
exports.verifySolanaTransaction = verifySolanaTransaction;
|
|
4696
|
+
exports.verifySubmit = verifySolanaSubmit;
|
|
4697
|
+
exports.verifyTransaction = verifySolanaTransaction;
|
|
3032
4698
|
exports.withVaultArtwork = withVaultArtwork;
|