@anywalletkit/protocol-swap2-stargate 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 +502 -2
- package/dist/abi.cjs +91 -0
- package/dist/abi.cjs.map +1 -0
- package/dist/abi.d.cts +810 -0
- package/dist/abi.d.ts +810 -0
- package/dist/abi.js +13 -0
- package/dist/abi.js.map +1 -0
- package/dist/amounts.cjs +73 -0
- package/dist/amounts.cjs.map +1 -0
- package/dist/amounts.d.cts +21 -0
- package/dist/amounts.d.ts +21 -0
- package/dist/amounts.js +15 -0
- package/dist/amounts.js.map +1 -0
- package/dist/bus-Cdw8iwOv.d.cts +59 -0
- package/dist/bus-vAWqTAkq.d.ts +59 -0
- package/dist/bus.cjs +237 -0
- package/dist/bus.cjs.map +1 -0
- package/dist/bus.d.cts +4 -0
- package/dist/bus.d.ts +4 -0
- package/dist/bus.js +22 -0
- package/dist/bus.js.map +1 -0
- package/dist/chunk-3NTMZUAU.js +128 -0
- package/dist/chunk-3NTMZUAU.js.map +1 -0
- package/dist/chunk-4HU46QF2.js +256 -0
- package/dist/chunk-4HU46QF2.js.map +1 -0
- package/dist/chunk-4IDDRIE2.js +125 -0
- package/dist/chunk-4IDDRIE2.js.map +1 -0
- package/dist/chunk-EANM3EI3.js +71 -0
- package/dist/chunk-EANM3EI3.js.map +1 -0
- package/dist/chunk-ERC6LKMN.js +87 -0
- package/dist/chunk-ERC6LKMN.js.map +1 -0
- package/dist/chunk-FLAXDJPE.js +24 -0
- package/dist/chunk-FLAXDJPE.js.map +1 -0
- package/dist/chunk-N54YIG6T.js +33 -0
- package/dist/chunk-N54YIG6T.js.map +1 -0
- package/dist/chunk-OUGUX3JK.js +53 -0
- package/dist/chunk-OUGUX3JK.js.map +1 -0
- package/dist/chunk-PJXDMVW3.js +909 -0
- package/dist/chunk-PJXDMVW3.js.map +1 -0
- package/dist/chunk-QNVTQEOV.js +72 -0
- package/dist/chunk-QNVTQEOV.js.map +1 -0
- package/dist/chunk-UDJL7BUP.js +249 -0
- package/dist/chunk-UDJL7BUP.js.map +1 -0
- package/dist/chunk-YHHV3XHY.js +139 -0
- package/dist/chunk-YHHV3XHY.js.map +1 -0
- package/dist/compose-dex.cjs +148 -0
- package/dist/compose-dex.cjs.map +1 -0
- package/dist/compose-dex.d.cts +113 -0
- package/dist/compose-dex.d.ts +113 -0
- package/dist/compose-dex.js +25 -0
- package/dist/compose-dex.js.map +1 -0
- package/dist/compose-route.cjs +1019 -0
- package/dist/compose-route.cjs.map +1 -0
- package/dist/compose-route.d.cts +93 -0
- package/dist/compose-route.d.ts +93 -0
- package/dist/compose-route.js +45 -0
- package/dist/compose-route.js.map +1 -0
- package/dist/compose.cjs +287 -0
- package/dist/compose.cjs.map +1 -0
- package/dist/compose.d.cts +293 -0
- package/dist/compose.d.ts +293 -0
- package/dist/compose.js +30 -0
- package/dist/compose.js.map +1 -0
- package/dist/deployments.cjs +350 -0
- package/dist/deployments.cjs.map +1 -0
- package/dist/deployments.d.cts +12 -0
- package/dist/deployments.d.ts +12 -0
- package/dist/deployments.js +11 -0
- package/dist/deployments.js.map +1 -0
- package/dist/index.cjs +1862 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +46 -0
- package/dist/index.js.map +1 -0
- package/dist/native-drop.cjs +117 -0
- package/dist/native-drop.cjs.map +1 -0
- package/dist/native-drop.d.cts +13 -0
- package/dist/native-drop.d.ts +13 -0
- package/dist/native-drop.js +11 -0
- package/dist/native-drop.js.map +1 -0
- package/dist/pins.cjs +1618 -0
- package/dist/pins.cjs.map +1 -0
- package/dist/pins.d.cts +39 -0
- package/dist/pins.d.ts +39 -0
- package/dist/pins.js +21 -0
- package/dist/pins.js.map +1 -0
- package/dist/protocol.cjs +1851 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +24 -0
- package/dist/protocol.d.ts +24 -0
- package/dist/protocol.js +18 -0
- package/dist/protocol.js.map +1 -0
- package/dist/provider.cjs +1833 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.cts +30 -0
- package/dist/provider.d.ts +30 -0
- package/dist/provider.js +17 -0
- package/dist/provider.js.map +1 -0
- package/dist/quote-r1bA8XbO.d.cts +102 -0
- package/dist/quote-t7UJSxbU.d.ts +102 -0
- package/dist/quote.cjs +618 -0
- package/dist/quote.cjs.map +1 -0
- package/dist/quote.d.cts +3 -0
- package/dist/quote.d.ts +3 -0
- package/dist/quote.js +16 -0
- package/dist/quote.js.map +1 -0
- package/dist/registry.cjs +100 -0
- package/dist/registry.cjs.map +1 -0
- package/dist/registry.d.cts +42 -0
- package/dist/registry.d.ts +42 -0
- package/dist/registry.js +8 -0
- package/dist/registry.js.map +1 -0
- package/dist/tracking.cjs +1143 -0
- package/dist/tracking.cjs.map +1 -0
- package/dist/tracking.d.cts +57 -0
- package/dist/tracking.d.ts +57 -0
- package/dist/tracking.js +23 -0
- package/dist/tracking.js.map +1 -0
- package/package.json +134 -3
package/dist/compose.cjs
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
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/compose.ts
|
|
21
|
+
var compose_exports = {};
|
|
22
|
+
__export(compose_exports, {
|
|
23
|
+
COMPOSE_ABI: () => COMPOSE_ABI,
|
|
24
|
+
LIFI_COMPOSE_ABI: () => LIFI_COMPOSE_ABI,
|
|
25
|
+
LIFI_COMPOSE_PAYLOAD: () => LIFI_COMPOSE_PAYLOAD,
|
|
26
|
+
LIFI_ETHEREUM_COMPOSER: () => LIFI_ETHEREUM_COMPOSER,
|
|
27
|
+
lifiStargateComposeOutcome: () => lifiStargateComposeOutcome,
|
|
28
|
+
proveLifiStargateCompose: () => proveLifiStargateCompose,
|
|
29
|
+
stargateComposeOptions: () => stargateComposeOptions,
|
|
30
|
+
stargateComposeQueueState: () => stargateComposeQueueState
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(compose_exports);
|
|
33
|
+
var import_viem5 = require("viem");
|
|
34
|
+
|
|
35
|
+
// src/rpc.ts
|
|
36
|
+
var import_viem2 = require("viem");
|
|
37
|
+
|
|
38
|
+
// src/abi.ts
|
|
39
|
+
var import_viem = require("viem");
|
|
40
|
+
var EXECUTOR_ABI = (0, import_viem.parseAbi)([
|
|
41
|
+
"struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }",
|
|
42
|
+
"struct NativeDropParams { address receiver; uint256 amount; }",
|
|
43
|
+
"function endpoint() view returns (address)",
|
|
44
|
+
"function localEid() view returns (uint32)",
|
|
45
|
+
"event NativeDropApplied(Origin origin, uint32 dstEid, address oapp, NativeDropParams[] params, bool[] success)"
|
|
46
|
+
]);
|
|
47
|
+
var ENDPOINT_ABI = (0, import_viem.parseAbi)([
|
|
48
|
+
"struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }",
|
|
49
|
+
"function inboundPayloadHash(address receiver, uint32 srcEid, bytes32 sender, uint64 nonce) view returns (bytes32)",
|
|
50
|
+
"function lzReceive(Origin origin, address receiver, bytes32 guid, bytes message, bytes extraData) payable",
|
|
51
|
+
"event PacketSent(bytes encodedPayload, bytes options, address sendLibrary)",
|
|
52
|
+
"event PacketDelivered(Origin origin, address receiver)"
|
|
53
|
+
]);
|
|
54
|
+
var STARGATE_ABI = (0, import_viem.parseAbi)([
|
|
55
|
+
"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }",
|
|
56
|
+
"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }",
|
|
57
|
+
"struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; }",
|
|
58
|
+
"struct OFTLimit { uint256 minAmountLD; uint256 maxAmountLD; }",
|
|
59
|
+
"struct OFTFeeDetail { int256 feeAmountLD; string description; }",
|
|
60
|
+
"struct OFTReceipt { uint256 amountSentLD; uint256 amountReceivedLD; }",
|
|
61
|
+
"struct Ticket { uint72 ticketId; bytes passengerBytes; }",
|
|
62
|
+
"struct AddressConfig { address feeLib; address planner; address treasurer; address tokenMessaging; address creditMessaging; address lzToken; }",
|
|
63
|
+
"function token() view returns (address)",
|
|
64
|
+
"function sharedDecimals() view returns (uint8)",
|
|
65
|
+
"function approvalRequired() pure returns (bool)",
|
|
66
|
+
"function localEid() view returns (uint32)",
|
|
67
|
+
"function endpoint() view returns (address)",
|
|
68
|
+
"function status() view returns (uint8)",
|
|
69
|
+
"function stargateType() pure returns (uint8)",
|
|
70
|
+
"function paths(uint32 eid) view returns (uint64 credit)",
|
|
71
|
+
"function getAddressConfig() view returns (AddressConfig)",
|
|
72
|
+
"function quoteOFT(SendParam s) view returns (OFTLimit limit, OFTFeeDetail[] oftFeeDetails, OFTReceipt receipt)",
|
|
73
|
+
"function quoteSend(SendParam s, bool payInLzToken) view returns (MessagingFee fee)",
|
|
74
|
+
"function send(SendParam s, MessagingFee fee, address refundAddress) payable returns (MessagingReceipt msgReceipt, OFTReceipt oftReceipt)",
|
|
75
|
+
"function sendToken(SendParam s, MessagingFee fee, address refundAddress) payable returns (MessagingReceipt msgReceipt, OFTReceipt oftReceipt, Ticket ticket)",
|
|
76
|
+
"function unreceivedTokens(bytes32 guid, uint8 index) view returns (bytes32)",
|
|
77
|
+
"function retryReceiveToken(bytes32 guid, uint8 index, uint32 srcEid, address receiver, uint256 amountLD, bytes composeMsg)",
|
|
78
|
+
"event OFTSent(bytes32 indexed guid, uint32 dstEid, address indexed fromAddress, uint256 amountSentLD, uint256 amountReceivedLD)",
|
|
79
|
+
"event OFTReceived(bytes32 indexed guid, uint32 srcEid, address indexed toAddress, uint256 amountReceivedLD)",
|
|
80
|
+
"event UnreceivedTokenCached(bytes32 guid, uint8 index, uint32 srcEid, address receiver, uint256 amountLD, bytes composeMsg)"
|
|
81
|
+
]);
|
|
82
|
+
var TOKEN_MESSAGING_ABI = (0, import_viem.parseAbi)([
|
|
83
|
+
"error Bus_InvalidFare(bool nativeDrop)",
|
|
84
|
+
"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }",
|
|
85
|
+
"struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; }",
|
|
86
|
+
"function assetIds(address stargateImpl) view returns (uint16)",
|
|
87
|
+
"function stargateImpls(uint16 assetId) view returns (address)",
|
|
88
|
+
"function peers(uint32 eid) view returns (bytes32)",
|
|
89
|
+
"function endpoint() view returns (address)",
|
|
90
|
+
"function nativeDropAmounts(uint32 eid) view returns (uint128)",
|
|
91
|
+
"function queueCapacity() view returns (uint16)",
|
|
92
|
+
"function busQueues(uint32 eid) view returns (uint8 maxNumPassengers, uint80 busFare, uint80 busAndNativeDropFare, uint16 qLength, uint72 nextTicketId)",
|
|
93
|
+
"function getPassengerHash(uint32 eid, uint16 index) view returns (bytes32)",
|
|
94
|
+
"function quoteDriveBus(uint32 dstEid, bytes passengers) view returns (MessagingFee fee)",
|
|
95
|
+
"function driveBus(uint32 dstEid, bytes passengers) payable returns (MessagingReceipt receipt)",
|
|
96
|
+
"event BusRode(uint32 dstEid, uint72 ticketId, uint80 fare, bytes passenger)",
|
|
97
|
+
"event BusDriven(uint32 dstEid, uint72 startTicketId, uint8 numPassengers, bytes32 guid)",
|
|
98
|
+
"event NativeDropApplied(address receiver, uint128 amount)",
|
|
99
|
+
"event NativeDropFailed(address receiver, uint128 amount)"
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
// src/rpc.ts
|
|
103
|
+
var StargateReadError = class extends Error {
|
|
104
|
+
constructor(message) {
|
|
105
|
+
super(`stargate: ${message}`);
|
|
106
|
+
this.name = "StargateReadError";
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
var auxiliaryAbi = (0, import_viem2.parseAbi)(["function decimals() view returns (uint8)", "function eid() view returns (uint32)"]);
|
|
110
|
+
var sameAddress = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
111
|
+
function assertStargate(condition, message) {
|
|
112
|
+
if (!condition) throw new StargateReadError(message);
|
|
113
|
+
}
|
|
114
|
+
function nonzeroAddress(value) {
|
|
115
|
+
return /^0x[0-9a-fA-F]{40}$/.test(value) && !/^0x0{40}$/.test(value);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/tracking.ts
|
|
119
|
+
var import_viem4 = require("viem");
|
|
120
|
+
var import_util = require("@anywalletkit/protocol-swap2-core/util");
|
|
121
|
+
|
|
122
|
+
// src/amounts.ts
|
|
123
|
+
var UINT64_MAX = (1n << 64n) - 1n;
|
|
124
|
+
var UINT256_MAX = (1n << 256n) - 1n;
|
|
125
|
+
function uint256(amount) {
|
|
126
|
+
if (typeof amount !== "bigint" || amount < 0n || amount > UINT256_MAX) throw new RangeError("stargate: amount must be uint256 bigint");
|
|
127
|
+
}
|
|
128
|
+
function conversionRate(localDecimals, sharedDecimals) {
|
|
129
|
+
if (!Number.isInteger(localDecimals) || !Number.isInteger(sharedDecimals) || sharedDecimals < 0 || localDecimals < sharedDecimals || localDecimals > 255 || localDecimals - sharedDecimals > 77) {
|
|
130
|
+
throw new RangeError("stargate: invalid local/shared decimals");
|
|
131
|
+
}
|
|
132
|
+
return 10n ** BigInt(localDecimals - sharedDecimals);
|
|
133
|
+
}
|
|
134
|
+
function splitSourceAmount(amountLD, localDecimals, sharedDecimals) {
|
|
135
|
+
uint256(amountLD);
|
|
136
|
+
const rate = conversionRate(localDecimals, sharedDecimals);
|
|
137
|
+
const amountSD = amountLD / rate;
|
|
138
|
+
if (amountSD > UINT64_MAX) throw new RangeError("stargate: shared amount exceeds uint64");
|
|
139
|
+
return { amountSD, sentLD: amountSD * rate, dustLD: amountLD % rate };
|
|
140
|
+
}
|
|
141
|
+
function destinationAmount(receivedSourceLD, sourceDecimals, destinationDecimals, sharedDecimals) {
|
|
142
|
+
const { amountSD, dustLD } = splitSourceAmount(receivedSourceLD, sourceDecimals, sharedDecimals);
|
|
143
|
+
if (dustLD !== 0n) throw new RangeError("stargate: quote receipt is not shared-decimal aligned");
|
|
144
|
+
const amount = amountSD * conversionRate(destinationDecimals, sharedDecimals);
|
|
145
|
+
uint256(amount);
|
|
146
|
+
return amount;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/quote.ts
|
|
150
|
+
var import_viem3 = require("viem");
|
|
151
|
+
var UINT64_MAX2 = (1n << 64n) - 1n;
|
|
152
|
+
var UINT256_MAX2 = (1n << 256n) - 1n;
|
|
153
|
+
function stargateComposeOptions(gas) {
|
|
154
|
+
assertStargate(typeof gas === "bigint" && gas > 0n && gas < 1n << 128n, "compose gas must be a positive uint128");
|
|
155
|
+
return (0, import_viem3.encodePacked)(["uint16", "uint8", "uint16", "uint8", "uint16", "uint128"], [3, 1, 19, 3, 0, gas]);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// src/tracking.ts
|
|
159
|
+
var endpointAbi = (0, import_viem4.parseAbi)(["event PacketSent(bytes encodedPayload, bytes options, address sendLibrary)"]);
|
|
160
|
+
var ZERO_HASH = `0x${"00".repeat(32)}`;
|
|
161
|
+
function stargateComposedTaxiProof(i, receipt, composeFrom, composeMsg) {
|
|
162
|
+
assertStargate(nonzeroAddress(composeFrom) && /^0x(?:[0-9a-f]{2}){1,16384}$/i.test(composeMsg), "invalid expected compose payload");
|
|
163
|
+
return taxiProof(i, receipt, `${(0, import_viem4.pad)(composeFrom, { size: 32 })}${composeMsg.slice(2)}`);
|
|
164
|
+
}
|
|
165
|
+
function taxiProof(i, receipt, expectedCompose) {
|
|
166
|
+
assertStargate(i.mode === "taxi" && receipt.status === "success", "not a successful Taxi source receipt");
|
|
167
|
+
const sent = (0, import_viem4.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);
|
|
168
|
+
assertStargate(sent.length === 1, "missing or ambiguous source transfer");
|
|
169
|
+
const event = sent[0].args;
|
|
170
|
+
assertStargate(event.guid !== ZERO_HASH && event.amountSentLD === splitSourceAmount(i.amount, i.source.localDecimals, i.source.sharedDecimals).sentLD, "source amount mismatch");
|
|
171
|
+
const amount = destinationAmount(event.amountReceivedLD, i.source.localDecimals, i.destination.localDecimals, i.source.sharedDecimals);
|
|
172
|
+
assertStargate(amount >= i.minimum, "source output is below the intent minimum");
|
|
173
|
+
const packets = (0, import_viem4.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((0, import_viem4.slice)(l.args.encodedPayload, 81, 113), event.guid));
|
|
174
|
+
assertStargate(packets.length === 1, "missing or ambiguous endpoint packet");
|
|
175
|
+
const packet = packets[0].args.encodedPayload;
|
|
176
|
+
assertStargate((0, import_viem4.slice)(packet, 0, 1) === "0x01" && BigInt((0, import_viem4.slice)(packet, 9, 13)) === BigInt(i.source.eid) && BigInt((0, import_viem4.slice)(packet, 45, 49)) === BigInt(i.destination.eid), "packet pathway mismatch");
|
|
177
|
+
assertStargate(sameAddress((0, import_viem4.slice)(packet, 13, 45), (0, import_viem4.pad)(i.source.tokenMessaging, { size: 32 })) && sameAddress((0, import_viem4.slice)(packet, 49, 81), (0, import_viem4.pad)(i.destination.tokenMessaging, { size: 32 })), "packet messaging contracts mismatch");
|
|
178
|
+
const message = (0, import_viem4.slice)(packet, 113);
|
|
179
|
+
assertStargate(expectedCompose === void 0 ? /^0x01[0-9a-f]{84}$/i.test(message) : /^0x01[0-9a-f]+$/i.test(message) && sameAddress((0, import_viem4.slice)(message, 43), expectedCompose), "unsupported Taxi compose payload");
|
|
180
|
+
assertStargate(BigInt((0, import_viem4.slice)(message, 1, 3)) === BigInt(i.source.assetId) && sameAddress((0, import_viem4.slice)(message, 3, 35), (0, import_viem4.pad)(i.recipient, { size: 32 })) && BigInt((0, import_viem4.slice)(message, 35, 43)) * conversionRate(i.destination.localDecimals, i.destination.sharedDecimals) === amount, "Taxi passenger mismatch");
|
|
181
|
+
return { intent: i, guid: event.guid, amount, packet, message, nonce: BigInt((0, import_viem4.slice)(packet, 1, 9)), sourceHash: receipt.transactionHash };
|
|
182
|
+
}
|
|
183
|
+
function stargateTaxiPayout(proof, receipt) {
|
|
184
|
+
if (receipt.status !== "success") return false;
|
|
185
|
+
const i = proof.intent;
|
|
186
|
+
const received = (0, import_viem4.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));
|
|
187
|
+
return received.length === 1 && received[0].args.srcEid === i.source.eid && sameAddress(received[0].args.toAddress, i.recipient) && received[0].args.amountReceivedLD === proof.amount;
|
|
188
|
+
}
|
|
189
|
+
function checkStargateReceipt(receipt, expectedHash, blockHash) {
|
|
190
|
+
assertStargate(sameAddress(receipt.transactionHash, expectedHash) && sameAddress(receipt.blockHash, blockHash), "receipt block/hash mismatch");
|
|
191
|
+
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");
|
|
192
|
+
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");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/compose.ts
|
|
196
|
+
var COMPOSE_ABI = (0, import_viem5.parseAbi)([
|
|
197
|
+
"function composeQueue(address from, address to, bytes32 guid, uint16 index) view returns (bytes32)",
|
|
198
|
+
"function lzCompose(address from, address to, bytes32 guid, uint16 index, bytes message, bytes extraData) payable",
|
|
199
|
+
"event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message)",
|
|
200
|
+
"event ComposeDelivered(address from, address to, bytes32 guid, uint16 index)"
|
|
201
|
+
]);
|
|
202
|
+
var LIFI_COMPOSE_ABI = (0, import_viem5.parseAbi)([
|
|
203
|
+
"function executor() view returns (address)",
|
|
204
|
+
"function endpointV2() view returns (address)",
|
|
205
|
+
"function tokenMessaging() view returns (address)",
|
|
206
|
+
"function recoverGas() view returns (uint256)",
|
|
207
|
+
"event LiFiTransferCompleted(bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp)",
|
|
208
|
+
"event LiFiTransferRecovered(bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp)",
|
|
209
|
+
"event AssetSwapped(bytes32 transactionId, address dex, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount, uint256 timestamp)",
|
|
210
|
+
"event Transfer(address indexed from, address indexed to, uint256 value)"
|
|
211
|
+
]);
|
|
212
|
+
var LIFI_COMPOSE_PAYLOAD = (0, import_viem5.parseAbiParameters)("bytes32 transactionId, (address callTo, address approveTo, address sendingAssetId, address receivingAssetId, uint256 fromAmount, bytes callData, bool requiresDeposit)[] swaps, address receiver");
|
|
213
|
+
var LIFI_ETHEREUM_COMPOSER = Object.freeze({
|
|
214
|
+
chain: "eip155:1",
|
|
215
|
+
receiver: "0xB539B40793171211DCA8834da044fC14bCe64BDC",
|
|
216
|
+
executor: "0xd9B2Da9C45b118e4e93A004FB1452bCDB6cC0E88",
|
|
217
|
+
receiverCodeHash: "0x535b6e74e5bbb38e9a469de60ff2587cf498b92a99be01f34d20c37a77e4cea2",
|
|
218
|
+
executorCodeHash: "0xf937f13890d789171f0bcf3c558a64869105000b6771dc182ddc165bde92ddfe"
|
|
219
|
+
});
|
|
220
|
+
function stargateComposeQueueState(messageHash, queue) {
|
|
221
|
+
assertStargate(/^0x[0-9a-f]{64}$/i.test(messageHash) && /^0x[0-9a-f]{64}$/i.test(queue), "invalid compose commitment");
|
|
222
|
+
if (BigInt(queue) === 0n) return "absent";
|
|
223
|
+
if (BigInt(queue) === 1n) return "consumed";
|
|
224
|
+
return sameAddress(messageHash, queue) ? "pending" : "mismatch";
|
|
225
|
+
}
|
|
226
|
+
function proveLifiStargateCompose(expected, source, delivery, code) {
|
|
227
|
+
const pins = LIFI_ETHEREUM_COMPOSER, i = expected.bridge;
|
|
228
|
+
assertStargate(i.destination.chain === pins.chain && sameAddress(i.recipient, pins.receiver), "unreviewed composer");
|
|
229
|
+
assertStargate((0, import_viem5.keccak256)(code.receiver) === pins.receiverCodeHash && (0, import_viem5.keccak256)(code.executor) === pins.executorCodeHash, "composer bytecode changed");
|
|
230
|
+
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");
|
|
231
|
+
for (const receipt of [source, delivery]) checkStargateReceipt(receipt, receipt.transactionHash, receipt.blockHash);
|
|
232
|
+
const bridge = stargateComposedTaxiProof(i, source, expected.composeFrom, expected.composeMsg);
|
|
233
|
+
const [transactionId, swaps, recipient] = (0, import_viem5.decodeAbiParameters)(LIFI_COMPOSE_PAYLOAD, expected.composeMsg);
|
|
234
|
+
assertStargate((0, import_viem5.encodeAbiParameters)(LIFI_COMPOSE_PAYLOAD, [transactionId, swaps, recipient]).toLowerCase() === expected.composeMsg.toLowerCase(), "noncanonical compose message");
|
|
235
|
+
assertStargate(BigInt(transactionId) !== 0n && swaps.length === 1 && sameAddress(recipient, expected.recipient), "unsupported compose action or recipient");
|
|
236
|
+
const swap = swaps[0];
|
|
237
|
+
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");
|
|
238
|
+
assertStargate(stargateTaxiPayout(bridge, delivery), "bridge has not paid the composer");
|
|
239
|
+
const message = (0, import_viem5.encodePacked)(["uint64", "uint32", "uint256", "bytes32", "bytes"], [bridge.nonce, i.source.eid, bridge.amount, (0, import_viem5.pad)(expected.composeFrom, { size: 32 }), expected.composeMsg]);
|
|
240
|
+
const sent = (0, import_viem5.parseEventLogs)({ 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));
|
|
241
|
+
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");
|
|
242
|
+
const intent = Object.freeze({ ...i, source: Object.freeze({ ...i.source }), destination: Object.freeze({ ...i.destination }) });
|
|
243
|
+
return Object.freeze({ bridge: Object.freeze({ ...bridge, intent }), transactionId, message, messageHash: (0, import_viem5.keccak256)(message), recipient, finalToken: expected.finalToken, minimum: expected.minimum, swap: Object.freeze({ callTo: swap.callTo, fromAmount: swap.fromAmount }), executionSupported: false });
|
|
244
|
+
}
|
|
245
|
+
function lifiStargateComposeOutcome(p, receipt) {
|
|
246
|
+
const unknown = { state: "unverified" };
|
|
247
|
+
try {
|
|
248
|
+
let paid2 = function(token, from, before) {
|
|
249
|
+
const transfers = (0, import_viem5.parseEventLogs)({ abi: LIFI_COMPOSE_ABI, eventName: "Transfer", logs: receipt.logs.filter((l) => sameAddress(l.address, token) && l.logIndex < before), strict: true });
|
|
250
|
+
let net = 0n;
|
|
251
|
+
for (const { args } of transfers) {
|
|
252
|
+
if (sameAddress(args.to, p.recipient) && sameAddress(args.from, from)) net += args.value;
|
|
253
|
+
if (sameAddress(args.from, p.recipient)) net -= args.value;
|
|
254
|
+
}
|
|
255
|
+
return net;
|
|
256
|
+
};
|
|
257
|
+
var paid = paid2;
|
|
258
|
+
if (receipt.status !== "success") return unknown;
|
|
259
|
+
checkStargateReceipt(receipt, receipt.transactionHash, receipt.blockHash);
|
|
260
|
+
const pins = LIFI_ETHEREUM_COMPOSER, d = p.bridge.intent.destination;
|
|
261
|
+
const delivered = (0, import_viem5.parseEventLogs)({ abi: COMPOSE_ABI, eventName: "ComposeDelivered", logs: receipt.logs.filter((l) => sameAddress(l.address, d.endpoint)), strict: true });
|
|
262
|
+
if (delivered.length !== 1) return unknown;
|
|
263
|
+
const end = delivered[0];
|
|
264
|
+
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;
|
|
265
|
+
const recovered = (0, import_viem5.parseEventLogs)({ 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));
|
|
266
|
+
const completed = (0, import_viem5.parseEventLogs)({ 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));
|
|
267
|
+
if (recovered.length === 1 && completed.length === 0) {
|
|
268
|
+
const event2 = recovered[0];
|
|
269
|
+
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;
|
|
270
|
+
if (d.token !== import_viem5.zeroAddress && paid2(d.token, pins.receiver, event2.logIndex) !== p.bridge.amount) return unknown;
|
|
271
|
+
return { state: "intermediate-refunded", token: d.token, amount: p.bridge.amount, transactionHash: receipt.transactionHash };
|
|
272
|
+
}
|
|
273
|
+
if (completed.length !== 1 || recovered.length !== 0 || p.finalToken === import_viem5.zeroAddress) return unknown;
|
|
274
|
+
const event = completed[0];
|
|
275
|
+
if (event.logIndex >= end.logIndex || !sameAddress(event.args.receiver, p.recipient) || !sameAddress(event.args.receivingAssetId, d.token)) return unknown;
|
|
276
|
+
const swaps = (0, import_viem5.parseEventLogs)({ 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));
|
|
277
|
+
if (swaps.length !== 1) return unknown;
|
|
278
|
+
const swap = swaps[0];
|
|
279
|
+
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;
|
|
280
|
+
const amount = paid2(p.finalToken, pins.executor, event.logIndex);
|
|
281
|
+
if (amount < p.minimum || amount !== swap.args.toAmount) return unknown;
|
|
282
|
+
return { state: "completed", token: p.finalToken, amount, transactionHash: receipt.transactionHash };
|
|
283
|
+
} catch {
|
|
284
|
+
return unknown;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
//# sourceMappingURL=compose.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/compose.ts","../src/rpc.ts","../src/abi.ts","../src/tracking.ts","../src/amounts.ts","../src/quote.ts"],"sourcesContent":["import {decodeAbiParameters, encodeAbiParameters, encodePacked, keccak256, pad, parseAbi, parseAbiParameters, parseEventLogs, zeroAddress, type Address, type Hex, type TransactionReceipt} from \"viem\";\nimport type {StargateIntent} from \"./intent.js\";\nimport {assertStargate, nonzeroAddress, sameAddress} from \"./rpc.js\";\nimport {checkStargateReceipt, stargateComposedTaxiProof, stargateTaxiPayout, type StargateTaxiProof} from \"./tracking.js\";\n\nexport const COMPOSE_ABI = parseAbi([\n \"function composeQueue(address from, address to, bytes32 guid, uint16 index) view returns (bytes32)\",\n \"function lzCompose(address from, address to, bytes32 guid, uint16 index, bytes message, bytes extraData) payable\",\n \"event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message)\",\n \"event ComposeDelivered(address from, address to, bytes32 guid, uint16 index)\",\n]);\nexport const LIFI_COMPOSE_ABI = parseAbi([\n \"function executor() view returns (address)\",\n \"function endpointV2() view returns (address)\",\n \"function tokenMessaging() view returns (address)\",\n \"function recoverGas() view returns (uint256)\",\n \"event LiFiTransferCompleted(bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp)\",\n \"event LiFiTransferRecovered(bytes32 indexed transactionId, address receivingAssetId, address receiver, uint256 amount, uint256 timestamp)\",\n \"event AssetSwapped(bytes32 transactionId, address dex, address fromAssetId, address toAssetId, uint256 fromAmount, uint256 toAmount, uint256 timestamp)\",\n \"event Transfer(address indexed from, address indexed to, uint256 value)\",\n]);\nexport const LIFI_COMPOSE_PAYLOAD = parseAbiParameters(\"bytes32 transactionId, (address callTo, address approveTo, address sendingAssetId, address receivingAssetId, uint256 fromAmount, bytes callData, bool requiresDeposit)[] swaps, address receiver\");\n\n/** Observational pins only; these addresses are NOT a call/spender allowlist. */\nexport const LIFI_ETHEREUM_COMPOSER = Object.freeze({\n chain: \"eip155:1\",\n receiver: \"0xB539B40793171211DCA8834da044fC14bCe64BDC\" as Address,\n executor: \"0xd9B2Da9C45b118e4e93A004FB1452bCDB6cC0E88\" as Address,\n receiverCodeHash: \"0x535b6e74e5bbb38e9a469de60ff2587cf498b92a99be01f34d20c37a77e4cea2\" as Hex,\n executorCodeHash: \"0xf937f13890d789171f0bcf3c558a64869105000b6771dc182ddc165bde92ddfe\" as Hex,\n});\n\nexport interface StargateComposeExpectation {\n /** Bridge recipient must be the pinned composer; sender is the actual OFTSent actor. */\n bridge: StargateIntent;\n composeFrom: Address;\n composeMsg: Hex;\n recipient: Address;\n finalToken: Address;\n minimum: bigint;\n}\nexport interface LifiStargateComposeProof {\n readonly bridge: StargateTaxiProof;\n readonly transactionId: Hex;\n readonly message: Hex;\n readonly messageHash: Hex;\n readonly recipient: Address;\n readonly finalToken: Address;\n readonly minimum: bigint;\n readonly swap: {readonly callTo: Address; readonly fromAmount: bigint};\n /** True only for routes this SDK encoded and checked before signing (`compose-route`); historical proofs are evidence only. */\n readonly executionSupported: boolean;\n}\n\nexport {stargateComposeOptions} from \"./quote.js\";\n\n/** Zero is absent; ONE is consumed (unlike cleared inboundPayloadHash for lzReceive). */\nexport function stargateComposeQueueState(messageHash: Hex, queue: Hex): \"absent\" | \"consumed\" | \"pending\" | \"mismatch\" {\n assertStargate(/^0x[0-9a-f]{64}$/i.test(messageHash) && /^0x[0-9a-f]{64}$/i.test(queue), \"invalid compose commitment\");\n if (BigInt(queue) === 0n) return \"absent\";\n if (BigInt(queue) === 1n) return \"consumed\";\n return sameAddress(messageHash, queue) ? \"pending\" : \"mismatch\";\n}\n\n/**\n * Read-only single-swap LI.FI adapter. Receipts/code must first be obtained from\n * canonical finalized blocks on their respective chains. Consistency is checked\n * here; untrusted JSON supplied by a remote server is not independent RPC evidence.\n */\nexport function proveLifiStargateCompose(expected: StargateComposeExpectation, source: TransactionReceipt, delivery: TransactionReceipt, code: {receiver: Hex; executor: Hex}): LifiStargateComposeProof {\n const pins = LIFI_ETHEREUM_COMPOSER, i = expected.bridge;\n assertStargate(i.destination.chain === pins.chain && sameAddress(i.recipient, pins.receiver), \"unreviewed composer\");\n assertStargate(keccak256(code.receiver) === pins.receiverCodeHash && keccak256(code.executor) === pins.executorCodeHash, \"composer bytecode changed\");\n 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\");\n for (const receipt of [source, delivery]) checkStargateReceipt(receipt, receipt.transactionHash, receipt.blockHash);\n const bridge = stargateComposedTaxiProof(i, source, expected.composeFrom, expected.composeMsg);\n const [transactionId, swaps, recipient] = decodeAbiParameters(LIFI_COMPOSE_PAYLOAD, expected.composeMsg);\n assertStargate(encodeAbiParameters(LIFI_COMPOSE_PAYLOAD, [transactionId, swaps, recipient]).toLowerCase() === expected.composeMsg.toLowerCase(), \"noncanonical compose message\");\n assertStargate(BigInt(transactionId) !== 0n && swaps.length === 1 && sameAddress(recipient, expected.recipient), \"unsupported compose action or recipient\");\n const swap = swaps[0]!;\n 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\");\n assertStargate(stargateTaxiPayout(bridge, delivery), \"bridge has not paid the composer\");\n const message = encodePacked([\"uint64\", \"uint32\", \"uint256\", \"bytes32\", \"bytes\"], [bridge.nonce, i.source.eid, bridge.amount, pad(expected.composeFrom, {size: 32}), expected.composeMsg]);\n const sent = parseEventLogs({abi: COMPOSE_ABI, eventName: \"ComposeSent\", logs: delivery.logs.filter((l) => sameAddress(l.address, i.destination.endpoint)), strict: true})\n .filter((l) => sameAddress(l.args.guid, bridge.guid));\n 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\");\n const intent = Object.freeze({...i, source: Object.freeze({...i.source}), destination: Object.freeze({...i.destination})});\n return Object.freeze({bridge: Object.freeze({...bridge, intent}), transactionId, message, messageHash: keccak256(message), recipient, finalToken: expected.finalToken, minimum: expected.minimum, swap: Object.freeze({callTo: swap.callTo, fromAmount: swap.fromAmount}), executionSupported: false as boolean});\n}\n\nexport type StargateComposeOutcome =\n | {state: \"unverified\"}\n | {state: \"completed\"; token: Address; amount: bigint; transactionHash: Hex}\n | {state: \"intermediate-refunded\"; token: Address; amount: bigint; transactionHash: Hex};\n\n/** Final token payment is separate from successful Endpoint compose delivery. */\nexport function lifiStargateComposeOutcome(p: LifiStargateComposeProof, receipt: TransactionReceipt): StargateComposeOutcome {\n const unknown = {state: \"unverified\"} as const;\n try {\n if (receipt.status !== \"success\") return unknown;\n checkStargateReceipt(receipt, receipt.transactionHash, receipt.blockHash);\n const pins = LIFI_ETHEREUM_COMPOSER, d = p.bridge.intent.destination;\n const delivered = parseEventLogs({abi: COMPOSE_ABI, eventName: \"ComposeDelivered\", logs: receipt.logs.filter((l) => sameAddress(l.address, d.endpoint)), strict: true});\n // Refuse batched attribution until every compose invocation can be delimited.\n if (delivered.length !== 1) return unknown;\n const end = delivered[0]!;\n 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;\n const recovered = parseEventLogs({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));\n const completed = parseEventLogs({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));\n function paid(token: Address, from: Address, before: number): bigint {\n const transfers = parseEventLogs({abi: LIFI_COMPOSE_ABI, eventName: \"Transfer\", logs: receipt.logs.filter((l) => sameAddress(l.address, token) && l.logIndex! < before), strict: true});\n let net = 0n;\n for (const {args} of transfers) {\n if (sameAddress(args.to, p.recipient) && sameAddress(args.from, from)) net += args.value;\n if (sameAddress(args.from, p.recipient)) net -= args.value;\n }\n return net;\n }\n if (recovered.length === 1 && completed.length === 0) {\n const event = recovered[0]!;\n if (event.logIndex! >= end.logIndex! || !sameAddress(event.args.receivingAssetId, d.token) || !sameAddress(event.args.receiver, p.recipient) || event.args.amount !== p.bridge.amount) return unknown;\n // Native payout is proven by the pinned receiver's event after safeTransferETH.\n if (d.token !== zeroAddress && paid(d.token, pins.receiver, event.logIndex!) !== p.bridge.amount) return unknown;\n return {state: \"intermediate-refunded\", token: d.token, amount: p.bridge.amount, transactionHash: receipt.transactionHash};\n }\n if (completed.length !== 1 || recovered.length !== 0 || p.finalToken === zeroAddress) return unknown;\n const event = completed[0]!;\n if (event.logIndex! >= end.logIndex! || !sameAddress(event.args.receiver, p.recipient) || !sameAddress(event.args.receivingAssetId, d.token)) return unknown;\n const swaps = parseEventLogs({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));\n if (swaps.length !== 1) return unknown;\n const swap = swaps[0]!;\n 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;\n // Executor's Completed event names the INPUT asset and may report a gross balance.\n // Count actual final-token transfers instead of trusting those two fields.\n const amount = paid(p.finalToken, pins.executor, event.logIndex!);\n if (amount < p.minimum || amount !== swap.args.toAmount) return unknown;\n return {state: \"completed\", token: p.finalToken, amount, transactionHash: receipt.transactionHash};\n } catch { return unknown; }\n}\n","import {createPublicClient, fallback, http, pad, parseAbi, type Address, type Hex, type PublicClient} from \"viem\";\nimport {STARGATE_ABI, TOKEN_MESSAGING_ABI} from \"./abi.js\";\nimport type {StargateDeployment} from \"./registry.js\";\n\nexport class StargateReadError extends Error {\n constructor(message: string) { super(`stargate: ${message}`); this.name = \"StargateReadError\"; }\n}\n\nexport interface StargateRpcConfig {\n /** Both source and destination RPCs are required. URLs are never included in errors. */\n rpcUrls: Readonly<Record<string, string | readonly string[]>>;\n fetchImpl?: typeof fetch;\n}\nexport interface StargateBlock {readonly number: bigint; readonly hash: Hex; readonly timestamp: bigint}\nexport interface StargateRpc {\n has(chain: string): boolean;\n client(chain: string, signal?: AbortSignal): PublicClient;\n snapshot(client: PublicClient, chainId: number): Promise<StargateBlock>;\n verify(client: PublicClient, deployment: StargateDeployment, peer: StargateDeployment, block: StargateBlock): Promise<void>;\n unchanged(client: PublicClient, block: StargateBlock): Promise<void>;\n}\nconst auxiliaryAbi = parseAbi([\"function decimals() view returns (uint8)\", \"function eid() view returns (uint32)\"]);\nexport const sameAddress = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase();\nexport function assertStargate(condition: unknown, message: string): asserts condition {\n if (!condition) throw new StargateReadError(message);\n}\nexport function assertNotAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw new StargateReadError(\"request cancelled\");\n}\n\n/** No mutable deployment/peer/paused-state cache: every quote verifies a fresh snapshot. */\nexport function stargateRpc(config: StargateRpcConfig): StargateRpc {\n const urls = new Map(Object.entries(config.rpcUrls).map(([chain, value]) => {\n const list = typeof value === \"string\" ? [value] : [...value];\n assertStargate(list.length && list.every((url) => /^https?:\\/\\//.test(url)), \"invalid RPC configuration\");\n return [chain, list] as const;\n }));\n function client(chain: string, signal?: AbortSignal): PublicClient {\n const list = urls.get(chain);\n assertStargate(list, `no RPC configured for ${chain}`);\n assertNotAborted(signal);\n const transport = (url: string) => http(url, {timeout: 12_000, retryCount: 0, ...(config.fetchImpl ? {fetchFn: config.fetchImpl} : {}), ...(signal ? {fetchOptions: {signal}} : {})});\n return createPublicClient({transport: list.length === 1 ? transport(list[0]!) : fallback(list.map(transport), {retryCount: 0}), ccipRead: false});\n }\n type Client = ReturnType<typeof client>;\n async function snapshot(c: Client, chainId: number): Promise<StargateBlock> {\n const [actual, block] = await Promise.all([c.getChainId(), c.getBlock({blockTag: \"latest\"})]);\n assertStargate(actual === chainId, \"RPC chain id mismatch\");\n assertStargate(block.hash && block.number !== null, \"RPC returned an unmined block\");\n // Stale nodes must not turn old fees/credits into a new, apparently fresh quote.\n const now = BigInt(Math.floor(Date.now() / 1000));\n assertStargate(block.timestamp >= now - 300n && block.timestamp <= now + 60n, \"RPC block is stale or in the future\");\n return Object.freeze({number: block.number, hash: block.hash, timestamp: block.timestamp});\n }\n async function verify(c: Client, d: StargateDeployment, peer: StargateDeployment, block: StargateBlock): Promise<void> {\n const at = {blockNumber: block.number};\n const pool = {address: d.address, abi: STARGATE_ABI, ...at};\n const messaging = {address: d.tokenMessaging, abi: TOKEN_MESSAGING_ABI, ...at};\n const [token, shared, approval, eid, endpoint, status, kind, roles, assetId, implementation, messagingEndpoint, remotePeer, endpointEid, decimals] = await Promise.all([\n c.readContract({...pool, functionName: \"token\"}),\n c.readContract({...pool, functionName: \"sharedDecimals\"}),\n c.readContract({...pool, functionName: \"approvalRequired\"}),\n c.readContract({...pool, functionName: \"localEid\"}),\n c.readContract({...pool, functionName: \"endpoint\"}),\n c.readContract({...pool, functionName: \"status\"}),\n c.readContract({...pool, functionName: \"stargateType\"}),\n c.readContract({...pool, functionName: \"getAddressConfig\"}),\n c.readContract({...messaging, functionName: \"assetIds\", args: [d.address]}),\n c.readContract({...messaging, functionName: \"stargateImpls\", args: [d.assetId]}),\n c.readContract({...messaging, functionName: \"endpoint\"}),\n c.readContract({...messaging, functionName: \"peers\", args: [peer.eid]}),\n c.readContract({address: d.endpoint, abi: auxiliaryAbi, functionName: \"eid\", ...at}),\n d.kind === \"native\" ? Promise.resolve(d.localDecimals) : c.readContract({address: d.token, abi: auxiliaryAbi, functionName: \"decimals\", ...at}),\n ]);\n assertStargate(sameAddress(token, d.token) && shared === d.sharedDecimals && decimals === d.localDecimals && approval === d.approvalRequired && eid === d.eid && endpointEid === d.eid && sameAddress(endpoint, d.endpoint) && sameAddress(messagingEndpoint, d.endpoint) && sameAddress(roles.tokenMessaging, d.tokenMessaging) && assetId === d.assetId && sameAddress(implementation, d.address) && kind === (d.kind === \"oft\" ? 1 : 0), `deployment identity changed on ${d.chain}`);\n assertStargate(status === 1, `deployment is not active on ${d.chain}`);\n assertStargate(sameAddress(remotePeer, pad(peer.tokenMessaging, {size: 32})), `messaging peer mismatch on ${d.chain}`);\n }\n async function unchanged(c: Client, block: StargateBlock): Promise<void> {\n assertStargate((await c.getBlock({blockNumber: block.number})).hash === block.hash, \"block changed during quote\");\n }\n return {has: (chain: string) => urls.has(chain), client, snapshot, verify, unchanged};\n}\n\n/** Never propagate viem errors: they can contain credential-bearing URLs and request bodies. */\nexport function safeReadError(error: unknown): StargateReadError {\n return error instanceof StargateReadError ? error : new StargateReadError(\"RPC read, quote or decoding failed\");\n}\n\nexport function nonzeroAddress(value: string): value is Address {\n return /^0x[0-9a-fA-F]{40}$/.test(value) && !/^0x0{40}$/.test(value);\n}\n","import {parseAbi} from \"viem\";\n\n// LayerZero-v2 592625b9e5967643853476445ffe0e777360b906: historical Executor/IExecutor.\nexport const EXECUTOR_ABI = parseAbi([\n \"struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }\",\n \"struct NativeDropParams { address receiver; uint256 amount; }\",\n \"function endpoint() view returns (address)\",\n \"function localEid() view returns (uint32)\",\n \"event NativeDropApplied(Origin origin, uint32 dstEid, address oapp, NativeDropParams[] params, bool[] success)\",\n]);\n\nexport const ENDPOINT_ABI = parseAbi([\n \"struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }\",\n \"function inboundPayloadHash(address receiver, uint32 srcEid, bytes32 sender, uint64 nonce) view returns (bytes32)\",\n \"function lzReceive(Origin origin, address receiver, bytes32 guid, bytes message, bytes extraData) payable\",\n \"event PacketSent(bytes encodedPayload, bytes options, address sendLibrary)\",\n \"event PacketDelivered(Origin origin, address receiver)\",\n]);\n\n// SDK-322: checked against pinned upstream deployment ABI by abi.test.ts.\n// Provenance: tests/fixtures/upstream.json. This is an interface, not a deployment allowlist.\nexport const STARGATE_ABI = parseAbi([\n \"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; }\",\n \"struct OFTLimit { uint256 minAmountLD; uint256 maxAmountLD; }\",\n \"struct OFTFeeDetail { int256 feeAmountLD; string description; }\",\n \"struct OFTReceipt { uint256 amountSentLD; uint256 amountReceivedLD; }\",\n \"struct Ticket { uint72 ticketId; bytes passengerBytes; }\",\n \"struct AddressConfig { address feeLib; address planner; address treasurer; address tokenMessaging; address creditMessaging; address lzToken; }\",\n \"function token() view returns (address)\",\n \"function sharedDecimals() view returns (uint8)\",\n \"function approvalRequired() pure returns (bool)\",\n \"function localEid() view returns (uint32)\",\n \"function endpoint() view returns (address)\",\n \"function status() view returns (uint8)\",\n \"function stargateType() pure returns (uint8)\",\n \"function paths(uint32 eid) view returns (uint64 credit)\",\n \"function getAddressConfig() view returns (AddressConfig)\",\n \"function quoteOFT(SendParam s) view returns (OFTLimit limit, OFTFeeDetail[] oftFeeDetails, OFTReceipt receipt)\",\n \"function quoteSend(SendParam s, bool payInLzToken) view returns (MessagingFee fee)\",\n \"function send(SendParam s, MessagingFee fee, address refundAddress) payable returns (MessagingReceipt msgReceipt, OFTReceipt oftReceipt)\",\n \"function sendToken(SendParam s, MessagingFee fee, address refundAddress) payable returns (MessagingReceipt msgReceipt, OFTReceipt oftReceipt, Ticket ticket)\",\n \"function unreceivedTokens(bytes32 guid, uint8 index) view returns (bytes32)\",\n \"function retryReceiveToken(bytes32 guid, uint8 index, uint32 srcEid, address receiver, uint256 amountLD, bytes composeMsg)\",\n \"event OFTSent(bytes32 indexed guid, uint32 dstEid, address indexed fromAddress, uint256 amountSentLD, uint256 amountReceivedLD)\",\n \"event OFTReceived(bytes32 indexed guid, uint32 srcEid, address indexed toAddress, uint256 amountReceivedLD)\",\n \"event UnreceivedTokenCached(bytes32 guid, uint8 index, uint32 srcEid, address receiver, uint256 amountLD, bytes composeMsg)\",\n]);\n\nexport const TOKEN_MESSAGING_ABI = parseAbi([\n \"error Bus_InvalidFare(bool nativeDrop)\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; }\",\n \"function assetIds(address stargateImpl) view returns (uint16)\",\n \"function stargateImpls(uint16 assetId) view returns (address)\",\n \"function peers(uint32 eid) view returns (bytes32)\",\n \"function endpoint() view returns (address)\",\n \"function nativeDropAmounts(uint32 eid) view returns (uint128)\",\n \"function queueCapacity() view returns (uint16)\",\n \"function busQueues(uint32 eid) view returns (uint8 maxNumPassengers, uint80 busFare, uint80 busAndNativeDropFare, uint16 qLength, uint72 nextTicketId)\",\n \"function getPassengerHash(uint32 eid, uint16 index) view returns (bytes32)\",\n \"function quoteDriveBus(uint32 dstEid, bytes passengers) view returns (MessagingFee fee)\",\n \"function driveBus(uint32 dstEid, bytes passengers) payable returns (MessagingReceipt receipt)\",\n \"event BusRode(uint32 dstEid, uint72 ticketId, uint80 fare, bytes passenger)\",\n \"event BusDriven(uint32 dstEid, uint72 startTicketId, uint8 numPassengers, bytes32 guid)\",\n \"event NativeDropApplied(address receiver, uint128 amount)\",\n \"event NativeDropFailed(address receiver, uint128 amount)\",\n]);\n","import {encodeFunctionData, encodePacked, keccak256, pad, parseAbi, parseEventLogs, slice, type Hex, type PublicClient, type TransactionReceipt} from \"viem\";\nimport {timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {IntentRef, IntentStatus, RecoveryQuote} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {ENDPOINT_ABI, STARGATE_ABI, TOKEN_MESSAGING_ABI} from \"./abi.js\";\nimport {conversionRate, destinationAmount, splitSourceAmount} from \"./amounts.js\";\nimport {stargateRegistry} from \"./deployments.js\";\nimport {parseStargateIntent, type StargateIntent} from \"./intent.js\";\nimport type {StargateRegistry} from \"./registry.js\";\nimport {assertStargate, nonzeroAddress, sameAddress, stargateRpc, type StargateRpcConfig} from \"./rpc.js\";\nimport {busDriveData, busPassengerPrefix, stargateBusNativeDrop, stargateBusPayout, stargateBusProof, stargateBusTicket, type StargateBusProof, type StargateBusTicket} from \"./bus.js\";\nimport {STARGATE_TAXI_EXECUTORS, stargateTaxiNativeDrop} from \"./native-drop.js\";\nimport {COMPOSE_ABI, LIFI_ETHEREUM_COMPOSER, lifiStargateComposeOutcome, stargateComposeQueueState, type LifiStargateComposeProof} from \"./compose.js\";\nimport {checkStargateComposer, isStargateComposeIntent, parseStargateComposeIntent, stargateComposeMessage, stargateComposeProof, stargateComposeRetryGas, type StargateComposeIntent} from \"./compose-route.js\";\n\nexport interface StargateTrackingConfig extends StargateRpcConfig {\n registry?: StargateRegistry;\n scanUrl?: string;\n /** Default: RPC finalized block. Explicit depths are an app finality policy, not universal finality. */\n confirmations?: Readonly<Record<string, number>>;\n /** Seconds after the compose delivery before a manual lzCompose retry is offered. Default 600. */\n composeRetryAfterS?: number;\n /** Explicit reviewed executor pins for Taxi native-drop evidence. Default: verified Base executor only. */\n taxiExecutors?: Readonly<Record<string, readonly Hex[]>>;\n /** Bounded default log discovery. Older queues can use the indexer callbacks below. */\n busLogPageSize?: number;\n busLogPages?: number;\n /** Untrusted discovery hints: every candidate is authenticated against a source receipt/packet. */\n findBusDrive?: (ticket: Readonly<StargateBusTicket>) => Promise<readonly Hex[]>;\n /** Untrusted queue bytes: the current on-chain passenger hash chain must match. */\n queuedBusPassengers?: (query: {chain: string; tokenMessaging: Hex; dstEid: number; firstTicketId: bigint; count: number; blockNumber: bigint}) => Promise<readonly {ticketId: bigint; passenger: Hex}[]>;\n}\nconst endpointAbi = parseAbi([\"event PacketSent(bytes encodedPayload, bytes options, address sendLibrary)\"]);\nconst hash = (v: unknown): v is Hex => typeof v === \"string\" && /^0x[0-9a-fA-F]{64}$/.test(v);\nconst ZERO_HASH = `0x${\"00\".repeat(32)}`;\nclass SourceReverted extends Error {}\nexport interface StargateTaxiProof {\n intent: StargateIntent;\n guid: Hex;\n amount: bigint;\n packet: Hex;\n message: Hex;\n nonce: bigint;\n sourceHash: Hex;\n}\ntype TransferProof = StargateTaxiProof | StargateBusProof;\nconst seatOf = (p: TransferProof) => \"seat\" in p ? p.seat : 0;\n\n/** Source pool + endpoint packet, independent of Scan. Plain Taxi only. */\nexport function stargateTaxiProof(i: StargateIntent, receipt: TransactionReceipt): StargateTaxiProof {\n return taxiProof(i, receipt);\n}\n\n/** Read-only packet evidence. This does not approve the destination call for execution. */\nexport function stargateComposedTaxiProof(i: StargateIntent, receipt: TransactionReceipt, composeFrom: Hex, composeMsg: Hex): StargateTaxiProof {\n assertStargate(nonzeroAddress(composeFrom) && /^0x(?:[0-9a-f]{2}){1,16384}$/i.test(composeMsg), \"invalid expected compose payload\");\n return taxiProof(i, receipt, `${pad(composeFrom, {size: 32})}${composeMsg.slice(2)}` as Hex);\n}\n\nfunction taxiProof(i: StargateIntent, receipt: TransactionReceipt, expectedCompose?: Hex): StargateTaxiProof {\n assertStargate(i.mode === \"taxi\" && receipt.status === \"success\", \"not a successful Taxi source receipt\");\n const sent = parseEventLogs({abi: STARGATE_ABI, eventName: \"OFTSent\", logs: receipt.logs.filter((l) => sameAddress(l.address, i.source.address)), strict: true})\n .filter((l) => sameAddress(l.args.fromAddress, i.sender) && l.args.dstEid === i.destination.eid);\n assertStargate(sent.length === 1, \"missing or ambiguous source transfer\");\n const event = sent[0]!.args;\n assertStargate(event.guid !== ZERO_HASH && event.amountSentLD === splitSourceAmount(i.amount, i.source.localDecimals, i.source.sharedDecimals).sentLD, \"source amount mismatch\");\n const amount = destinationAmount(event.amountReceivedLD, i.source.localDecimals, i.destination.localDecimals, i.source.sharedDecimals);\n assertStargate(amount >= i.minimum, \"source output is below the intent minimum\");\n const packets = parseEventLogs({abi: endpointAbi, eventName: \"PacketSent\", logs: receipt.logs.filter((l) => sameAddress(l.address, i.source.endpoint)), strict: true})\n .filter((l) => l.args.encodedPayload.length >= 228 && sameAddress(slice(l.args.encodedPayload, 81, 113), event.guid));\n assertStargate(packets.length === 1, \"missing or ambiguous endpoint packet\");\n const packet = packets[0]!.args.encodedPayload;\n 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\");\n 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\");\n const message = slice(packet, 113);\n assertStargate(expectedCompose === undefined ? /^0x01[0-9a-f]{84}$/i.test(message) : /^0x01[0-9a-f]+$/i.test(message) && sameAddress(slice(message, 43), expectedCompose), \"unsupported Taxi compose payload\");\n 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\");\n return {intent: i, guid: event.guid, amount, packet, message, nonce: BigInt(slice(packet, 1, 9)), sourceHash: receipt.transactionHash};\n}\n\nexport function stargateTaxiPayout(proof: StargateTaxiProof, receipt: TransactionReceipt): boolean {\n if (receipt.status !== \"success\") return false;\n const i = proof.intent;\n const received = parseEventLogs({abi: STARGATE_ABI, eventName: \"OFTReceived\", logs: receipt.logs.filter((l) => sameAddress(l.address, i.destination.address)), strict: true})\n .filter((l) => sameAddress(l.args.guid, proof.guid));\n return received.length === 1 && received[0]!.args.srcEid === i.source.eid && sameAddress(received[0]!.args.toAddress, i.recipient) && received[0]!.args.amountReceivedLD === proof.amount;\n}\n\n/** Receipt/block/log identity checks are separate from the provider's event semantics. */\nexport function checkStargateReceipt(receipt: TransactionReceipt, expectedHash: Hex, blockHash: Hex): void {\n assertStargate(sameAddress(receipt.transactionHash, expectedHash) && sameAddress(receipt.blockHash, blockHash), \"receipt block/hash mismatch\");\n 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\");\n 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\");\n}\n\nexport function createStargateTracker(config: StargateTrackingConfig) {\n const registry = config.registry ?? stargateRegistry;\n const rpc = stargateRpc(config);\n const confirmations = {...config.confirmations};\n const taxiExecutors = Object.fromEntries(Object.entries(config.taxiExecutors ?? STARGATE_TAXI_EXECUTORS).map(([chain, addresses]) => {\n assertStargate(/^eip155:[1-9][0-9]*$/.test(chain) && addresses.length <= 32 && addresses.every(nonzeroAddress), \"invalid Taxi executor pins\");\n return [chain, [...addresses]];\n }));\n assertStargate(Object.values(confirmations).every((n) => Number.isSafeInteger(n) && n >= 1 && n <= 100_000), \"invalid finality policy\");\n const scan = (config.scanUrl ?? \"https://scan.layerzero-api.com\").replace(/\\/+$/, \"\");\n assertStargate(/^https?:\\/\\//.test(scan), \"invalid Scan URL\");\n const fetchImpl = config.fetchImpl ?? fetch;\n // The LayerZero executor normally runs lzCompose right after delivery; racing it only wastes the user's gas.\n const composeRetryAfter = config.composeRetryAfterS ?? 600;\n assertStargate(Number.isSafeInteger(composeRetryAfter) && composeRetryAfter >= 0 && composeRetryAfter <= 7 * 86_400, \"invalid compose retry delay\");\n const pageSize = config.busLogPageSize ?? 2000, pages = config.busLogPages ?? 8;\n const findDrive = config.findBusDrive, queuedPassengers = config.queuedBusPassengers;\n assertStargate(Number.isSafeInteger(pageSize) && pageSize >= 1 && pageSize <= 10_000 && Number.isSafeInteger(pages) && pages >= 1 && pages <= 32, \"invalid Bus log discovery bounds\");\n\n async function receipt(c: PublicClient, chain: string, chainId: number, txHash: Hex): Promise<TransactionReceipt | null> {\n const [id, r] = await Promise.all([c.getChainId(), c.getTransactionReceipt({hash: txHash})]);\n assertStargate(id === chainId, \"receipt RPC chain mismatch\");\n const depth = confirmations[chain];\n const [block, head] = await Promise.all([c.getBlock({blockNumber: r.blockNumber}), c.getBlock({blockTag: depth === undefined ? \"finalized\" : \"latest\"})]);\n assertStargate(block.hash && head.hash && head.number !== null, \"missing receipt finality evidence\");\n checkStargateReceipt(r, txHash, block.hash);\n if (head.number < r.blockNumber + BigInt((depth ?? 1) - 1)) return null;\n return r;\n }\n async function busProof(ticket: StargateBusTicket, ref: IntentRef): Promise<StargateBusProof | null> {\n const i = ticket.intent, c = rpc.client(i.source.chain);\n const candidates: Hex[] = [];\n if (ref.recoveryChain === i.source.chain && hash(ref.recoveryTxHash)) candidates.push(ref.recoveryTxHash);\n if (findDrive) candidates.push(...(await findDrive(Object.freeze({...ticket, intent: Object.freeze({...ticket.intent})}))).filter(hash).slice(0, 32));\n const tryCandidates = async () => {\n for (const txHash of [...new Set(candidates.splice(0))]) {\n try {\n const r = await receipt(c, i.source.chain, i.source.chainId, txHash);\n if (r) return stargateBusProof(ticket, r);\n } catch { /* Hints never substitute for a confirmed drive packet. */ }\n }\n return null;\n };\n const hinted = await tryCandidates();\n if (hinted) return hinted;\n const head = await c.getBlockNumber();\n for (let page = 0; page < pages; page++) {\n const fromBlock = ticket.sourceBlock + BigInt(page * pageSize);\n if (fromBlock > head) break;\n const end = fromBlock + BigInt(pageSize - 1), toBlock = end < head ? end : head;\n const logs = await c.getContractEvents({address: i.source.tokenMessaging, abi: TOKEN_MESSAGING_ABI, eventName: \"BusDriven\", fromBlock, toBlock, strict: true});\n 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);\n const found = await tryCandidates();\n if (found) return found;\n }\n return null;\n }\n async function evidence(ref: IntentRef): Promise<{proof: TransferProof | null; ticket?: StargateBusTicket; compose?: StargateComposeIntent} | null> {\n const compose = isStargateComposeIntent(ref.intentId) ? parseStargateComposeIntent(ref.intentId, registry) : undefined;\n const i = compose ? compose.bridge : parseStargateIntent(ref.intentId, registry);\n if (!hash(ref.sourceTxHash)) return null;\n const r = await receipt(rpc.client(i.source.chain), i.source.chain, i.source.chainId, ref.sourceTxHash);\n if (r?.status === \"reverted\" && r.from && r.to && sameAddress(r.from, i.sender) && sameAddress(r.to, i.source.address)) throw new SourceReverted();\n if (!r) return null;\n if (compose) return {proof: stargateComposedTaxiProof(i, r, i.sender, stargateComposeMessage(compose)), compose};\n if (i.mode === \"taxi\") return {proof: stargateTaxiProof(i, r)};\n const ticket = stargateBusTicket(i, r);\n return {ticket, proof: await busProof(ticket, ref)};\n }\n async function cached(p: TransferProof): Promise<boolean> {\n const i = p.intent;\n const c = rpc.client(i.destination.chain);\n assertStargate(await c.getChainId() === i.destination.chainId, \"recovery RPC chain mismatch\");\n const actual = await c.readContract({address: i.destination.address, abi: STARGATE_ABI, functionName: \"unreceivedTokens\", args: [p.guid, seatOf(p)]});\n const expected = keccak256(encodePacked([\"uint32\", \"address\", \"uint256\", \"bytes\"], [i.source.eid, i.recipient, p.amount, \"0x\"]));\n return actual === expected;\n }\n async function retryableMessage(p: TransferProof): Promise<boolean> {\n const i = p.intent, c = rpc.client(i.destination.chain);\n assertStargate(await c.getChainId() === i.destination.chainId, \"recovery RPC chain mismatch\");\n 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]});\n return actual === keccak256(encodePacked([\"bytes32\", \"bytes\"], [p.guid, p.message]));\n }\n async function destinationHashes(ref: IntentRef, p: TransferProof): Promise<Hex[]> {\n const provided = [ref.destTxHash, ref.recoveryChain === p.intent.destination.chain ? ref.recoveryTxHash : undefined].filter(hash);\n try {\n const response = await fetchImpl(`${scan}/v1/messages/guid/${p.guid}`, {signal: timeoutSignal(12_000), headers: {accept: \"application/json\"}});\n if (!response.ok) return provided;\n const json: unknown = await response.json();\n const data = (json as {data?: unknown})?.data;\n if (!Array.isArray(data)) return provided;\n for (const item of data.slice(0, 32)) {\n const m = item as {guid?: string; destination?: {tx?: {txHash?: string}; nativeDrop?: {tx?: {txHash?: string}}; lzCompose?: {txs?: unknown}}};\n if (typeof m.guid === \"string\" && sameAddress(m.guid, p.guid)) {\n if (hash(m.destination?.tx?.txHash)) provided.push(m.destination.tx.txHash);\n if (hash(m.destination?.nativeDrop?.tx?.txHash)) provided.push(m.destination.nativeDrop.tx.txHash);\n const composed = m.destination?.lzCompose?.txs;\n if (Array.isArray(composed)) for (const tx of composed.slice(0, 8)) if (hash((tx as {txHash?: unknown})?.txHash)) provided.push((tx as {txHash: Hex}).txHash);\n }\n }\n } catch { /* Scan is discovery only; caller-supplied hashes still need receipt verification. */ }\n return [...new Set(provided)];\n }\n /**\n * Compose state from finalized receipts and the Endpoint queue. Scan names candidate\n * transactions only; the queue commitment decides whether a retry is possible at all.\n */\n type ComposeState = {outcome: \"completed\" | \"intermediate-refunded\"; txHash: Hex; lifi: LifiStargateComposeProof} | {queue: ReturnType<typeof stargateComposeQueueState>; retryable: boolean; delivered: Hex | undefined; lifi: LifiStargateComposeProof};\n async function composeState(ref: IntentRef, c: StargateComposeIntent, p: StargateTaxiProof): Promise<ComposeState> {\n const d = p.intent.destination, client = rpc.client(d.chain), lifi = stargateComposeProof(c, p);\n let deliveredAt: bigint | undefined, delivered: Hex | undefined;\n for (const txHash of await destinationHashes(ref, p)) {\n try {\n const r = await receipt(client, d.chain, d.chainId, txHash);\n if (!r) continue;\n if (stargateTaxiPayout(p, r)) { delivered = txHash; deliveredAt = (await client.getBlock({blockNumber: r.blockNumber})).timestamp; }\n const outcome = lifiStargateComposeOutcome(lifi, r);\n if (outcome.state !== \"unverified\") return {outcome: outcome.state, txHash, lifi};\n } catch { /* A bad or unindexed discovery candidate proves nothing. */ }\n }\n assertStargate(await client.getChainId() === d.chainId, \"compose RPC chain mismatch\");\n 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]}));\n const stale = deliveredAt !== undefined && deliveredAt + BigInt(composeRetryAfter) <= BigInt(Math.floor(Date.now() / 1000));\n return {queue, retryable: queue === \"pending\" && stale, delivered, lifi};\n }\n async function trackIntent(ref: IntentRef): Promise<IntentStatus> {\n let deposited = false;\n try {\n const e = await evidence(ref);\n if (!e) return {state: \"pending\"};\n deposited = true;\n const p = e.proof;\n if (!p) return {state: \"pending\", depositReceived: true};\n if (e.compose && !(\"seat\" in p)) {\n const s = await composeState(ref, e.compose, p);\n // A receiver fallback pays the bridged asset instead of the requested output.\n if (\"outcome\" in s) return {state: s.outcome === \"completed\" ? \"completed\" : \"partial\", depositReceived: true, destTxHash: s.txHash};\n if (s.retryable) return {state: \"action-required\", depositReceived: true, ...(s.delivered ? {destTxHash: s.delivered} : {})};\n if (!s.delivered && (await cached(p) || await retryableMessage(p))) return {state: \"action-required\", depositReceived: true};\n return {state: \"pending\", depositReceived: true};\n }\n const d = p.intent.destination, c = rpc.client(d.chain);\n let paidHash: Hex | undefined, nativeDropProved = false;\n for (const txHash of await destinationHashes(ref, p)) {\n try {\n const r = await receipt(c, d.chain, d.chainId, txHash);\n if (r) {\n if (\"seat\" in p && stargateBusNativeDrop(p, r)) nativeDropProved = true;\n if (!(\"seat\" in p) && stargateTaxiNativeDrop(p, r, taxiExecutors[d.chain] ?? [])) nativeDropProved = true;\n let paid = \"seat\" in p ? stargateBusPayout(p, r) === \"paid\" : stargateTaxiPayout(p, r);\n if (!paid && \"seat\" in p && stargateTaxiPayout({...p, packet: \"0x\"}, r)) {\n // A later retry has one payout event, without the original batch sequence.\n const tx = await c.getTransaction({hash: txHash});\n paid = !!tx.to && sameAddress(tx.to, d.address) && tx.blockHash === r.blockHash && tx.input.toLowerCase() === retryTokenData(p).toLowerCase();\n }\n if (paid) paidHash = txHash;\n }\n } catch { /* A bad or unindexed discovery candidate proves no payout. */ }\n }\n if (paidHash) return {state: p.intent.nativeDrop > 0n && !nativeDropProved ? \"partial\" : \"completed\", depositReceived: true, destTxHash: paidHash};\n if (await cached(p) || await retryableMessage(p)) return {state: \"action-required\", depositReceived: true};\n return {state: \"pending\", depositReceived: true};\n } catch (error) { return error instanceof SourceReverted ? {state: \"failed\"} : {state: \"pending\", ...(deposited ? {depositReceived: true} : {})}; }\n }\n function retryTokenData(p: TransferProof): Hex {\n const i = p.intent;\n return encodeFunctionData({abi: STARGATE_ABI, functionName: \"retryReceiveToken\", args: [p.guid, seatOf(p), i.source.eid, i.recipient, p.amount, \"0x\"]});\n }\n async function driveRecovery(ticket: StargateBusTicket): Promise<RecoveryQuote[]> {\n const started = Date.now();\n const i = ticket.intent, c = rpc.client(i.source.chain), d = rpc.client(i.destination.chain);\n const [block, destinationBlock] = await Promise.all([rpc.snapshot(c, i.source.chainId), rpc.snapshot(d, i.destination.chainId)]);\n await Promise.all([rpc.verify(c, i.source, i.destination, block), rpc.verify(d, i.destination, i.source, destinationBlock)]);\n const at = {address: i.source.tokenMessaging, abi: TOKEN_MESSAGING_ABI, blockNumber: block.number};\n const [[maxPassengers, , , length, first], capacity] = await Promise.all([\n c.readContract({...at, functionName: \"busQueues\", args: [i.destination.eid]}),\n c.readContract({...at, functionName: \"queueCapacity\"}),\n ]);\n if (capacity === 0 || first > ticket.ticketId || ticket.ticketId >= first + BigInt(length) || ticket.ticketId >= first + BigInt(maxPassengers)) return [];\n let count = 1;\n while (first + BigInt(count - 1) < ticket.ticketId) count++;\n const rows: {ticketId: bigint; passenger: Hex}[] = [];\n if (queuedPassengers) rows.push(...await queuedPassengers({chain: i.source.chain, tokenMessaging: i.source.tokenMessaging, dstEid: i.destination.eid, firstTicketId: first, count, blockNumber: block.number}));\n else {\n // Every ticket in this prefix was queued no later than our own source receipt.\n for (let page = 0; page < pages; page++) {\n const end = ticket.sourceBlock - BigInt(page * pageSize);\n if (end < 0n) break;\n const start = end - BigInt(pageSize - 1);\n const logs = await c.getContractEvents({address: i.source.tokenMessaging, abi: TOKEN_MESSAGING_ABI, eventName: \"BusRode\", fromBlock: start > 0n ? start : 0n, toBlock: end, strict: true});\n 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});\n if (rows.length >= count) break;\n }\n }\n assertStargate(rows.length <= 4096, \"too many indexed queue rows\");\n const previousIndex = parseInt(((first - 1n + BigInt(capacity)) % BigInt(capacity)).toString(), 10);\n const lastIndex = parseInt((ticket.ticketId % BigInt(capacity)).toString(), 10);\n const [previous, last] = await Promise.all([\n first === 0n ? Promise.resolve(ZERO_HASH as Hex) : c.readContract({...at, functionName: \"getPassengerHash\", args: [i.destination.eid, previousIndex]}),\n c.readContract({...at, functionName: \"getPassengerHash\", args: [i.destination.eid, lastIndex]}),\n ]);\n const passengers = busPassengerPrefix(rows, first, count, previous, last, ticket);\n const fee = await c.readContract({...at, functionName: \"quoteDriveBus\", args: [i.destination.eid, passengers]});\n assertStargate(fee.lzTokenFee === 0n, \"unsupported drive fee token\");\n await Promise.all([rpc.unchanged(c, block), rpc.unchanged(d, destinationBlock)]);\n assertStargate(Date.now() < started + 60_000, \"drive quote expired during reads\");\n return [{id: `bus-drive:${ticket.sourceHash}:${first}:${keccak256(passengers)}`, kind: \"drive-bus\", description: `Pay to drive ${count} queued passenger(s), including this ticket. The payment covers the whole batch; source transaction gas is additional.`, validUntilMs: started + 60_000,\n tx: {chain: i.source.chain, chainId: i.source.chainId, to: i.source.tokenMessaging, value: String(fee.nativeFee), data: busDriveData(i.destination.eid, passengers)},\n }];\n }\n async function getRecoveryQuotes(ref: IntentRef): Promise<RecoveryQuote[]> {\n try {\n const e = await evidence(ref);\n if (!e) return [];\n const p = e.proof;\n if (!p) return e.ticket ? await driveRecovery(e.ticket) : [];\n const i = p.intent;\n const c = rpc.client(i.destination.chain);\n if (e.compose && !(\"seat\" in p)) {\n const s = await composeState(ref, e.compose, p);\n if (!(\"outcome\" in s) && s.retryable) {\n // Fresh pins and recoverGas: a retry with too little gas would make the receiver pay out the bridged token.\n const block = await c.getBlock({blockTag: \"latest\"});\n const {recoverGas} = await checkStargateComposer(c, i.destination, block.number);\n return [{id: `${p.guid}:compose:0`, kind: \"compose\", 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.\", validUntilMs: Date.now() + 60_000,\n 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\"]})},\n }];\n }\n if (\"outcome\" in s || s.delivered || s.queue !== \"absent\") return [];\n }\n if (await c.readContract({address: i.destination.address, abi: STARGATE_ABI, functionName: \"status\"}) !== 1) return [];\n if (await cached(p)) return [{id: `${p.guid}:retry-token:${seatOf(p)}`, kind: \"retry-token\", description: \"Retry the cached Stargate token payout to the original recipient. Destination transaction gas is paid separately.\", validUntilMs: Date.now() + 60_000,\n tx: {chain: i.destination.chain, chainId: i.destination.chainId, to: i.destination.address, value: \"0\", data: retryTokenData(p)},\n }];\n if (await retryableMessage(p)) return [{id: `${p.guid}:retry-message`, kind: \"retry-message\", description: \"Retry the verified LayerZero message. Any attached value funds native drops for the entire Bus batch; destination transaction gas is additional.\", validUntilMs: Date.now() + 60_000,\n 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\"]})},\n }];\n return [];\n } catch { return []; }\n }\n async function verifyRecovery(ref: IntentRef, offered: RecoveryQuote, actor: string): Promise<string | null> {\n if (!nonzeroAddress(actor) || !Number.isFinite(offered.validUntilMs) || offered.validUntilMs <= Date.now() || offered.validUntilMs > Date.now() + 60_000) return \"stargate: invalid recovery actor or expiry\";\n const fresh = (await getRecoveryQuotes(ref)).find((q) => q.id === offered.id);\n 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 as keyof typeof offered.tx] !== value)) return \"stargate: recovery no longer matches the cached on-chain payout\";\n return null;\n }\n return {trackIntent, getRecoveryQuotes, verifyRecovery, recoveryTargets: (chain: string) => [...new Set([...registry.callTargets(chain), ...registry.deployments.filter((d) => d.chain === chain).flatMap((d) => [d.endpoint, d.tokenMessaging])])]};\n}\n","const UINT64_MAX = (1n << 64n) - 1n;\nconst UINT256_MAX = (1n << 256n) - 1n;\n\nfunction uint256(amount: bigint): void {\n if (typeof amount !== \"bigint\" || amount < 0n || amount > UINT256_MAX) throw new RangeError(\"stargate: amount must be uint256 bigint\");\n}\n\n/** Stargate converts through a uint64 shared-decimal amount. */\nexport function conversionRate(localDecimals: number, sharedDecimals: number): bigint {\n if (!Number.isInteger(localDecimals) || !Number.isInteger(sharedDecimals) || sharedDecimals < 0 || localDecimals < sharedDecimals || localDecimals > 255 || localDecimals - sharedDecimals > 77) {\n throw new RangeError(\"stargate: invalid local/shared decimals\");\n }\n return 10n ** BigInt(localDecimals - sharedDecimals);\n}\n\n/** Source amount that can be represented on the wire; dust is not silently added to the output. */\nexport function splitSourceAmount(amountLD: bigint, localDecimals: number, sharedDecimals: number): {amountSD: bigint; sentLD: bigint; dustLD: bigint} {\n uint256(amountLD);\n const rate = conversionRate(localDecimals, sharedDecimals);\n const amountSD = amountLD / rate;\n if (amountSD > UINT64_MAX) throw new RangeError(\"stargate: shared amount exceeds uint64\");\n return {amountSD, sentLD: amountSD * rate, dustLD: amountLD % rate};\n}\n\n/** quoteOFT's received amount uses SOURCE local decimals, not destination decimals. */\nexport function destinationAmount(receivedSourceLD: bigint, sourceDecimals: number, destinationDecimals: number, sharedDecimals: number): bigint {\n const {amountSD, dustLD} = splitSourceAmount(receivedSourceLD, sourceDecimals, sharedDecimals);\n if (dustLD !== 0n) throw new RangeError(\"stargate: quote receipt is not shared-decimal aligned\");\n const amount = amountSD * conversionRate(destinationDecimals, sharedDecimals);\n uint256(amount);\n return amount;\n}\n\n/** Round the caller's destination floor UP, then encode it in source local units. */\nexport function sourceMinimum(minDestinationLD: bigint, sourceDecimals: number, destinationDecimals: number, sharedDecimals: number): bigint {\n uint256(minDestinationLD);\n const destinationRate = conversionRate(destinationDecimals, sharedDecimals);\n const minimumSD = (minDestinationLD + destinationRate - 1n) / destinationRate;\n if (minimumSD > UINT64_MAX) throw new RangeError(\"stargate: minimum exceeds uint64 shared amount\");\n const minimumLD = minimumSD * conversionRate(sourceDecimals, sharedDecimals);\n uint256(minimumLD);\n return minimumLD;\n}\n\n/** Stargate fee details are negative for charges, positive for rewards. Both use source local units. */\nexport function splitFeeDetails(details: readonly {feeAmountLD: bigint}[]): {feeLD: bigint; rewardLD: bigint} {\n let feeLD = 0n, rewardLD = 0n;\n for (const {feeAmountLD} of details) {\n if (typeof feeAmountLD !== \"bigint\" || feeAmountLD < -(1n << 255n) || feeAmountLD >= (1n << 255n)) throw new RangeError(\"stargate: fee must be int256 bigint\");\n if (feeAmountLD < 0n) feeLD -= feeAmountLD;\n else rewardLD += feeAmountLD;\n }\n return {feeLD, rewardLD};\n}\n","import {encodePacked, getAddress, pad, type Address, type Hex} from \"viem\";\nimport {STARGATE_ABI} from \"./abi.js\";\nimport {conversionRate, destinationAmount, sourceMinimum, splitFeeDetails, splitSourceAmount} from \"./amounts.js\";\nimport {stargateRegistry} from \"./deployments.js\";\nimport {STARGATE_BUS_RETIRED, stargateChainActive, stargateChainCutoff} from \"./availability.js\";\nimport type {StargateDeployment, StargateRegistry} from \"./registry.js\";\nimport {assertNotAborted, assertStargate, nonzeroAddress, safeReadError, stargateRpc, type StargateBlock, type StargateRpcConfig} from \"./rpc.js\";\n\n/** Bus is retained for historical intents; new quotes accept Taxi only. */\nexport type StargateMode = \"taxi\" | \"bus\";\nexport interface StargateQuoteRequest {\n sourceChain: string;\n /** Exact token address; zero address denotes native coin. No symbol aliases. */\n sourceToken: string;\n destinationChain: string;\n destinationToken: string;\n sender: string;\n recipient: string;\n amount: bigint;\n minimum?: bigint;\n /** Defaults to zero: the entire expected output is protected. */\n slippageBps?: number;\n mode: StargateMode;\n /** Taxi specifies a uint128 amount. The legacy Bus option is refused for new quotes. */\n nativeDrop?: {amount: bigint} | {bus: true};\n /**\n * Taxi compose: the bridge output must arrive exactly (no slippage on the bridge\n * leg), and `message` builds the composeMsg for that exact destination amount.\n */\n compose?: {gas: bigint; message: (received: bigint, signal?: AbortSignal) => Promise<Hex>};\n}\nexport interface StargateSendParam {\n readonly dstEid: number;\n readonly to: Hex;\n readonly amountLD: bigint;\n readonly minAmountLD: bigint;\n readonly extraOptions: Hex;\n readonly composeMsg: Hex;\n readonly oftCmd: Hex;\n}\nexport interface StargateQuote {\n readonly mode: StargateMode;\n readonly source: StargateDeployment;\n readonly destination: StargateDeployment;\n readonly sender: Address;\n readonly recipient: Address;\n readonly sourceBlock: StargateBlock;\n readonly destinationBlock: StargateBlock;\n readonly requestedAmount: bigint;\n readonly sentAmount: bigint;\n readonly dust: bigint;\n readonly destinationAmount: bigint;\n readonly minimumDestinationAmount: bigint;\n readonly protocolFee: bigint;\n readonly protocolReward: bigint;\n readonly messagingFee: bigint;\n /** Fee including configured headroom. Surplus is sent to sender as the refund address. */\n readonly messagingFeeCap: bigint;\n /** Native input (including refundable dust) plus messagingFeeCap. */\n readonly nativeValue: bigint;\n readonly nativeDrop: bigint;\n readonly creditSD: bigint;\n readonly sendParam: StargateSendParam;\n readonly validUntilMs: number;\n /** A quote does not reserve credits or promise a delivery time (especially for queued Bus). */\n readonly liquidityReserved: false;\n readonly etaSeconds: null;\n /** Wallet simulation determines gas; an unavailable estimate is never reported as zero. */\n readonly sourceGas: null;\n readonly approvalGas: null;\n}\nexport interface StargateQuoteConfig extends StargateRpcConfig {\n /** Locally reviewed pins; never populate this from an untrusted discovery API. */\n registry?: StargateRegistry;\n quoteTtlMs?: number;\n /** Integer 0..10000, default 2500. This is a cap, not an additional charged fee. */\n feeHeadroomBps?: number;\n}\n\nconst UINT64_MAX = (1n << 64n) - 1n;\nconst UINT256_MAX = (1n << 256n) - 1n;\n\n/** Type-3 index-zero compose gas. No arbitrary native value or extra executor options. */\nexport function stargateComposeOptions(gas: bigint): Hex {\n assertStargate(typeof gas === \"bigint\" && gas > 0n && gas < (1n << 128n), \"compose gas must be a positive uint128\");\n return encodePacked([\"uint16\", \"uint8\", \"uint16\", \"uint8\", \"uint16\", \"uint128\"], [3, 1, 19, 3, 0, gas]);\n}\n\n/** Type 3 / executor worker 1 / native-drop option 2, with a 48-byte payload. */\nexport function taxiNativeDrop(amount: bigint, recipient: Address): Hex {\n assertStargate(typeof amount === \"bigint\" && amount > 0n && amount < (1n << 128n), \"native drop must be a positive uint128\");\n assertStargate(nonzeroAddress(recipient), \"invalid native drop recipient\");\n return encodePacked([\"uint16\", \"uint8\", \"uint16\", \"uint8\", \"uint128\", \"bytes32\"], [3, 1, 49, 2, amount, pad(recipient, {size: 32})]);\n}\n\n/** Read-only direct Stargate quotes. No transaction is signed, sent, or liquidity reserved. */\nexport function createStargateQuoter(config: StargateQuoteConfig) {\n const registry = config.registry ?? stargateRegistry;\n const rpc = stargateRpc(config);\n const ttl = config.quoteTtlMs ?? 60_000;\n const headroom = config.feeHeadroomBps ?? 2500;\n assertStargate(Number.isSafeInteger(ttl) && ttl > 0 && ttl <= 300_000, \"invalid quote lifetime\");\n assertStargate(Number.isInteger(headroom) && headroom >= 0 && headroom <= 10_000, \"invalid messaging fee headroom\");\n\n function supportsRoute(sourceChain: string, sourceToken: string, destinationChain: string, destinationToken: string): boolean {\n return stargateChainActive(sourceChain) && stargateChainActive(destinationChain) && rpc.has(sourceChain) && rpc.has(destinationChain) && !!registry.route(sourceChain, sourceToken, destinationChain, destinationToken);\n }\n\n async function quote(input: StargateQuoteRequest, signal?: AbortSignal): Promise<StargateQuote> {\n // Copy mutable caller objects before any await.\n const request = {...input, ...(input.nativeDrop ? {nativeDrop: {...input.nativeDrop}} : {})};\n const started = Date.now();\n try {\n assertNotAborted(signal);\n assertStargate(request.mode === \"taxi\" || request.mode === \"bus\", \"invalid transport mode\");\n assertStargate(request.mode !== \"bus\", STARGATE_BUS_RETIRED);\n assertStargate(stargateChainActive(request.sourceChain) && stargateChainActive(request.destinationChain), \"chain support has ended for new transfers\");\n const route = registry.route(request.sourceChain, request.sourceToken, request.destinationChain, request.destinationToken);\n assertStargate(route, \"unsupported token route\");\n const {source, destination} = route;\n assertStargate(nonzeroAddress(request.sender) && nonzeroAddress(request.recipient), \"sender and recipient must be nonzero EVM addresses\");\n const sender = getAddress(request.sender), recipient = getAddress(request.recipient);\n const slippage = request.slippageBps ?? 0;\n assertStargate(Number.isInteger(slippage) && slippage >= 0 && slippage < 10_000, \"invalid slippage\");\n const minimum = request.minimum ?? 0n;\n assertStargate(typeof minimum === \"bigint\" && minimum >= 0n && minimum <= UINT256_MAX, \"invalid minimum\");\n const split = splitSourceAmount(request.amount, source.localDecimals, source.sharedDecimals);\n assertStargate(split.amountSD > 0n, \"amount is below shared-decimal precision\");\n const src = rpc.client(source.chain, signal), dst = rpc.client(destination.chain, signal);\n const [sourceBlock, destinationBlock] = await Promise.all([rpc.snapshot(src, source.chainId), rpc.snapshot(dst, destination.chainId)]);\n await Promise.all([rpc.verify(src, source, destination, sourceBlock), rpc.verify(dst, destination, source, destinationBlock)]);\n assertNotAborted(signal);\n const at = {address: source.address, abi: STARGATE_ABI, blockNumber: sourceBlock.number, account: sender};\n const creditSD = await src.readContract({...at, functionName: \"paths\", args: [destination.eid]});\n let extraOptions: Hex = \"0x\", nativeDrop = 0n;\n const compose = request.compose;\n assertStargate(!compose || (!request.nativeDrop && slippage === 0 && minimum === 0n), \"compose takes an exact bridge output without native drop\");\n if (request.nativeDrop) {\n assertStargate(\"amount\" in request.nativeDrop && !(\"bus\" in request.nativeDrop), \"Taxi requires an explicit native drop amount\");\n nativeDrop = request.nativeDrop.amount;\n extraOptions = taxiNativeDrop(nativeDrop, recipient);\n }\n const probe: StargateSendParam = {dstEid: destination.eid, to: pad(recipient, {size: 32}), amountLD: request.amount, minAmountLD: 0n, extraOptions, composeMsg: \"0x\", oftCmd: \"0x\"};\n const [limit, details, receipt] = await src.readContract({...at, functionName: \"quoteOFT\", args: [probe]});\n assertStargate(limit.minAmountLD <= split.sentLD && split.sentLD <= limit.maxAmountLD, \"amount exceeds available OFT limits\");\n assertStargate(receipt.amountSentLD === split.sentLD, \"quote clipped the exact input amount\");\n const received = destinationAmount(receipt.amountReceivedLD, source.localDecimals, destination.localDecimals, source.sharedDecimals);\n assertStargate(received > 0n, \"quote has no output\");\n const receivedSD = receipt.amountReceivedLD / conversionRate(source.localDecimals, source.sharedDecimals);\n assertStargate(creditSD === UINT64_MAX || receivedSD <= creditSD, \"insufficient credits for output including reward\");\n const fees = splitFeeDetails(details);\n assertStargate(receipt.amountSentLD - fees.feeLD + fees.rewardLD === receipt.amountReceivedLD, \"protocol fee accounting mismatch\");\n // Ceil the slippage floor, then ceil again to a representable shared amount.\n const slipFloor = (received * BigInt(10_000 - slippage) + 9999n) / 10_000n;\n const minAmountLD = sourceMinimum(minimum > slipFloor ? minimum : slipFloor, source.localDecimals, destination.localDecimals, source.sharedDecimals);\n assertStargate(minAmountLD <= receipt.amountReceivedLD, \"output is below the caller's minimum\");\n const sendParam = Object.freeze(compose\n ? {...probe, minAmountLD, extraOptions: stargateComposeOptions(compose.gas), composeMsg: await compose.message(received, signal)}\n : {...probe, minAmountLD});\n assertNotAborted(signal);\n const fee = await src.readContract({...at, functionName: \"quoteSend\", args: [sendParam, false]});\n assertStargate(fee.lzTokenFee === 0n, \"LZ token fees are unsupported\");\n const cap = fee.nativeFee + (fee.nativeFee * BigInt(headroom) + 9999n) / 10_000n;\n const nativeValue = cap + (source.kind === \"native\" ? request.amount : 0n);\n assertStargate(nativeValue <= UINT256_MAX, \"native value overflow\");\n await Promise.all([rpc.unchanged(src, sourceBlock), rpc.unchanged(dst, destinationBlock)]);\n assertNotAborted(signal);\n const validUntilMs = Math.min(started + ttl, stargateChainCutoff(source.chain), stargateChainCutoff(destination.chain));\n assertStargate(Date.now() < validUntilMs, \"quote expired during RPC reads\");\n return Object.freeze({mode: request.mode, source, destination, sender, recipient, sourceBlock, destinationBlock, requestedAmount: request.amount, sentAmount: split.sentLD, dust: split.dustLD, destinationAmount: received, minimumDestinationAmount: destinationAmount(minAmountLD, source.localDecimals, destination.localDecimals, source.sharedDecimals), protocolFee: fees.feeLD, protocolReward: fees.rewardLD, messagingFee: fee.nativeFee, messagingFeeCap: cap, nativeValue, nativeDrop, creditSD, sendParam, validUntilMs, liquidityReserved: false, etaSeconds: null, sourceGas: null, approvalGas: null});\n } catch (error) { throw safeReadError(error); }\n }\n return Object.freeze({supportsRoute, quote});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAiM;;;ACAjM,IAAAC,eAA2G;;;ACA3G,kBAAuB;AAGhB,IAAM,mBAAe,sBAAS;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,mBAAe,sBAAS;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAIM,IAAM,mBAAe,sBAAS;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,0BAAsB,sBAAS;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;;;ADhEM,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAAE,UAAM,aAAa,OAAO,EAAE;AAAG,SAAK,OAAO;AAAA,EAAqB;AACjG;AAeA,IAAM,mBAAe,uBAAS,CAAC,4CAA4C,sCAAsC,CAAC;AAC3G,IAAM,cAAc,CAAC,GAAW,MAAuB,EAAE,YAAY,MAAM,EAAE,YAAY;AACzF,SAAS,eAAe,WAAoB,SAAoC;A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