@anywalletkit/protocol-swap2-stargate 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +502 -2
  3. package/dist/abi.cjs +91 -0
  4. package/dist/abi.cjs.map +1 -0
  5. package/dist/abi.d.cts +810 -0
  6. package/dist/abi.d.ts +810 -0
  7. package/dist/abi.js +13 -0
  8. package/dist/abi.js.map +1 -0
  9. package/dist/amounts.cjs +73 -0
  10. package/dist/amounts.cjs.map +1 -0
  11. package/dist/amounts.d.cts +21 -0
  12. package/dist/amounts.d.ts +21 -0
  13. package/dist/amounts.js +15 -0
  14. package/dist/amounts.js.map +1 -0
  15. package/dist/bus-Cdw8iwOv.d.cts +59 -0
  16. package/dist/bus-vAWqTAkq.d.ts +59 -0
  17. package/dist/bus.cjs +237 -0
  18. package/dist/bus.cjs.map +1 -0
  19. package/dist/bus.d.cts +4 -0
  20. package/dist/bus.d.ts +4 -0
  21. package/dist/bus.js +22 -0
  22. package/dist/bus.js.map +1 -0
  23. package/dist/chunk-3NTMZUAU.js +128 -0
  24. package/dist/chunk-3NTMZUAU.js.map +1 -0
  25. package/dist/chunk-4HU46QF2.js +256 -0
  26. package/dist/chunk-4HU46QF2.js.map +1 -0
  27. package/dist/chunk-4IDDRIE2.js +125 -0
  28. package/dist/chunk-4IDDRIE2.js.map +1 -0
  29. package/dist/chunk-EANM3EI3.js +71 -0
  30. package/dist/chunk-EANM3EI3.js.map +1 -0
  31. package/dist/chunk-ERC6LKMN.js +87 -0
  32. package/dist/chunk-ERC6LKMN.js.map +1 -0
  33. package/dist/chunk-FLAXDJPE.js +24 -0
  34. package/dist/chunk-FLAXDJPE.js.map +1 -0
  35. package/dist/chunk-N54YIG6T.js +33 -0
  36. package/dist/chunk-N54YIG6T.js.map +1 -0
  37. package/dist/chunk-OUGUX3JK.js +53 -0
  38. package/dist/chunk-OUGUX3JK.js.map +1 -0
  39. package/dist/chunk-PJXDMVW3.js +909 -0
  40. package/dist/chunk-PJXDMVW3.js.map +1 -0
  41. package/dist/chunk-QNVTQEOV.js +72 -0
  42. package/dist/chunk-QNVTQEOV.js.map +1 -0
  43. package/dist/chunk-UDJL7BUP.js +249 -0
  44. package/dist/chunk-UDJL7BUP.js.map +1 -0
  45. package/dist/chunk-YHHV3XHY.js +139 -0
  46. package/dist/chunk-YHHV3XHY.js.map +1 -0
  47. package/dist/compose-dex.cjs +148 -0
  48. package/dist/compose-dex.cjs.map +1 -0
  49. package/dist/compose-dex.d.cts +113 -0
  50. package/dist/compose-dex.d.ts +113 -0
  51. package/dist/compose-dex.js +25 -0
  52. package/dist/compose-dex.js.map +1 -0
  53. package/dist/compose-route.cjs +1019 -0
  54. package/dist/compose-route.cjs.map +1 -0
  55. package/dist/compose-route.d.cts +93 -0
  56. package/dist/compose-route.d.ts +93 -0
  57. package/dist/compose-route.js +45 -0
  58. package/dist/compose-route.js.map +1 -0
  59. package/dist/compose.cjs +287 -0
  60. package/dist/compose.cjs.map +1 -0
  61. package/dist/compose.d.cts +293 -0
  62. package/dist/compose.d.ts +293 -0
  63. package/dist/compose.js +30 -0
  64. package/dist/compose.js.map +1 -0
  65. package/dist/deployments.cjs +350 -0
  66. package/dist/deployments.cjs.map +1 -0
  67. package/dist/deployments.d.cts +12 -0
  68. package/dist/deployments.d.ts +12 -0
  69. package/dist/deployments.js +11 -0
  70. package/dist/deployments.js.map +1 -0
  71. package/dist/index.cjs +1862 -0
  72. package/dist/index.cjs.map +1 -0
  73. package/dist/index.d.cts +23 -0
  74. package/dist/index.d.ts +23 -0
  75. package/dist/index.js +46 -0
  76. package/dist/index.js.map +1 -0
  77. package/dist/native-drop.cjs +117 -0
  78. package/dist/native-drop.cjs.map +1 -0
  79. package/dist/native-drop.d.cts +13 -0
  80. package/dist/native-drop.d.ts +13 -0
  81. package/dist/native-drop.js +11 -0
  82. package/dist/native-drop.js.map +1 -0
  83. package/dist/pins.cjs +1618 -0
  84. package/dist/pins.cjs.map +1 -0
  85. package/dist/pins.d.cts +39 -0
  86. package/dist/pins.d.ts +39 -0
  87. package/dist/pins.js +21 -0
  88. package/dist/pins.js.map +1 -0
  89. package/dist/protocol.cjs +1851 -0
  90. package/dist/protocol.cjs.map +1 -0
  91. package/dist/protocol.d.cts +24 -0
  92. package/dist/protocol.d.ts +24 -0
  93. package/dist/protocol.js +18 -0
  94. package/dist/protocol.js.map +1 -0
  95. package/dist/provider.cjs +1833 -0
  96. package/dist/provider.cjs.map +1 -0
  97. package/dist/provider.d.cts +30 -0
  98. package/dist/provider.d.ts +30 -0
  99. package/dist/provider.js +17 -0
  100. package/dist/provider.js.map +1 -0
  101. package/dist/quote-r1bA8XbO.d.cts +102 -0
  102. package/dist/quote-t7UJSxbU.d.ts +102 -0
  103. package/dist/quote.cjs +618 -0
  104. package/dist/quote.cjs.map +1 -0
  105. package/dist/quote.d.cts +3 -0
  106. package/dist/quote.d.ts +3 -0
  107. package/dist/quote.js +16 -0
  108. package/dist/quote.js.map +1 -0
  109. package/dist/registry.cjs +100 -0
  110. package/dist/registry.cjs.map +1 -0
  111. package/dist/registry.d.cts +42 -0
  112. package/dist/registry.d.ts +42 -0
  113. package/dist/registry.js +8 -0
  114. package/dist/registry.js.map +1 -0
  115. package/dist/tracking.cjs +1143 -0
  116. package/dist/tracking.cjs.map +1 -0
  117. package/dist/tracking.d.cts +57 -0
  118. package/dist/tracking.d.ts +57 -0
  119. package/dist/tracking.js +23 -0
  120. package/dist/tracking.js.map +1 -0
  121. package/package.json +134 -3
@@ -0,0 +1,909 @@
1
+ import {
2
+ STARGATE_TAXI_EXECUTORS,
3
+ stargateTaxiNativeDrop
4
+ } from "./chunk-N54YIG6T.js";
5
+ import {
6
+ createStargateQuoter,
7
+ stargateChainActive,
8
+ stargateComposeOptions
9
+ } from "./chunk-3NTMZUAU.js";
10
+ import {
11
+ busDriveData,
12
+ busPassengerPrefix,
13
+ stargateBusNativeDrop,
14
+ stargateBusPayout,
15
+ stargateBusProof,
16
+ stargateBusTicket
17
+ } from "./chunk-4IDDRIE2.js";
18
+ import {
19
+ assertNotAborted,
20
+ assertStargate,
21
+ nonzeroAddress,
22
+ safeReadError,
23
+ sameAddress,
24
+ stargateRpc
25
+ } from "./chunk-ERC6LKMN.js";
26
+ import {
27
+ ENDPOINT_ABI,
28
+ STARGATE_ABI,
29
+ TOKEN_MESSAGING_ABI
30
+ } from "./chunk-EANM3EI3.js";
31
+ import {
32
+ stargateRegistry
33
+ } from "./chunk-4HU46QF2.js";
34
+ import {
35
+ conversionRate,
36
+ destinationAmount,
37
+ sourceMinimum,
38
+ splitSourceAmount
39
+ } from "./chunk-OUGUX3JK.js";
40
+
41
+ // src/compose-route.ts
42
+ import { encodeAbiParameters as encodeAbiParameters2, encodeFunctionData as encodeFunctionData3, encodePacked as encodePacked3, getAddress as getAddress3, keccak256 as keccak2564, pad as pad3, parseAbi as parseAbi4, toHex as toHex2 } from "viem";
43
+
44
+ // src/compose.ts
45
+ import { decodeAbiParameters, encodeAbiParameters, encodePacked as encodePacked2, keccak256 as keccak2562, pad as pad2, parseAbi as parseAbi2, parseAbiParameters, parseEventLogs as parseEventLogs2, zeroAddress as zeroAddress2 } from "viem";
46
+
47
+ // src/tracking.ts
48
+ import { encodeFunctionData, encodePacked, keccak256, pad, parseAbi, parseEventLogs, slice } from "viem";
49
+ import { timeoutSignal } from "@anywalletkit/protocol-swap2-core/util";
50
+
51
+ // src/intent.ts
52
+ import { getAddress, zeroAddress } from "viem";
53
+ import { ccAsset, ccAssetByToken } from "@anywalletkit/swap2-assets";
54
+ function stargateToken(chain, token) {
55
+ if (/^0x[0-9a-fA-F]{40}$/.test(token)) return token;
56
+ const asset = ccAsset(chain, token) ?? ccAssetByToken(chain, token);
57
+ return asset ? asset.contract ?? zeroAddress : void 0;
58
+ }
59
+ function stargateIntent(q) {
60
+ return ["stargate", "1", q.source.eid, q.destination.eid, q.source.assetId, q.mode, q.sender.toLowerCase(), q.recipient.toLowerCase(), q.requestedAmount, q.minimumDestinationAmount, q.nativeDrop].join(":");
61
+ }
62
+ function parseStargateIntent(id, registry) {
63
+ const fields = id.split("~", 1)[0].split(":");
64
+ const [tag, version, srcEid, dstEid, assetId, mode, sender, recipient, amountText, minText, dropText] = fields;
65
+ assertStargate(fields.length === 11 && tag === "stargate" && version === "1" && (mode === "taxi" || mode === "bus"), "invalid intent identity");
66
+ assertStargate([srcEid, dstEid, assetId, amountText, minText, dropText].every((v) => typeof v === "string" && /^(0|[1-9][0-9]{0,77})$/.test(v)), "invalid intent amounts");
67
+ assertStargate(sender && recipient && nonzeroAddress(sender) && nonzeroAddress(recipient), "invalid intent actors");
68
+ const source = registry.deployments.find((d) => String(d.eid) === srcEid && String(d.assetId) === assetId);
69
+ const destination = registry.deployments.find((d) => String(d.eid) === dstEid && String(d.assetId) === assetId);
70
+ assertStargate(source && destination && registry.route(source.chain, source.token, destination.chain, destination.token), "unreviewed intent route");
71
+ const amount = BigInt(amountText), minimum = BigInt(minText), nativeDrop = BigInt(dropText);
72
+ assertStargate(splitSourceAmount(amount, source.localDecimals, source.sharedDecimals).amountSD > 0n && minimum > 0n && nativeDrop < 1n << 128n, "invalid intent bounds");
73
+ assertStargate(destinationAmount(sourceMinimum(minimum, source.localDecimals, destination.localDecimals, source.sharedDecimals), source.localDecimals, destination.localDecimals, source.sharedDecimals) === minimum, "unaligned intent minimum");
74
+ return { source, destination, mode, sender: getAddress(sender), recipient: getAddress(recipient), amount, minimum, nativeDrop };
75
+ }
76
+
77
+ // src/tracking.ts
78
+ var endpointAbi = parseAbi(["event PacketSent(bytes encodedPayload, bytes options, address sendLibrary)"]);
79
+ var hash = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{64}$/.test(v);
80
+ var ZERO_HASH = `0x${"00".repeat(32)}`;
81
+ var SourceReverted = class extends Error {
82
+ };
83
+ var seatOf = (p) => "seat" in p ? p.seat : 0;
84
+ function stargateTaxiProof(i, receipt) {
85
+ return taxiProof(i, receipt);
86
+ }
87
+ function stargateComposedTaxiProof(i, receipt, composeFrom, composeMsg) {
88
+ assertStargate(nonzeroAddress(composeFrom) && /^0x(?:[0-9a-f]{2}){1,16384}$/i.test(composeMsg), "invalid expected compose payload");
89
+ return taxiProof(i, receipt, `${pad(composeFrom, { size: 32 })}${composeMsg.slice(2)}`);
90
+ }
91
+ function taxiProof(i, receipt, expectedCompose) {
92
+ assertStargate(i.mode === "taxi" && receipt.status === "success", "not a successful Taxi source receipt");
93
+ const sent = parseEventLogs({ abi: STARGATE_ABI, eventName: "OFTSent", logs: receipt.logs.filter((l) => sameAddress(l.address, i.source.address)), strict: true }).filter((l) => sameAddress(l.args.fromAddress, i.sender) && l.args.dstEid === i.destination.eid);
94
+ assertStargate(sent.length === 1, "missing or ambiguous source transfer");
95
+ const event = sent[0].args;
96
+ assertStargate(event.guid !== ZERO_HASH && event.amountSentLD === splitSourceAmount(i.amount, i.source.localDecimals, i.source.sharedDecimals).sentLD, "source amount mismatch");
97
+ const amount = destinationAmount(event.amountReceivedLD, i.source.localDecimals, i.destination.localDecimals, i.source.sharedDecimals);
98
+ assertStargate(amount >= i.minimum, "source output is below the intent minimum");
99
+ const packets = parseEventLogs({ abi: endpointAbi, eventName: "PacketSent", logs: receipt.logs.filter((l) => sameAddress(l.address, i.source.endpoint)), strict: true }).filter((l) => l.args.encodedPayload.length >= 228 && sameAddress(slice(l.args.encodedPayload, 81, 113), event.guid));
100
+ assertStargate(packets.length === 1, "missing or ambiguous endpoint packet");
101
+ const packet = packets[0].args.encodedPayload;
102
+ assertStargate(slice(packet, 0, 1) === "0x01" && BigInt(slice(packet, 9, 13)) === BigInt(i.source.eid) && BigInt(slice(packet, 45, 49)) === BigInt(i.destination.eid), "packet pathway mismatch");
103
+ assertStargate(sameAddress(slice(packet, 13, 45), pad(i.source.tokenMessaging, { size: 32 })) && sameAddress(slice(packet, 49, 81), pad(i.destination.tokenMessaging, { size: 32 })), "packet messaging contracts mismatch");
104
+ const message = slice(packet, 113);
105
+ assertStargate(expectedCompose === void 0 ? /^0x01[0-9a-f]{84}$/i.test(message) : /^0x01[0-9a-f]+$/i.test(message) && sameAddress(slice(message, 43), expectedCompose), "unsupported Taxi compose payload");
106
+ assertStargate(BigInt(slice(message, 1, 3)) === BigInt(i.source.assetId) && sameAddress(slice(message, 3, 35), pad(i.recipient, { size: 32 })) && BigInt(slice(message, 35, 43)) * conversionRate(i.destination.localDecimals, i.destination.sharedDecimals) === amount, "Taxi passenger mismatch");
107
+ return { intent: i, guid: event.guid, amount, packet, message, nonce: BigInt(slice(packet, 1, 9)), sourceHash: receipt.transactionHash };
108
+ }
109
+ function stargateTaxiPayout(proof, receipt) {
110
+ if (receipt.status !== "success") return false;
111
+ const i = proof.intent;
112
+ const received = parseEventLogs({ abi: STARGATE_ABI, eventName: "OFTReceived", logs: receipt.logs.filter((l) => sameAddress(l.address, i.destination.address)), strict: true }).filter((l) => sameAddress(l.args.guid, proof.guid));
113
+ return received.length === 1 && received[0].args.srcEid === i.source.eid && sameAddress(received[0].args.toAddress, i.recipient) && received[0].args.amountReceivedLD === proof.amount;
114
+ }
115
+ function checkStargateReceipt(receipt, expectedHash, blockHash) {
116
+ assertStargate(sameAddress(receipt.transactionHash, expectedHash) && sameAddress(receipt.blockHash, blockHash), "receipt block/hash mismatch");
117
+ assertStargate(receipt.logs.every((l) => !l.removed && l.blockNumber === receipt.blockNumber && l.transactionHash !== null && sameAddress(l.transactionHash, expectedHash) && l.blockHash !== null && sameAddress(l.blockHash, blockHash)), "receipt contains foreign or removed logs");
118
+ assertStargate(receipt.logs.every((l, index) => l.logIndex !== null && l.logIndex >= 0 && (index === 0 || l.logIndex > receipt.logs[index - 1].logIndex)), "receipt log order is invalid");
119
+ }
120
+ function createStargateTracker(config) {
121
+ const registry = config.registry ?? stargateRegistry;
122
+ const rpc = stargateRpc(config);
123
+ const confirmations = { ...config.confirmations };
124
+ const taxiExecutors = Object.fromEntries(Object.entries(config.taxiExecutors ?? STARGATE_TAXI_EXECUTORS).map(([chain, addresses]) => {
125
+ assertStargate(/^eip155:[1-9][0-9]*$/.test(chain) && addresses.length <= 32 && addresses.every(nonzeroAddress), "invalid Taxi executor pins");
126
+ return [chain, [...addresses]];
127
+ }));
128
+ assertStargate(Object.values(confirmations).every((n) => Number.isSafeInteger(n) && n >= 1 && n <= 1e5), "invalid finality policy");
129
+ const scan = (config.scanUrl ?? "https://scan.layerzero-api.com").replace(/\/+$/, "");
130
+ assertStargate(/^https?:\/\//.test(scan), "invalid Scan URL");
131
+ const fetchImpl = config.fetchImpl ?? fetch;
132
+ const composeRetryAfter = config.composeRetryAfterS ?? 600;
133
+ assertStargate(Number.isSafeInteger(composeRetryAfter) && composeRetryAfter >= 0 && composeRetryAfter <= 7 * 86400, "invalid compose retry delay");
134
+ const pageSize = config.busLogPageSize ?? 2e3, pages = config.busLogPages ?? 8;
135
+ const findDrive = config.findBusDrive, queuedPassengers = config.queuedBusPassengers;
136
+ assertStargate(Number.isSafeInteger(pageSize) && pageSize >= 1 && pageSize <= 1e4 && Number.isSafeInteger(pages) && pages >= 1 && pages <= 32, "invalid Bus log discovery bounds");
137
+ async function receipt(c, chain, chainId, txHash) {
138
+ const [id, r] = await Promise.all([c.getChainId(), c.getTransactionReceipt({ hash: txHash })]);
139
+ assertStargate(id === chainId, "receipt RPC chain mismatch");
140
+ const depth = confirmations[chain];
141
+ const [block, head] = await Promise.all([c.getBlock({ blockNumber: r.blockNumber }), c.getBlock({ blockTag: depth === void 0 ? "finalized" : "latest" })]);
142
+ assertStargate(block.hash && head.hash && head.number !== null, "missing receipt finality evidence");
143
+ checkStargateReceipt(r, txHash, block.hash);
144
+ if (head.number < r.blockNumber + BigInt((depth ?? 1) - 1)) return null;
145
+ return r;
146
+ }
147
+ async function busProof(ticket, ref) {
148
+ const i = ticket.intent, c = rpc.client(i.source.chain);
149
+ const candidates = [];
150
+ if (ref.recoveryChain === i.source.chain && hash(ref.recoveryTxHash)) candidates.push(ref.recoveryTxHash);
151
+ if (findDrive) candidates.push(...(await findDrive(Object.freeze({ ...ticket, intent: Object.freeze({ ...ticket.intent }) }))).filter(hash).slice(0, 32));
152
+ const tryCandidates = async () => {
153
+ for (const txHash of [...new Set(candidates.splice(0))]) {
154
+ try {
155
+ const r = await receipt(c, i.source.chain, i.source.chainId, txHash);
156
+ if (r) return stargateBusProof(ticket, r);
157
+ } catch {
158
+ }
159
+ }
160
+ return null;
161
+ };
162
+ const hinted = await tryCandidates();
163
+ if (hinted) return hinted;
164
+ const head = await c.getBlockNumber();
165
+ for (let page = 0; page < pages; page++) {
166
+ const fromBlock = ticket.sourceBlock + BigInt(page * pageSize);
167
+ if (fromBlock > head) break;
168
+ const end = fromBlock + BigInt(pageSize - 1), toBlock = end < head ? end : head;
169
+ const logs = await c.getContractEvents({ address: i.source.tokenMessaging, abi: TOKEN_MESSAGING_ABI, eventName: "BusDriven", fromBlock, toBlock, strict: true });
170
+ for (const log of logs) if (!log.removed && log.args.dstEid === i.destination.eid && log.args.startTicketId <= ticket.ticketId && ticket.ticketId < log.args.startTicketId + BigInt(log.args.numPassengers) && hash(log.transactionHash)) candidates.push(log.transactionHash);
171
+ const found = await tryCandidates();
172
+ if (found) return found;
173
+ }
174
+ return null;
175
+ }
176
+ async function evidence(ref) {
177
+ const compose = isStargateComposeIntent(ref.intentId) ? parseStargateComposeIntent(ref.intentId, registry) : void 0;
178
+ const i = compose ? compose.bridge : parseStargateIntent(ref.intentId, registry);
179
+ if (!hash(ref.sourceTxHash)) return null;
180
+ const r = await receipt(rpc.client(i.source.chain), i.source.chain, i.source.chainId, ref.sourceTxHash);
181
+ if (r?.status === "reverted" && r.from && r.to && sameAddress(r.from, i.sender) && sameAddress(r.to, i.source.address)) throw new SourceReverted();
182
+ if (!r) return null;
183
+ if (compose) return { proof: stargateComposedTaxiProof(i, r, i.sender, stargateComposeMessage(compose)), compose };
184
+ if (i.mode === "taxi") return { proof: stargateTaxiProof(i, r) };
185
+ const ticket = stargateBusTicket(i, r);
186
+ return { ticket, proof: await busProof(ticket, ref) };
187
+ }
188
+ async function cached(p) {
189
+ const i = p.intent;
190
+ const c = rpc.client(i.destination.chain);
191
+ assertStargate(await c.getChainId() === i.destination.chainId, "recovery RPC chain mismatch");
192
+ const actual = await c.readContract({ address: i.destination.address, abi: STARGATE_ABI, functionName: "unreceivedTokens", args: [p.guid, seatOf(p)] });
193
+ const expected = keccak256(encodePacked(["uint32", "address", "uint256", "bytes"], [i.source.eid, i.recipient, p.amount, "0x"]));
194
+ return actual === expected;
195
+ }
196
+ async function retryableMessage(p) {
197
+ const i = p.intent, c = rpc.client(i.destination.chain);
198
+ assertStargate(await c.getChainId() === i.destination.chainId, "recovery RPC chain mismatch");
199
+ const actual = await c.readContract({ address: i.destination.endpoint, abi: ENDPOINT_ABI, functionName: "inboundPayloadHash", args: [i.destination.tokenMessaging, i.source.eid, pad(i.source.tokenMessaging, { size: 32 }), p.nonce] });
200
+ return actual === keccak256(encodePacked(["bytes32", "bytes"], [p.guid, p.message]));
201
+ }
202
+ async function destinationHashes(ref, p) {
203
+ const provided = [ref.destTxHash, ref.recoveryChain === p.intent.destination.chain ? ref.recoveryTxHash : void 0].filter(hash);
204
+ try {
205
+ const response = await fetchImpl(`${scan}/v1/messages/guid/${p.guid}`, { signal: timeoutSignal(12e3), headers: { accept: "application/json" } });
206
+ if (!response.ok) return provided;
207
+ const json = await response.json();
208
+ const data = json?.data;
209
+ if (!Array.isArray(data)) return provided;
210
+ for (const item of data.slice(0, 32)) {
211
+ const m = item;
212
+ if (typeof m.guid === "string" && sameAddress(m.guid, p.guid)) {
213
+ if (hash(m.destination?.tx?.txHash)) provided.push(m.destination.tx.txHash);
214
+ if (hash(m.destination?.nativeDrop?.tx?.txHash)) provided.push(m.destination.nativeDrop.tx.txHash);
215
+ const composed = m.destination?.lzCompose?.txs;
216
+ if (Array.isArray(composed)) {
217
+ for (const tx of composed.slice(0, 8)) if (hash(tx?.txHash)) provided.push(tx.txHash);
218
+ }
219
+ }
220
+ }
221
+ } catch {
222
+ }
223
+ return [...new Set(provided)];
224
+ }
225
+ async function composeState(ref, c, p) {
226
+ const d = p.intent.destination, client = rpc.client(d.chain), lifi = stargateComposeProof(c, p);
227
+ let deliveredAt, delivered;
228
+ for (const txHash of await destinationHashes(ref, p)) {
229
+ try {
230
+ const r = await receipt(client, d.chain, d.chainId, txHash);
231
+ if (!r) continue;
232
+ if (stargateTaxiPayout(p, r)) {
233
+ delivered = txHash;
234
+ deliveredAt = (await client.getBlock({ blockNumber: r.blockNumber })).timestamp;
235
+ }
236
+ const outcome = lifiStargateComposeOutcome(lifi, r);
237
+ if (outcome.state !== "unverified") return { outcome: outcome.state, txHash, lifi };
238
+ } catch {
239
+ }
240
+ }
241
+ assertStargate(await client.getChainId() === d.chainId, "compose RPC chain mismatch");
242
+ const queue = stargateComposeQueueState(lifi.messageHash, await client.readContract({ address: d.endpoint, abi: COMPOSE_ABI, functionName: "composeQueue", args: [d.address, LIFI_ETHEREUM_COMPOSER.receiver, p.guid, 0] }));
243
+ const stale = deliveredAt !== void 0 && deliveredAt + BigInt(composeRetryAfter) <= BigInt(Math.floor(Date.now() / 1e3));
244
+ return { queue, retryable: queue === "pending" && stale, delivered, lifi };
245
+ }
246
+ async function trackIntent(ref) {
247
+ let deposited = false;
248
+ try {
249
+ const e = await evidence(ref);
250
+ if (!e) return { state: "pending" };
251
+ deposited = true;
252
+ const p = e.proof;
253
+ if (!p) return { state: "pending", depositReceived: true };
254
+ if (e.compose && !("seat" in p)) {
255
+ const s = await composeState(ref, e.compose, p);
256
+ if ("outcome" in s) return { state: s.outcome === "completed" ? "completed" : "partial", depositReceived: true, destTxHash: s.txHash };
257
+ if (s.retryable) return { state: "action-required", depositReceived: true, ...s.delivered ? { destTxHash: s.delivered } : {} };
258
+ if (!s.delivered && (await cached(p) || await retryableMessage(p))) return { state: "action-required", depositReceived: true };
259
+ return { state: "pending", depositReceived: true };
260
+ }
261
+ const d = p.intent.destination, c = rpc.client(d.chain);
262
+ let paidHash, nativeDropProved = false;
263
+ for (const txHash of await destinationHashes(ref, p)) {
264
+ try {
265
+ const r = await receipt(c, d.chain, d.chainId, txHash);
266
+ if (r) {
267
+ if ("seat" in p && stargateBusNativeDrop(p, r)) nativeDropProved = true;
268
+ if (!("seat" in p) && stargateTaxiNativeDrop(p, r, taxiExecutors[d.chain] ?? [])) nativeDropProved = true;
269
+ let paid = "seat" in p ? stargateBusPayout(p, r) === "paid" : stargateTaxiPayout(p, r);
270
+ if (!paid && "seat" in p && stargateTaxiPayout({ ...p, packet: "0x" }, r)) {
271
+ const tx = await c.getTransaction({ hash: txHash });
272
+ paid = !!tx.to && sameAddress(tx.to, d.address) && tx.blockHash === r.blockHash && tx.input.toLowerCase() === retryTokenData(p).toLowerCase();
273
+ }
274
+ if (paid) paidHash = txHash;
275
+ }
276
+ } catch {
277
+ }
278
+ }
279
+ if (paidHash) return { state: p.intent.nativeDrop > 0n && !nativeDropProved ? "partial" : "completed", depositReceived: true, destTxHash: paidHash };
280
+ if (await cached(p) || await retryableMessage(p)) return { state: "action-required", depositReceived: true };
281
+ return { state: "pending", depositReceived: true };
282
+ } catch (error) {
283
+ return error instanceof SourceReverted ? { state: "failed" } : { state: "pending", ...deposited ? { depositReceived: true } : {} };
284
+ }
285
+ }
286
+ function retryTokenData(p) {
287
+ const i = p.intent;
288
+ return encodeFunctionData({ abi: STARGATE_ABI, functionName: "retryReceiveToken", args: [p.guid, seatOf(p), i.source.eid, i.recipient, p.amount, "0x"] });
289
+ }
290
+ async function driveRecovery(ticket) {
291
+ const started = Date.now();
292
+ const i = ticket.intent, c = rpc.client(i.source.chain), d = rpc.client(i.destination.chain);
293
+ const [block, destinationBlock] = await Promise.all([rpc.snapshot(c, i.source.chainId), rpc.snapshot(d, i.destination.chainId)]);
294
+ await Promise.all([rpc.verify(c, i.source, i.destination, block), rpc.verify(d, i.destination, i.source, destinationBlock)]);
295
+ const at = { address: i.source.tokenMessaging, abi: TOKEN_MESSAGING_ABI, blockNumber: block.number };
296
+ const [[maxPassengers, , , length, first], capacity] = await Promise.all([
297
+ c.readContract({ ...at, functionName: "busQueues", args: [i.destination.eid] }),
298
+ c.readContract({ ...at, functionName: "queueCapacity" })
299
+ ]);
300
+ if (capacity === 0 || first > ticket.ticketId || ticket.ticketId >= first + BigInt(length) || ticket.ticketId >= first + BigInt(maxPassengers)) return [];
301
+ let count = 1;
302
+ while (first + BigInt(count - 1) < ticket.ticketId) count++;
303
+ const rows = [];
304
+ if (queuedPassengers) rows.push(...await queuedPassengers({ chain: i.source.chain, tokenMessaging: i.source.tokenMessaging, dstEid: i.destination.eid, firstTicketId: first, count, blockNumber: block.number }));
305
+ else {
306
+ for (let page = 0; page < pages; page++) {
307
+ const end = ticket.sourceBlock - BigInt(page * pageSize);
308
+ if (end < 0n) break;
309
+ const start = end - BigInt(pageSize - 1);
310
+ const logs = await c.getContractEvents({ address: i.source.tokenMessaging, abi: TOKEN_MESSAGING_ABI, eventName: "BusRode", fromBlock: start > 0n ? start : 0n, toBlock: end, strict: true });
311
+ for (const log of logs) if (!log.removed && log.args.dstEid === i.destination.eid && log.args.ticketId >= first && log.args.ticketId <= ticket.ticketId) rows.push({ ticketId: log.args.ticketId, passenger: log.args.passenger });
312
+ if (rows.length >= count) break;
313
+ }
314
+ }
315
+ assertStargate(rows.length <= 4096, "too many indexed queue rows");
316
+ const previousIndex = parseInt(((first - 1n + BigInt(capacity)) % BigInt(capacity)).toString(), 10);
317
+ const lastIndex = parseInt((ticket.ticketId % BigInt(capacity)).toString(), 10);
318
+ const [previous, last] = await Promise.all([
319
+ first === 0n ? Promise.resolve(ZERO_HASH) : c.readContract({ ...at, functionName: "getPassengerHash", args: [i.destination.eid, previousIndex] }),
320
+ c.readContract({ ...at, functionName: "getPassengerHash", args: [i.destination.eid, lastIndex] })
321
+ ]);
322
+ const passengers = busPassengerPrefix(rows, first, count, previous, last, ticket);
323
+ const fee = await c.readContract({ ...at, functionName: "quoteDriveBus", args: [i.destination.eid, passengers] });
324
+ assertStargate(fee.lzTokenFee === 0n, "unsupported drive fee token");
325
+ await Promise.all([rpc.unchanged(c, block), rpc.unchanged(d, destinationBlock)]);
326
+ assertStargate(Date.now() < started + 6e4, "drive quote expired during reads");
327
+ return [{
328
+ id: `bus-drive:${ticket.sourceHash}:${first}:${keccak256(passengers)}`,
329
+ kind: "drive-bus",
330
+ description: `Pay to drive ${count} queued passenger(s), including this ticket. The payment covers the whole batch; source transaction gas is additional.`,
331
+ validUntilMs: started + 6e4,
332
+ tx: { chain: i.source.chain, chainId: i.source.chainId, to: i.source.tokenMessaging, value: String(fee.nativeFee), data: busDriveData(i.destination.eid, passengers) }
333
+ }];
334
+ }
335
+ async function getRecoveryQuotes(ref) {
336
+ try {
337
+ const e = await evidence(ref);
338
+ if (!e) return [];
339
+ const p = e.proof;
340
+ if (!p) return e.ticket ? await driveRecovery(e.ticket) : [];
341
+ const i = p.intent;
342
+ const c = rpc.client(i.destination.chain);
343
+ if (e.compose && !("seat" in p)) {
344
+ const s = await composeState(ref, e.compose, p);
345
+ if (!("outcome" in s) && s.retryable) {
346
+ const block = await c.getBlock({ blockTag: "latest" });
347
+ const { recoverGas } = await checkStargateComposer(c, i.destination, block.number);
348
+ return [{
349
+ id: `${p.guid}:compose:0`,
350
+ kind: "compose",
351
+ description: "Run the pending LI.FI compose on Ethereum again with the reviewed swap minimum. If the swap still fails, the composer pays the bridged token to the recipient. Ethereum transaction gas is paid separately.",
352
+ validUntilMs: Date.now() + 6e4,
353
+ tx: { chain: i.destination.chain, chainId: i.destination.chainId, to: i.destination.endpoint, value: "0", gasLimit: String(stargateComposeRetryGas(e.compose, recoverGas)), data: encodeFunctionData({ abi: COMPOSE_ABI, functionName: "lzCompose", args: [i.destination.address, LIFI_ETHEREUM_COMPOSER.receiver, p.guid, 0, s.lifi.message, "0x"] }) }
354
+ }];
355
+ }
356
+ if ("outcome" in s || s.delivered || s.queue !== "absent") return [];
357
+ }
358
+ if (await c.readContract({ address: i.destination.address, abi: STARGATE_ABI, functionName: "status" }) !== 1) return [];
359
+ if (await cached(p)) return [{
360
+ id: `${p.guid}:retry-token:${seatOf(p)}`,
361
+ kind: "retry-token",
362
+ description: "Retry the cached Stargate token payout to the original recipient. Destination transaction gas is paid separately.",
363
+ validUntilMs: Date.now() + 6e4,
364
+ tx: { chain: i.destination.chain, chainId: i.destination.chainId, to: i.destination.address, value: "0", data: retryTokenData(p) }
365
+ }];
366
+ if (await retryableMessage(p)) return [{
367
+ id: `${p.guid}:retry-message`,
368
+ kind: "retry-message",
369
+ description: "Retry the verified LayerZero message. Any attached value funds native drops for the entire Bus batch; destination transaction gas is additional.",
370
+ validUntilMs: Date.now() + 6e4,
371
+ tx: { chain: i.destination.chain, chainId: i.destination.chainId, to: i.destination.endpoint, value: "totalNativeDrops" in p ? String(p.totalNativeDrops * p.nativeDropAmount) : "0", data: encodeFunctionData({ abi: ENDPOINT_ABI, functionName: "lzReceive", args: [{ srcEid: i.source.eid, sender: pad(i.source.tokenMessaging, { size: 32 }), nonce: p.nonce }, i.destination.tokenMessaging, p.guid, p.message, "0x"] }) }
372
+ }];
373
+ return [];
374
+ } catch {
375
+ return [];
376
+ }
377
+ }
378
+ async function verifyRecovery(ref, offered, actor) {
379
+ if (!nonzeroAddress(actor) || !Number.isFinite(offered.validUntilMs) || offered.validUntilMs <= Date.now() || offered.validUntilMs > Date.now() + 6e4) return "stargate: invalid recovery actor or expiry";
380
+ const fresh = (await getRecoveryQuotes(ref)).find((q) => q.id === offered.id);
381
+ if (!fresh || fresh.kind !== offered.kind || Object.keys(offered.tx).length !== Object.keys(fresh.tx).length || Object.entries(fresh.tx).some(([key, value]) => offered.tx[key] !== value)) return "stargate: recovery no longer matches the cached on-chain payout";
382
+ return null;
383
+ }
384
+ return { trackIntent, getRecoveryQuotes, verifyRecovery, recoveryTargets: (chain) => [.../* @__PURE__ */ new Set([...registry.callTargets(chain), ...registry.deployments.filter((d) => d.chain === chain).flatMap((d) => [d.endpoint, d.tokenMessaging])])] };
385
+ }
386
+
387
+ // src/compose.ts
388
+ var COMPOSE_ABI = parseAbi2([
389
+ "function composeQueue(address from, address to, bytes32 guid, uint16 index) view returns (bytes32)",
390
+ "function lzCompose(address from, address to, bytes32 guid, uint16 index, bytes message, bytes extraData) payable",
391
+ "event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message)",
392
+ "event ComposeDelivered(address from, address to, bytes32 guid, uint16 index)"
393
+ ]);
394
+ var LIFI_COMPOSE_ABI = parseAbi2([
395
+ "function executor() view returns (address)",
396
+ "function endpointV2() view returns (address)",
397
+ "function tokenMessaging() view returns (address)",
398
+ "function recoverGas() view returns (uint256)",
399
+ "event LiFiTransferCompleted(bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp)",
400
+ "event LiFiTransferRecovered(bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp)",
401
+ "event AssetSwapped(bytes32 transactionId, address dex, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount, uint256 timestamp)",
402
+ "event Transfer(address indexed from, address indexed to, uint256 value)"
403
+ ]);
404
+ var LIFI_COMPOSE_PAYLOAD = parseAbiParameters("bytes32 transactionId, (address callTo, address approveTo, address sendingAssetId, address receivingAssetId, uint256 fromAmount, bytes callData, bool requiresDeposit)[] swaps, address receiver");
405
+ var LIFI_ETHEREUM_COMPOSER = Object.freeze({
406
+ chain: "eip155:1",
407
+ receiver: "0xB539B40793171211DCA8834da044fC14bCe64BDC",
408
+ executor: "0xd9B2Da9C45b118e4e93A004FB1452bCDB6cC0E88",
409
+ receiverCodeHash: "0x535b6e74e5bbb38e9a469de60ff2587cf498b92a99be01f34d20c37a77e4cea2",
410
+ executorCodeHash: "0xf937f13890d789171f0bcf3c558a64869105000b6771dc182ddc165bde92ddfe"
411
+ });
412
+ function stargateComposeQueueState(messageHash, queue) {
413
+ assertStargate(/^0x[0-9a-f]{64}$/i.test(messageHash) && /^0x[0-9a-f]{64}$/i.test(queue), "invalid compose commitment");
414
+ if (BigInt(queue) === 0n) return "absent";
415
+ if (BigInt(queue) === 1n) return "consumed";
416
+ return sameAddress(messageHash, queue) ? "pending" : "mismatch";
417
+ }
418
+ function proveLifiStargateCompose(expected, source, delivery, code) {
419
+ const pins = LIFI_ETHEREUM_COMPOSER, i = expected.bridge;
420
+ assertStargate(i.destination.chain === pins.chain && sameAddress(i.recipient, pins.receiver), "unreviewed composer");
421
+ assertStargate(keccak2562(code.receiver) === pins.receiverCodeHash && keccak2562(code.executor) === pins.executorCodeHash, "composer bytecode changed");
422
+ assertStargate(nonzeroAddress(expected.recipient) && /^0x[0-9a-f]{40}$/i.test(expected.finalToken) && typeof expected.minimum === "bigint" && expected.minimum > 0n && expected.minimum < 1n << 256n, "invalid final action");
423
+ for (const receipt of [source, delivery]) checkStargateReceipt(receipt, receipt.transactionHash, receipt.blockHash);
424
+ const bridge = stargateComposedTaxiProof(i, source, expected.composeFrom, expected.composeMsg);
425
+ const [transactionId, swaps, recipient] = decodeAbiParameters(LIFI_COMPOSE_PAYLOAD, expected.composeMsg);
426
+ assertStargate(encodeAbiParameters(LIFI_COMPOSE_PAYLOAD, [transactionId, swaps, recipient]).toLowerCase() === expected.composeMsg.toLowerCase(), "noncanonical compose message");
427
+ assertStargate(BigInt(transactionId) !== 0n && swaps.length === 1 && sameAddress(recipient, expected.recipient), "unsupported compose action or recipient");
428
+ const swap = swaps[0];
429
+ assertStargate(nonzeroAddress(swap.callTo) && nonzeroAddress(swap.approveTo) && swap.fromAmount > 0n && swap.fromAmount <= bridge.amount && sameAddress(swap.sendingAssetId, i.destination.token) && sameAddress(swap.receivingAssetId, expected.finalToken) && !sameAddress(swap.sendingAssetId, swap.receivingAssetId), "compose asset or amount mismatch");
430
+ assertStargate(stargateTaxiPayout(bridge, delivery), "bridge has not paid the composer");
431
+ const message = encodePacked2(["uint64", "uint32", "uint256", "bytes32", "bytes"], [bridge.nonce, i.source.eid, bridge.amount, pad2(expected.composeFrom, { size: 32 }), expected.composeMsg]);
432
+ const sent = parseEventLogs2({ abi: COMPOSE_ABI, eventName: "ComposeSent", logs: delivery.logs.filter((l) => sameAddress(l.address, i.destination.endpoint)), strict: true }).filter((l) => sameAddress(l.args.guid, bridge.guid));
433
+ assertStargate(sent.length === 1 && sameAddress(sent[0].args.from, i.destination.address) && sameAddress(sent[0].args.to, pins.receiver) && sent[0].args.index === 0 && sameAddress(sent[0].args.message, message), "compose queue message mismatch");
434
+ const intent = Object.freeze({ ...i, source: Object.freeze({ ...i.source }), destination: Object.freeze({ ...i.destination }) });
435
+ return Object.freeze({ bridge: Object.freeze({ ...bridge, intent }), transactionId, message, messageHash: keccak2562(message), recipient, finalToken: expected.finalToken, minimum: expected.minimum, swap: Object.freeze({ callTo: swap.callTo, fromAmount: swap.fromAmount }), executionSupported: false });
436
+ }
437
+ function lifiStargateComposeOutcome(p, receipt) {
438
+ const unknown = { state: "unverified" };
439
+ try {
440
+ let paid2 = function(token, from, before) {
441
+ const transfers = parseEventLogs2({ abi: LIFI_COMPOSE_ABI, eventName: "Transfer", logs: receipt.logs.filter((l) => sameAddress(l.address, token) && l.logIndex < before), strict: true });
442
+ let net = 0n;
443
+ for (const { args } of transfers) {
444
+ if (sameAddress(args.to, p.recipient) && sameAddress(args.from, from)) net += args.value;
445
+ if (sameAddress(args.from, p.recipient)) net -= args.value;
446
+ }
447
+ return net;
448
+ };
449
+ var paid = paid2;
450
+ if (receipt.status !== "success") return unknown;
451
+ checkStargateReceipt(receipt, receipt.transactionHash, receipt.blockHash);
452
+ const pins = LIFI_ETHEREUM_COMPOSER, d = p.bridge.intent.destination;
453
+ const delivered = parseEventLogs2({ abi: COMPOSE_ABI, eventName: "ComposeDelivered", logs: receipt.logs.filter((l) => sameAddress(l.address, d.endpoint)), strict: true });
454
+ if (delivered.length !== 1) return unknown;
455
+ const end = delivered[0];
456
+ if (!sameAddress(end.args.guid, p.bridge.guid) || !sameAddress(end.args.from, d.address) || !sameAddress(end.args.to, pins.receiver) || end.args.index !== 0) return unknown;
457
+ const recovered = parseEventLogs2({ abi: LIFI_COMPOSE_ABI, eventName: "LiFiTransferRecovered", logs: receipt.logs.filter((l) => sameAddress(l.address, pins.receiver)), strict: true }).filter((l) => sameAddress(l.args.transactionId, p.transactionId));
458
+ const completed = parseEventLogs2({ abi: LIFI_COMPOSE_ABI, eventName: "LiFiTransferCompleted", logs: receipt.logs.filter((l) => sameAddress(l.address, pins.executor)), strict: true }).filter((l) => sameAddress(l.args.transactionId, p.transactionId));
459
+ if (recovered.length === 1 && completed.length === 0) {
460
+ const event2 = recovered[0];
461
+ if (event2.logIndex >= end.logIndex || !sameAddress(event2.args.receivingAssetId, d.token) || !sameAddress(event2.args.receiver, p.recipient) || event2.args.amount !== p.bridge.amount) return unknown;
462
+ if (d.token !== zeroAddress2 && paid2(d.token, pins.receiver, event2.logIndex) !== p.bridge.amount) return unknown;
463
+ return { state: "intermediate-refunded", token: d.token, amount: p.bridge.amount, transactionHash: receipt.transactionHash };
464
+ }
465
+ if (completed.length !== 1 || recovered.length !== 0 || p.finalToken === zeroAddress2) return unknown;
466
+ const event = completed[0];
467
+ if (event.logIndex >= end.logIndex || !sameAddress(event.args.receiver, p.recipient) || !sameAddress(event.args.receivingAssetId, d.token)) return unknown;
468
+ const swaps = parseEventLogs2({ abi: LIFI_COMPOSE_ABI, eventName: "AssetSwapped", logs: receipt.logs.filter((l) => sameAddress(l.address, pins.executor)), strict: true }).filter((l) => sameAddress(l.args.transactionId, p.transactionId));
469
+ if (swaps.length !== 1) return unknown;
470
+ const swap = swaps[0];
471
+ if (swap.logIndex >= event.logIndex || !sameAddress(swap.args.dex, p.swap.callTo) || !sameAddress(swap.args.fromAssetId, d.token) || !sameAddress(swap.args.toAssetId, p.finalToken) || swap.args.fromAmount !== p.swap.fromAmount) return unknown;
472
+ const amount = paid2(p.finalToken, pins.executor, event.logIndex);
473
+ if (amount < p.minimum || amount !== swap.args.toAmount) return unknown;
474
+ return { state: "completed", token: p.finalToken, amount, transactionHash: receipt.transactionHash };
475
+ } catch {
476
+ return unknown;
477
+ }
478
+ }
479
+
480
+ // src/compose-dex.ts
481
+ import { decodeAbiParameters as decodeAbiParameters2, decodeFunctionData, encodeFunctionData as encodeFunctionData2, getAddress as getAddress2, keccak256 as keccak2563, parseAbi as parseAbi3, slice as slice2, toHex, zeroAddress as zeroAddress3 } from "viem";
482
+ var COMPOSE_UNOSWAP_ABI = parseAbi3(["function unoswap2(uint256 token, uint256 amount, uint256 minReturn, uint256 dex, uint256 dex2) returns (uint256)"]);
483
+ var COMPOSE_POOL_ABI = parseAbi3([
484
+ "function token0() view returns (address)",
485
+ "function token1() view returns (address)",
486
+ "function fee() view returns (uint24)",
487
+ "function getPool(address tokenA, address tokenB, uint24 fee) view returns (address)"
488
+ ]);
489
+ var COMPOSE_DEX_PINS = Object.freeze({
490
+ router: "0x111111125421cA6dc452d289314280a0f8842A65",
491
+ routerCodeHash: "0xa5a286be4b80006cc547d7e899871aa01a0e0551e2a509233375405f92098c2f",
492
+ factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984",
493
+ factoryCodeHash: "0x4d7b8525cd5d14343fa67a732fba5b24cddba11620ca88392f4ec6c52f91fd69",
494
+ /** Observed four-byte suffix; its ownership/meaning is not an authorization signal. */
495
+ calldataSuffix: "2a94d114"
496
+ });
497
+ var UNOSWAP_FLAGS = Object.freeze({ V3: 1n << 253n, NO_WRAP: 1n << 251n, ZERO_FOR_ONE: 1n << 247n });
498
+ var ADDRESS = (1n << 160n) - 1n;
499
+ var { V3, NO_WRAP, ZERO_FOR_ONE } = UNOSWAP_FLAGS;
500
+ async function unoswap2V3Path(client, blockNumber, input, words, output) {
501
+ let current = input;
502
+ const pools = [], fees = [], tokens = [input];
503
+ for (const encoded of words) {
504
+ assertStargate(encoded >> 253n === 1n && (encoded & ~(ADDRESS | V3 | NO_WRAP | ZERO_FOR_ONE)) === 0n, "unsupported compose DEX flags");
505
+ const address = getAddress2(toHex(encoded & ADDRESS, { size: 20 }));
506
+ const at = { address, abi: COMPOSE_POOL_ABI, blockNumber };
507
+ const [token0, token1, fee] = await Promise.all([
508
+ client.readContract({ ...at, functionName: "token0" }),
509
+ client.readContract({ ...at, functionName: "token1" }),
510
+ client.readContract({ ...at, functionName: "fee" })
511
+ ]);
512
+ const canonical = await client.readContract({ address: COMPOSE_DEX_PINS.factory, abi: COMPOSE_POOL_ABI, functionName: "getPool", args: [token0, token1, fee], blockNumber });
513
+ assertStargate(sameAddress(canonical, address) && address !== zeroAddress3 && !sameAddress(token0, token1), "unreviewed compose DEX pool");
514
+ const forward = (encoded & ZERO_FOR_ONE) !== 0n;
515
+ assertStargate(sameAddress(current, forward ? token0 : token1), "compose DEX path input mismatch");
516
+ current = forward ? token1 : token0;
517
+ pools.push(address);
518
+ fees.push(fee);
519
+ tokens.push(current);
520
+ }
521
+ assertStargate(sameAddress(current, output), "compose DEX path output mismatch");
522
+ return Object.freeze({ pools: Object.freeze(pools), fees: Object.freeze(fees), tokens: Object.freeze(tokens) });
523
+ }
524
+ async function validateLifiUnoswap2Compose(p, client, blockNumber) {
525
+ assertStargate(await client.getChainId() === 1 && p.bridge.intent.destination.chain === "eip155:1", "wrong compose DEX chain");
526
+ const block = await client.getBlock({ blockNumber });
527
+ assertStargate(block.hash, "compose DEX block unavailable");
528
+ const pins = COMPOSE_DEX_PINS;
529
+ for (const [address, expectedHash] of [
530
+ [pins.router, pins.routerCodeHash],
531
+ [pins.factory, pins.factoryCodeHash],
532
+ [LIFI_ETHEREUM_COMPOSER.receiver, LIFI_ETHEREUM_COMPOSER.receiverCodeHash],
533
+ [LIFI_ETHEREUM_COMPOSER.executor, LIFI_ETHEREUM_COMPOSER.executorCodeHash]
534
+ ]) {
535
+ const code = await client.getCode({ address, blockNumber });
536
+ assertStargate(code && keccak2563(code) === expectedHash, "compose DEX bytecode mismatch");
537
+ }
538
+ assertStargate(keccak2563(p.message) === p.messageHash, "changed compose message");
539
+ const [transactionId, swaps, recipient] = decodeAbiParameters2(LIFI_COMPOSE_PAYLOAD, slice2(p.message, 76));
540
+ assertStargate(swaps.length === 1 && sameAddress(transactionId, p.transactionId) && sameAddress(recipient, p.recipient), "compose DEX action mismatch");
541
+ const swap = swaps[0];
542
+ assertStargate(sameAddress(swap.callTo, pins.router) && sameAddress(swap.approveTo, pins.router) && swap.requiresDeposit && swap.fromAmount > 0n && swap.fromAmount <= p.bridge.amount && swap.fromAmount === p.swap.fromAmount, "unsupported compose DEX target or amount");
543
+ assertStargate(sameAddress(swap.sendingAssetId, p.bridge.intent.destination.token) && sameAddress(swap.receivingAssetId, p.finalToken) && swap.sendingAssetId !== zeroAddress3 && p.finalToken !== zeroAddress3, "unsupported compose DEX assets");
544
+ const call = decodeFunctionData({ abi: COMPOSE_UNOSWAP_ABI, data: swap.callData });
545
+ const [token, amount, minimum, dex, dex2] = call.args;
546
+ const canonicalCall = encodeFunctionData2({ abi: COMPOSE_UNOSWAP_ABI, functionName: "unoswap2", args: call.args }).toLowerCase();
547
+ assertStargate([canonicalCall, canonicalCall + pins.calldataSuffix].includes(swap.callData.toLowerCase()), "noncanonical compose DEX calldata");
548
+ assertStargate(token > 0n && token <= ADDRESS && sameAddress(toHex(token, { size: 20 }), swap.sendingAssetId) && amount === swap.fromAmount && minimum > 0n && minimum >= p.minimum, "compose DEX input or minimum mismatch");
549
+ const { pools } = await unoswap2V3Path(client, blockNumber, swap.sendingAssetId, [dex, dex2], p.finalToken);
550
+ assertStargate((await client.getBlock({ blockNumber })).hash === block.hash, "compose DEX block changed");
551
+ return Object.freeze({ adapter: "lifi-ethereum-unoswap2-v3", amount, minimum, finalToken: p.finalToken, recipient: p.recipient, pools, blockNumber, blockHash: block.hash, executionSupported: false });
552
+ }
553
+
554
+ // src/source-tx.ts
555
+ import { zeroAddress as zeroAddress4 } from "viem";
556
+ import { ccAssetByToken as ccAssetByToken2 } from "@anywalletkit/swap2-assets";
557
+ function stargateFees(source, protocolFee, cap) {
558
+ const nativeToken = ccAssetByToken2(source.chain, zeroAddress4)?.assetId ?? zeroAddress4;
559
+ return [
560
+ ...protocolFee ? [{ type: "protocol", amount: String(protocolFee), token: source.kind === "native" ? nativeToken : source.token, included: true, description: "Stargate protocol fee, already deducted from output" }] : [],
561
+ { type: "network", amount: String(cap), token: nativeToken, included: false, description: "Messaging fee cap; unused headroom is refunded. Source transaction gas is additional." }
562
+ ];
563
+ }
564
+ function checkedStargateSource(q, source, destination, amount, routeId) {
565
+ assertStargate(stargateChainActive(source.chain) && stargateChainActive(destination.chain), "chain support has ended for new transfers");
566
+ const tx = q.txRequest;
567
+ assertStargate(q.provider === "stargate" && q.routeId === routeId && tx && tx.to && tx.data, "missing Stargate transaction");
568
+ assertStargate(q.depositAddress === "" && q.depositMemo === null && tx.serializedTx === void 0 && tx.gasLimit === void 0, "unexpected transaction fields");
569
+ assertStargate(sameAddress(tx.to, source.address) && tx.chainId === source.chainId && q.sourceAmount === String(amount), "quote identity mismatch");
570
+ assertStargate(Number.isFinite(q.validUntilMs) && q.validUntilMs > Date.now(), "quote expired");
571
+ assertStargate(typeof tx.nativeFee === "string" && /^(0|[1-9][0-9]{0,77})$/.test(tx.nativeFee), "invalid messaging fee cap");
572
+ const cap = BigInt(tx.nativeFee);
573
+ const value = cap + (source.kind === "native" ? amount : 0n);
574
+ assertStargate(value < 1n << 256n && tx.value === String(value), "native value mismatch");
575
+ assertStargate(source.kind !== "native" && source.approvalRequired ? !!tx.approvalAddress && sameAddress(tx.approvalAddress, source.address) : tx.approvalAddress === void 0, "approval spender mismatch");
576
+ return { tx: { ...tx, to: tx.to, data: tx.data }, cap };
577
+ }
578
+ function checkedStargateAccounting(q, source, destination, amount, cap, received) {
579
+ const pd = q.providerData;
580
+ assertStargate(pd && ["sentAmount", "dust", "protocolFee", "protocolReward", "messagingFee"].every((key) => /^(0|[1-9][0-9]{0,77})$/.test(pd[key] ?? "")), "missing amount accounting");
581
+ const split = splitSourceAmount(amount, source.localDecimals, source.sharedDecimals);
582
+ assertStargate(pd.sentAmount === String(split.sentLD) && pd.dust === String(split.dustLD), "dust accounting mismatch");
583
+ assertStargate(destinationAmount(split.sentLD - BigInt(pd.protocolFee) + BigInt(pd.protocolReward), source.localDecimals, destination.localDecimals, source.sharedDecimals) === received, "fee accounting mismatch");
584
+ assertStargate(BigInt(pd.messagingFee) <= cap, "messaging fee exceeds cap");
585
+ const fees = stargateFees(source, BigInt(pd.protocolFee), cap);
586
+ assertStargate(q.fees?.length === fees.length && fees.every((fee, index) => Object.entries(fee).every(([key, value]) => q.fees[index][key] === value)), "fee display mismatch");
587
+ }
588
+
589
+ // src/compose-route.ts
590
+ var STARGATE_COMPOSE_CHAIN = "eip155:1";
591
+ var UNISWAP_V3_QUOTER_V2 = "0x61fFE014bA17989E743c5F6cB21bF9697530B21e";
592
+ var MULTICALL3 = "0xcA11bde05977b3631167028862bE2a173976CA11";
593
+ var ONE_BATCH = 1 << 16;
594
+ var QUOTE_GROUP = 4;
595
+ var COMPOSE_INTERMEDIATES = Object.freeze([
596
+ "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
597
+ "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
598
+ "0xdAC17F958D2ee523a2206206994597C13D831ec7"
599
+ ]);
600
+ var FEE_TIERS = [100, 500, 3e3, 1e4];
601
+ var COMPOSE_SWAP_GAS = 400000n;
602
+ var MIN_SWAP_GAS = 250000n;
603
+ var MAX_COMPOSE_GAS = 2000000n;
604
+ var RETRY_OVERHEAD = 250000n;
605
+ var QUOTER_ABI = parseAbi4(["function quoteExactInput(bytes path, uint256 amountIn) view returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);
606
+ var ADDRESS2 = (1n << 160n) - 1n;
607
+ var { V3: V32, NO_WRAP: NO_WRAP2, ZERO_FOR_ONE: ZERO_FOR_ONE2 } = UNOSWAP_FLAGS;
608
+ var PREFIX = "stargate:2:compose";
609
+ var isStargateComposeIntent = (id) => id.startsWith(`${PREFIX}:`);
610
+ function stargateComposeIntentId(c) {
611
+ const b = c.bridge;
612
+ return [PREFIX, b.source.eid, b.destination.eid, b.source.assetId, b.sender.toLowerCase(), c.recipient.toLowerCase(), b.amount, b.minimum, c.finalToken.toLowerCase(), toHex2(c.dex[0]), toHex2(c.dex[1]), c.minReturn, c.gas, c.transactionId.toLowerCase()].join(":");
613
+ }
614
+ function parseStargateComposeIntent(id, registry) {
615
+ const fields = id.split("~", 1)[0].split(":");
616
+ const [tag, version, mode, srcEid, dstEid, assetId, sender, recipient, amountText, fromText, finalToken, dex0, dex1, minText, gasText, transactionId] = fields;
617
+ assertStargate(fields.length === 16 && `${tag}:${version}:${mode}` === PREFIX, "invalid compose intent identity");
618
+ assertStargate([srcEid, dstEid, assetId, amountText, fromText, minText, gasText].every((v) => typeof v === "string" && /^(0|[1-9][0-9]{0,77})$/.test(v)), "invalid compose intent amounts");
619
+ assertStargate([dex0, dex1].every((v) => typeof v === "string" && /^0x[1-9a-f][0-9a-f]{0,63}$/.test(v)) && /^0x[0-9a-f]{64}$/.test(transactionId ?? "") && BigInt(transactionId) !== 0n, "invalid compose intent fields");
620
+ assertStargate(sender && recipient && finalToken && nonzeroAddress(sender) && nonzeroAddress(recipient) && nonzeroAddress(finalToken), "invalid compose intent actors");
621
+ const source = registry.deployments.find((d) => String(d.eid) === srcEid && String(d.assetId) === assetId);
622
+ const destination = registry.deployments.find((d) => String(d.eid) === dstEid && String(d.assetId) === assetId);
623
+ assertStargate(source && destination && destination.chain === STARGATE_COMPOSE_CHAIN && source.kind !== "native" && destination.kind !== "native" && registry.route(source.chain, source.token, destination.chain, destination.token), "unreviewed compose route");
624
+ assertStargate(!sameAddress(finalToken, destination.token), "compose output equals the bridged asset");
625
+ const amount = BigInt(amountText), fromAmount = BigInt(fromText), minReturn = BigInt(minText), gas = BigInt(gasText);
626
+ assertStargate(splitSourceAmount(amount, source.localDecimals, source.sharedDecimals).amountSD > 0n && fromAmount > 0n && minReturn > 0n && minReturn < 1n << 256n && gas >= MIN_SWAP_GAS && gas <= MAX_COMPOSE_GAS, "invalid compose intent bounds");
627
+ assertStargate(destinationAmount(sourceMinimum(fromAmount, source.localDecimals, destination.localDecimals, source.sharedDecimals), source.localDecimals, destination.localDecimals, source.sharedDecimals) === fromAmount, "unaligned compose bridge amount");
628
+ const dex = [BigInt(dex0), BigInt(dex1)];
629
+ assertStargate(dex.every((w) => w >> 253n === 1n && (w & ~(ADDRESS2 | V32 | NO_WRAP2 | ZERO_FOR_ONE2)) === 0n && (w & ADDRESS2) !== 0n), "unsupported compose DEX word");
630
+ const bridge = Object.freeze({ source, destination, mode: "taxi", sender: getAddress3(sender), recipient: LIFI_ETHEREUM_COMPOSER.receiver, amount, minimum: fromAmount, nativeDrop: 0n });
631
+ return Object.freeze({ bridge, recipient: getAddress3(recipient), finalToken: getAddress3(finalToken), dex: Object.freeze(dex), minReturn, gas, transactionId });
632
+ }
633
+ function stargateComposeSwapCall(c) {
634
+ return encodeFunctionData3({ abi: COMPOSE_UNOSWAP_ABI, functionName: "unoswap2", args: [BigInt(c.bridge.destination.token), c.bridge.minimum, c.minReturn, c.dex[0], c.dex[1]] });
635
+ }
636
+ function stargateComposeMessage(c) {
637
+ const router = getAddress3(COMPOSE_DEX_PINS.router);
638
+ return encodeAbiParameters2(LIFI_COMPOSE_PAYLOAD, [c.transactionId, [{ callTo: router, approveTo: router, sendingAssetId: c.bridge.destination.token, receivingAssetId: c.finalToken, fromAmount: c.bridge.minimum, callData: stargateComposeSwapCall(c), requiresDeposit: true }], c.recipient]);
639
+ }
640
+ function stargateComposeSendParam(c) {
641
+ const { source, destination } = c.bridge;
642
+ return Object.freeze({
643
+ dstEid: destination.eid,
644
+ to: pad3(LIFI_ETHEREUM_COMPOSER.receiver, { size: 32 }),
645
+ amountLD: c.bridge.amount,
646
+ minAmountLD: sourceMinimum(c.bridge.minimum, source.localDecimals, destination.localDecimals, source.sharedDecimals),
647
+ extraOptions: stargateComposeOptions(c.gas),
648
+ composeMsg: stargateComposeMessage(c),
649
+ oftCmd: "0x"
650
+ });
651
+ }
652
+ function stargateComposeProof(c, bridge) {
653
+ const composeMsg = stargateComposeMessage(c);
654
+ const message = encodePacked3(["uint64", "uint32", "uint256", "bytes32", "bytes"], [bridge.nonce, c.bridge.source.eid, bridge.amount, pad3(c.bridge.sender, { size: 32 }), composeMsg]);
655
+ return Object.freeze({
656
+ bridge,
657
+ transactionId: c.transactionId,
658
+ message,
659
+ messageHash: keccak2564(message),
660
+ recipient: c.recipient,
661
+ finalToken: c.finalToken,
662
+ minimum: c.minReturn,
663
+ swap: Object.freeze({ callTo: getAddress3(COMPOSE_DEX_PINS.router), fromAmount: c.bridge.minimum }),
664
+ executionSupported: true
665
+ });
666
+ }
667
+ function stargateComposeRetryGas(c, recoverGas) {
668
+ const floor = recoverGas + MIN_SWAP_GAS;
669
+ return (c.gas > floor ? c.gas : floor) + RETRY_OVERHEAD;
670
+ }
671
+ async function checkStargateComposer(client, destination, blockNumber) {
672
+ assertStargate(await client.getChainId() === 1 && destination.chain === STARGATE_COMPOSE_CHAIN, "wrong compose chain");
673
+ const pins = LIFI_ETHEREUM_COMPOSER;
674
+ for (const [address, expected] of [[pins.receiver, pins.receiverCodeHash], [pins.executor, pins.executorCodeHash], [COMPOSE_DEX_PINS.router, COMPOSE_DEX_PINS.routerCodeHash], [COMPOSE_DEX_PINS.factory, COMPOSE_DEX_PINS.factoryCodeHash]]) {
675
+ const code = await client.getCode({ address, blockNumber });
676
+ assertStargate(code && keccak2564(code) === expected, "compose contract bytecode changed");
677
+ }
678
+ const at = { address: pins.receiver, abi: LIFI_COMPOSE_ABI, blockNumber };
679
+ const [executor, endpoint, messaging, recoverGas] = await Promise.all([
680
+ client.readContract({ ...at, functionName: "executor" }),
681
+ client.readContract({ ...at, functionName: "endpointV2" }),
682
+ client.readContract({ ...at, functionName: "tokenMessaging" }),
683
+ client.readContract({ ...at, functionName: "recoverGas" })
684
+ ]);
685
+ assertStargate(sameAddress(executor, pins.executor) && sameAddress(endpoint, destination.endpoint) && sameAddress(messaging, destination.tokenMessaging), "composer wiring changed");
686
+ assertStargate(recoverGas + MIN_SWAP_GAS <= MAX_COMPOSE_GAS, "composer recovery reserve is out of range");
687
+ return { recoverGas };
688
+ }
689
+ async function quoteStargateComposeSwap(client, blockNumber, input, output, amount) {
690
+ const factory = getAddress3(COMPOSE_DEX_PINS.factory);
691
+ const legs = COMPOSE_INTERMEDIATES.filter((mid) => !sameAddress(mid, input) && !sameAddress(mid, output)).flatMap((mid) => FEE_TIERS.flatMap((fee) => [[input, mid, fee], [mid, output, fee]]));
692
+ const pools = await client.multicall({
693
+ multicallAddress: MULTICALL3,
694
+ batchSize: ONE_BATCH,
695
+ blockNumber,
696
+ allowFailure: false,
697
+ contracts: legs.map(([a, b, fee]) => ({ address: factory, abi: COMPOSE_POOL_ABI, functionName: "getPool", args: [a, b, fee] }))
698
+ });
699
+ const pool = new Map(legs.map(([a, b, fee], i) => [`${a}:${b}:${fee}`, pools[i]]));
700
+ const paths = [];
701
+ for (const mid of COMPOSE_INTERMEDIATES) for (const f0 of FEE_TIERS) for (const f1 of FEE_TIERS) {
702
+ const p0 = pool.get(`${input}:${mid}:${f0}`), p1 = pool.get(`${mid}:${output}:${f1}`);
703
+ if (p0 && p1 && nonzeroAddress(p0) && nonzeroAddress(p1)) paths.push({ mid, fees: [f0, f1], pools: [p0, p1] });
704
+ }
705
+ assertStargate(paths.length, "no two-pool Uniswap V3 path for the requested output");
706
+ let best = -1, out = 0n;
707
+ for (let start = 0; start < paths.length; start += QUOTE_GROUP) {
708
+ const group = paths.slice(start, start + QUOTE_GROUP);
709
+ const quotes = await client.multicall({
710
+ multicallAddress: MULTICALL3,
711
+ batchSize: ONE_BATCH,
712
+ blockNumber,
713
+ allowFailure: true,
714
+ contracts: group.map((p2) => ({ address: UNISWAP_V3_QUOTER_V2, abi: QUOTER_ABI, functionName: "quoteExactInput", args: [encodePacked3(["address", "uint24", "address", "uint24", "address"], [input, p2.fees[0], p2.mid, p2.fees[1], output]), amount] }))
715
+ });
716
+ quotes.forEach((q, i) => {
717
+ if (q.status === "success" && q.result[0] > out) {
718
+ out = q.result[0];
719
+ best = start + i;
720
+ }
721
+ });
722
+ }
723
+ assertStargate(best >= 0 && out > 0n, "no Uniswap V3 path can fill the bridged amount");
724
+ const p = paths[best], word = (address, from, to) => BigInt(address) | V32 | (BigInt(from) < BigInt(to) ? ZERO_FOR_ONE2 : 0n);
725
+ return { dex: Object.freeze([word(p.pools[0], input, p.mid) | NO_WRAP2, word(p.pools[1], p.mid, output)]), amountOut: out };
726
+ }
727
+ async function quoteIntentPath(client, blockNumber, c) {
728
+ const { fees, tokens } = await unoswap2V3Path(client, blockNumber, c.bridge.destination.token, c.dex, c.finalToken);
729
+ const path = encodePacked3(["address", "uint24", "address", "uint24", "address"], [tokens[0], fees[0], tokens[1], fees[1], tokens[2]]);
730
+ const [amountOut] = await client.readContract({ address: UNISWAP_V3_QUOTER_V2, abi: QUOTER_ABI, functionName: "quoteExactInput", args: [path, c.bridge.minimum], blockNumber });
731
+ return amountOut;
732
+ }
733
+ function checkedStargateComposeQuote(q, registry) {
734
+ const compose = parseStargateComposeIntent(q.intentId, registry), { source, destination, sender, amount, minimum } = compose.bridge;
735
+ const { tx, cap } = checkedStargateSource(q, source, destination, amount, "compose");
736
+ assertStargate(q.minDestAmount === String(compose.minReturn), "quote identity mismatch");
737
+ const sendParam = stargateComposeSendParam(compose);
738
+ const expected = encodeFunctionData3({ abi: STARGATE_ABI, functionName: "sendToken", args: [sendParam, { nativeFee: cap, lzTokenFee: 0n }, sender] });
739
+ assertStargate(tx.data.toLowerCase() === expected.toLowerCase(), "calldata differs from the reviewed intent");
740
+ assertStargate(/^[0-9]{1,78}$/.test(q.destAmount) && BigInt(q.destAmount) >= compose.minReturn, "invalid quoted output");
741
+ checkedStargateAccounting(q, source, destination, amount, cap, minimum);
742
+ assertStargate(q.providerData.nativeDrop === "0", "native drop display mismatch");
743
+ return { compose, sendParam, cap, tx };
744
+ }
745
+ function createStargateComposer(config) {
746
+ const registry = config.registry ?? stargateRegistry;
747
+ const rpc = stargateRpc(config), quoter = createStargateQuoter(config);
748
+ const swapGas = config.compose?.swapGas ?? COMPOSE_SWAP_GAS;
749
+ assertStargate(typeof swapGas === "bigint" && swapGas >= MIN_SWAP_GAS && swapGas <= MAX_COMPOSE_GAS, "invalid compose swap gas");
750
+ const bridged = (chain, token) => {
751
+ const source = registry.find(chain, token);
752
+ const destination = source && registry.deployments.find((d) => d.chain === STARGATE_COMPOSE_CHAIN && d.assetId === source.assetId);
753
+ return source && destination && source.kind !== "native" && destination.kind !== "native" && registry.route(source.chain, source.token, destination.chain, destination.token) ? { source, destination } : void 0;
754
+ };
755
+ function supportsRoute(sourceChain, sourceToken, destinationChain, finalToken) {
756
+ const route = destinationChain === STARGATE_COMPOSE_CHAIN ? bridged(sourceChain, sourceToken) : void 0;
757
+ return !!route && nonzeroAddress(finalToken) && !sameAddress(finalToken, route.destination.token) && stargateChainActive(sourceChain) && stargateChainActive(STARGATE_COMPOSE_CHAIN) && rpc.has(sourceChain) && rpc.has(STARGATE_COMPOSE_CHAIN);
758
+ }
759
+ async function quote(request, signal) {
760
+ try {
761
+ const r = { ...request };
762
+ const route = bridged(r.sourceChain, r.sourceToken);
763
+ assertStargate(route && supportsRoute(r.sourceChain, r.sourceToken, STARGATE_COMPOSE_CHAIN, r.finalToken), "unsupported compose route");
764
+ assertStargate(nonzeroAddress(r.sender) && nonzeroAddress(r.recipient), "sender and recipient must be nonzero EVM addresses");
765
+ const slippage = r.slippageBps ?? 0, minimum = r.minimum ?? 0n;
766
+ assertStargate(Number.isInteger(slippage) && slippage >= 0 && slippage < 1e4 && typeof minimum === "bigint" && minimum >= 0n && minimum < 1n << 256n, "invalid slippage or minimum");
767
+ const { source, destination } = route, recipient = getAddress3(r.recipient), finalToken = getAddress3(r.finalToken);
768
+ const eth = rpc.client(STARGATE_COMPOSE_CHAIN, signal), block = await rpc.snapshot(eth, 1);
769
+ const { recoverGas } = await checkStargateComposer(eth, destination, block.number);
770
+ const gas = recoverGas + swapGas;
771
+ assertStargate(gas <= MAX_COMPOSE_GAS, "compose gas exceeds the cap");
772
+ const transactionId = toHex2(globalThis.crypto.getRandomValues(new Uint8Array(32)));
773
+ let built, amountOut = 0n;
774
+ const q = await quoter.quote({
775
+ sourceChain: source.chain,
776
+ sourceToken: source.token,
777
+ destinationChain: destination.chain,
778
+ destinationToken: destination.token,
779
+ sender: r.sender,
780
+ recipient: LIFI_ETHEREUM_COMPOSER.receiver,
781
+ amount: r.amount,
782
+ mode: "taxi",
783
+ compose: { gas, async message(received, s) {
784
+ const swap = await quoteStargateComposeSwap(rpc.client(STARGATE_COMPOSE_CHAIN, s), block.number, destination.token, finalToken, received);
785
+ const floor = (swap.amountOut * BigInt(1e4 - slippage) + 9999n) / 10000n, minReturn = minimum > floor ? minimum : floor;
786
+ assertStargate(minReturn > 0n && minReturn <= swap.amountOut, "output is below the caller's minimum");
787
+ amountOut = swap.amountOut;
788
+ built = { bridge: { source, destination, mode: "taxi", sender: getAddress3(r.sender), recipient: LIFI_ETHEREUM_COMPOSER.receiver, amount: r.amount, minimum: received, nativeDrop: 0n }, recipient, finalToken, dex: swap.dex, minReturn, gas, transactionId };
789
+ return stargateComposeMessage(built);
790
+ } }
791
+ }, signal);
792
+ assertStargate(built && q.minimumDestinationAmount === built.bridge.minimum && q.destinationAmount === built.bridge.minimum, "bridge output is not exact");
793
+ await rpc.unchanged(eth, block);
794
+ assertNotAborted(signal);
795
+ const intent = Object.freeze({ ...built, bridge: Object.freeze(built.bridge) });
796
+ const data = encodeFunctionData3({ abi: STARGATE_ABI, functionName: "sendToken", args: [stargateComposeSendParam(intent), { nativeFee: q.messagingFeeCap, lzTokenFee: 0n }, q.sender] });
797
+ assertStargate(data === encodeFunctionData3({ abi: STARGATE_ABI, functionName: "sendToken", args: [q.sendParam, { nativeFee: q.messagingFeeCap, lzTokenFee: 0n }, q.sender] }), "compose encoding drifted");
798
+ const out = {
799
+ provider: "stargate",
800
+ routeId: "compose",
801
+ intentId: stargateComposeIntentId(intent),
802
+ depositAddress: "",
803
+ depositMemo: null,
804
+ sourceAmount: String(r.amount),
805
+ destAmount: String(amountOut),
806
+ minDestAmount: String(intent.minReturn),
807
+ txRequest: { to: source.address, data, value: String(q.nativeValue), nativeFee: String(q.messagingFeeCap), chainId: source.chainId, ...source.approvalRequired ? { approvalAddress: source.address } : {} },
808
+ feeUsd: 0,
809
+ etaSeconds: null,
810
+ reliability: 0.85,
811
+ validUntilMs: q.validUntilMs,
812
+ fees: stargateFees(source, q.protocolFee, q.messagingFeeCap),
813
+ providerData: {
814
+ sentAmount: String(q.sentAmount),
815
+ dust: String(q.dust),
816
+ protocolFee: String(q.protocolFee),
817
+ protocolReward: String(q.protocolReward),
818
+ messagingFee: String(q.messagingFee),
819
+ nativeDrop: "0",
820
+ sourceBlock: String(q.sourceBlock.number),
821
+ sourceBlockHash: q.sourceBlock.hash,
822
+ destinationBlock: String(block.number),
823
+ destinationBlockHash: block.hash,
824
+ bridgedAmount: String(intent.bridge.minimum),
825
+ bridgedToken: destination.token,
826
+ composer: LIFI_ETHEREUM_COMPOSER.receiver,
827
+ composeGas: String(gas),
828
+ recoverGas: String(recoverGas),
829
+ liquidityReserved: "false",
830
+ feeUsdKnown: "false",
831
+ sourceGas: "unknown",
832
+ approvalGas: "unknown"
833
+ }
834
+ };
835
+ checkedStargateComposeQuote(out, registry);
836
+ return out;
837
+ } catch (error) {
838
+ throw safeReadError(error);
839
+ }
840
+ }
841
+ async function verifyBuild(c, cap) {
842
+ const b = c.bridge;
843
+ const fresh = await quoter.quote({
844
+ sourceChain: b.source.chain,
845
+ sourceToken: b.source.token,
846
+ destinationChain: b.destination.chain,
847
+ destinationToken: b.destination.token,
848
+ sender: b.sender,
849
+ recipient: b.recipient,
850
+ amount: b.amount,
851
+ mode: "taxi",
852
+ compose: { gas: c.gas, message: async (received) => {
853
+ assertStargate(received === b.minimum, "bridge output changed");
854
+ return stargateComposeMessage(c);
855
+ } }
856
+ });
857
+ assertStargate(fresh.messagingFee <= cap, "messaging fee exceeds the reviewed cap");
858
+ const eth = rpc.client(STARGATE_COMPOSE_CHAIN), block = await rpc.snapshot(eth, 1);
859
+ const { recoverGas } = await checkStargateComposer(eth, b.destination, block.number);
860
+ assertStargate(c.gas >= recoverGas + MIN_SWAP_GAS, "compose gas no longer covers the swap");
861
+ assertStargate(await quoteIntentPath(eth, block.number, c) >= c.minReturn, "destination price moved below the reviewed minimum");
862
+ await rpc.unchanged(eth, block);
863
+ }
864
+ return Object.freeze({ supportsRoute, quote, verifyBuild });
865
+ }
866
+
867
+ export {
868
+ stargateToken,
869
+ stargateIntent,
870
+ parseStargateIntent,
871
+ stargateFees,
872
+ checkedStargateSource,
873
+ checkedStargateAccounting,
874
+ STARGATE_COMPOSE_CHAIN,
875
+ UNISWAP_V3_QUOTER_V2,
876
+ COMPOSE_INTERMEDIATES,
877
+ COMPOSE_SWAP_GAS,
878
+ isStargateComposeIntent,
879
+ stargateComposeIntentId,
880
+ parseStargateComposeIntent,
881
+ stargateComposeSwapCall,
882
+ stargateComposeMessage,
883
+ stargateComposeSendParam,
884
+ stargateComposeProof,
885
+ stargateComposeRetryGas,
886
+ checkStargateComposer,
887
+ quoteStargateComposeSwap,
888
+ checkedStargateComposeQuote,
889
+ createStargateComposer,
890
+ stargateTaxiProof,
891
+ stargateComposedTaxiProof,
892
+ stargateTaxiPayout,
893
+ checkStargateReceipt,
894
+ createStargateTracker,
895
+ COMPOSE_ABI,
896
+ LIFI_COMPOSE_ABI,
897
+ LIFI_COMPOSE_PAYLOAD,
898
+ LIFI_ETHEREUM_COMPOSER,
899
+ stargateComposeQueueState,
900
+ proveLifiStargateCompose,
901
+ lifiStargateComposeOutcome,
902
+ COMPOSE_UNOSWAP_ABI,
903
+ COMPOSE_POOL_ABI,
904
+ COMPOSE_DEX_PINS,
905
+ UNOSWAP_FLAGS,
906
+ unoswap2V3Path,
907
+ validateLifiUnoswap2Compose
908
+ };
909
+ //# sourceMappingURL=chunk-PJXDMVW3.js.map