@anywalletkit/protocol-swap2-layerswap 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +97 -2
- package/dist/activity.cjs +122 -0
- package/dist/activity.cjs.map +1 -0
- package/dist/activity.d.cts +15 -0
- package/dist/activity.d.ts +15 -0
- package/dist/activity.js +10 -0
- package/dist/activity.js.map +1 -0
- package/dist/chunk-5QTIHCE4.js +99 -0
- package/dist/chunk-5QTIHCE4.js.map +1 -0
- package/dist/chunk-KCAZCR4I.js +27 -0
- package/dist/chunk-KCAZCR4I.js.map +1 -0
- package/dist/chunk-TEL62A5J.js +564 -0
- package/dist/chunk-TEL62A5J.js.map +1 -0
- package/dist/chunk-WEMNS3LY.js +21 -0
- package/dist/chunk-WEMNS3LY.js.map +1 -0
- package/dist/chunk-ZKT24QPJ.js +123 -0
- package/dist/chunk-ZKT24QPJ.js.map +1 -0
- package/dist/chunk-ZTFJO6AI.js +410 -0
- package/dist/chunk-ZTFJO6AI.js.map +1 -0
- package/dist/config.cjs +143 -0
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +74 -0
- package/dist/config.d.ts +74 -0
- package/dist/config.js +31 -0
- package/dist/config.js.map +1 -0
- package/dist/index.cjs +1189 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +84 -0
- package/dist/index.d.ts +84 -0
- package/dist/index.js +126 -0
- package/dist/index.js.map +1 -0
- package/dist/pins.cjs +557 -0
- package/dist/pins.cjs.map +1 -0
- package/dist/pins.d.cts +6 -0
- package/dist/pins.d.ts +6 -0
- package/dist/pins.js +11 -0
- package/dist/pins.js.map +1 -0
- package/dist/protocol.cjs +1052 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +19 -0
- package/dist/protocol.d.ts +19 -0
- package/dist/protocol.js +11 -0
- package/dist/protocol.js.map +1 -0
- package/dist/provider.cjs +1039 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.cts +23 -0
- package/dist/provider.d.ts +23 -0
- package/dist/provider.js +16 -0
- package/dist/provider.js.map +1 -0
- package/dist/verify.cjs +554 -0
- package/dist/verify.cjs.map +1 -0
- package/dist/verify.d.cts +169 -0
- package/dist/verify.d.ts +169 -0
- package/dist/verify.js +46 -0
- package/dist/verify.js.map +1 -0
- package/module.json +64 -0
- package/package.json +100 -3
|
@@ -0,0 +1,1052 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/protocol.ts
|
|
21
|
+
var protocol_exports = {};
|
|
22
|
+
__export(protocol_exports, {
|
|
23
|
+
LayerswapSwap2Protocol: () => LayerswapSwap2Protocol
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(protocol_exports);
|
|
26
|
+
var import_single = require("@anywalletkit/protocol-swap2-core/swap2/single");
|
|
27
|
+
|
|
28
|
+
// src/config.ts
|
|
29
|
+
var import_util = require("@anywalletkit/protocol-swap2-core/util");
|
|
30
|
+
var LAYERSWAP_API = "https://api.layerswap.io/api/v2";
|
|
31
|
+
var LAYERSWAP_DEPOSITORY = "0xe226e4825cb215abafad98fdd400583eab6a594f";
|
|
32
|
+
var LAYERSWAP_RECEIVERS = Object.freeze([
|
|
33
|
+
"0x2fc617e933a52713247ce25730f6695920b3befe",
|
|
34
|
+
"0x08b00ceee2fb66029b53d76110b19eeaabfd1e65"
|
|
35
|
+
]);
|
|
36
|
+
var DEPOSIT_NATIVE_SELECTOR = "0x80a6de92";
|
|
37
|
+
var DEPOSIT_ERC20_SELECTOR = "0xf4371f63";
|
|
38
|
+
var LAYERSWAP_DEPOSITORY_CHAINS = Object.freeze([
|
|
39
|
+
1,
|
|
40
|
+
10,
|
|
41
|
+
56,
|
|
42
|
+
100,
|
|
43
|
+
130,
|
|
44
|
+
137,
|
|
45
|
+
143,
|
|
46
|
+
146,
|
|
47
|
+
169,
|
|
48
|
+
196,
|
|
49
|
+
204,
|
|
50
|
+
252,
|
|
51
|
+
324,
|
|
52
|
+
360,
|
|
53
|
+
480,
|
|
54
|
+
988,
|
|
55
|
+
999,
|
|
56
|
+
1329,
|
|
57
|
+
1868,
|
|
58
|
+
2020,
|
|
59
|
+
2741,
|
|
60
|
+
2818,
|
|
61
|
+
4217,
|
|
62
|
+
4326,
|
|
63
|
+
4663,
|
|
64
|
+
5e3,
|
|
65
|
+
5042,
|
|
66
|
+
8217,
|
|
67
|
+
8453,
|
|
68
|
+
9745,
|
|
69
|
+
13371,
|
|
70
|
+
42161,
|
|
71
|
+
42220,
|
|
72
|
+
42793,
|
|
73
|
+
43114,
|
|
74
|
+
48900,
|
|
75
|
+
57073,
|
|
76
|
+
59144,
|
|
77
|
+
60808,
|
|
78
|
+
80094,
|
|
79
|
+
99901,
|
|
80
|
+
167e3,
|
|
81
|
+
534352,
|
|
82
|
+
747474,
|
|
83
|
+
7777777
|
|
84
|
+
]);
|
|
85
|
+
var LAYERSWAP_EVM_CHAINS = Object.freeze([
|
|
86
|
+
...LAYERSWAP_DEPOSITORY_CHAINS,
|
|
87
|
+
14,
|
|
88
|
+
25,
|
|
89
|
+
30,
|
|
90
|
+
40,
|
|
91
|
+
122,
|
|
92
|
+
747,
|
|
93
|
+
4114,
|
|
94
|
+
16661,
|
|
95
|
+
34443
|
|
96
|
+
].sort((a, b) => a - b));
|
|
97
|
+
var LAYERSWAP_NON_EVM = Object.freeze({
|
|
98
|
+
"solana:mainnet": "SOLANA_MAINNET",
|
|
99
|
+
"ton:-239": "TON_MAINNET",
|
|
100
|
+
"tron:728126428": "TRON_MAINNET",
|
|
101
|
+
"bitcoin:mainnet": "BITCOIN_MAINNET"
|
|
102
|
+
});
|
|
103
|
+
function fundingFor(sourceChain) {
|
|
104
|
+
const ns = (0, import_util.namespace)(sourceChain);
|
|
105
|
+
if (ns === "eip155") return LAYERSWAP_DEPOSITORY_CHAINS.includes(evmChainId(sourceChain) ?? -1) ? "depository" : null;
|
|
106
|
+
if (ns === "solana" || ns === "ton" || ns === "tron") return sourceChain in LAYERSWAP_NON_EVM ? "wallet" : null;
|
|
107
|
+
if (ns === "bitcoin") return sourceChain in LAYERSWAP_NON_EVM ? "deposit_address" : null;
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
function evmChainId(caip2) {
|
|
111
|
+
const m = /^eip155:([1-9]\d{0,9})$/.exec(caip2);
|
|
112
|
+
return m ? Number(m[1]) : null;
|
|
113
|
+
}
|
|
114
|
+
function layerswapNetwork(caip2) {
|
|
115
|
+
const id = evmChainId(caip2);
|
|
116
|
+
if (id !== null) return LAYERSWAP_EVM_CHAINS.includes(id) ? String(id) : null;
|
|
117
|
+
return Object.prototype.hasOwnProperty.call(LAYERSWAP_NON_EVM, caip2) ? LAYERSWAP_NON_EVM[caip2] : null;
|
|
118
|
+
}
|
|
119
|
+
function sameNetwork(caip2, network) {
|
|
120
|
+
if (!network) return false;
|
|
121
|
+
const id = evmChainId(caip2);
|
|
122
|
+
if (id !== null) return String(network.chain_id ?? "") === String(id);
|
|
123
|
+
return network.name === LAYERSWAP_NON_EVM[caip2];
|
|
124
|
+
}
|
|
125
|
+
var layerswap = {
|
|
126
|
+
supportsChain(chain) {
|
|
127
|
+
return layerswapNetwork(chain) !== null;
|
|
128
|
+
},
|
|
129
|
+
/** A route this module can try: a source with a funding method, any served destination, never the same chain. */
|
|
130
|
+
supports(from, to) {
|
|
131
|
+
return from !== to && fundingFor(from) !== null && layerswapNetwork(to) !== null;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
// src/provider.ts
|
|
136
|
+
var import_swap2_assets = require("@anywalletkit/swap2-assets");
|
|
137
|
+
var import_util4 = require("@anywalletkit/protocol-swap2-core/util");
|
|
138
|
+
var import_errors3 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
139
|
+
|
|
140
|
+
// src/activity.ts
|
|
141
|
+
var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
|
|
142
|
+
var LAYERSWAP_MODULE = "@anywalletkit/protocol-swap2-layerswap";
|
|
143
|
+
function describeLayerswapActivity(tx, ctx) {
|
|
144
|
+
if (fundingFor(tx.chain) !== "depository") return null;
|
|
145
|
+
if (!(0, import_activity.matchesCall)(tx, [LAYERSWAP_DEPOSITORY], [DEPOSIT_NATIVE_SELECTOR, DEPOSIT_ERC20_SELECTOR])) return null;
|
|
146
|
+
return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: LAYERSWAP_MODULE, subtitle: `Layerswap \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "bridge", outVerb: "Bridged" });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/api.ts
|
|
150
|
+
var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
|
|
151
|
+
var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
|
|
152
|
+
var MAX_BODY = 1024 * 1024;
|
|
153
|
+
var MAX_NETWORKS_BODY = 8 * 1024 * 1024;
|
|
154
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
155
|
+
var LAYERSWAP_ERROR_REASONS = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), {
|
|
156
|
+
ROUTE_NOT_FOUND_ERROR: "unsupported_pair",
|
|
157
|
+
VALIDATION_ERROR: "unsupported_pair",
|
|
158
|
+
UNSUPPORTED_GASLESS_SOURCE: "unsupported_pair",
|
|
159
|
+
LESS_THAN_MIN_ERROR: "amount_too_small",
|
|
160
|
+
GREATER_THAN_MAX_ERROR: "amount_too_large",
|
|
161
|
+
INVALID_ADDRESS_ERROR: "recipient_mismatch",
|
|
162
|
+
UNACTIVATED_ADDRESS_ERROR: "recipient_mismatch",
|
|
163
|
+
REFUND_ADDRESS_MISSING: "policy_refused",
|
|
164
|
+
DUPLICATE_REFERENCE_ID: "policy_refused",
|
|
165
|
+
PRICE_IMPACT_TOO_HIGH: "price_check_failed",
|
|
166
|
+
API_KEY_FORBIDDEN: "key_rejected",
|
|
167
|
+
UNEXPECTED_ERROR: "upstream_unavailable",
|
|
168
|
+
NOT_FOUND: "upstream_unavailable"
|
|
169
|
+
}));
|
|
170
|
+
function clip(text, max = 240) {
|
|
171
|
+
const t = (0, import_util2.redactUrls)(text).replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
|
|
172
|
+
return t.length > max ? `${t.slice(0, max)}\u2026` : t;
|
|
173
|
+
}
|
|
174
|
+
function layerswapClient(config, defaultBase) {
|
|
175
|
+
const base = (config.baseUrl ?? defaultBase).replace(/\/+$/, "");
|
|
176
|
+
if (!/^https?:\/\//.test(base)) throw new Error("layerswap: baseUrl must use http or https");
|
|
177
|
+
if (config.apiKey !== void 0 && (typeof config.apiKey !== "string" || !/^[\x21-\x7e]{1,256}$/.test(config.apiKey))) {
|
|
178
|
+
throw new Error("layerswap: apiKey must be a printable string");
|
|
179
|
+
}
|
|
180
|
+
const doFetch = (input, init) => (config.fetchImpl ?? fetch)(input, init);
|
|
181
|
+
const headers = (json) => ({
|
|
182
|
+
accept: "application/json",
|
|
183
|
+
...json ? { "content-type": "application/json" } : {},
|
|
184
|
+
...config.apiKey ? { "X-LS-APIKEY": config.apiKey } : {}
|
|
185
|
+
});
|
|
186
|
+
async function call(method, path, opts = {}) {
|
|
187
|
+
const qs = opts.query ? `?${new URLSearchParams(opts.query).toString()}` : "";
|
|
188
|
+
const timeout = (0, import_util2.timeoutSignal)(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
189
|
+
const res = await doFetch(`${base}${path}${qs}`, {
|
|
190
|
+
method,
|
|
191
|
+
headers: headers(opts.body !== void 0),
|
|
192
|
+
...opts.body !== void 0 ? { body: opts.body } : {},
|
|
193
|
+
signal: opts.signal ? (0, import_util2.anySignal)([opts.signal, timeout]) : timeout
|
|
194
|
+
});
|
|
195
|
+
const text = await res.text();
|
|
196
|
+
if (text.length > (opts.maxBody ?? MAX_BODY)) throw new Error("layerswap: response too large");
|
|
197
|
+
let body = null;
|
|
198
|
+
if (text.trim() !== "") {
|
|
199
|
+
try {
|
|
200
|
+
const parsed = JSON.parse(text);
|
|
201
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) body = parsed;
|
|
202
|
+
} catch {
|
|
203
|
+
body = null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return { ok: res.ok, status: res.status, body, retryAfter: res.headers?.get?.("retry-after") ?? null };
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
base,
|
|
210
|
+
get: (path, query, signal, timeoutMs, maxBody) => call("GET", path, { ...query ? { query } : {}, ...signal ? { signal } : {}, ...timeoutMs ? { timeoutMs } : {}, ...maxBody ? { maxBody } : {} }),
|
|
211
|
+
post: (path, body, signal, timeoutMs) => call("POST", path, { body, ...signal ? { signal } : {}, ...timeoutMs ? { timeoutMs } : {} })
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function answerRefusal(a) {
|
|
215
|
+
const code = typeof a.body?.error?.code === "string" ? a.body.error.code : "";
|
|
216
|
+
const message = typeof a.body?.error?.message === "string" ? clip(a.body.error.message) : "";
|
|
217
|
+
const byStatus = (0, import_errors.httpRefusal)(a.status, a.retryAfter);
|
|
218
|
+
const text = code ? `${clip(code, 60)}${message ? `: ${message}` : ""}` : a.body === null ? `HTTP ${a.status} with no body` : `HTTP ${a.status}`;
|
|
219
|
+
if (byStatus?.reason === "rate_limited") return { text, info: byStatus };
|
|
220
|
+
const byCode = code && Object.prototype.hasOwnProperty.call(LAYERSWAP_ERROR_REASONS, code) ? LAYERSWAP_ERROR_REASONS[code] : void 0;
|
|
221
|
+
if (byCode) return { text, info: byCode === "upstream_unavailable" || byCode === "key_rejected" ? { reason: byCode, httpStatus: a.status } : { reason: byCode } };
|
|
222
|
+
if (a.status === 400 && a.body === null) return { text, info: { reason: "unsupported_pair" } };
|
|
223
|
+
if (byStatus) return { text, info: byStatus };
|
|
224
|
+
return { text, info: a.body?.error ? { reason: "no_route" } : { reason: "upstream_unavailable", httpStatus: a.status } };
|
|
225
|
+
}
|
|
226
|
+
function unitsToDecimal(units, decimals) {
|
|
227
|
+
if (units < 0n) throw new Error("layerswap: negative amount");
|
|
228
|
+
const digits = units.toString(10).padStart(decimals + 1, "0");
|
|
229
|
+
const whole = digits.slice(0, digits.length - decimals);
|
|
230
|
+
const frac = decimals > 0 ? digits.slice(digits.length - decimals).replace(/0+$/, "") : "";
|
|
231
|
+
return frac ? `${whole}.${frac}` : whole;
|
|
232
|
+
}
|
|
233
|
+
function decimalToUnits(value, decimals) {
|
|
234
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1e30) return null;
|
|
235
|
+
let text = String(value);
|
|
236
|
+
if (/e/i.test(text)) text = value.toFixed(Math.min(100, Math.max(decimals, 20)));
|
|
237
|
+
const m = /^(\d+)(?:\.(\d+))?$/.exec(text);
|
|
238
|
+
if (!m) return null;
|
|
239
|
+
const frac = (m[2] ?? "").slice(0, decimals).padEnd(decimals, "0");
|
|
240
|
+
return BigInt(m[1] + frac);
|
|
241
|
+
}
|
|
242
|
+
function baseUnits(value) {
|
|
243
|
+
return typeof value === "string" && /^(?:0|[1-9]\d{0,77})$/.test(value) ? BigInt(value) : null;
|
|
244
|
+
}
|
|
245
|
+
function parseNetworks(data) {
|
|
246
|
+
if (!Array.isArray(data)) throw new Error("layerswap: /networks did not answer a list");
|
|
247
|
+
const out = [];
|
|
248
|
+
for (const n of data) {
|
|
249
|
+
if (!n || typeof n !== "object" || typeof n.name !== "string" || typeof n.type !== "string") continue;
|
|
250
|
+
const tokens = [];
|
|
251
|
+
for (const t of Array.isArray(n.tokens) ? n.tokens : []) {
|
|
252
|
+
if (!t || typeof t.symbol !== "string" || !/^[\x21-\x7e]{1,40}$/.test(t.symbol)) continue;
|
|
253
|
+
if (typeof t.decimals !== "number" || !Number.isInteger(t.decimals) || t.decimals < 0 || t.decimals > 36) continue;
|
|
254
|
+
if (t.contract !== null && t.contract !== void 0 && typeof t.contract !== "string") continue;
|
|
255
|
+
tokens.push({ symbol: t.symbol, contract: typeof t.contract === "string" && t.contract !== "" ? t.contract : null, decimals: t.decimals });
|
|
256
|
+
}
|
|
257
|
+
out.push({ name: n.name, type: n.type, chainId: n.chain_id === null || n.chain_id === void 0 ? null : String(n.chain_id), tokens });
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
}
|
|
261
|
+
function networkFor(caip2, networks) {
|
|
262
|
+
const id = evmChainId(caip2);
|
|
263
|
+
if (id !== null) return networks.find((n) => n.type === "evm" && n.chainId === String(id));
|
|
264
|
+
const name = Object.prototype.hasOwnProperty.call(LAYERSWAP_NON_EVM, caip2) ? LAYERSWAP_NON_EVM[caip2] : void 0;
|
|
265
|
+
return name ? networks.find((n) => n.name === name) : void 0;
|
|
266
|
+
}
|
|
267
|
+
function tokenKey(caip2, contract) {
|
|
268
|
+
if (contract === null || contract === void 0 || contract === "" || /^0x0{40}$/i.test(contract)) return null;
|
|
269
|
+
if (caip2.startsWith("eip155:")) return contract.toLowerCase();
|
|
270
|
+
if (caip2.startsWith("ton:")) return (0, import_util2.tonRawAddress)(contract) ?? `?${contract}`;
|
|
271
|
+
return contract;
|
|
272
|
+
}
|
|
273
|
+
function tokenOn(caip2, network, contract) {
|
|
274
|
+
const want = tokenKey(caip2, contract);
|
|
275
|
+
return network.tokens.find((t) => tokenKey(caip2, t.contract) === want);
|
|
276
|
+
}
|
|
277
|
+
function addressKey(caip2, address) {
|
|
278
|
+
if (typeof address !== "string" || address.trim() === "") return null;
|
|
279
|
+
const a = address.trim();
|
|
280
|
+
if (caip2.startsWith("eip155:")) return /^0x[0-9a-fA-F]{40}$/.test(a) ? a.toLowerCase() : null;
|
|
281
|
+
if (caip2.startsWith("ton:")) return (0, import_util2.tonRawAddress)(a);
|
|
282
|
+
return a;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/verify.ts
|
|
286
|
+
var import_viem = require("viem");
|
|
287
|
+
var import_ed25519 = require("@noble/curves/ed25519.js");
|
|
288
|
+
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
289
|
+
var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
|
|
290
|
+
var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
291
|
+
var LayerswapRefusal = class extends Error {
|
|
292
|
+
constructor(check, message, reason) {
|
|
293
|
+
super(`layerswap: ${message}`);
|
|
294
|
+
this.check = check;
|
|
295
|
+
this.name = "LayerswapRefusal";
|
|
296
|
+
(0, import_errors2.withReason)(this, reason);
|
|
297
|
+
}
|
|
298
|
+
check;
|
|
299
|
+
};
|
|
300
|
+
function fail(check, message, reason = "policy_refused") {
|
|
301
|
+
throw new LayerswapRefusal(check, message, reason);
|
|
302
|
+
}
|
|
303
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
304
|
+
function checkSwapRecord(request, swap) {
|
|
305
|
+
if (swap === null || typeof swap !== "object") fail("swap-record", "the answer carries no swap", "upstream_unavailable");
|
|
306
|
+
const s = swap;
|
|
307
|
+
const id = typeof s.id === "string" ? s.id : "";
|
|
308
|
+
if (!UUID.test(id)) fail("swap-record", "the swap has no id", "upstream_unavailable");
|
|
309
|
+
const seqRaw = s.metadata?.sequence_number;
|
|
310
|
+
if (typeof seqRaw !== "number" || !Number.isSafeInteger(seqRaw) || seqRaw <= 0) fail("swap-record", "the swap has no sequence number", "upstream_unavailable");
|
|
311
|
+
if (!sameNetwork(request.sourceChain, s.source_network)) fail("swap-source", `the swap leaves from ${describe(s.source_network)}, not ${request.sourceChain}`, "vault_mismatch");
|
|
312
|
+
if (!sameNetwork(request.destChain, s.destination_network)) fail("swap-destination", `the swap pays out on ${describe(s.destination_network)}, not ${request.destChain}`, "vault_mismatch");
|
|
313
|
+
const srcToken = s.source_token ?? null;
|
|
314
|
+
const dstToken = s.destination_token ?? null;
|
|
315
|
+
if (!srcToken || tokenKey(request.sourceChain, srcToken.contract) !== tokenKey(request.sourceChain, request.sourceContract)) {
|
|
316
|
+
fail("swap-source-token", "the swap takes another source token than the one asked", "policy_refused");
|
|
317
|
+
}
|
|
318
|
+
if (!dstToken || tokenKey(request.destChain, dstToken.contract) !== tokenKey(request.destChain, request.destContract)) {
|
|
319
|
+
fail("swap-destination-token", "the swap pays out another token than the one asked", "policy_refused");
|
|
320
|
+
}
|
|
321
|
+
const recipient = addressKey(request.destChain, s.destination_address);
|
|
322
|
+
if (!recipient || recipient !== addressKey(request.destChain, request.recipient)) {
|
|
323
|
+
fail("swap-recipient", "the swap pays out to another address than the recipient asked", "recipient_mismatch");
|
|
324
|
+
}
|
|
325
|
+
if (s.source_address !== void 0 && s.source_address !== null && addressKey(request.sourceChain, s.source_address) !== addressKey(request.sourceChain, request.sender)) {
|
|
326
|
+
fail("swap-sender", "the swap is recorded for another source address", "policy_refused");
|
|
327
|
+
}
|
|
328
|
+
if (Array.isArray(s.integrator_fee_splits) ? s.integrator_fee_splits.length > 0 : s.integrator_fee_splits !== void 0 && s.integrator_fee_splits !== null) {
|
|
329
|
+
fail("swap-fee", "the swap carries an integrator fee this module did not ask for", "policy_refused");
|
|
330
|
+
}
|
|
331
|
+
const asked = Number(unitsToDecimal(request.amount, request.sourceDecimals));
|
|
332
|
+
if (typeof s.requested_amount !== "number" || !(Math.abs(s.requested_amount - asked) <= Math.abs(asked) * 1e-9)) {
|
|
333
|
+
fail("swap-amount", "the swap is recorded for another amount than the input", "policy_refused");
|
|
334
|
+
}
|
|
335
|
+
if (s.use_deposit_address === true !== (request.funding === "deposit_address")) {
|
|
336
|
+
fail("swap-funding", "the swap was created for another funding method", "policy_refused");
|
|
337
|
+
}
|
|
338
|
+
const status = typeof s.status === "string" ? s.status : "";
|
|
339
|
+
return { id: id.toLowerCase(), sequence: BigInt(seqRaw), status };
|
|
340
|
+
}
|
|
341
|
+
function describe(network) {
|
|
342
|
+
const n = network;
|
|
343
|
+
return clipName(n?.name ?? n?.chain_id ?? "an unnamed network");
|
|
344
|
+
}
|
|
345
|
+
function clipName(v) {
|
|
346
|
+
return String(v).replace(/[^\x20-\x7e]/g, "?").slice(0, 60);
|
|
347
|
+
}
|
|
348
|
+
function pickAction(actions) {
|
|
349
|
+
if (!Array.isArray(actions) || actions.length === 0 || actions.length > 8) fail("actions", "the swap has no deposit action", "upstream_unavailable");
|
|
350
|
+
const steps = actions.filter((a2) => a2 && typeof a2 === "object" && !/approve/i.test(String(a2.step ?? "")));
|
|
351
|
+
const open = (want) => steps.filter((a2) => want(a2.status));
|
|
352
|
+
let usable = open((st) => st === void 0 || st === null || st === "action_required");
|
|
353
|
+
if (usable.length === 0) usable = open((st) => st === "pending");
|
|
354
|
+
if (usable.length !== 1) fail("actions", usable.length === 0 ? "the swap asks for no deposit this account can make" : "the swap asks for more than one deposit transaction", "unsupported_pair");
|
|
355
|
+
const a = usable[0];
|
|
356
|
+
const type = typeof a.type === "string" ? a.type : "";
|
|
357
|
+
if (type !== "transfer" && type !== "manual_transfer") fail("actions", `the swap asks for a "${clipName(type)}" action, only a transfer is made`, "unsupported_pair");
|
|
358
|
+
if (a.typed_data !== void 0 && a.typed_data !== null) fail("actions", "the deposit action carries typed data to sign", "policy_refused");
|
|
359
|
+
if (typeof a.to_address !== "string" || a.to_address.trim() === "") fail("actions", "the deposit action names no address", "upstream_unavailable");
|
|
360
|
+
const gas = typeof a.gas_limit === "string" && /^[1-9]\d{0,9}$/.test(a.gas_limit) ? BigInt(a.gas_limit) : null;
|
|
361
|
+
const token = a.token;
|
|
362
|
+
return {
|
|
363
|
+
type,
|
|
364
|
+
step: typeof a.step === "string" ? a.step : "",
|
|
365
|
+
toAddress: a.to_address.trim(),
|
|
366
|
+
amountInBaseUnits: baseUnits(a.amount_in_base_units),
|
|
367
|
+
callData: typeof a.call_data === "string" && a.call_data !== "" ? a.call_data : null,
|
|
368
|
+
gasLimit: gas,
|
|
369
|
+
network: a.network ?? null,
|
|
370
|
+
tokenContract: typeof token?.contract === "string" && token.contract !== "" ? token.contract : null
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function commonAction(request, a) {
|
|
374
|
+
if (!sameNetwork(request.sourceChain, a.network)) fail("action-network", `the deposit is on ${describe(a.network)}, not ${request.sourceChain}`, "vault_mismatch");
|
|
375
|
+
if (tokenKey(request.sourceChain, a.tokenContract) !== tokenKey(request.sourceChain, request.sourceContract)) {
|
|
376
|
+
fail("action-token", "the deposit moves another token than the swap's input", "policy_refused");
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
var DEPOSITORY_ABI = [
|
|
380
|
+
{ type: "function", name: "depositNative", stateMutability: "payable", inputs: [{ name: "id", type: "bytes32" }, { name: "receiver", type: "address" }], outputs: [] },
|
|
381
|
+
{ type: "function", name: "depositERC20", stateMutability: "nonpayable", inputs: [{ name: "id", type: "bytes32" }, { name: "token", type: "address" }, { name: "receiver", type: "address" }, { name: "amount", type: "uint256" }], outputs: [] }
|
|
382
|
+
];
|
|
383
|
+
function depositId(sequence) {
|
|
384
|
+
return (0, import_viem.pad)((0, import_viem.toHex)(sequence), { size: 32 });
|
|
385
|
+
}
|
|
386
|
+
function checkEvmDeposit(request, swap, a) {
|
|
387
|
+
commonAction(request, a);
|
|
388
|
+
const chainId = evmChainId(request.sourceChain);
|
|
389
|
+
if (chainId === null) fail("evm-chain", `${request.sourceChain} is not an EVM chain`, "vault_mismatch");
|
|
390
|
+
if (a.type !== "transfer") fail("evm-action", "an EVM deposit must be the Depository call", "unsupported_pair");
|
|
391
|
+
if (a.toAddress.toLowerCase() !== LAYERSWAP_DEPOSITORY) fail("evm-target", `the deposit calls ${clipName(a.toAddress)}, not the pinned Depository`, "policy_refused");
|
|
392
|
+
const data = a.callData;
|
|
393
|
+
if (!data || !/^0x[0-9a-fA-F]+$/.test(data)) fail("evm-calldata", "the deposit carries no calldata", "upstream_unavailable");
|
|
394
|
+
let decoded;
|
|
395
|
+
try {
|
|
396
|
+
decoded = (0, import_viem.decodeFunctionData)({ abi: DEPOSITORY_ABI, data });
|
|
397
|
+
} catch {
|
|
398
|
+
return fail("evm-calldata", "the deposit is not a Depository deposit call", "policy_refused");
|
|
399
|
+
}
|
|
400
|
+
const receiver = String(decoded.args[decoded.functionName === "depositNative" ? 1 : 2] ?? "").toLowerCase();
|
|
401
|
+
if (!LAYERSWAP_RECEIVERS.includes(receiver)) fail("evm-receiver", `the deposit forwards to ${clipName(receiver)}, not a pinned Layerswap receiver`, "policy_refused");
|
|
402
|
+
const id = depositId(swap.sequence);
|
|
403
|
+
const native = request.sourceContract === null;
|
|
404
|
+
const expected = native ? (0, import_viem.encodeFunctionData)({ abi: DEPOSITORY_ABI, functionName: "depositNative", args: [id, receiver] }) : (0, import_viem.encodeFunctionData)({ abi: DEPOSITORY_ABI, functionName: "depositERC20", args: [id, request.sourceContract, receiver, request.amount] });
|
|
405
|
+
if (data.toLowerCase() !== expected.toLowerCase()) {
|
|
406
|
+
fail("evm-calldata", native ? "the deposit is not depositNative for this swap" : "the deposit is not depositERC20 of exactly the input for this swap", "policy_refused");
|
|
407
|
+
}
|
|
408
|
+
const value = a.amountInBaseUnits ?? 0n;
|
|
409
|
+
if (native ? value !== request.amount : value !== 0n) fail("evm-value", native ? `the deposit sends ${value}, not the input ${request.amount}` : "an ERC-20 deposit must not attach native value", "policy_refused");
|
|
410
|
+
return {
|
|
411
|
+
to: LAYERSWAP_DEPOSITORY,
|
|
412
|
+
data: expected,
|
|
413
|
+
value: native ? request.amount : 0n,
|
|
414
|
+
chainId,
|
|
415
|
+
...native ? {} : { approvalAddress: LAYERSWAP_DEPOSITORY },
|
|
416
|
+
receiver,
|
|
417
|
+
gasLimit: a.gasLimit
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function checkTonDeposit(request, swap, a) {
|
|
421
|
+
commonAction(request, a);
|
|
422
|
+
if (a.type !== "transfer") fail("ton-action", "a TON deposit must be a transfer with the swap's comment", "unsupported_pair");
|
|
423
|
+
let payload;
|
|
424
|
+
try {
|
|
425
|
+
payload = JSON.parse(a.callData ?? "");
|
|
426
|
+
} catch {
|
|
427
|
+
return fail("ton-payload", "the TON deposit carries no comment payload", "upstream_unavailable");
|
|
428
|
+
}
|
|
429
|
+
const comment = typeof payload?.comment === "string" ? payload.comment : "";
|
|
430
|
+
if (comment !== swap.sequence.toString(10)) fail("ton-comment", "the TON deposit comment does not name this swap", "policy_refused");
|
|
431
|
+
if (request.sourceContract === null) {
|
|
432
|
+
if (a.amountInBaseUnits !== request.amount) fail("ton-amount", `the deposit sends ${a.amountInBaseUnits ?? "nothing"}, not the input ${request.amount}`, "policy_refused");
|
|
433
|
+
} else if (baseUnits(payload.amount) !== request.amount) {
|
|
434
|
+
fail("ton-amount", "the jetton transfer amount is not the input", "policy_refused");
|
|
435
|
+
}
|
|
436
|
+
if (!addressKey(request.sourceChain, a.toAddress)) fail("ton-target", "the TON deposit address is not a TON address", "upstream_unavailable");
|
|
437
|
+
return { to: a.toAddress, value: request.amount, memo: comment };
|
|
438
|
+
}
|
|
439
|
+
var TRON_ADDRESS = /^T[1-9A-HJ-NP-Za-km-z]{33}$/;
|
|
440
|
+
function checkTronDeposit(request, swap, a) {
|
|
441
|
+
commonAction(request, a);
|
|
442
|
+
if (a.type !== "transfer") fail("tron-action", "a Tron deposit must be a transfer with the swap's memo", "unsupported_pair");
|
|
443
|
+
if (!TRON_ADDRESS.test(a.toAddress)) fail("tron-target", "the Tron deposit address is not a Tron address", "upstream_unavailable");
|
|
444
|
+
const memo = a.callData ?? "";
|
|
445
|
+
if (memo !== swap.sequence.toString(10)) fail("tron-memo", "the Tron deposit memo does not name this swap", "policy_refused");
|
|
446
|
+
if (a.amountInBaseUnits !== request.amount) fail("tron-amount", `the deposit sends ${a.amountInBaseUnits ?? "nothing"}, not the input ${request.amount}`, "policy_refused");
|
|
447
|
+
return { to: a.toAddress, value: request.amount, memo };
|
|
448
|
+
}
|
|
449
|
+
var BTC_ADDRESS = /^(?:bc1[02-9ac-hj-np-z]{11,87}|[13][1-9A-HJ-NP-Za-km-z]{25,34})$/;
|
|
450
|
+
function checkBitcoinDeposit(request, a) {
|
|
451
|
+
commonAction(request, a);
|
|
452
|
+
if (a.type !== "manual_transfer") fail("btc-action", "a Bitcoin deposit must go to the swap's deposit address", "unsupported_pair");
|
|
453
|
+
if (a.callData !== null) fail("btc-action", "the Bitcoin deposit asks for a memo output, which this account does not write", "unsupported_pair");
|
|
454
|
+
if (!BTC_ADDRESS.test(a.toAddress)) fail("btc-target", "the deposit address is not a Bitcoin mainnet address", "upstream_unavailable");
|
|
455
|
+
if (a.amountInBaseUnits !== request.amount) fail("btc-amount", `the deposit asks for ${a.amountInBaseUnits ?? "nothing"} sat, not the input ${request.amount}`, "policy_refused");
|
|
456
|
+
return { to: a.toAddress, value: request.amount };
|
|
457
|
+
}
|
|
458
|
+
var B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
459
|
+
function base58Decode(text) {
|
|
460
|
+
if (!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(text)) return null;
|
|
461
|
+
let n = 0n;
|
|
462
|
+
for (const ch of text) n = n * 58n + BigInt(B58.indexOf(ch));
|
|
463
|
+
const bytes = [];
|
|
464
|
+
while (n > 0n) {
|
|
465
|
+
bytes.unshift(Number(n & 0xffn));
|
|
466
|
+
n >>= 8n;
|
|
467
|
+
}
|
|
468
|
+
for (const ch of text) {
|
|
469
|
+
if (ch !== "1") break;
|
|
470
|
+
bytes.unshift(0);
|
|
471
|
+
}
|
|
472
|
+
return Uint8Array.from(bytes);
|
|
473
|
+
}
|
|
474
|
+
function base58Encode(bytes) {
|
|
475
|
+
let n = 0n;
|
|
476
|
+
for (const b of bytes) n = n << 8n | BigInt(b);
|
|
477
|
+
let out = "";
|
|
478
|
+
while (n > 0n) {
|
|
479
|
+
out = B58[Number(n % 58n)] + out;
|
|
480
|
+
n /= 58n;
|
|
481
|
+
}
|
|
482
|
+
for (const b of bytes) {
|
|
483
|
+
if (b !== 0) break;
|
|
484
|
+
out = `1${out}`;
|
|
485
|
+
}
|
|
486
|
+
return out;
|
|
487
|
+
}
|
|
488
|
+
var SOLANA_MAX_COMPUTE_UNITS = 4e5;
|
|
489
|
+
var SOLANA_MAX_MICROLAMPORTS = 5000000n;
|
|
490
|
+
var SOLANA_PROGRAMS = Object.freeze({
|
|
491
|
+
system: "11111111111111111111111111111111",
|
|
492
|
+
token: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
|
|
493
|
+
token2022: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PazqiGFRk8ZVvo",
|
|
494
|
+
ata: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",
|
|
495
|
+
computeBudget: "ComputeBudget111111111111111111111111111111",
|
|
496
|
+
memoV1: "Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo",
|
|
497
|
+
memoV2: "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"
|
|
498
|
+
});
|
|
499
|
+
function withSignatureSlot(bytes, messageOffset) {
|
|
500
|
+
const message = bytes.subarray(messageOffset);
|
|
501
|
+
const out = new Uint8Array(1 + 64 + message.length);
|
|
502
|
+
out[0] = 1;
|
|
503
|
+
out.set(message, 65);
|
|
504
|
+
return base64Encode(out);
|
|
505
|
+
}
|
|
506
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
507
|
+
function base64Encode(bytes) {
|
|
508
|
+
let out = "";
|
|
509
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
510
|
+
const b0 = bytes[i], b1 = bytes[i + 1], b2 = bytes[i + 2];
|
|
511
|
+
const n = b0 << 16 | (b1 ?? 0) << 8 | (b2 ?? 0);
|
|
512
|
+
out += B64[n >> 18 & 63] + B64[n >> 12 & 63] + (b1 === void 0 ? "=" : B64[n >> 6 & 63]) + (b2 === void 0 ? "=" : B64[n & 63]);
|
|
513
|
+
}
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
var SOLANA_RENT_SYSVAR = "SysvarRent111111111111111111111111111111111";
|
|
517
|
+
function parseLegacyTransaction(bytes) {
|
|
518
|
+
let o = 0;
|
|
519
|
+
const u8 = () => {
|
|
520
|
+
if (o >= bytes.length) throw new Error("short");
|
|
521
|
+
return bytes[o++];
|
|
522
|
+
};
|
|
523
|
+
const cu16 = () => {
|
|
524
|
+
let v = 0;
|
|
525
|
+
for (let s = 0; s < 21; s += 7) {
|
|
526
|
+
const b = u8();
|
|
527
|
+
v |= (b & 127) << s;
|
|
528
|
+
if (!(b & 128)) return v;
|
|
529
|
+
}
|
|
530
|
+
throw new Error("bad length");
|
|
531
|
+
};
|
|
532
|
+
const take = (n) => {
|
|
533
|
+
if (n < 0 || o + n > bytes.length) throw new Error("short");
|
|
534
|
+
const out = bytes.subarray(o, o + n);
|
|
535
|
+
o += n;
|
|
536
|
+
return out;
|
|
537
|
+
};
|
|
538
|
+
try {
|
|
539
|
+
const numSignatures = cu16();
|
|
540
|
+
if (numSignatures > 8) return null;
|
|
541
|
+
take(64 * numSignatures);
|
|
542
|
+
const messageOffset = o;
|
|
543
|
+
const first = u8();
|
|
544
|
+
if (first & 128) return null;
|
|
545
|
+
const requiredSignatures = first;
|
|
546
|
+
u8();
|
|
547
|
+
u8();
|
|
548
|
+
const numKeys = cu16();
|
|
549
|
+
if (numKeys === 0 || numKeys > 64) return null;
|
|
550
|
+
const keys = [];
|
|
551
|
+
for (let i = 0; i < numKeys; i++) keys.push(base58Encode(take(32)));
|
|
552
|
+
take(32);
|
|
553
|
+
const numIx = cu16();
|
|
554
|
+
if (numIx > 16) return null;
|
|
555
|
+
const instructions = [];
|
|
556
|
+
for (let i = 0; i < numIx; i++) {
|
|
557
|
+
const p = u8();
|
|
558
|
+
const na = cu16();
|
|
559
|
+
const idx = Array.from(take(na));
|
|
560
|
+
const data = take(cu16());
|
|
561
|
+
if (p >= keys.length || idx.some((k) => k >= keys.length)) return null;
|
|
562
|
+
instructions.push({ program: keys[p], accounts: idx.map((k) => keys[k]), data: Uint8Array.from(data) });
|
|
563
|
+
}
|
|
564
|
+
if (o !== bytes.length) return null;
|
|
565
|
+
return { numSignatures, requiredSignatures, messageOffset, keys, instructions };
|
|
566
|
+
} catch {
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function associatedTokenAccount(owner, mint, tokenProgram) {
|
|
571
|
+
const o = base58Decode(owner), m = base58Decode(mint), t = base58Decode(tokenProgram), ata = base58Decode(SOLANA_PROGRAMS.ata);
|
|
572
|
+
if (!o || !m || !t || !ata || o.length !== 32 || m.length !== 32 || t.length !== 32) return null;
|
|
573
|
+
const marker = new TextEncoder().encode("ProgramDerivedAddress");
|
|
574
|
+
for (let bump = 255; bump >= 0; bump--) {
|
|
575
|
+
const h = (0, import_sha2.sha256)(Uint8Array.from([...o, ...t, ...m, bump, ...ata, ...marker]));
|
|
576
|
+
let onCurve = true;
|
|
577
|
+
try {
|
|
578
|
+
import_ed25519.ed25519.Point.fromBytes(h);
|
|
579
|
+
} catch {
|
|
580
|
+
onCurve = false;
|
|
581
|
+
}
|
|
582
|
+
if (!onCurve) return base58Encode(h);
|
|
583
|
+
}
|
|
584
|
+
return null;
|
|
585
|
+
}
|
|
586
|
+
var u64le = (d, at) => {
|
|
587
|
+
let v = 0n;
|
|
588
|
+
for (let i = 7; i >= 0; i--) v = v << 8n | BigInt(d[at + i]);
|
|
589
|
+
return v;
|
|
590
|
+
};
|
|
591
|
+
function checkSolanaDeposit(request, swap, a) {
|
|
592
|
+
commonAction(request, a);
|
|
593
|
+
if (a.type !== "transfer") fail("solana-action", "a Solana deposit must be the prepared transfer", "unsupported_pair");
|
|
594
|
+
const bytes = a.callData ? (0, import_util3.base64Bytes)(a.callData) : null;
|
|
595
|
+
const tx = bytes ? parseLegacyTransaction(bytes) : null;
|
|
596
|
+
if (!tx) fail("solana-tx", "the Solana deposit is not a legacy transaction", "policy_refused");
|
|
597
|
+
const t = tx;
|
|
598
|
+
if (t.requiredSignatures !== 1 || t.keys[0] !== request.sender) fail("solana-signer", "the Solana deposit is not signed by this account alone", "policy_refused");
|
|
599
|
+
if (t.numSignatures !== 0 && t.numSignatures !== 1) fail("solana-signer", "the Solana deposit carries signature slots for other signers", "policy_refused");
|
|
600
|
+
const allowed = new Set(Object.values(SOLANA_PROGRAMS));
|
|
601
|
+
const foreign = t.instructions.find((ix) => !allowed.has(ix.program));
|
|
602
|
+
if (foreign) fail("solana-program", `the Solana deposit calls ${clipName(foreign.program)}`, "policy_refused");
|
|
603
|
+
const memos = t.instructions.filter((ix) => ix.program === SOLANA_PROGRAMS.memoV1 || ix.program === SOLANA_PROGRAMS.memoV2);
|
|
604
|
+
const want = new TextEncoder().encode(swap.sequence.toString(10));
|
|
605
|
+
const memo = memos[0]?.data;
|
|
606
|
+
if (memos.length !== 1 || !memo || memo.length !== want.length || memo.some((b, i) => b !== want[i])) {
|
|
607
|
+
fail("solana-memo", "the Solana deposit does not carry exactly this swap's memo", "policy_refused");
|
|
608
|
+
}
|
|
609
|
+
const native = request.sourceContract === null;
|
|
610
|
+
let transfers = 0;
|
|
611
|
+
let limits = 0, prices = 0, creates = 0;
|
|
612
|
+
let createdUnder = null, transferredUnder = null;
|
|
613
|
+
for (const ix of t.instructions) {
|
|
614
|
+
if (ix.program === SOLANA_PROGRAMS.memoV1 || ix.program === SOLANA_PROGRAMS.memoV2) continue;
|
|
615
|
+
if (ix.program === SOLANA_PROGRAMS.computeBudget) {
|
|
616
|
+
if (ix.data.length === 5 && ix.data[0] === 2) {
|
|
617
|
+
const units = ix.data[1] | ix.data[2] << 8 | ix.data[3] << 16 | ix.data[4] * 2 ** 24;
|
|
618
|
+
if (++limits > 1 || units > SOLANA_MAX_COMPUTE_UNITS) fail("solana-compute", "the Solana deposit sets a compute limit above a transfer's", "policy_refused");
|
|
619
|
+
} else if (ix.data.length === 9 && ix.data[0] === 3) {
|
|
620
|
+
if (++prices > 1 || u64le(ix.data, 1) > SOLANA_MAX_MICROLAMPORTS) fail("solana-compute", "the Solana deposit sets a priority fee above the cap", "policy_refused");
|
|
621
|
+
} else {
|
|
622
|
+
fail("solana-compute", "the Solana deposit sets an unexpected compute-budget instruction", "policy_refused");
|
|
623
|
+
}
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
if (ix.program === SOLANA_PROGRAMS.system) {
|
|
627
|
+
if (!native || ix.data.length !== 12 || ix.data[0] !== 2 || ix.data[1] !== 0 || ix.data[2] !== 0 || ix.data[3] !== 0) fail("solana-system", "the Solana deposit runs an unexpected system instruction", "policy_refused");
|
|
628
|
+
if (ix.accounts[0] !== request.sender || ix.accounts[1] !== a.toAddress) fail("solana-transfer", "the SOL transfer is not from this account to the deposit address", "policy_refused");
|
|
629
|
+
if (u64le(ix.data, 4) !== request.amount) fail("solana-amount", "the SOL transfer is not exactly the input", "policy_refused");
|
|
630
|
+
transfers++;
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
if (ix.program === SOLANA_PROGRAMS.ata) {
|
|
634
|
+
if (native || !(ix.data.length === 0 || ix.data.length === 1 && (ix.data[0] === 0 || ix.data[0] === 1))) fail("solana-ata", "the Solana deposit runs an unexpected account instruction", "policy_refused");
|
|
635
|
+
const program = ix.accounts[5];
|
|
636
|
+
if (++creates > 1 || ix.accounts.length !== 6 && !(ix.accounts.length === 7 && ix.accounts[6] === SOLANA_RENT_SYSVAR) || ix.accounts[4] !== SOLANA_PROGRAMS.system || program !== SOLANA_PROGRAMS.token && program !== SOLANA_PROGRAMS.token2022) {
|
|
637
|
+
fail("solana-ata", "the Solana deposit runs an unexpected account instruction", "policy_refused");
|
|
638
|
+
}
|
|
639
|
+
const owner2 = ix.accounts[2];
|
|
640
|
+
const created = owner2 === request.sender || owner2 === a.toAddress ? associatedTokenAccount(owner2, request.sourceContract, program) : null;
|
|
641
|
+
if (ix.accounts[0] !== request.sender || ix.accounts[3] !== request.sourceContract || !created || ix.accounts[1] !== created) {
|
|
642
|
+
fail("solana-ata", "the Solana deposit creates an account that is neither this account's nor the deposit address's", "policy_refused");
|
|
643
|
+
}
|
|
644
|
+
createdUnder = program;
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
if (native) fail("solana-token", "a SOL deposit runs a token instruction", "policy_refused");
|
|
648
|
+
const checked = ix.data.length === 10 && ix.data[0] === 12;
|
|
649
|
+
const plain = ix.data.length === 9 && ix.data[0] === 3;
|
|
650
|
+
if (!checked && !plain) fail("solana-token", "the Solana deposit runs an unexpected token instruction", "policy_refused");
|
|
651
|
+
const [src, dst, owner] = checked ? [ix.accounts[0], ix.accounts[2], ix.accounts[3]] : [ix.accounts[0], ix.accounts[1], ix.accounts[2]];
|
|
652
|
+
if (checked && (ix.accounts[1] !== request.sourceContract || ix.data[9] !== request.sourceDecimals)) fail("solana-token", "the token transfer is not of the source mint", "policy_refused");
|
|
653
|
+
if (owner !== request.sender) fail("solana-token", "the token transfer is not authorized by this account", "policy_refused");
|
|
654
|
+
if (u64le(ix.data, 1) !== request.amount) fail("solana-amount", "the token transfer is not exactly the input", "policy_refused");
|
|
655
|
+
const own = associatedTokenAccount(request.sender, request.sourceContract, ix.program);
|
|
656
|
+
if (!own || src !== own) fail("solana-token", "the token transfer does not spend this account's own token account", "policy_refused");
|
|
657
|
+
const theirs = associatedTokenAccount(a.toAddress, request.sourceContract, ix.program);
|
|
658
|
+
if (!theirs || dst !== theirs) fail("solana-transfer", "the token transfer does not pay the deposit address's token account", "policy_refused");
|
|
659
|
+
transferredUnder = ix.program;
|
|
660
|
+
transfers++;
|
|
661
|
+
}
|
|
662
|
+
if (transfers !== 1) fail("solana-transfer", "the Solana deposit does not make exactly one transfer", "policy_refused");
|
|
663
|
+
if (createdUnder !== null && createdUnder !== transferredUnder) fail("solana-ata", "the Solana deposit creates the account under another token program than the transfer's", "policy_refused");
|
|
664
|
+
return { serializedTx: t.numSignatures === 1 ? a.callData : withSignatureSlot(bytes, t.messageOffset), depositTo: a.toAddress, value: native ? request.amount : 0n };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// src/provider.ts
|
|
668
|
+
var INTENT_PREFIX = "layerswap:";
|
|
669
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
670
|
+
var QUOTE_TTL_MS = 6e4;
|
|
671
|
+
var SOLANA_QUOTE_TTL_MS = 4e4;
|
|
672
|
+
var NETWORKS_TTL_MS = 15 * 6e4;
|
|
673
|
+
var NETWORKS_TIMEOUT_MS = 25e3;
|
|
674
|
+
var CREATE_TIMEOUT_MS = 25e3;
|
|
675
|
+
var STATUS_TIMEOUT_MS = 12e3;
|
|
676
|
+
var MAX_REMEMBERED = 256;
|
|
677
|
+
var GAS_FLOOR_NATIVE = 120000n;
|
|
678
|
+
var GAS_FLOOR_ERC20 = 160000n;
|
|
679
|
+
var GAS_CAP = 3000000n;
|
|
680
|
+
var MAX_SIGNIFICANT_DIGITS = 15;
|
|
681
|
+
var dryCounter = 0;
|
|
682
|
+
var LAYERSWAP_STATUS_MAP = Object.freeze({
|
|
683
|
+
user_transfer_pending: "pending",
|
|
684
|
+
ls_transfer_pending: "pending",
|
|
685
|
+
completed: "completed",
|
|
686
|
+
failed: "failed",
|
|
687
|
+
expired: "expired",
|
|
688
|
+
pending_refund: "refund-pending",
|
|
689
|
+
refunded: "refunded"
|
|
690
|
+
});
|
|
691
|
+
function etaSeconds(value) {
|
|
692
|
+
if (typeof value !== "string") return null;
|
|
693
|
+
const m = /^(?:(\d{1,3})\.)?(\d{1,2}):(\d{2}):(\d{2})(\.\d{1,9})?$/.exec(value.trim());
|
|
694
|
+
if (!m) return null;
|
|
695
|
+
const s = Number(m[1] ?? 0) * 86400 + Number(m[2]) * 3600 + Number(m[3]) * 60 + Number(m[4]) + Number(m[5] ?? 0);
|
|
696
|
+
return Math.min(Math.max(1, Math.ceil(s)), 7 * 86400);
|
|
697
|
+
}
|
|
698
|
+
function slippageText(bps) {
|
|
699
|
+
const tight = Math.max(0, Math.floor(bps) - 1);
|
|
700
|
+
return unitsToDecimal(BigInt(tight), 4);
|
|
701
|
+
}
|
|
702
|
+
var NETWORK_NAME = /^[A-Z][A-Z0-9_]{1,47}$/;
|
|
703
|
+
function layerswapProvider(config = {}) {
|
|
704
|
+
config = Object.freeze({ ...config });
|
|
705
|
+
const api = layerswapClient(config, LAYERSWAP_API);
|
|
706
|
+
let networksCache = null;
|
|
707
|
+
async function networks(signal) {
|
|
708
|
+
if (networksCache && Date.now() - networksCache.at < NETWORKS_TTL_MS) return networksCache.list;
|
|
709
|
+
const a = await api.get("/networks", void 0, signal, NETWORKS_TIMEOUT_MS, MAX_NETWORKS_BODY);
|
|
710
|
+
if (!a.ok) throw new LayerswapRefusal("networks", `the network list is unavailable (${answerRefusal(a).text})`, "upstream_unavailable");
|
|
711
|
+
const list = parseNetworks(a.body?.data);
|
|
712
|
+
networksCache = { at: Date.now(), list };
|
|
713
|
+
return list;
|
|
714
|
+
}
|
|
715
|
+
const issued = /* @__PURE__ */ new Map();
|
|
716
|
+
const cleared = /* @__PURE__ */ new Set();
|
|
717
|
+
const remember = (m, k, v) => {
|
|
718
|
+
m.delete(k);
|
|
719
|
+
m.set(k, v);
|
|
720
|
+
if (m.size > MAX_REMEMBERED) m.delete(m.keys().next().value);
|
|
721
|
+
};
|
|
722
|
+
async function resolve(params, live, signal) {
|
|
723
|
+
const funding = fundingFor(params.sourceChain);
|
|
724
|
+
if (!funding || !layerswapNetwork(params.destChain) || params.sourceChain === params.destChain) {
|
|
725
|
+
throw new LayerswapRefusal("route", `does not serve ${params.sourceChain} \u2192 ${params.destChain}`, "unsupported_pair");
|
|
726
|
+
}
|
|
727
|
+
if (params.flex) throw new LayerswapRefusal("route", "only an exact input is quoted", "unsupported_pair");
|
|
728
|
+
const source = (0, import_util4.sourceAssetOf)(params);
|
|
729
|
+
if (!source) throw new LayerswapRefusal("source-token", `unknown source token ${clip(params.sourceToken, 60)} on ${params.sourceChain}`, "unsupported_pair");
|
|
730
|
+
const listedDest = (0, import_swap2_assets.resolveAsset)(params.destChain, params.destToken);
|
|
731
|
+
const destContract = listedDest ? listedDest.contract ?? null : params.destToken === "" || /^0x0{40}$/i.test(params.destToken) ? null : params.destToken;
|
|
732
|
+
const list = await networks(signal);
|
|
733
|
+
const srcNet = networkFor(params.sourceChain, list);
|
|
734
|
+
const dstNet = networkFor(params.destChain, list);
|
|
735
|
+
if (!srcNet || !dstNet) throw new LayerswapRefusal("route", `Layerswap does not list ${!srcNet ? params.sourceChain : params.destChain}`, "unsupported_pair");
|
|
736
|
+
if (!NETWORK_NAME.test(srcNet.name) || !NETWORK_NAME.test(dstNet.name)) throw new LayerswapRefusal("route", "Layerswap names the network unreadably", "upstream_unavailable");
|
|
737
|
+
const srcToken = tokenOn(params.sourceChain, srcNet, source.contract ?? null);
|
|
738
|
+
if (!srcToken) throw new LayerswapRefusal("source-token", `Layerswap does not take ${source.symbol} on ${params.sourceChain}`, "unsupported_pair");
|
|
739
|
+
if (srcToken.decimals !== source.decimals) throw new LayerswapRefusal("source-token", `Layerswap counts ${source.symbol} in ${srcToken.decimals} decimals, not ${source.decimals}`, "policy_refused");
|
|
740
|
+
const dstToken = tokenOn(params.destChain, dstNet, destContract);
|
|
741
|
+
if (!dstToken) throw new LayerswapRefusal("destination-token", `Layerswap does not pay out ${clip(params.destToken || "the native coin", 60)} on ${params.destChain}`, "unsupported_pair");
|
|
742
|
+
if (listedDest && dstToken.decimals !== listedDest.decimals) throw new LayerswapRefusal("destination-token", `Layerswap counts the output in ${dstToken.decimals} decimals, not ${listedDest.decimals}`, "policy_refused");
|
|
743
|
+
if (!/^[1-9]\d{0,77}$/.test(params.amountIn)) throw new LayerswapRefusal("amount", "the input amount is not a positive integer", "policy_refused");
|
|
744
|
+
const significant = unitsToDecimal(BigInt(params.amountIn), source.decimals).replace(".", "").replace(/^0+/, "").replace(/0+$/, "");
|
|
745
|
+
if (significant.length > MAX_SIGNIFICANT_DIGITS) {
|
|
746
|
+
throw new LayerswapRefusal("amount", `Layerswap takes amounts as a double: at most ${MAX_SIGNIFICANT_DIGITS} significant digits \u2014 round the amount`, "policy_refused");
|
|
747
|
+
}
|
|
748
|
+
const sender = params.sender ?? params.refundAddress ?? "";
|
|
749
|
+
if (live) {
|
|
750
|
+
if (!params.destAddress) throw new LayerswapRefusal("request", "a swap is never created without the recipient", "recipient_mismatch");
|
|
751
|
+
if (!sender) throw new LayerswapRefusal("request", "a swap is never created without the sending account", "policy_refused");
|
|
752
|
+
if (params.refundAddress && params.refundAddress !== sender) throw new LayerswapRefusal("request", "the refund address must be the sending account", "policy_refused");
|
|
753
|
+
}
|
|
754
|
+
return {
|
|
755
|
+
funding,
|
|
756
|
+
sourceNetwork: srcNet.name,
|
|
757
|
+
destNetwork: dstNet.name,
|
|
758
|
+
sourceSymbol: srcToken.symbol,
|
|
759
|
+
destSymbol: dstToken.symbol,
|
|
760
|
+
destDecimals: dstToken.decimals,
|
|
761
|
+
request: {
|
|
762
|
+
sourceChain: params.sourceChain,
|
|
763
|
+
destChain: params.destChain,
|
|
764
|
+
sourceContract: source.contract ?? null,
|
|
765
|
+
sourceDecimals: source.decimals,
|
|
766
|
+
destContract,
|
|
767
|
+
amount: BigInt(params.amountIn),
|
|
768
|
+
sender,
|
|
769
|
+
recipient: params.destAddress,
|
|
770
|
+
funding
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
function readQuote(r, quote) {
|
|
775
|
+
const q = quote ?? null;
|
|
776
|
+
if (!q) throw new LayerswapRefusal("quote", "the answer carries no quote", "upstream_unavailable");
|
|
777
|
+
const splits = q.integrator_fee_splits;
|
|
778
|
+
const integratorFee = q.integrator_fee;
|
|
779
|
+
if ((Array.isArray(splits) ? splits.length > 0 : splits !== void 0 && splits !== null) || typeof integratorFee === "number" && integratorFee > 0) {
|
|
780
|
+
throw new LayerswapRefusal("quote", "the quote charges an integrator fee this module did not ask for", "policy_refused");
|
|
781
|
+
}
|
|
782
|
+
if (typeof q.refuel_in_source === "number" && q.refuel_in_source > 0) throw new LayerswapRefusal("quote", "the quote converts part of the input into a gas top-up this module did not ask for", "policy_refused");
|
|
783
|
+
const dest = decimalToUnits(q.receive_amount, r.destDecimals);
|
|
784
|
+
const min = decimalToUnits(q.min_receive_amount, r.destDecimals);
|
|
785
|
+
if (dest === null || min === null || dest <= 0n || min <= 0n || min > dest) throw new LayerswapRefusal("quote", "the quote's amounts are unreadable", "upstream_unavailable");
|
|
786
|
+
const fee = typeof q.total_fee_in_usd === "number" && Number.isFinite(q.total_fee_in_usd) && q.total_fee_in_usd >= 0 ? q.total_fee_in_usd : 0;
|
|
787
|
+
const path = Array.isArray(q.path) ? q.path.map((p) => clip(String(p?.provider ?? "?"), 30)).join(">") : "";
|
|
788
|
+
return { dest, min, feeUsd: fee, eta: etaSeconds(q.avg_completion_time), path };
|
|
789
|
+
}
|
|
790
|
+
function routeQuery(r, params) {
|
|
791
|
+
return {
|
|
792
|
+
source_network: r.sourceNetwork,
|
|
793
|
+
source_token: r.sourceSymbol,
|
|
794
|
+
destination_network: r.destNetwork,
|
|
795
|
+
destination_token: r.destSymbol,
|
|
796
|
+
amount: unitsToDecimal(r.request.amount, r.request.sourceDecimals),
|
|
797
|
+
...r.funding === "depository" ? { use_depository: "true" } : {},
|
|
798
|
+
...r.funding === "deposit_address" ? { use_deposit_address: "true" } : {},
|
|
799
|
+
...params.slippageBps !== void 0 ? { slippage: slippageText(params.slippageBps) } : {}
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
function checkDeposit(request, swap, actions) {
|
|
803
|
+
const a = pickAction(actions);
|
|
804
|
+
const ns = request.sourceChain.split(":")[0];
|
|
805
|
+
if (ns === "eip155") return { kind: "evm", evm: checkEvmDeposit(request, swap, a) };
|
|
806
|
+
if (ns === "solana") return { kind: "solana", solana: checkSolanaDeposit(request, swap, a) };
|
|
807
|
+
if (ns === "ton") return { kind: "memo", memo: checkTonDeposit(request, swap, a) };
|
|
808
|
+
if (ns === "tron") return { kind: "memo", memo: checkTronDeposit(request, swap, a) };
|
|
809
|
+
return { kind: "memo", memo: checkBitcoinDeposit(request, a) };
|
|
810
|
+
}
|
|
811
|
+
function requestOf(quote) {
|
|
812
|
+
const mine = issued.get(quote.intentId);
|
|
813
|
+
if (!mine) throw new LayerswapRefusal("request", "this quote was not issued by this provider instance \u2014 quote again", "policy_refused");
|
|
814
|
+
return mine;
|
|
815
|
+
}
|
|
816
|
+
function swapIdOf(intentId) {
|
|
817
|
+
const id = intentId.startsWith(INTENT_PREFIX) ? intentId.slice(INTENT_PREFIX.length) : "";
|
|
818
|
+
if (!UUID2.test(id)) throw new LayerswapRefusal("intent", "malformed Layerswap intent id", "policy_refused");
|
|
819
|
+
return id;
|
|
820
|
+
}
|
|
821
|
+
async function readBack(request, swapId) {
|
|
822
|
+
const [a, d] = await Promise.all([
|
|
823
|
+
api.get(`/swaps/${swapId}`, { exclude_deposit_actions: "true" }, void 0, STATUS_TIMEOUT_MS),
|
|
824
|
+
api.get(`/swaps/${swapId}/deposit_actions`, { source_address: request.sender }, void 0, STATUS_TIMEOUT_MS)
|
|
825
|
+
]);
|
|
826
|
+
for (const r of [a, d]) {
|
|
827
|
+
if (!r.ok) {
|
|
828
|
+
const why = answerRefusal(r);
|
|
829
|
+
throw new LayerswapRefusal("read-back", `the swap could not be read back (${why.text})`, why.info.reason);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
const data = a.body?.data ?? null;
|
|
833
|
+
const record = checkSwapRecord(request, data?.swap);
|
|
834
|
+
if (record.id !== swapId) throw new LayerswapRefusal("read-back", "the read-back answered another swap", "policy_refused");
|
|
835
|
+
if (record.status !== "user_transfer_pending") throw new LayerswapRefusal("read-back", `the swap is ${clip(record.status || "in an unknown state", 40)}, no longer waiting for a deposit \u2014 quote again`, "quote_expired");
|
|
836
|
+
return { record, actions: d.body?.data };
|
|
837
|
+
}
|
|
838
|
+
function currentDeposit(quote, request, now) {
|
|
839
|
+
const { record, actions } = now;
|
|
840
|
+
if (record.sequence.toString(10) !== quote.providerData?.sequence) throw new LayerswapRefusal("read-back", "the swap's sequence number changed", "policy_refused");
|
|
841
|
+
const tx = quote.txRequest;
|
|
842
|
+
if (request.sourceChain.startsWith("eip155:")) {
|
|
843
|
+
const e = checkEvmDeposit(request, record, pickAction(actions));
|
|
844
|
+
if (!tx || tx.to !== e.to || tx.data !== e.data || tx.value !== e.value.toString(10)) throw new LayerswapRefusal("build", "the swap's deposit changed since the quote \u2014 quote again", "quote_expired");
|
|
845
|
+
return { chain: request.sourceChain, to: e.to, value: tx.value, data: e.data, chainId: e.chainId, ...tx.gasLimit ? { gasLimit: tx.gasLimit } : {}, ...e.approvalAddress ? { approvalAddress: e.approvalAddress } : {} };
|
|
846
|
+
}
|
|
847
|
+
if (request.sourceChain.startsWith("solana:")) {
|
|
848
|
+
if (!tx?.serializedTx) throw new LayerswapRefusal("build", "the Solana quote carries no transaction", "policy_refused");
|
|
849
|
+
const s = checkSolanaDeposit(request, record, { ...pickAction(actions), callData: tx.serializedTx });
|
|
850
|
+
if (s.depositTo !== quote.providerData?.depositTo) throw new LayerswapRefusal("build", "the swap's deposit address changed since the quote \u2014 quote again", "quote_expired");
|
|
851
|
+
return { chain: request.sourceChain, to: "", value: s.value.toString(10), serializedTx: s.serializedTx };
|
|
852
|
+
}
|
|
853
|
+
const d = checkDeposit(request, record, actions);
|
|
854
|
+
if (d.kind !== "memo" || d.memo.to !== quote.depositAddress || (d.memo.memo ?? null) !== quote.depositMemo) {
|
|
855
|
+
throw new LayerswapRefusal("build", "the swap's deposit address or memo changed since the quote \u2014 quote again", "quote_expired");
|
|
856
|
+
}
|
|
857
|
+
return { chain: request.sourceChain, to: d.memo.to, value: d.memo.value.toString(10), ...d.memo.memo !== void 0 ? { memo: d.memo.memo } : {} };
|
|
858
|
+
}
|
|
859
|
+
return {
|
|
860
|
+
name: "layerswap",
|
|
861
|
+
describeActivity: describeLayerswapActivity,
|
|
862
|
+
enabled: () => config.enabled ?? true,
|
|
863
|
+
// The Depository call goes out with the account's own gas estimate of exactly that call, dry-run before broadcast.
|
|
864
|
+
ownGasEstimate: true,
|
|
865
|
+
supportsChain: (chain) => layerswap.supportsChain(chain),
|
|
866
|
+
supportsChainPair: (from, to) => layerswap.supports(from, to),
|
|
867
|
+
supportsRoute: (from, to) => layerswap.supports(from.chain, to.chain),
|
|
868
|
+
async getQuote(params, signal) {
|
|
869
|
+
const refuse = (text, info) => {
|
|
870
|
+
params.onRefusal?.(text.startsWith("layerswap:") ? text : `layerswap: ${text}`, info);
|
|
871
|
+
return null;
|
|
872
|
+
};
|
|
873
|
+
const live = params.dry === false;
|
|
874
|
+
try {
|
|
875
|
+
const r = await resolve(params, live, signal);
|
|
876
|
+
if (!live) {
|
|
877
|
+
const a2 = await api.get("/quote", routeQuery(r, params), signal);
|
|
878
|
+
if (!a2.ok || !a2.body?.data) {
|
|
879
|
+
const why = answerRefusal(a2);
|
|
880
|
+
return refuse(`no quote \u2014 ${why.text}`, signal?.aborted ? void 0 : why.info);
|
|
881
|
+
}
|
|
882
|
+
const q2 = readQuote(r, a2.body.data.quote);
|
|
883
|
+
return {
|
|
884
|
+
provider: "layerswap",
|
|
885
|
+
intentId: `dry:${Date.now().toString(36)}-${(dryCounter = (dryCounter + 1) % 1e6).toString(36)}`,
|
|
886
|
+
depositAddress: "",
|
|
887
|
+
depositMemo: null,
|
|
888
|
+
sourceAmount: params.amountIn,
|
|
889
|
+
destAmount: q2.dest.toString(10),
|
|
890
|
+
minDestAmount: q2.min.toString(10),
|
|
891
|
+
destDecimals: r.destDecimals,
|
|
892
|
+
feeUsd: q2.feeUsd,
|
|
893
|
+
etaSeconds: q2.eta,
|
|
894
|
+
reliability: 0.95,
|
|
895
|
+
validUntilMs: Date.now() + QUOTE_TTL_MS,
|
|
896
|
+
providerData: { path: q2.path, funding: r.funding }
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
const query = routeQuery(r, params);
|
|
900
|
+
const body = JSON.stringify({
|
|
901
|
+
source_network: query.source_network,
|
|
902
|
+
source_token: query.source_token,
|
|
903
|
+
destination_network: query.destination_network,
|
|
904
|
+
destination_token: query.destination_token,
|
|
905
|
+
amount: "__AMOUNT__",
|
|
906
|
+
source_address: r.request.sender,
|
|
907
|
+
destination_address: r.request.recipient,
|
|
908
|
+
refund_address: r.request.sender,
|
|
909
|
+
refuel: false,
|
|
910
|
+
...r.funding === "depository" ? { use_depository: true } : {},
|
|
911
|
+
...r.funding === "deposit_address" ? { use_deposit_address: true } : {},
|
|
912
|
+
...query.slippage !== void 0 ? { slippage: query.slippage } : {}
|
|
913
|
+
}).replace('"__AMOUNT__"', query.amount);
|
|
914
|
+
const a = await api.post("/swaps", body, signal, CREATE_TIMEOUT_MS);
|
|
915
|
+
if (!a.ok || !a.body?.data) {
|
|
916
|
+
const why = answerRefusal(a);
|
|
917
|
+
return refuse(`no swap \u2014 ${why.text}`, signal?.aborted ? void 0 : why.info);
|
|
918
|
+
}
|
|
919
|
+
const data = a.body.data;
|
|
920
|
+
const record = checkSwapRecord(r.request, data.swap);
|
|
921
|
+
if (record.status !== "user_transfer_pending") return refuse(`the new swap is ${clip(record.status, 40)}, not waiting for a deposit`, { reason: "upstream_unavailable" });
|
|
922
|
+
const q = readQuote(r, data.quote);
|
|
923
|
+
const deposit = checkDeposit(r.request, record, data.deposit_actions);
|
|
924
|
+
const intentId = `${INTENT_PREFIX}${record.id}`;
|
|
925
|
+
remember(issued, intentId, r.request);
|
|
926
|
+
const ttl = deposit.kind === "solana" ? SOLANA_QUOTE_TTL_MS : QUOTE_TTL_MS;
|
|
927
|
+
const common = {
|
|
928
|
+
provider: "layerswap",
|
|
929
|
+
intentId,
|
|
930
|
+
sourceAmount: params.amountIn,
|
|
931
|
+
destAmount: q.dest.toString(10),
|
|
932
|
+
minDestAmount: q.min.toString(10),
|
|
933
|
+
destDecimals: r.destDecimals,
|
|
934
|
+
feeUsd: q.feeUsd,
|
|
935
|
+
etaSeconds: q.eta,
|
|
936
|
+
reliability: 0.95,
|
|
937
|
+
validUntilMs: Date.now() + ttl
|
|
938
|
+
};
|
|
939
|
+
const pd = { swapId: record.id, sequence: record.sequence.toString(10), funding: r.funding, path: q.path, depositTo: deposit.kind === "evm" ? deposit.evm.to : deposit.kind === "solana" ? deposit.solana.depositTo : deposit.memo.to };
|
|
940
|
+
if (deposit.kind === "evm") {
|
|
941
|
+
const e = deposit.evm;
|
|
942
|
+
const floor = e.approvalAddress ? GAS_FLOOR_ERC20 : GAS_FLOOR_NATIVE;
|
|
943
|
+
const doubled = e.gasLimit !== null ? e.gasLimit * 2n : 0n;
|
|
944
|
+
const gas = doubled > GAS_CAP ? GAS_CAP : doubled > floor ? doubled : floor;
|
|
945
|
+
return {
|
|
946
|
+
...common,
|
|
947
|
+
depositAddress: "",
|
|
948
|
+
depositMemo: null,
|
|
949
|
+
txRequest: {
|
|
950
|
+
to: e.to,
|
|
951
|
+
data: e.data,
|
|
952
|
+
value: e.value.toString(10),
|
|
953
|
+
chainId: e.chainId,
|
|
954
|
+
gasLimit: gas.toString(10),
|
|
955
|
+
...e.approvalAddress ? { approvalAddress: e.approvalAddress } : {}
|
|
956
|
+
},
|
|
957
|
+
providerData: { ...pd, receiver: e.receiver }
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
if (deposit.kind === "solana") {
|
|
961
|
+
return {
|
|
962
|
+
...common,
|
|
963
|
+
depositAddress: "",
|
|
964
|
+
depositMemo: null,
|
|
965
|
+
txRequest: { value: deposit.solana.value.toString(10), serializedTx: deposit.solana.serializedTx },
|
|
966
|
+
providerData: pd
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
return { ...common, depositAddress: deposit.memo.to, depositMemo: deposit.memo.memo ?? null, providerData: pd };
|
|
970
|
+
} catch (err) {
|
|
971
|
+
if (err instanceof LayerswapRefusal) return refuse(err.message, (0, import_errors3.refusalOf)(err));
|
|
972
|
+
const info = (0, import_errors3.refusalOf)(err) ?? (signal?.aborted ? void 0 : { reason: "upstream_unavailable" });
|
|
973
|
+
return refuse(`request failed \u2014 ${clip(err instanceof Error ? err.message : String(err))}`, info);
|
|
974
|
+
}
|
|
975
|
+
},
|
|
976
|
+
/** The quote's own deposit, after the swap has been read back and its deposit checked once more. */
|
|
977
|
+
async buildDeposit(quote) {
|
|
978
|
+
const request = requestOf(quote);
|
|
979
|
+
return currentDeposit(quote, request, await readBack(request, swapIdOf(quote.intentId)));
|
|
980
|
+
},
|
|
981
|
+
/** Right before the signature: the swap read back once more, and each swap funded once. */
|
|
982
|
+
async preflightDeposit(quote, tx) {
|
|
983
|
+
const request = requestOf(quote);
|
|
984
|
+
const swapId = swapIdOf(quote.intentId);
|
|
985
|
+
if (tx.chain && tx.chain !== request.sourceChain) throw new LayerswapRefusal("preflight", `the deposit is for ${clip(tx.chain, 40)}, not ${request.sourceChain}`, "vault_mismatch");
|
|
986
|
+
if (tx.typedData !== void 0 || tx.bodyBoc !== void 0 || tx.permit2Transfer !== void 0) throw new LayerswapRefusal("preflight", "a Layerswap deposit is one transfer or one Depository call", "policy_refused");
|
|
987
|
+
const valueLeg = request.sourceChain.startsWith("eip155:") || request.sourceChain.startsWith("solana:");
|
|
988
|
+
const expected = valueLeg ? request.sourceContract === null ? request.amount : 0n : request.amount;
|
|
989
|
+
if (!/^\d{1,78}$/.test(tx.value || "") || BigInt(tx.value) !== expected) throw new LayerswapRefusal("preflight", "the deposit value is not the input", "policy_refused");
|
|
990
|
+
if (cleared.has(swapId)) throw new LayerswapRefusal("preflight", "this swap was already cleared for a deposit \u2014 quote again", "policy_refused");
|
|
991
|
+
const now = currentDeposit(quote, request, await readBack(request, swapId));
|
|
992
|
+
const same = (x, y) => (x ?? "").toLowerCase() === (y ?? "").toLowerCase();
|
|
993
|
+
if (!same(tx.to, now.to) || tx.value !== now.value || !same(tx.data, now.data) || tx.serializedTx !== now.serializedTx || (tx.memo ?? null) !== (now.memo ?? null) || !same(tx.approvalAddress, now.approvalAddress)) {
|
|
994
|
+
throw new LayerswapRefusal("preflight", "the transaction about to be signed is not the swap's deposit", "policy_refused");
|
|
995
|
+
}
|
|
996
|
+
cleared.add(swapId);
|
|
997
|
+
if (cleared.size > MAX_REMEMBERED) cleared.delete(cleared.values().next().value);
|
|
998
|
+
},
|
|
999
|
+
/** Layerswap matches deposits on its own; the hash speeds that up. Best effort. */
|
|
1000
|
+
async notifyDeposit(intentId, txHash) {
|
|
1001
|
+
const swapId = swapIdOf(intentId);
|
|
1002
|
+
if (typeof txHash !== "string" || !/^[\x21-\x7e]{8,200}$/.test(txHash)) return;
|
|
1003
|
+
const a = await api.post(`/swaps/${swapId}/deposit_speedup`, JSON.stringify({ transaction_id: txHash }), void 0, STATUS_TIMEOUT_MS);
|
|
1004
|
+
if (!a.ok) {
|
|
1005
|
+
const why = answerRefusal(a);
|
|
1006
|
+
throw new LayerswapRefusal("notify", `deposit speed-up failed (${why.text})`, why.info.reason);
|
|
1007
|
+
}
|
|
1008
|
+
},
|
|
1009
|
+
async trackIntent(ref) {
|
|
1010
|
+
let swapId;
|
|
1011
|
+
try {
|
|
1012
|
+
swapId = swapIdOf(ref.intentId);
|
|
1013
|
+
} catch {
|
|
1014
|
+
return { state: "failed" };
|
|
1015
|
+
}
|
|
1016
|
+
try {
|
|
1017
|
+
const a = await api.get(`/swaps/${swapId}`, { exclude_deposit_actions: "true" }, void 0, STATUS_TIMEOUT_MS);
|
|
1018
|
+
if (!a.ok) return { state: "pending" };
|
|
1019
|
+
const swap = (a.body?.data ?? null)?.swap;
|
|
1020
|
+
const status = typeof swap?.status === "string" ? swap.status : "";
|
|
1021
|
+
if (String(swap?.id ?? "").toLowerCase() !== swapId) return { state: "pending" };
|
|
1022
|
+
if (status === "user_transfer_pending" && ref.sourceTxHash) {
|
|
1023
|
+
await this.notifyDeposit?.(ref.intentId, ref.sourceTxHash).catch(() => {
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
const state = Object.prototype.hasOwnProperty.call(LAYERSWAP_STATUS_MAP, status) ? LAYERSWAP_STATUS_MAP[status] : "pending";
|
|
1027
|
+
const txs = Array.isArray(swap?.transactions) ? swap.transactions : [];
|
|
1028
|
+
const output = txs.find((t) => t?.type === "output" && typeof t.transaction_hash === "string" && /^[\x21-\x7e]{8,200}$/.test(t.transaction_hash));
|
|
1029
|
+
const received = status !== "user_transfer_pending" && status !== "expired" && status !== "";
|
|
1030
|
+
return { state, ...received ? { depositReceived: true } : {}, ...state === "completed" && output ? { destTxHash: output.transaction_hash } : {} };
|
|
1031
|
+
} catch {
|
|
1032
|
+
return { state: "pending" };
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// src/protocol.ts
|
|
1039
|
+
var LayerswapSwap2Protocol = class extends import_single.SingleProviderSwap2 {
|
|
1040
|
+
provider;
|
|
1041
|
+
constructor(account, config) {
|
|
1042
|
+
super(account, config);
|
|
1043
|
+
this.provider = layerswapProvider(config);
|
|
1044
|
+
}
|
|
1045
|
+
chainSupported(caip2) {
|
|
1046
|
+
return layerswap.supportsChain(caip2);
|
|
1047
|
+
}
|
|
1048
|
+
pairSupported(fromChain, toChain) {
|
|
1049
|
+
return layerswap.supports(fromChain, toChain);
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
//# sourceMappingURL=protocol.cjs.map
|