@humanode-hyperlane/cli 1045.2.1 → 1045.2.3
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/bundle/230.index.js +262 -131
- package/bundle/546.index.js +1057 -0
- package/bundle/59.index.js +1368 -0
- package/bundle/655.index.js +361 -0
- package/bundle/748.index.js +2 -2
- package/bundle/index.js +2 -2
- package/package.json +2 -2
|
@@ -0,0 +1,1368 @@
|
|
|
1
|
+
export const id = 59;
|
|
2
|
+
export const ids = [59];
|
|
3
|
+
export const modules = {
|
|
4
|
+
|
|
5
|
+
/***/ 61059:
|
|
6
|
+
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
7
|
+
|
|
8
|
+
__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
|
|
9
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
10
|
+
/* harmony export */ SwapsXyzBridge: () => (/* binding */ SwapsXyzBridge)
|
|
11
|
+
/* harmony export */ });
|
|
12
|
+
/* harmony import */ var _humanode_hyperlane_sdk__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(74728);
|
|
13
|
+
/* harmony import */ var _humanode_hyperlane_tron_sdk_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(61151);
|
|
14
|
+
/* harmony import */ var _solana_spl_token__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(56125);
|
|
15
|
+
/* harmony import */ var _solana_spl_token__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(54825);
|
|
16
|
+
/* harmony import */ var _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4346);
|
|
17
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(21387);
|
|
18
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(16639);
|
|
19
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(11666);
|
|
20
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(93142);
|
|
21
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(53616);
|
|
22
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(14918);
|
|
23
|
+
/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(62418);
|
|
24
|
+
/* harmony import */ var tronweb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89448);
|
|
25
|
+
/* harmony import */ var _config_types_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(69743);
|
|
26
|
+
/* harmony import */ var _utils_quoteBudget_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(3987);
|
|
27
|
+
/* harmony import */ var _utils_solanaKeyParser_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(97781);
|
|
28
|
+
/* harmony import */ var _erc20Approve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(51846);
|
|
29
|
+
/* harmony import */ var _SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(36173);
|
|
30
|
+
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_erc20Approve_js__WEBPACK_IMPORTED_MODULE_5__]);
|
|
31
|
+
_erc20Approve_js__WEBPACK_IMPORTED_MODULE_5__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
const NATIVE_TOKEN_ADDRESS = '0x0000000000000000000000000000000000000000';
|
|
45
|
+
const DEFAULT_SLIPPAGE = 0.005;
|
|
46
|
+
const REVERSE_QUOTE_ATTEMPTS = 4;
|
|
47
|
+
const REVERSE_QUOTE_HEADROOM_BPS = 30n;
|
|
48
|
+
const BPS_DENOMINATOR = 10000n;
|
|
49
|
+
const ERC20_DECIMALS_ABI = ['function decimals() view returns (uint8)'];
|
|
50
|
+
const ERC20_TRANSFER_INTERFACE = new ethers__WEBPACK_IMPORTED_MODULE_7__.utils.Interface([
|
|
51
|
+
'function transfer(address recipient, uint256 amount) returns (bool)',
|
|
52
|
+
]);
|
|
53
|
+
const REGISTER_TX_RETRY_DELAY_MS = 2_000;
|
|
54
|
+
const MAX_REGISTRATION_ATTEMPTS = 3;
|
|
55
|
+
const MAX_TRANSACTION_AGE_MS = 30_000;
|
|
56
|
+
const MAX_PREPARATION_ATTEMPTS = 3;
|
|
57
|
+
const DEFAULT_MAX_EVM_NATIVE_FEE_WEI = 10000000000000000n;
|
|
58
|
+
const DEFAULT_MAX_TRON_NATIVE_FEE_SUN = 20000000n;
|
|
59
|
+
const DEFAULT_MAX_SOLANA_NATIVE_SPEND_LAMPORTS = 10_000_000;
|
|
60
|
+
const tokenAmountOffset = _solana_spl_token__WEBPACK_IMPORTED_MODULE_8__/* .AccountLayout */ .O9.offsetOf('amount');
|
|
61
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(tokenAmountOffset !== undefined, 'SPL token account layout is missing amount');
|
|
62
|
+
const TOKEN_AMOUNT_OFFSET = tokenAmountOffset;
|
|
63
|
+
function ceilDiv(numerator, denominator) {
|
|
64
|
+
return (numerator + denominator - 1n) / denominator;
|
|
65
|
+
}
|
|
66
|
+
function isRecord(value) {
|
|
67
|
+
return typeof value === 'object' && value !== null;
|
|
68
|
+
}
|
|
69
|
+
function transactionValue(tx, context) {
|
|
70
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(isRecord(tx), `${context} transaction is missing`);
|
|
71
|
+
const value = tx.value;
|
|
72
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(value === undefined || typeof value === 'string', `${context} transaction value is invalid`);
|
|
73
|
+
return value === undefined || value === '' ? 0n : BigInt(value);
|
|
74
|
+
}
|
|
75
|
+
function isTokenProgram(programId) {
|
|
76
|
+
return (programId.equals(_solana_spl_token__WEBPACK_IMPORTED_MODULE_10__/* .TOKEN_PROGRAM_ID */ .x5) ||
|
|
77
|
+
programId.equals(_solana_spl_token__WEBPACK_IMPORTED_MODULE_10__/* .TOKEN_2022_PROGRAM_ID */ .sy));
|
|
78
|
+
}
|
|
79
|
+
function decodeTokenAccount(programId, data) {
|
|
80
|
+
if (!isTokenProgram(programId) || data.length < _solana_spl_token__WEBPACK_IMPORTED_MODULE_8__/* .ACCOUNT_SIZE */ .a8)
|
|
81
|
+
return undefined;
|
|
82
|
+
const decoded = _solana_spl_token__WEBPACK_IMPORTED_MODULE_8__/* .AccountLayout */ .O9.decode(data.subarray(0, _solana_spl_token__WEBPACK_IMPORTED_MODULE_8__/* .ACCOUNT_SIZE */ .a8));
|
|
83
|
+
return {
|
|
84
|
+
mint: decoded.mint,
|
|
85
|
+
owner: decoded.owner,
|
|
86
|
+
amount: decoded.amount,
|
|
87
|
+
delegateOption: decoded.delegateOption,
|
|
88
|
+
delegate: decoded.delegate,
|
|
89
|
+
delegatedAmount: decoded.delegatedAmount,
|
|
90
|
+
closeAuthorityOption: decoded.closeAuthorityOption,
|
|
91
|
+
closeAuthority: decoded.closeAuthority,
|
|
92
|
+
state: decoded.state,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function simulatedAccountData(account) {
|
|
96
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(account.data[1] === 'base64', 'SwapsXyzBridge.execute Solana simulation account must use base64 encoding');
|
|
97
|
+
return Buffer.from(account.data[0], 'base64');
|
|
98
|
+
}
|
|
99
|
+
class SwapsXyzBridge {
|
|
100
|
+
externalBridgeId = _config_types_js__WEBPACK_IMPORTED_MODULE_3__/* .ExternalBridgeType */ .rm.SwapsXyz;
|
|
101
|
+
logger;
|
|
102
|
+
client;
|
|
103
|
+
config;
|
|
104
|
+
chainMetadataByChainId = new Map();
|
|
105
|
+
tokenDecimalsCache = new Map();
|
|
106
|
+
evmProviderFactory;
|
|
107
|
+
solanaConnectionFactory;
|
|
108
|
+
maxSolanaNativeSpendLamports;
|
|
109
|
+
maxSolanaTransactionFeeLamports;
|
|
110
|
+
solanaTransactionFeeWarningLamports;
|
|
111
|
+
tronWalletFactory;
|
|
112
|
+
registerTxRetryDelayMs;
|
|
113
|
+
// Prevent source-account races when movements share a source in one cycle.
|
|
114
|
+
_executeLock = Promise.resolve();
|
|
115
|
+
constructor(config, logger, client) {
|
|
116
|
+
this.config = config;
|
|
117
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(config.maxQuoteLossBps === undefined ||
|
|
118
|
+
(Number.isInteger(config.maxQuoteLossBps) &&
|
|
119
|
+
config.maxQuoteLossBps >= 0 &&
|
|
120
|
+
config.maxQuoteLossBps <= Number(BPS_DENOMINATOR)), 'maxQuoteLossBps must be an integer between 0 and 10000');
|
|
121
|
+
const maxSolanaNativeSpendLamports = config.maxSolanaNativeSpendLamports ??
|
|
122
|
+
DEFAULT_MAX_SOLANA_NATIVE_SPEND_LAMPORTS;
|
|
123
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Number.isSafeInteger(maxSolanaNativeSpendLamports) &&
|
|
124
|
+
maxSolanaNativeSpendLamports >= 0, 'maxSolanaNativeSpendLamports must be a non-negative safe integer');
|
|
125
|
+
this.maxSolanaTransactionFeeLamports =
|
|
126
|
+
config.maxSolanaTransactionFeeLamports ??
|
|
127
|
+
_config_types_js__WEBPACK_IMPORTED_MODULE_3__/* .DEFAULT_MAX_SOLANA_TRANSACTION_FEE_LAMPORTS */ .zY;
|
|
128
|
+
this.solanaTransactionFeeWarningLamports =
|
|
129
|
+
config.solanaTransactionFeeWarningLamports ??
|
|
130
|
+
_config_types_js__WEBPACK_IMPORTED_MODULE_3__/* .DEFAULT_SOLANA_TRANSACTION_FEE_WARNING_LAMPORTS */ .l7;
|
|
131
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Number.isSafeInteger(this.maxSolanaTransactionFeeLamports) &&
|
|
132
|
+
this.maxSolanaTransactionFeeLamports >= 0, 'maxSolanaTransactionFeeLamports must be a non-negative safe integer');
|
|
133
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Number.isSafeInteger(this.solanaTransactionFeeWarningLamports) &&
|
|
134
|
+
this.solanaTransactionFeeWarningLamports >= 0 &&
|
|
135
|
+
this.solanaTransactionFeeWarningLamports <=
|
|
136
|
+
this.maxSolanaTransactionFeeLamports, 'solanaTransactionFeeWarningLamports must be a non-negative safe integer at most maxSolanaTransactionFeeLamports');
|
|
137
|
+
this.logger = logger;
|
|
138
|
+
this.getSlippageBps(); // Validate the bridge-level default at construction.
|
|
139
|
+
this.client =
|
|
140
|
+
client ??
|
|
141
|
+
new _SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .SwapsXyzClient */ .NQ({
|
|
142
|
+
apiKey: config.apiKey,
|
|
143
|
+
apiUrl: config.apiUrl,
|
|
144
|
+
}, logger);
|
|
145
|
+
this.evmProviderFactory =
|
|
146
|
+
config.evmProviderFactory ??
|
|
147
|
+
((rpcUrl) => new ethers__WEBPACK_IMPORTED_MODULE_7__.providers.StaticJsonRpcProvider(rpcUrl));
|
|
148
|
+
this.solanaConnectionFactory =
|
|
149
|
+
config.solanaConnectionFactory ??
|
|
150
|
+
((rpcUrl) => new _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .Connection */ .Ng(rpcUrl, 'confirmed'));
|
|
151
|
+
this.maxSolanaNativeSpendLamports = maxSolanaNativeSpendLamports;
|
|
152
|
+
this.tronWalletFactory =
|
|
153
|
+
config.tronWalletFactory ??
|
|
154
|
+
((privateKey, rpcUrl) => new _humanode_hyperlane_tron_sdk_runtime__WEBPACK_IMPORTED_MODULE_0__/* .TronWallet */ .t$(privateKey, rpcUrl));
|
|
155
|
+
this.registerTxRetryDelayMs =
|
|
156
|
+
config.registerTxRetryDelayMs ?? REGISTER_TX_RETRY_DELAY_MS;
|
|
157
|
+
if (config.chainMetadata) {
|
|
158
|
+
for (const metadata of Object.values(config.chainMetadata)) {
|
|
159
|
+
if (metadata.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Sealevel &&
|
|
160
|
+
!this.chainMetadataByChainId.has(metadata.domainId)) {
|
|
161
|
+
this.chainMetadataByChainId.set(metadata.domainId, metadata);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
for (const metadata of Object.values(config.chainMetadata)) {
|
|
165
|
+
if (metadata.chainId !== undefined && (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .isEVMLike */ .Us)(metadata.protocol)) {
|
|
166
|
+
this.chainMetadataByChainId.set(Number(metadata.chainId), metadata);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
getNativeTokenAddress() {
|
|
172
|
+
return NATIVE_TOKEN_ADDRESS;
|
|
173
|
+
}
|
|
174
|
+
async quote(params) {
|
|
175
|
+
this.validateQuoteParams(params);
|
|
176
|
+
try {
|
|
177
|
+
const response = await this.client.getAction(this.buildActionRequest(params));
|
|
178
|
+
return this.toBridgeQuote(params, response);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
if (params.toAmount !== undefined &&
|
|
182
|
+
error instanceof _SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .SwapsXyzRequestError */ .VT &&
|
|
183
|
+
error.code === 'UNSUPPORTED_SWAP_DIRECTION') {
|
|
184
|
+
return this.quoteExactOutWithForwardFallback(params);
|
|
185
|
+
}
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
execute(quote, privateKeys, options) {
|
|
190
|
+
const execution = this._executeLock.then(() => new _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_12__/* .TransactionSubmission */ .P(options).run((observers) => this.executeUnlocked(quote, privateKeys, { ...options, ...observers })));
|
|
191
|
+
this._executeLock = execution.then(() => undefined, () => undefined);
|
|
192
|
+
return execution;
|
|
193
|
+
}
|
|
194
|
+
async getStatus(txHash, fromChain, toChain, transferId) {
|
|
195
|
+
let response;
|
|
196
|
+
let statusError;
|
|
197
|
+
const statusRequest = {
|
|
198
|
+
txHash,
|
|
199
|
+
chainId: fromChain,
|
|
200
|
+
...(transferId === undefined ? {} : { txId: transferId }),
|
|
201
|
+
};
|
|
202
|
+
try {
|
|
203
|
+
response = await this.client.getStatus(statusRequest);
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
statusError = error;
|
|
207
|
+
}
|
|
208
|
+
// registerTxs is idempotent. Retrying it here heals transient registration
|
|
209
|
+
// outages without re-broadcasting the source transaction.
|
|
210
|
+
if (transferId !== undefined &&
|
|
211
|
+
(response?.status.toLowerCase() === 'not yet created' ||
|
|
212
|
+
(0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isSwapsXyzNotFoundError */ .fV)(statusError)) &&
|
|
213
|
+
(await this.registerTransaction(transferId, txHash))) {
|
|
214
|
+
try {
|
|
215
|
+
response = await this.client.getStatus(statusRequest);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
statusError = error;
|
|
219
|
+
response = undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (response === undefined) {
|
|
223
|
+
if ((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isSwapsXyzNotFoundError */ .fV)(statusError)) {
|
|
224
|
+
return { status: 'not_found' };
|
|
225
|
+
}
|
|
226
|
+
this.logger.warn({
|
|
227
|
+
txHash,
|
|
228
|
+
transferId,
|
|
229
|
+
error: statusError instanceof Error ? statusError.message : statusError,
|
|
230
|
+
}, 'Failed to get swaps.xyz status');
|
|
231
|
+
throw statusError instanceof Error
|
|
232
|
+
? statusError
|
|
233
|
+
: new Error('Failed to get swaps.xyz status');
|
|
234
|
+
}
|
|
235
|
+
return this.toBridgeTransferStatus(response, txHash, fromChain, toChain, transferId);
|
|
236
|
+
}
|
|
237
|
+
toBridgeTransferStatus(response, txHash, fromChain, toChain, transferId) {
|
|
238
|
+
const protocol = this.chainMetadataByChainId.get(fromChain)?.protocol;
|
|
239
|
+
const normalizeHash = (hash) => protocol !== undefined && (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .isEVMLike */ .Us)(protocol)
|
|
240
|
+
? hash.replace(/^0x/i, '').toLowerCase()
|
|
241
|
+
: hash;
|
|
242
|
+
if ((transferId !== undefined && response.txId !== transferId) ||
|
|
243
|
+
(response.srcTxHash != null &&
|
|
244
|
+
normalizeHash(response.srcTxHash) !== normalizeHash(txHash))) {
|
|
245
|
+
this.logger.warn({
|
|
246
|
+
txHash,
|
|
247
|
+
transferId,
|
|
248
|
+
responseTransferId: response.txId,
|
|
249
|
+
responseSourceHash: response.srcTxHash,
|
|
250
|
+
}, 'swaps.xyz status transfer identity mismatch');
|
|
251
|
+
return { status: 'not_found' };
|
|
252
|
+
}
|
|
253
|
+
// The API's chainId param is advisory: a hash registered on a different
|
|
254
|
+
// chain is still returned. Such an entry is not our transfer.
|
|
255
|
+
if (response.srcChainId !== null && response.srcChainId !== fromChain) {
|
|
256
|
+
this.logger.warn({ txHash, fromChain, responseSrcChainId: response.srcChainId }, 'swaps.xyz status srcChainId does not match requested chain');
|
|
257
|
+
return { status: 'not_found' };
|
|
258
|
+
}
|
|
259
|
+
if (response.dstChainId !== null && response.dstChainId !== toChain) {
|
|
260
|
+
this.logger.warn({ txHash, toChain, responseDstChainId: response.dstChainId }, 'swaps.xyz status dstChainId does not match requested chain');
|
|
261
|
+
return { status: 'not_found' };
|
|
262
|
+
}
|
|
263
|
+
const rawStatus = response.status;
|
|
264
|
+
switch (rawStatus.toLowerCase()) {
|
|
265
|
+
case 'success':
|
|
266
|
+
case 'completed':
|
|
267
|
+
if (response.srcChainId === null ||
|
|
268
|
+
response.dstChainId === null ||
|
|
269
|
+
(transferId === undefined && !response.srcTxHash) ||
|
|
270
|
+
!response.dstTxHash) {
|
|
271
|
+
this.logger.warn({
|
|
272
|
+
txHash,
|
|
273
|
+
responseSrcChainId: response.srcChainId,
|
|
274
|
+
responseDstChainId: response.dstChainId,
|
|
275
|
+
}, 'swaps.xyz completed status is missing route identity');
|
|
276
|
+
return { status: 'pending', substatus: rawStatus };
|
|
277
|
+
}
|
|
278
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(response.actionResponse, 'Completed swaps.xyz status is missing actionResponse');
|
|
279
|
+
return {
|
|
280
|
+
status: 'complete',
|
|
281
|
+
receivingTxHash: response.dstTxHash,
|
|
282
|
+
receivedAmount: BigInt(response.actionResponse.amountOut.amount),
|
|
283
|
+
};
|
|
284
|
+
case 'failed':
|
|
285
|
+
return {
|
|
286
|
+
status: 'failed',
|
|
287
|
+
error: 'swaps.xyz reported transfer failed',
|
|
288
|
+
};
|
|
289
|
+
case 'refunded':
|
|
290
|
+
return { status: 'failed', error: 'refunded' };
|
|
291
|
+
case 'requires refund':
|
|
292
|
+
return {
|
|
293
|
+
status: 'failed',
|
|
294
|
+
error: 'requires refund (claim via swaps.xyz)',
|
|
295
|
+
};
|
|
296
|
+
case 'expired':
|
|
297
|
+
return { status: 'failed', error: 'swaps.xyz transfer expired' };
|
|
298
|
+
default:
|
|
299
|
+
return { status: 'pending', substatus: rawStatus };
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
validateQuoteParams(params) {
|
|
303
|
+
for (const [chainId, token] of [
|
|
304
|
+
[params.fromChain, params.fromToken],
|
|
305
|
+
[params.toChain, params.toToken],
|
|
306
|
+
]) {
|
|
307
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(this.chainMetadataByChainId.get(chainId)?.protocol !==
|
|
308
|
+
_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Sealevel || token !== NATIVE_TOKEN_ADDRESS, 'swaps.xyz native SOL is not supported; use an SPL token');
|
|
309
|
+
}
|
|
310
|
+
if (params.fromAmount !== undefined && params.toAmount !== undefined) {
|
|
311
|
+
throw new Error('Cannot specify both fromAmount and toAmount - provide exactly one');
|
|
312
|
+
}
|
|
313
|
+
if (params.fromAmount === undefined && params.toAmount === undefined) {
|
|
314
|
+
throw new Error('Must specify either fromAmount or toAmount');
|
|
315
|
+
}
|
|
316
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(params.fromAmount === undefined || params.fromAmount > 0n, 'fromAmount must be positive');
|
|
317
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(params.toAmount === undefined || params.toAmount > 0n, 'toAmount must be positive');
|
|
318
|
+
}
|
|
319
|
+
buildActionRequest(params) {
|
|
320
|
+
const amount = params.fromAmount ?? params.toAmount;
|
|
321
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(amount !== undefined, 'Must specify either fromAmount or toAmount');
|
|
322
|
+
return {
|
|
323
|
+
actionType: 'swap-action',
|
|
324
|
+
sender: this.formatAddressForApi(params.fromChain, params.fromAddress),
|
|
325
|
+
recipient: this.formatAddressForApi(params.toChain, params.toAddress ?? params.fromAddress),
|
|
326
|
+
srcChainId: params.fromChain,
|
|
327
|
+
dstChainId: params.toChain,
|
|
328
|
+
srcToken: this.formatAddressForApi(params.fromChain, params.fromToken),
|
|
329
|
+
dstToken: this.formatAddressForApi(params.toChain, params.toToken),
|
|
330
|
+
slippage: this.getSlippageBps(params.slippage),
|
|
331
|
+
amount: amount.toString(),
|
|
332
|
+
swapDirection: params.fromAmount !== undefined
|
|
333
|
+
? 'exact-amount-in'
|
|
334
|
+
: 'exact-amount-out',
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
formatAddressForApi(chainId, address) {
|
|
338
|
+
const protocol = this.chainMetadataByChainId.get(chainId)?.protocol;
|
|
339
|
+
if (protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron) {
|
|
340
|
+
return tronweb__WEBPACK_IMPORTED_MODULE_2__/* .TronWeb */ .K_.address.fromHex(`41${this.tronAddressHex20(address)}`);
|
|
341
|
+
}
|
|
342
|
+
if (protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Ethereum && address.startsWith('T')) {
|
|
343
|
+
return this.tronAddressToEvm(address);
|
|
344
|
+
}
|
|
345
|
+
return address;
|
|
346
|
+
}
|
|
347
|
+
tronAddressHex20(address) {
|
|
348
|
+
if (address.startsWith('T')) {
|
|
349
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(tronweb__WEBPACK_IMPORTED_MODULE_2__/* .TronWeb */ .K_.isAddress(address), `SwapsXyzBridge: invalid Tron address ${address}`);
|
|
350
|
+
const hex = tronweb__WEBPACK_IMPORTED_MODULE_2__/* .TronWeb */ .K_.address.toHex(address);
|
|
351
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(/^41[0-9a-fA-F]{40}$/.test(hex), `SwapsXyzBridge: invalid Tron address ${address}`);
|
|
352
|
+
return hex.slice(2).toLowerCase();
|
|
353
|
+
}
|
|
354
|
+
let hex = address.startsWith('0x') ? address.slice(2) : address;
|
|
355
|
+
if (/^41[0-9a-fA-F]{40}$/.test(hex))
|
|
356
|
+
hex = hex.slice(2);
|
|
357
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(/^[0-9a-fA-F]{40}$/.test(hex) && tronweb__WEBPACK_IMPORTED_MODULE_2__/* .TronWeb */ .K_.isAddress(`41${hex}`), `SwapsXyzBridge: invalid Tron address ${address}`);
|
|
358
|
+
return hex.toLowerCase();
|
|
359
|
+
}
|
|
360
|
+
tronAddressToEvm(address) {
|
|
361
|
+
return (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__/* .ensure0x */ .Ho)(this.tronAddressHex20(address));
|
|
362
|
+
}
|
|
363
|
+
getSlippageBps(slippage) {
|
|
364
|
+
const fraction = slippage ?? this.config.defaultSlippage ?? DEFAULT_SLIPPAGE;
|
|
365
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Number.isFinite(fraction) && fraction >= 0 && fraction <= 1, 'swaps.xyz slippage must be between 0 and 1');
|
|
366
|
+
return Math.round(fraction * 10_000);
|
|
367
|
+
}
|
|
368
|
+
async quoteExactOutWithForwardFallback(params) {
|
|
369
|
+
const toAmount = params.toAmount;
|
|
370
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(toAmount !== undefined, 'Reverse quote requires toAmount');
|
|
371
|
+
const slippageBps = this.getSlippageBps(params.slippage);
|
|
372
|
+
const [sourceDecimals, destinationDecimals] = await Promise.all([
|
|
373
|
+
this.getTokenDecimals(params.fromChain, params.fromToken),
|
|
374
|
+
this.getTokenDecimals(params.toChain, params.toToken),
|
|
375
|
+
]);
|
|
376
|
+
let fromAmount = ceilDiv(toAmount * 10n ** BigInt(sourceDecimals), 10n ** BigInt(destinationDecimals));
|
|
377
|
+
fromAmount =
|
|
378
|
+
(fromAmount *
|
|
379
|
+
(BPS_DENOMINATOR + BigInt(slippageBps) + REVERSE_QUOTE_HEADROOM_BPS)) /
|
|
380
|
+
BPS_DENOMINATOR;
|
|
381
|
+
let lastAmountOutMin = 0n;
|
|
382
|
+
for (let attempt = 1; attempt <= REVERSE_QUOTE_ATTEMPTS; attempt++) {
|
|
383
|
+
const forwardParams = {
|
|
384
|
+
...params,
|
|
385
|
+
fromAmount,
|
|
386
|
+
toAmount: undefined,
|
|
387
|
+
};
|
|
388
|
+
const response = await this.client.getAction(this.buildActionRequest(forwardParams));
|
|
389
|
+
lastAmountOutMin = BigInt(response.amountOutMin.amount);
|
|
390
|
+
this.logger.debug({
|
|
391
|
+
attempt,
|
|
392
|
+
fromAmount: fromAmount.toString(),
|
|
393
|
+
amountOutMin: lastAmountOutMin.toString(),
|
|
394
|
+
requestedToAmount: toAmount.toString(),
|
|
395
|
+
}, 'swaps.xyz reverse quote forward fallback attempt');
|
|
396
|
+
if (lastAmountOutMin >= toAmount) {
|
|
397
|
+
const quote = await this.toBridgeQuote(forwardParams, response);
|
|
398
|
+
// This executable request is exact input, but retains the original target.
|
|
399
|
+
return {
|
|
400
|
+
...quote,
|
|
401
|
+
toAmountMin: quote.toAmountMin > toAmount ? quote.toAmountMin : toAmount,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(lastAmountOutMin > 0n, 'SwapsXyzBridge reverse quote fallback returned zero amountOutMin');
|
|
405
|
+
fromAmount = ceilDiv(fromAmount * toAmount, lastAmountOutMin) + 1n;
|
|
406
|
+
}
|
|
407
|
+
throw new Error(`SwapsXyzBridge reverse quote fallback exhausted after ${REVERSE_QUOTE_ATTEMPTS} attempts; last amountOutMin ${lastAmountOutMin.toString()} was short of requested ${toAmount.toString()}`);
|
|
408
|
+
}
|
|
409
|
+
getTokenDecimals(chainId, token) {
|
|
410
|
+
const cacheKey = `${chainId}:${token}`;
|
|
411
|
+
const cached = this.tokenDecimalsCache.get(cacheKey);
|
|
412
|
+
if (cached)
|
|
413
|
+
return cached;
|
|
414
|
+
const decimals = this.fetchTokenDecimals(chainId, token);
|
|
415
|
+
this.tokenDecimalsCache.set(cacheKey, decimals);
|
|
416
|
+
void decimals.catch(() => {
|
|
417
|
+
if (this.tokenDecimalsCache.get(cacheKey) === decimals) {
|
|
418
|
+
this.tokenDecimalsCache.delete(cacheKey);
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
return decimals;
|
|
422
|
+
}
|
|
423
|
+
async fetchTokenDecimals(chainId, token) {
|
|
424
|
+
const metadata = this.chainMetadataByChainId.get(chainId);
|
|
425
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(metadata, `SwapsXyzBridge: no chain metadata configured for chainId ${chainId}`);
|
|
426
|
+
if (metadata.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Sealevel) {
|
|
427
|
+
const rpcUrl = metadata.rpcUrls[0]?.http;
|
|
428
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(rpcUrl, `SwapsXyzBridge: no RPC URL configured for chainId ${chainId}`);
|
|
429
|
+
const supply = await this.solanaConnectionFactory(rpcUrl).getTokenSupply(new _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .PublicKey */ .J3(token));
|
|
430
|
+
return supply.value.decimals;
|
|
431
|
+
}
|
|
432
|
+
if (token.toLowerCase() === NATIVE_TOKEN_ADDRESS) {
|
|
433
|
+
const decimals = metadata.nativeToken?.decimals;
|
|
434
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(decimals !== undefined, `Missing native token decimals for ${metadata.name}`);
|
|
435
|
+
return decimals;
|
|
436
|
+
}
|
|
437
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .isEVMLike */ .Us)(metadata.protocol), `SwapsXyzBridge: unsupported token decimals protocol ${metadata.protocol}`);
|
|
438
|
+
const rpcUrl = metadata.rpcUrls[0]?.http;
|
|
439
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(rpcUrl, `SwapsXyzBridge: no RPC URL configured for chainId ${chainId}`);
|
|
440
|
+
const provider = metadata.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron
|
|
441
|
+
? new _humanode_hyperlane_tron_sdk_runtime__WEBPACK_IMPORTED_MODULE_0__/* .TronJsonRpcProvider */ .yb(rpcUrl)
|
|
442
|
+
: this.evmProviderFactory(rpcUrl);
|
|
443
|
+
const tokenAddress = metadata.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron
|
|
444
|
+
? this.tronAddressToEvm(token)
|
|
445
|
+
: token;
|
|
446
|
+
const tokenContract = new ethers__WEBPACK_IMPORTED_MODULE_7__.Contract(tokenAddress, ERC20_DECIMALS_ABI, provider);
|
|
447
|
+
return Number(await tokenContract.decimals());
|
|
448
|
+
}
|
|
449
|
+
async toBridgeQuote(params, response) {
|
|
450
|
+
let feeCosts = 0n;
|
|
451
|
+
for (const fee of [
|
|
452
|
+
response.protocolFee,
|
|
453
|
+
response.applicationFee,
|
|
454
|
+
response.bridgeFee,
|
|
455
|
+
]) {
|
|
456
|
+
if (fee?.amount)
|
|
457
|
+
feeCosts += BigInt(fee.amount);
|
|
458
|
+
}
|
|
459
|
+
const fromAmount = BigInt((response.amountInMax ?? response.amountIn).amount);
|
|
460
|
+
await this.validateQuoteLoss(params, response, fromAmount, BigInt(response.amountOut.amount));
|
|
461
|
+
return {
|
|
462
|
+
id: response.txId,
|
|
463
|
+
tool: response.bridgeIds?.join('+') || 'swapsxyz',
|
|
464
|
+
fromAmount,
|
|
465
|
+
toAmount: BigInt(response.amountOut.amount),
|
|
466
|
+
toAmountMin: await this.executionMinimum(params, response),
|
|
467
|
+
executionDuration: response.estimatedTxTime ?? 0,
|
|
468
|
+
gasCosts: 0n,
|
|
469
|
+
feeCosts,
|
|
470
|
+
route: { actionResponse: response },
|
|
471
|
+
requestParams: params,
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
async executionMinimum(params, response) {
|
|
475
|
+
let expectedFloor;
|
|
476
|
+
if (params.toAmount !== undefined) {
|
|
477
|
+
expectedFloor = params.toAmount;
|
|
478
|
+
}
|
|
479
|
+
else {
|
|
480
|
+
const maxLoss = this.config.maxQuoteLossBps;
|
|
481
|
+
// No economic drift budget was configured for this exact-input request.
|
|
482
|
+
if (maxLoss === undefined)
|
|
483
|
+
return BigInt(response.amountOutMin.amount);
|
|
484
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(params.fromAmount !== undefined, 'Missing exact-input amount');
|
|
485
|
+
const [sourceDecimals, destinationDecimals] = await Promise.all([
|
|
486
|
+
this.getTokenDecimals(params.fromChain, params.fromToken),
|
|
487
|
+
this.getTokenDecimals(params.toChain, params.toToken),
|
|
488
|
+
]);
|
|
489
|
+
expectedFloor = (0,_utils_quoteBudget_js__WEBPACK_IMPORTED_MODULE_14__/* .minimumOutputForLoss */ .c)(params.fromAmount, sourceDecimals, destinationDecimals, maxLoss);
|
|
490
|
+
}
|
|
491
|
+
const minimum = (expectedFloor *
|
|
492
|
+
(BPS_DENOMINATOR - BigInt(this.getSlippageBps(params.slippage)))) /
|
|
493
|
+
BPS_DENOMINATOR;
|
|
494
|
+
return minimum > 0n ? minimum : 1n;
|
|
495
|
+
}
|
|
496
|
+
async executeUnlocked(quote, privateKeys, options) {
|
|
497
|
+
this.validateQuoteParams(quote.requestParams);
|
|
498
|
+
const { fromChain, toChain } = quote.requestParams;
|
|
499
|
+
const metadata = this.chainMetadataByChainId.get(fromChain);
|
|
500
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(metadata, `SwapsXyzBridge.execute: no chain metadata configured for chainId ${fromChain}`);
|
|
501
|
+
const rpcUrl = metadata.rpcUrls[0]?.http;
|
|
502
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(rpcUrl, `SwapsXyzBridge.execute: no RPC URL configured for chainId ${fromChain}`);
|
|
503
|
+
if (metadata.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Sealevel) {
|
|
504
|
+
return this.executeSolana(quote, privateKeys, rpcUrl, options);
|
|
505
|
+
}
|
|
506
|
+
if (metadata.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron) {
|
|
507
|
+
return this.executeTron(quote, privateKeys, rpcUrl, options);
|
|
508
|
+
}
|
|
509
|
+
const privateKey = privateKeys[_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Ethereum];
|
|
510
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(privateKey, 'SwapsXyzBridge.execute requires an Ethereum (EVM) private key');
|
|
511
|
+
const provider = this.evmProviderFactory(rpcUrl);
|
|
512
|
+
const signer = new ethers__WEBPACK_IMPORTED_MODULE_7__.Wallet((0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__/* .ensure0x */ .Ho)(privateKey), provider);
|
|
513
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(this.addressesEqual(await signer.getAddress(), quote.requestParams.fromAddress, fromChain), 'SwapsXyzBridge.execute signer does not match quote fromAddress');
|
|
514
|
+
for (let attempt = 0; attempt < MAX_PREPARATION_ATTEMPTS; attempt++) {
|
|
515
|
+
const { response: fresh, preparedAt } = await this.prepare(quote);
|
|
516
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isEvmTx */ .VQ)(fresh.tx), 'SwapsXyzBridge.execute requires an EVM tx');
|
|
517
|
+
if (fresh.requiresTokenApproval) {
|
|
518
|
+
await (0,_erc20Approve_js__WEBPACK_IMPORTED_MODULE_5__/* .approveErc20IfNeeded */ .Cp)(signer, quote.requestParams.fromToken, fresh.tx.to, BigInt((fresh.amountInMax ?? fresh.amountIn).amount), this.logger, {
|
|
519
|
+
contractFactory: this.config.erc20ContractFactory,
|
|
520
|
+
onApproval: options?.onApproval,
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
if (Date.now() - preparedAt >= MAX_TRANSACTION_AGE_MS)
|
|
524
|
+
continue;
|
|
525
|
+
await this.validatePreparedEvmOrder(quote, fresh);
|
|
526
|
+
if (Date.now() - preparedAt >= MAX_TRANSACTION_AGE_MS)
|
|
527
|
+
continue;
|
|
528
|
+
const transaction = {
|
|
529
|
+
to: fresh.tx.to,
|
|
530
|
+
data: fresh.tx.data,
|
|
531
|
+
value: fresh.tx.value ? ethers__WEBPACK_IMPORTED_MODULE_7__.BigNumber.from(fresh.tx.value) : undefined,
|
|
532
|
+
};
|
|
533
|
+
await signer.estimateGas(transaction);
|
|
534
|
+
await options?.onTransferId?.(fresh.txId);
|
|
535
|
+
const txResponse = await (0,_humanode_hyperlane_sdk__WEBPACK_IMPORTED_MODULE_15__/* .submitEvmLikeTransaction */ .k)(signer, transaction, options);
|
|
536
|
+
// Source-action tracking takes priority over waiting here: once a
|
|
537
|
+
// source transaction is broadcast, receipt/status failures must not cause
|
|
538
|
+
// the planner to send the same movement again.
|
|
539
|
+
void this.registerIfRequired(fresh, txResponse.hash);
|
|
540
|
+
return {
|
|
541
|
+
txHash: txResponse.hash,
|
|
542
|
+
fromChain,
|
|
543
|
+
toChain,
|
|
544
|
+
transferId: fresh.txId,
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
throw new Error('swaps.xyz transaction expired repeatedly during preparation');
|
|
548
|
+
}
|
|
549
|
+
/** Validate a fresh unsigned payload without keys, approvals or signing. */
|
|
550
|
+
async prepare(quote) {
|
|
551
|
+
this.validateQuoteParams(quote.requestParams);
|
|
552
|
+
const metadata = this.chainMetadataByChainId.get(quote.requestParams.fromChain);
|
|
553
|
+
if (metadata?.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Sealevel) {
|
|
554
|
+
const rpcUrl = metadata.rpcUrls[0]?.http;
|
|
555
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(rpcUrl, 'Missing Solana RPC for unsigned preparation');
|
|
556
|
+
return this.prepareSolana(quote, rpcUrl);
|
|
557
|
+
}
|
|
558
|
+
let preparedAt = Date.now();
|
|
559
|
+
const response = await this.client.getAction(this.buildActionRequest(quote.requestParams), (startedAt) => {
|
|
560
|
+
preparedAt = startedAt;
|
|
561
|
+
});
|
|
562
|
+
if (metadata?.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron)
|
|
563
|
+
this.validatePreparedTronOrder(quote, response);
|
|
564
|
+
else
|
|
565
|
+
await this.validatePreparedEvmOrder(quote, response);
|
|
566
|
+
await this.validateQuoteLoss(quote.requestParams, response, BigInt((response.amountInMax ?? response.amountIn).amount), BigInt(response.amountOut.amount));
|
|
567
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Date.now() - preparedAt < MAX_TRANSACTION_AGE_MS, 'swaps.xyz transaction expired during preparation');
|
|
568
|
+
return { response, preparedAt };
|
|
569
|
+
}
|
|
570
|
+
async validatePreparedEvmOrder(quote, fresh) {
|
|
571
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isEvmTx */ .VQ)(fresh.tx), 'SwapsXyzBridge.execute requires an EVM tx');
|
|
572
|
+
this.validateActionResponse(fresh, quote, 'evm');
|
|
573
|
+
}
|
|
574
|
+
async executeSolana(quote, privateKeys, rpcUrl, options) {
|
|
575
|
+
const { fromChain, toChain } = quote.requestParams;
|
|
576
|
+
const rawKey = privateKeys[_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Sealevel];
|
|
577
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(rawKey, 'SwapsXyzBridge.execute requires a Sealevel private key for Solana-source routes');
|
|
578
|
+
const keypair = _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .Keypair */ .AX.fromSecretKey((0,_utils_solanaKeyParser_js__WEBPACK_IMPORTED_MODULE_4__/* .parseSolanaPrivateKey */ .E)(rawKey));
|
|
579
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(keypair.publicKey.toBase58() === quote.requestParams.fromAddress, 'SwapsXyzBridge.execute Solana signer does not match quote fromAddress');
|
|
580
|
+
const { response: fresh, transaction } = await this.prepareSolana(quote, rpcUrl);
|
|
581
|
+
const connection = this.solanaConnectionFactory(rpcUrl);
|
|
582
|
+
await options?.onTransferId?.(fresh.txId);
|
|
583
|
+
transaction.sign([keypair]);
|
|
584
|
+
const signedSignature = (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_16__/* .bufferToBase58 */ .un)(Buffer.from(transaction.signatures[0]));
|
|
585
|
+
const signature = await new _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_12__/* .TransactionSubmission */ .P(options).submit(() => connection.sendRawTransaction(transaction.serialize(), {
|
|
586
|
+
skipPreflight: false,
|
|
587
|
+
maxRetries: 5,
|
|
588
|
+
}), (submittedSignature) => {
|
|
589
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(submittedSignature === signedSignature, 'swaps.xyz RPC returned a different Solana signature');
|
|
590
|
+
return signedSignature;
|
|
591
|
+
}, signedSignature);
|
|
592
|
+
void this.registerIfRequired(fresh, signature);
|
|
593
|
+
return {
|
|
594
|
+
txHash: signature,
|
|
595
|
+
fromChain,
|
|
596
|
+
toChain,
|
|
597
|
+
transferId: fresh.txId,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
async prepareSolana(quote, rpcUrl) {
|
|
601
|
+
let preparedAt = Date.now();
|
|
602
|
+
const signer = new _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .PublicKey */ .J3(quote.requestParams.fromAddress);
|
|
603
|
+
const fresh = await this.client.getAction(this.buildActionRequest(quote.requestParams), (startedAt) => {
|
|
604
|
+
preparedAt = startedAt;
|
|
605
|
+
});
|
|
606
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isSolanaTx */ .DZ)(fresh.tx), 'SwapsXyzBridge.execute requires a Solana tx');
|
|
607
|
+
this.validateSolanaActionResponse(fresh, quote);
|
|
608
|
+
await this.validateQuoteLoss(quote.requestParams, fresh, BigInt((fresh.amountInMax ?? fresh.amountIn).amount), BigInt(fresh.amountOut.amount));
|
|
609
|
+
const transaction = _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .VersionedTransaction */ .Kt.deserialize(Buffer.from(fresh.tx.base64Tx, 'base64'));
|
|
610
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(transaction.message.header.numRequiredSignatures === 1, 'SwapsXyzBridge.execute Solana transaction must require exactly one signer');
|
|
611
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(transaction.message.staticAccountKeys[0]?.equals(signer), 'SwapsXyzBridge.execute Solana payer does not match inventory signer');
|
|
612
|
+
if (fresh.tx.payer !== undefined) {
|
|
613
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(fresh.tx.payer === signer.toBase58(), `SwapsXyzBridge.execute Solana payer ${fresh.tx.payer} does not match signer ${signer.toBase58()}`);
|
|
614
|
+
}
|
|
615
|
+
const connection = this.solanaConnectionFactory(rpcUrl);
|
|
616
|
+
const addressLookupTables = await this.resolveAddressLookupTables(connection, transaction);
|
|
617
|
+
const accountKeys = transaction.message.getAccountKeys({
|
|
618
|
+
addressLookupTableAccounts: addressLookupTables,
|
|
619
|
+
});
|
|
620
|
+
const writableKeys = accountKeys
|
|
621
|
+
.keySegments()
|
|
622
|
+
.flat()
|
|
623
|
+
.filter((_, index) => transaction.message.isAccountWritable(index));
|
|
624
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(writableKeys.some((key) => key.equals(signer)), 'SwapsXyzBridge.execute Solana payer must be writable');
|
|
625
|
+
const preAccounts = await connection.getMultipleAccountsInfoAndContext(writableKeys, { commitment: 'confirmed' });
|
|
626
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(preAccounts.value.length === writableKeys.length, 'SwapsXyzBridge.execute Solana preflight did not return every writable account');
|
|
627
|
+
const { blockhash } = await connection.getLatestBlockhash('confirmed');
|
|
628
|
+
transaction.message.recentBlockhash = blockhash;
|
|
629
|
+
const fee = await connection.getFeeForMessage(transaction.message, 'confirmed');
|
|
630
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(fee.value !== null, 'SwapsXyzBridge.execute could not calculate the Solana transaction fee');
|
|
631
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Number.isSafeInteger(fee.value) && fee.value >= 0, 'SwapsXyzBridge.execute Solana transaction fee must be a non-negative safe integer');
|
|
632
|
+
const feeDiagnostics = {
|
|
633
|
+
chainId: quote.requestParams.fromChain,
|
|
634
|
+
transactionFeeLamports: fee.value,
|
|
635
|
+
maxSolanaTransactionFeeLamports: this.maxSolanaTransactionFeeLamports,
|
|
636
|
+
solanaTransactionFeeWarningLamports: this.solanaTransactionFeeWarningLamports,
|
|
637
|
+
};
|
|
638
|
+
if (fee.value > this.solanaTransactionFeeWarningLamports) {
|
|
639
|
+
this.logger.warn(feeDiagnostics, 'SwapsXyz Solana transaction fee exceeds warning threshold');
|
|
640
|
+
}
|
|
641
|
+
else {
|
|
642
|
+
this.logger.info(feeDiagnostics, 'SwapsXyz Solana transaction fee');
|
|
643
|
+
}
|
|
644
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(fee.value <= this.maxSolanaTransactionFeeLamports, `SwapsXyzBridge.execute Solana transaction fee ${fee.value} exceeds maximum ${this.maxSolanaTransactionFeeLamports}`);
|
|
645
|
+
const simulation = await connection.simulateTransaction(transaction, {
|
|
646
|
+
sigVerify: false,
|
|
647
|
+
commitment: 'confirmed',
|
|
648
|
+
minContextSlot: preAccounts.context.slot,
|
|
649
|
+
accounts: {
|
|
650
|
+
encoding: 'base64',
|
|
651
|
+
addresses: writableKeys.map((key) => key.toBase58()),
|
|
652
|
+
},
|
|
653
|
+
});
|
|
654
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(simulation.value.err === null, `SwapsXyzBridge.execute Solana simulation failed: ${JSON.stringify(simulation.value.err)}`);
|
|
655
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(simulation.value.accounts?.length === writableKeys.length, 'SwapsXyzBridge.execute Solana simulation did not return every writable account');
|
|
656
|
+
const signerDebit = this.validateSolanaAccountEffects(quote, fresh, signer, writableKeys, preAccounts.value, simulation.value.accounts, fee.value);
|
|
657
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(Date.now() - preparedAt < MAX_TRANSACTION_AGE_MS, 'swaps.xyz transaction expired during preparation');
|
|
658
|
+
return {
|
|
659
|
+
response: fresh,
|
|
660
|
+
preparedAt,
|
|
661
|
+
transaction,
|
|
662
|
+
solanaDiagnostics: {
|
|
663
|
+
transactionFeeLamports: fee.value,
|
|
664
|
+
maxSolanaTransactionFeeLamports: this.maxSolanaTransactionFeeLamports,
|
|
665
|
+
solanaTransactionFeeWarningLamports: this.solanaTransactionFeeWarningLamports,
|
|
666
|
+
maxSolanaNativeSpendLamports: this.maxSolanaNativeSpendLamports,
|
|
667
|
+
simulatedSignerDebitLamports: signerDebit.toString(),
|
|
668
|
+
computeUnitsConsumed: simulation.value.unitsConsumed,
|
|
669
|
+
accountContextSlot: preAccounts.context.slot,
|
|
670
|
+
simulationContextSlot: simulation.context.slot,
|
|
671
|
+
},
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
async executeTron(quote, privateKeys, rpcUrl, options) {
|
|
675
|
+
const { fromChain, toChain } = quote.requestParams;
|
|
676
|
+
const privateKey = privateKeys[_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron];
|
|
677
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(privateKey, 'SwapsXyzBridge.execute requires a Tron private key for Tron-source routes');
|
|
678
|
+
const signer = this.tronWalletFactory((0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__/* .ensure0x */ .Ho)(privateKey), rpcUrl);
|
|
679
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(this.addressesEqual(await signer.getAddress(), quote.requestParams.fromAddress, fromChain), 'SwapsXyzBridge.execute Tron signer does not match quote fromAddress');
|
|
680
|
+
for (let attempt = 0; attempt < MAX_PREPARATION_ATTEMPTS; attempt++) {
|
|
681
|
+
const { response: fresh, preparedAt } = await this.prepare(quote);
|
|
682
|
+
const freshTx = fresh.tx;
|
|
683
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isTronTx */ .Y2)(freshTx), 'SwapsXyzBridge.execute requires a Tron tx');
|
|
684
|
+
const transactionTo = this.tronAddressToEvm(freshTx.to);
|
|
685
|
+
const isNativeSource = this.addressesEqual(quote.requestParams.fromToken, NATIVE_TOKEN_ADDRESS, fromChain);
|
|
686
|
+
const sourceToken = isNativeSource
|
|
687
|
+
? undefined
|
|
688
|
+
: this.tronAddressToEvm(quote.requestParams.fromToken);
|
|
689
|
+
let transaction;
|
|
690
|
+
if (freshTx.toExtra === null) {
|
|
691
|
+
const transferAmount = ethers__WEBPACK_IMPORTED_MODULE_7__.BigNumber.from(freshTx.value);
|
|
692
|
+
transaction = isNativeSource
|
|
693
|
+
? { to: transactionTo, value: transferAmount }
|
|
694
|
+
: {
|
|
695
|
+
to: sourceToken,
|
|
696
|
+
data: ERC20_TRANSFER_INTERFACE.encodeFunctionData('transfer', [
|
|
697
|
+
transactionTo,
|
|
698
|
+
transferAmount,
|
|
699
|
+
]),
|
|
700
|
+
value: 0,
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
else {
|
|
704
|
+
if (fresh.requiresTokenApproval) {
|
|
705
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(sourceToken, 'Native Tron routes must not require approval');
|
|
706
|
+
await (0,_erc20Approve_js__WEBPACK_IMPORTED_MODULE_5__/* .approveErc20IfNeeded */ .Cp)(signer, sourceToken, transactionTo, BigInt((fresh.amountInMax ?? fresh.amountIn).amount), this.logger, {
|
|
707
|
+
contractFactory: this.config.erc20ContractFactory,
|
|
708
|
+
onApproval: options?.onApproval,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
if (Date.now() - preparedAt >= MAX_TRANSACTION_AGE_MS)
|
|
712
|
+
continue;
|
|
713
|
+
this.validatePreparedTronOrder(quote, fresh);
|
|
714
|
+
transaction = {
|
|
715
|
+
to: transactionTo,
|
|
716
|
+
data: (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__/* .ensure0x */ .Ho)(freshTx.toExtra),
|
|
717
|
+
value: ethers__WEBPACK_IMPORTED_MODULE_7__.BigNumber.from(freshTx.value),
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
await signer.estimateGas(transaction);
|
|
721
|
+
await options?.onTransferId?.(fresh.txId);
|
|
722
|
+
const txResponse = await (0,_humanode_hyperlane_sdk__WEBPACK_IMPORTED_MODULE_15__/* .submitEvmLikeTransaction */ .k)(signer, transaction, options);
|
|
723
|
+
const txHash = (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__/* .ensure0x */ .Ho)(txResponse.hash);
|
|
724
|
+
void this.registerIfRequired(fresh, txHash);
|
|
725
|
+
return {
|
|
726
|
+
txHash,
|
|
727
|
+
fromChain,
|
|
728
|
+
toChain,
|
|
729
|
+
transferId: fresh.txId,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
throw new Error('swaps.xyz transaction expired repeatedly during preparation');
|
|
733
|
+
}
|
|
734
|
+
async resolveAddressLookupTables(connection, transaction) {
|
|
735
|
+
return Promise.all(transaction.message.addressTableLookups.map(async (lookup) => {
|
|
736
|
+
const { value } = await connection.getAddressLookupTable(lookup.accountKey, { commitment: 'confirmed' });
|
|
737
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(value, `SwapsXyzBridge.execute Solana address lookup table ${lookup.accountKey.toBase58()} was not found`);
|
|
738
|
+
return value;
|
|
739
|
+
}));
|
|
740
|
+
}
|
|
741
|
+
validateActionResponseMetadata(response, quote, expectedVmId) {
|
|
742
|
+
const params = quote.requestParams;
|
|
743
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(response.vmId === undefined || response.vmId === expectedVmId, `SwapsXyzBridge.execute vmId ${response.vmId} does not match ${expectedVmId}`);
|
|
744
|
+
if (response.tx.chainId !== undefined) {
|
|
745
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(response.tx.chainId === params.fromChain, `SwapsXyzBridge.execute tx chainId ${response.tx.chainId} does not match requested ${params.fromChain}`);
|
|
746
|
+
}
|
|
747
|
+
if (response.amountIn.chainId !== undefined) {
|
|
748
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(response.amountIn.chainId === params.fromChain, `SwapsXyzBridge.execute amountIn chainId ${response.amountIn.chainId} does not match requested ${params.fromChain}`);
|
|
749
|
+
}
|
|
750
|
+
if (response.amountOut.chainId !== undefined) {
|
|
751
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(response.amountOut.chainId === params.toChain, `SwapsXyzBridge.execute amountOut chainId ${response.amountOut.chainId} does not match requested ${params.toChain}`);
|
|
752
|
+
}
|
|
753
|
+
if (response.amountIn.address !== undefined) {
|
|
754
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(this.addressesEqual(response.amountIn.address, params.fromToken, params.fromChain), `SwapsXyzBridge.execute amountIn token ${response.amountIn.address} does not match requested ${params.fromToken}`);
|
|
755
|
+
}
|
|
756
|
+
if (response.amountOut.address !== undefined) {
|
|
757
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(this.addressesEqual(response.amountOut.address, params.toToken, params.toChain), `SwapsXyzBridge.execute amountOut token ${response.amountOut.address} does not match requested ${params.toToken}`);
|
|
758
|
+
}
|
|
759
|
+
const freshFromAmount = BigInt((response.amountInMax ?? response.amountIn).amount);
|
|
760
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(freshFromAmount <= quote.fromAmount, `SwapsXyzBridge.execute fresh input ${freshFromAmount} exceeds accepted input cap ${quote.fromAmount}`);
|
|
761
|
+
const freshToAmountMin = BigInt(response.amountOutMin.amount);
|
|
762
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(freshToAmountMin >= quote.toAmountMin, `SwapsXyzBridge.execute fresh minimum output ${freshToAmountMin} is below accepted minimum ${quote.toAmountMin}`);
|
|
763
|
+
}
|
|
764
|
+
validateActionResponse(response, quote, expectedVmId) {
|
|
765
|
+
this.validateActionResponseMetadata(response, quote, expectedVmId);
|
|
766
|
+
const params = quote.requestParams;
|
|
767
|
+
const tx = response.tx;
|
|
768
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isEvmTx */ .VQ)(tx), 'SwapsXyzBridge.execute EVM transaction is invalid');
|
|
769
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(ethers__WEBPACK_IMPORTED_MODULE_7__.utils.isAddress(tx.to), `SwapsXyzBridge.execute transaction target ${tx.to} is invalid`);
|
|
770
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(/^0x(?:[0-9a-fA-F]{2})*$/.test(tx.data), 'SwapsXyzBridge.execute transaction calldata is invalid');
|
|
771
|
+
const freshFromAmount = BigInt((response.amountInMax ?? response.amountIn).amount);
|
|
772
|
+
const freshValue = transactionValue(response.tx, 'SwapsXyzBridge.execute fresh');
|
|
773
|
+
const nativePrincipal = this.addressesEqual(params.fromToken, NATIVE_TOKEN_ADDRESS, params.fromChain)
|
|
774
|
+
? freshFromAmount
|
|
775
|
+
: 0n;
|
|
776
|
+
const minimumNativePrincipal = this.addressesEqual(params.fromToken, NATIVE_TOKEN_ADDRESS, params.fromChain)
|
|
777
|
+
? BigInt(response.amountIn.amount)
|
|
778
|
+
: 0n;
|
|
779
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(freshValue >= minimumNativePrincipal, 'SwapsXyzBridge.execute transaction value is below the native token input');
|
|
780
|
+
const nativeFee = freshValue > nativePrincipal ? freshValue - nativePrincipal : 0n;
|
|
781
|
+
const maxNativeFee = this.config.maxEvmNativeFeeWei ?? DEFAULT_MAX_EVM_NATIVE_FEE_WEI;
|
|
782
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(nativeFee <= maxNativeFee, `SwapsXyzBridge.execute native fee ${nativeFee} exceeds configured maximum ${maxNativeFee}`);
|
|
783
|
+
}
|
|
784
|
+
validatePreparedTronOrder(quote, response) {
|
|
785
|
+
this.validateActionResponseMetadata(response, quote, 'alt-vm');
|
|
786
|
+
const tx = response.tx;
|
|
787
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isTronTx */ .Y2)(tx), 'SwapsXyzBridge.execute requires a Tron tx');
|
|
788
|
+
const target = this.tronAddressToEvm(tx.to);
|
|
789
|
+
const isNativeSource = this.addressesEqual(quote.requestParams.fromToken, NATIVE_TOKEN_ADDRESS, quote.requestParams.fromChain);
|
|
790
|
+
const sourceToken = isNativeSource
|
|
791
|
+
? undefined
|
|
792
|
+
: this.tronAddressToEvm(quote.requestParams.fromToken);
|
|
793
|
+
const freshFromAmount = BigInt((response.amountInMax ?? response.amountIn).amount);
|
|
794
|
+
if (tx.toExtra === null) {
|
|
795
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(response.requiresTokenApproval === false, 'SwapsXyzBridge.execute direct Tron transfers must not require token approval');
|
|
796
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(sourceToken === undefined ||
|
|
797
|
+
target.toLowerCase() !== sourceToken.toLowerCase(), 'SwapsXyzBridge.execute rejects direct Tron deposits to the source token');
|
|
798
|
+
const transferAmount = BigInt(tx.value);
|
|
799
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(transferAmount >= BigInt(response.amountIn.amount) &&
|
|
800
|
+
transferAmount <= freshFromAmount, `SwapsXyzBridge.execute Tron transfer amount ${transferAmount} is outside fresh input bounds`);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(/^0x(?:[0-9a-fA-F]{2})*$/.test((0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_13__/* .ensure0x */ .Ho)(tx.toExtra)), 'SwapsXyzBridge.execute Tron calldata is invalid');
|
|
804
|
+
const nativeValue = BigInt(tx.value);
|
|
805
|
+
const nativePrincipal = isNativeSource ? freshFromAmount : 0n;
|
|
806
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(nativeValue >= (isNativeSource ? BigInt(response.amountIn.amount) : 0n), 'SwapsXyzBridge.execute Tron transaction value is below the native token input');
|
|
807
|
+
const nativeFee = nativeValue > nativePrincipal ? nativeValue - nativePrincipal : 0n;
|
|
808
|
+
const maxNativeFee = this.config.maxTronNativeFeeSun ?? DEFAULT_MAX_TRON_NATIVE_FEE_SUN;
|
|
809
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(nativeFee <= maxNativeFee, `SwapsXyzBridge.execute Tron native fee ${nativeFee} exceeds configured maximum ${maxNativeFee}`);
|
|
810
|
+
}
|
|
811
|
+
validateSolanaActionResponse(response, quote) {
|
|
812
|
+
this.validateActionResponseMetadata(response, quote, 'solana');
|
|
813
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isSolanaTx */ .DZ)(response.tx), 'SwapsXyzBridge.execute Solana transaction is invalid');
|
|
814
|
+
}
|
|
815
|
+
validateSolanaAccountEffects(quote, response, signer, writableKeys, preAccounts, postAccounts, transactionFeeLamports) {
|
|
816
|
+
const sourceMint = new _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .PublicKey */ .J3(quote.requestParams.fromToken);
|
|
817
|
+
let sourceDebit = 0n;
|
|
818
|
+
let signerLamportDebit;
|
|
819
|
+
for (let index = 0; index < writableKeys.length; index++) {
|
|
820
|
+
const address = writableKeys[index];
|
|
821
|
+
const pre = preAccounts[index];
|
|
822
|
+
const post = postAccounts[index];
|
|
823
|
+
if (address.equals(signer)) {
|
|
824
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(pre && post, 'Solana signer account is missing from simulation');
|
|
825
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(post.owner === pre.owner.toBase58() &&
|
|
826
|
+
post.executable === pre.executable &&
|
|
827
|
+
simulatedAccountData(post).equals(pre.data), 'SwapsXyzBridge.execute Solana transaction changes signer account ownership or data');
|
|
828
|
+
signerLamportDebit =
|
|
829
|
+
pre.lamports > post.lamports
|
|
830
|
+
? BigInt(pre.lamports - post.lamports)
|
|
831
|
+
: 0n;
|
|
832
|
+
}
|
|
833
|
+
if (!pre)
|
|
834
|
+
continue;
|
|
835
|
+
const preToken = decodeTokenAccount(pre.owner, pre.data);
|
|
836
|
+
if (!preToken?.owner.equals(signer))
|
|
837
|
+
continue;
|
|
838
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(post, `SwapsXyzBridge.execute Solana transaction closes signer token account ${address.toBase58()}`);
|
|
839
|
+
const postData = simulatedAccountData(post);
|
|
840
|
+
const postToken = decodeTokenAccount(new _solana_web3_js__WEBPACK_IMPORTED_MODULE_1__/* .PublicKey */ .J3(post.owner), postData);
|
|
841
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(postToken, `SwapsXyzBridge.execute Solana transaction changes signer token account ${address.toBase58()} into a non-token account`);
|
|
842
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(postToken.mint.equals(preToken.mint) &&
|
|
843
|
+
postToken.owner.equals(preToken.owner) &&
|
|
844
|
+
postToken.delegateOption === preToken.delegateOption &&
|
|
845
|
+
postToken.delegate.equals(preToken.delegate) &&
|
|
846
|
+
postToken.delegatedAmount === preToken.delegatedAmount &&
|
|
847
|
+
postToken.closeAuthorityOption === preToken.closeAuthorityOption &&
|
|
848
|
+
postToken.closeAuthority.equals(preToken.closeAuthority) &&
|
|
849
|
+
postToken.state === preToken.state, `SwapsXyzBridge.execute Solana transaction changes authority or state for signer token account ${address.toBase58()}`);
|
|
850
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(postData.length === pre.data.length, `SwapsXyzBridge.execute Solana transaction changes data length for signer token account ${address.toBase58()}`);
|
|
851
|
+
const normalizedPostData = Buffer.from(postData);
|
|
852
|
+
pre.data.copy(normalizedPostData, TOKEN_AMOUNT_OFFSET, TOKEN_AMOUNT_OFFSET, TOKEN_AMOUNT_OFFSET + 8);
|
|
853
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(normalizedPostData.equals(pre.data), `SwapsXyzBridge.execute Solana transaction changes non-balance data for signer token account ${address.toBase58()}`);
|
|
854
|
+
const debit = preToken.amount > postToken.amount
|
|
855
|
+
? preToken.amount - postToken.amount
|
|
856
|
+
: 0n;
|
|
857
|
+
if (preToken.mint.equals(sourceMint)) {
|
|
858
|
+
sourceDebit += debit;
|
|
859
|
+
}
|
|
860
|
+
else {
|
|
861
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(debit === 0n, `SwapsXyzBridge.execute Solana transaction debits non-source token account ${address.toBase58()}`);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(signerLamportDebit !== undefined, 'SwapsXyzBridge.execute Solana simulation omitted the signer account');
|
|
865
|
+
const maxLamportDebit = BigInt(transactionFeeLamports) +
|
|
866
|
+
BigInt(this.maxSolanaNativeSpendLamports);
|
|
867
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(signerLamportDebit <= maxLamportDebit, `SwapsXyzBridge.execute Solana native spend ${signerLamportDebit} exceeds maximum ${maxLamportDebit}`);
|
|
868
|
+
if (quote.requestParams.fromAmount !== undefined) {
|
|
869
|
+
const expectedDebit = quote.requestParams.fromAmount;
|
|
870
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(sourceDebit === expectedDebit, `SwapsXyzBridge.execute Solana source-token debit ${sourceDebit} does not match exact input ${expectedDebit}`);
|
|
871
|
+
}
|
|
872
|
+
else {
|
|
873
|
+
const maxDebit = BigInt((response.amountInMax ?? response.amountIn).amount);
|
|
874
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(sourceDebit > 0n && sourceDebit <= maxDebit, `SwapsXyzBridge.execute Solana source-token debit ${sourceDebit} exceeds exact-output cap ${maxDebit}`);
|
|
875
|
+
}
|
|
876
|
+
return signerLamportDebit;
|
|
877
|
+
}
|
|
878
|
+
async validateQuoteLoss(params, response, fromAmount, toAmount) {
|
|
879
|
+
const amountIn = BigInt(response.amountIn.amount);
|
|
880
|
+
const maximumInput = BigInt((response.amountInMax ?? response.amountIn).amount);
|
|
881
|
+
const minimumOutput = BigInt(response.amountOutMin.amount);
|
|
882
|
+
const expectedOutput = BigInt(response.amountOut.amount);
|
|
883
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(amountIn > 0n && maximumInput >= amountIn, 'swaps.xyz invalid input amount bounds');
|
|
884
|
+
if (params.fromAmount !== undefined) {
|
|
885
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(amountIn === params.fromAmount && maximumInput === params.fromAmount, 'swaps.xyz exact input does not match the requested amount');
|
|
886
|
+
}
|
|
887
|
+
if (params.toAmount !== undefined) {
|
|
888
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(expectedOutput >= params.toAmount, 'swaps.xyz expected output is below the requested amount');
|
|
889
|
+
}
|
|
890
|
+
const slippageFloor = (expectedOutput *
|
|
891
|
+
(BPS_DENOMINATOR - BigInt(this.getSlippageBps(params.slippage)))) /
|
|
892
|
+
BPS_DENOMINATOR;
|
|
893
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(minimumOutput > 0n &&
|
|
894
|
+
minimumOutput <= expectedOutput &&
|
|
895
|
+
minimumOutput >= slippageFloor, 'swaps.xyz minimum output exceeds the requested slippage');
|
|
896
|
+
const maxQuoteLossBps = this.config.maxQuoteLossBps;
|
|
897
|
+
if (maxQuoteLossBps === undefined)
|
|
898
|
+
return;
|
|
899
|
+
const [sourceDecimals, destinationDecimals] = await Promise.all([
|
|
900
|
+
this.getTokenDecimals(params.fromChain, params.fromToken),
|
|
901
|
+
this.getTokenDecimals(params.toChain, params.toToken),
|
|
902
|
+
]);
|
|
903
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(sourceDecimals <= 255 && destinationDecimals <= 255, 'swaps.xyz quote token decimals must be at most 255');
|
|
904
|
+
for (const amount of [response.amountIn, response.amountInMax]) {
|
|
905
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(amount?.decimals === undefined || amount.decimals === sourceDecimals, 'swaps.xyz source token decimals do not match chain data');
|
|
906
|
+
}
|
|
907
|
+
for (const amount of [response.amountOut, response.amountOutMin]) {
|
|
908
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(amount.decimals === undefined ||
|
|
909
|
+
amount.decimals === destinationDecimals, 'swaps.xyz destination token decimals do not match chain data');
|
|
910
|
+
}
|
|
911
|
+
const commonDecimals = Math.max(sourceDecimals, destinationDecimals);
|
|
912
|
+
const normalizedFromAmount = fromAmount * 10n ** BigInt(commonDecimals - sourceDecimals);
|
|
913
|
+
const normalizedToAmount = toAmount * 10n ** BigInt(commonDecimals - destinationDecimals);
|
|
914
|
+
const lossBps = normalizedToAmount >= normalizedFromAmount
|
|
915
|
+
? 0n
|
|
916
|
+
: ceilDiv((normalizedFromAmount - normalizedToAmount) * BPS_DENOMINATOR, normalizedFromAmount);
|
|
917
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .v)(lossBps <= BigInt(maxQuoteLossBps), `swaps.xyz quote loss ${lossBps} bps exceeds configured maximum ${maxQuoteLossBps} bps`);
|
|
918
|
+
}
|
|
919
|
+
addressesEqual(left, right, chainId) {
|
|
920
|
+
if (this.chainMetadataByChainId.get(chainId)?.protocol === _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_11__/* .ProtocolType */ .Hb.Tron) {
|
|
921
|
+
return this.tronAddressHex20(left) === this.tronAddressHex20(right);
|
|
922
|
+
}
|
|
923
|
+
if (left.startsWith('0x') && right.startsWith('0x')) {
|
|
924
|
+
return left.toLowerCase() === right.toLowerCase();
|
|
925
|
+
}
|
|
926
|
+
return left === right;
|
|
927
|
+
}
|
|
928
|
+
async registerIfRequired(response, txHash) {
|
|
929
|
+
if (response.requiresRegisterTransaction !== true)
|
|
930
|
+
return;
|
|
931
|
+
await this.registerTransaction(response.txId, txHash);
|
|
932
|
+
}
|
|
933
|
+
async registerTransaction(txId, txHash) {
|
|
934
|
+
for (let attempt = 0;; attempt++) {
|
|
935
|
+
try {
|
|
936
|
+
const results = await this.client.registerTxs([{ txId, txHash }]);
|
|
937
|
+
const failed = results.find((result) => !result.success);
|
|
938
|
+
if (failed) {
|
|
939
|
+
throw new Error(`swaps.xyz registerTxs failed: ${failed.error ?? 'unknown error'}`);
|
|
940
|
+
}
|
|
941
|
+
return true;
|
|
942
|
+
}
|
|
943
|
+
catch (error) {
|
|
944
|
+
if ((0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isSwapsXyzTerminalError */ .Ub)(error) ||
|
|
945
|
+
(0,_SwapsXyzClient_js__WEBPACK_IMPORTED_MODULE_6__/* .isSwapsXyzDeferredError */ .R_)(error) ||
|
|
946
|
+
attempt >= MAX_REGISTRATION_ATTEMPTS - 1) {
|
|
947
|
+
this.logger.error({ txId, txHash, error }, 'Failed to register swaps.xyz transaction');
|
|
948
|
+
return false;
|
|
949
|
+
}
|
|
950
|
+
await (0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_17__/* .sleep */ .yy)(this.registerTxRetryDelayMs * 2 ** attempt);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
//# sourceMappingURL=SwapsXyzBridge.js.map
|
|
956
|
+
__webpack_async_result__();
|
|
957
|
+
} catch(e) { __webpack_async_result__(e); } });
|
|
958
|
+
|
|
959
|
+
/***/ }),
|
|
960
|
+
|
|
961
|
+
/***/ 36173:
|
|
962
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
963
|
+
|
|
964
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
965
|
+
/* harmony export */ DZ: () => (/* binding */ isSolanaTx),
|
|
966
|
+
/* harmony export */ NQ: () => (/* binding */ SwapsXyzClient),
|
|
967
|
+
/* harmony export */ R_: () => (/* binding */ isSwapsXyzDeferredError),
|
|
968
|
+
/* harmony export */ Ub: () => (/* binding */ isSwapsXyzTerminalError),
|
|
969
|
+
/* harmony export */ VQ: () => (/* binding */ isEvmTx),
|
|
970
|
+
/* harmony export */ VT: () => (/* binding */ SwapsXyzRequestError),
|
|
971
|
+
/* harmony export */ Y2: () => (/* binding */ isTronTx),
|
|
972
|
+
/* harmony export */ fV: () => (/* binding */ isSwapsXyzNotFoundError)
|
|
973
|
+
/* harmony export */ });
|
|
974
|
+
/* unused harmony exports SwapsXyzCooldownError, SwapsXyzResponseValidationError, TERMINAL_ERROR_CODES */
|
|
975
|
+
/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5884);
|
|
976
|
+
/* harmony import */ var _utils_fetchWithDeadline_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(84662);
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
const DEFAULT_API_URL = 'https://api-v2.swaps.xyz/api';
|
|
980
|
+
const MAX_RETRIES = 3;
|
|
981
|
+
const RETRY_DELAY_MS = 1_000;
|
|
982
|
+
const MAX_INLINE_COOLDOWN_MS = 30_000;
|
|
983
|
+
const INTEGER_STRING_REGEX = /^\d+$/;
|
|
984
|
+
const TRON_CALLDATA_REGEX = /^(?:0x)?(?:[0-9a-fA-F]{2}){4,}$/;
|
|
985
|
+
/**
|
|
986
|
+
* Error returned by the swaps.xyz API.
|
|
987
|
+
*
|
|
988
|
+
* The `code` field is the machine-readable error label from the API error
|
|
989
|
+
* envelope and is used to decide whether a request should be retried.
|
|
990
|
+
*/
|
|
991
|
+
class SwapsXyzRequestError extends Error {
|
|
992
|
+
status;
|
|
993
|
+
statusText;
|
|
994
|
+
code;
|
|
995
|
+
retryAt;
|
|
996
|
+
constructor(message, status, statusText, code, retryAt) {
|
|
997
|
+
super(message);
|
|
998
|
+
this.status = status;
|
|
999
|
+
this.statusText = statusText;
|
|
1000
|
+
this.code = code;
|
|
1001
|
+
this.retryAt = retryAt;
|
|
1002
|
+
this.name = 'SwapsXyzRequestError';
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/** The request can be retried later, but not within this call's wait budget. */
|
|
1006
|
+
class SwapsXyzCooldownError extends SwapsXyzRequestError {
|
|
1007
|
+
constructor(retryAt) {
|
|
1008
|
+
super('swaps.xyz rate limit cooldown exceeds the inline wait budget', 429, 'Too Many Requests', undefined, retryAt);
|
|
1009
|
+
this.name = 'SwapsXyzCooldownError';
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
function isSwapsXyzDeferredError(error) {
|
|
1013
|
+
return (error instanceof SwapsXyzCooldownError ||
|
|
1014
|
+
(error instanceof SwapsXyzRequestError &&
|
|
1015
|
+
error.retryAt !== undefined &&
|
|
1016
|
+
error.retryAt - Date.now() > MAX_INLINE_COOLDOWN_MS));
|
|
1017
|
+
}
|
|
1018
|
+
function retryAfterDeadline(header, now) {
|
|
1019
|
+
if (header === null)
|
|
1020
|
+
return undefined;
|
|
1021
|
+
const value = header.trim();
|
|
1022
|
+
if (/^\d+$/.test(value)) {
|
|
1023
|
+
const delay = Number(value) * 1_000;
|
|
1024
|
+
return Number.isSafeInteger(delay) && Number.isSafeInteger(now + delay)
|
|
1025
|
+
? now + delay
|
|
1026
|
+
: undefined;
|
|
1027
|
+
}
|
|
1028
|
+
// HTTP dates contain a weekday; do not interpret malformed numeric strings as dates.
|
|
1029
|
+
if (!/^[A-Za-z]{3},/.test(value))
|
|
1030
|
+
return undefined;
|
|
1031
|
+
const deadline = Date.parse(value);
|
|
1032
|
+
return Number.isFinite(deadline) ? Math.max(now, deadline) : undefined;
|
|
1033
|
+
}
|
|
1034
|
+
class SwapsXyzResponseValidationError extends Error {
|
|
1035
|
+
constructor(message) {
|
|
1036
|
+
super(message);
|
|
1037
|
+
this.name = 'SwapsXyzResponseValidationError';
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
const TERMINAL_ERROR_CODES = new Set([
|
|
1041
|
+
'INVALID_API_KEY',
|
|
1042
|
+
'MISSING_API_KEY',
|
|
1043
|
+
'GEO_BLOCKED',
|
|
1044
|
+
'WALLET_SCREENED',
|
|
1045
|
+
'NO_AVAILABLE_ROUTE',
|
|
1046
|
+
'INSUFFICIENT_LIQUIDITY',
|
|
1047
|
+
'AMOUNT_TOO_HIGH',
|
|
1048
|
+
'AMOUNT_TOO_LOW',
|
|
1049
|
+
'INVALID_PARAMETER',
|
|
1050
|
+
'INVALID_AMOUNT_ZERO',
|
|
1051
|
+
'INVALID_ADDRESS_FORMAT',
|
|
1052
|
+
'INVALID_SOURCE_TOKEN',
|
|
1053
|
+
'INVALID_DESTINATION_TOKEN',
|
|
1054
|
+
'MISSING_REQUIRED_FIELD',
|
|
1055
|
+
'CROSS_VM_RECEIVER_REQUIRED',
|
|
1056
|
+
'EXCESSIVE_FEE',
|
|
1057
|
+
'UNSUPPORTED_NETWORK',
|
|
1058
|
+
'UNSUPPORTED_NETWORK_PAIR',
|
|
1059
|
+
'UNSUPPORTED_NETWORK_TOKEN_PAIR',
|
|
1060
|
+
'UNSUPPORTED_SWAP_DIRECTION',
|
|
1061
|
+
]);
|
|
1062
|
+
function isSwapsXyzTerminalError(error) {
|
|
1063
|
+
if (error instanceof SwapsXyzResponseValidationError)
|
|
1064
|
+
return true;
|
|
1065
|
+
if (!(error instanceof SwapsXyzRequestError))
|
|
1066
|
+
return false;
|
|
1067
|
+
if (error.code && TERMINAL_ERROR_CODES.has(error.code))
|
|
1068
|
+
return true;
|
|
1069
|
+
if (error.status === 408 || error.status === 429)
|
|
1070
|
+
return false;
|
|
1071
|
+
return error.status >= 400 && error.status < 500;
|
|
1072
|
+
}
|
|
1073
|
+
const NOT_FOUND_ERROR_CODES = new Set([
|
|
1074
|
+
'NOT_FOUND',
|
|
1075
|
+
'TRANSACTION_NOT_FOUND',
|
|
1076
|
+
'TX_NOT_FOUND',
|
|
1077
|
+
]);
|
|
1078
|
+
function isSwapsXyzNotFoundError(error) {
|
|
1079
|
+
return (error instanceof SwapsXyzRequestError &&
|
|
1080
|
+
(error.status === 404 ||
|
|
1081
|
+
(error.status === 400 &&
|
|
1082
|
+
error.code !== undefined &&
|
|
1083
|
+
NOT_FOUND_ERROR_CODES.has(error.code))));
|
|
1084
|
+
}
|
|
1085
|
+
function sleep(ms) {
|
|
1086
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1087
|
+
}
|
|
1088
|
+
function isRecord(value) {
|
|
1089
|
+
return typeof value === 'object' && value !== null;
|
|
1090
|
+
}
|
|
1091
|
+
function isEvmTx(tx) {
|
|
1092
|
+
return (isRecord(tx) && typeof tx.to === 'string' && typeof tx.data === 'string');
|
|
1093
|
+
}
|
|
1094
|
+
function isSolanaTx(tx) {
|
|
1095
|
+
return isRecord(tx) && typeof tx.base64Tx === 'string';
|
|
1096
|
+
}
|
|
1097
|
+
function isTronTx(tx) {
|
|
1098
|
+
return (isRecord(tx) &&
|
|
1099
|
+
typeof tx.to === 'string' &&
|
|
1100
|
+
tx.to.length > 0 &&
|
|
1101
|
+
(tx.toExtra === null ||
|
|
1102
|
+
(typeof tx.toExtra === 'string' &&
|
|
1103
|
+
TRON_CALLDATA_REGEX.test(tx.toExtra))) &&
|
|
1104
|
+
typeof tx.value === 'string' &&
|
|
1105
|
+
INTEGER_STRING_REGEX.test(tx.value) &&
|
|
1106
|
+
typeof tx.chainId === 'number' &&
|
|
1107
|
+
Number.isInteger(tx.chainId) &&
|
|
1108
|
+
tx.chainId > 0 &&
|
|
1109
|
+
tx.chainKey === 'trx');
|
|
1110
|
+
}
|
|
1111
|
+
const IntegerStringSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().regex(INTEGER_STRING_REGEX);
|
|
1112
|
+
const TokenAmountSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1113
|
+
amount: IntegerStringSchema,
|
|
1114
|
+
decimals: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().nonnegative().optional(),
|
|
1115
|
+
chainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().optional(),
|
|
1116
|
+
address: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().optional(),
|
|
1117
|
+
})
|
|
1118
|
+
.passthrough();
|
|
1119
|
+
const PaymentSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1120
|
+
amount: IntegerStringSchema,
|
|
1121
|
+
token: zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1122
|
+
chainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int(),
|
|
1123
|
+
address: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1124
|
+
decimals: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().nonnegative().optional(),
|
|
1125
|
+
symbol: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().optional(),
|
|
1126
|
+
})
|
|
1127
|
+
.passthrough()
|
|
1128
|
+
.optional(),
|
|
1129
|
+
usdAmount: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().optional(),
|
|
1130
|
+
})
|
|
1131
|
+
.passthrough();
|
|
1132
|
+
const EvmTxSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1133
|
+
to: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1134
|
+
data: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1135
|
+
value: IntegerStringSchema.optional(),
|
|
1136
|
+
chainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().optional(),
|
|
1137
|
+
})
|
|
1138
|
+
.passthrough();
|
|
1139
|
+
const SolanaTxSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1140
|
+
base64Tx: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().min(1),
|
|
1141
|
+
recentBlockhash: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().optional(),
|
|
1142
|
+
payer: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().optional(),
|
|
1143
|
+
chainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().optional(),
|
|
1144
|
+
})
|
|
1145
|
+
.passthrough();
|
|
1146
|
+
const TronTxSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1147
|
+
to: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().min(1),
|
|
1148
|
+
toExtra: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().regex(TRON_CALLDATA_REGEX).nullable(),
|
|
1149
|
+
value: IntegerStringSchema,
|
|
1150
|
+
chainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().positive(),
|
|
1151
|
+
chainKey: zod__WEBPACK_IMPORTED_MODULE_0__/* .literal */ .eu('trx'),
|
|
1152
|
+
})
|
|
1153
|
+
.passthrough();
|
|
1154
|
+
const BridgeRouteHopSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1155
|
+
srcChainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int(),
|
|
1156
|
+
dstChainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int(),
|
|
1157
|
+
srcBridgeToken: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1158
|
+
dstBridgeToken: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1159
|
+
bridgeId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1160
|
+
})
|
|
1161
|
+
.passthrough();
|
|
1162
|
+
const ActionResponseSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1163
|
+
tx: zod__WEBPACK_IMPORTED_MODULE_0__/* .union */ .KC([EvmTxSchema, SolanaTxSchema, TronTxSchema]),
|
|
1164
|
+
txId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().min(1),
|
|
1165
|
+
vmId: zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5(['evm', 'solana', 'alt-vm', 'hypercore']),
|
|
1166
|
+
amountIn: TokenAmountSchema,
|
|
1167
|
+
amountInMax: TokenAmountSchema.optional(),
|
|
1168
|
+
amountOut: TokenAmountSchema,
|
|
1169
|
+
amountOutMin: TokenAmountSchema,
|
|
1170
|
+
protocolFee: PaymentSchema.optional(),
|
|
1171
|
+
applicationFee: PaymentSchema.optional(),
|
|
1172
|
+
bridgeFee: PaymentSchema.optional(),
|
|
1173
|
+
bridgeIds: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YO(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj()).optional(),
|
|
1174
|
+
bridgeRoute: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YO(BridgeRouteHopSchema).optional(),
|
|
1175
|
+
exchangeRate: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().optional(),
|
|
1176
|
+
estimatedTxTime: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().nonnegative().optional(),
|
|
1177
|
+
estimatedPriceImpact: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().nullable().optional(),
|
|
1178
|
+
requiresTokenApproval: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zM(),
|
|
1179
|
+
requiresRegisterTransaction: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zM().optional(),
|
|
1180
|
+
executionsType: zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5(['DEFAULT', 'GASLESS']).optional(),
|
|
1181
|
+
})
|
|
1182
|
+
.passthrough();
|
|
1183
|
+
const StatusResponseSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1184
|
+
status: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().min(1),
|
|
1185
|
+
txId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().min(1),
|
|
1186
|
+
srcChainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().nullable(),
|
|
1187
|
+
dstChainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int().nullable(),
|
|
1188
|
+
srcTxHash: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().nullish(),
|
|
1189
|
+
dstTxHash: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().nullish(),
|
|
1190
|
+
sender: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().nullish(),
|
|
1191
|
+
bridgeDetails: zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1192
|
+
isBridge: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zM(),
|
|
1193
|
+
bridgeTime: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().nullish(),
|
|
1194
|
+
txPath: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YO(zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1195
|
+
chainId: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai().int(),
|
|
1196
|
+
txHash: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(),
|
|
1197
|
+
timestamp: zod__WEBPACK_IMPORTED_MODULE_0__/* .union */ .KC([zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj(), zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai()]).nullish(),
|
|
1198
|
+
nextBridge: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().nullable().optional(),
|
|
1199
|
+
})
|
|
1200
|
+
.passthrough())
|
|
1201
|
+
.nullish(),
|
|
1202
|
+
})
|
|
1203
|
+
.passthrough()
|
|
1204
|
+
.nullish(),
|
|
1205
|
+
actionResponse: ActionResponseSchema.nullish(),
|
|
1206
|
+
})
|
|
1207
|
+
.passthrough();
|
|
1208
|
+
const RegisterTxResultsSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YO(zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ik({
|
|
1209
|
+
success: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zM(),
|
|
1210
|
+
error: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .Yj().nullable().optional(),
|
|
1211
|
+
})
|
|
1212
|
+
.passthrough());
|
|
1213
|
+
class SwapsXyzClient {
|
|
1214
|
+
logger;
|
|
1215
|
+
apiKey;
|
|
1216
|
+
apiUrl;
|
|
1217
|
+
requestTimeoutMs;
|
|
1218
|
+
cooldownUntil = 0;
|
|
1219
|
+
constructor(config, logger) {
|
|
1220
|
+
this.apiKey = config.apiKey;
|
|
1221
|
+
const apiUrl = new URL(config.apiUrl ?? DEFAULT_API_URL);
|
|
1222
|
+
if (apiUrl.protocol !== 'https:') {
|
|
1223
|
+
throw new Error('swaps.xyz API URL must use HTTPS');
|
|
1224
|
+
}
|
|
1225
|
+
this.apiUrl = apiUrl.toString().replace(/\/$/, '');
|
|
1226
|
+
this.requestTimeoutMs = config.requestTimeoutMs ?? 10_000;
|
|
1227
|
+
this.logger = logger;
|
|
1228
|
+
}
|
|
1229
|
+
getAction(req, onAttempt) {
|
|
1230
|
+
const query = new URLSearchParams();
|
|
1231
|
+
for (const [key, value] of Object.entries(req)) {
|
|
1232
|
+
if (value === undefined || value === null)
|
|
1233
|
+
continue;
|
|
1234
|
+
query.set(key, String(value));
|
|
1235
|
+
}
|
|
1236
|
+
return this.withRetry(() => this.request(`${this.apiUrl}/getAction?${query.toString()}`, { method: 'GET' }, ActionResponseSchema, onAttempt));
|
|
1237
|
+
}
|
|
1238
|
+
getStatus(req) {
|
|
1239
|
+
if (!req.txHash && !req.txId) {
|
|
1240
|
+
throw new Error('getStatus requires either txHash or txId');
|
|
1241
|
+
}
|
|
1242
|
+
const query = new URLSearchParams();
|
|
1243
|
+
if (req.txHash)
|
|
1244
|
+
query.set('txHash', req.txHash);
|
|
1245
|
+
if (req.txId)
|
|
1246
|
+
query.set('txId', req.txId);
|
|
1247
|
+
if (req.chainId !== undefined)
|
|
1248
|
+
query.set('chainId', String(req.chainId));
|
|
1249
|
+
return this.withRetry(() => this.request(`${this.apiUrl}/getStatus?${query.toString()}`, { method: 'GET' }, StatusResponseSchema));
|
|
1250
|
+
}
|
|
1251
|
+
registerTxs(entries) {
|
|
1252
|
+
// The bridge owns one retry budget for HTTP and unsuccessful API results.
|
|
1253
|
+
return this.request(`${this.apiUrl}/registerTxs`, {
|
|
1254
|
+
method: 'POST',
|
|
1255
|
+
body: JSON.stringify(entries),
|
|
1256
|
+
headers: { 'content-type': 'application/json' },
|
|
1257
|
+
}, RegisterTxResultsSchema);
|
|
1258
|
+
}
|
|
1259
|
+
async request(url, init, schema, onAttempt) {
|
|
1260
|
+
await this.waitForCooldown();
|
|
1261
|
+
onAttempt?.(Date.now());
|
|
1262
|
+
let responseError;
|
|
1263
|
+
try {
|
|
1264
|
+
return await (0,_utils_fetchWithDeadline_js__WEBPACK_IMPORTED_MODULE_1__/* .fetchWithDeadline */ .r)(url, {
|
|
1265
|
+
method: init.method,
|
|
1266
|
+
headers: {
|
|
1267
|
+
'x-api-key': this.apiKey,
|
|
1268
|
+
...init.headers,
|
|
1269
|
+
},
|
|
1270
|
+
body: init.body,
|
|
1271
|
+
}, this.requestTimeoutMs, async (response) => {
|
|
1272
|
+
if (!response.ok) {
|
|
1273
|
+
const retryAt = response.status === 429
|
|
1274
|
+
? retryAfterDeadline(response.headers.get('retry-after'), Date.now())
|
|
1275
|
+
: undefined;
|
|
1276
|
+
if (retryAt !== undefined)
|
|
1277
|
+
this.cooldownUntil = Math.max(this.cooldownUntil, retryAt);
|
|
1278
|
+
let code;
|
|
1279
|
+
let message = `${init.method} ${url} failed: ${response.status} ${response.statusText}`;
|
|
1280
|
+
// Keep the HTTP classification if reading its error body times out.
|
|
1281
|
+
responseError = new SwapsXyzRequestError(message, response.status, response.statusText, undefined, retryAt);
|
|
1282
|
+
try {
|
|
1283
|
+
const body = await response.json();
|
|
1284
|
+
if (isRecord(body) && isRecord(body.error)) {
|
|
1285
|
+
if (typeof body.error.code === 'string')
|
|
1286
|
+
code = body.error.code;
|
|
1287
|
+
if (typeof body.error.message === 'string') {
|
|
1288
|
+
message = `${message}: ${body.error.message}`;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
catch {
|
|
1293
|
+
// Keep the status-derived error when the response is not JSON.
|
|
1294
|
+
}
|
|
1295
|
+
responseError = new SwapsXyzRequestError(message, response.status, response.statusText, code, retryAt);
|
|
1296
|
+
throw responseError;
|
|
1297
|
+
}
|
|
1298
|
+
const body = await response.json();
|
|
1299
|
+
const result = schema.safeParse(body);
|
|
1300
|
+
if (!result.success) {
|
|
1301
|
+
throw new SwapsXyzResponseValidationError(`Invalid swaps.xyz response for ${init.method} ${new URL(url).pathname}: ${result.error.message}`);
|
|
1302
|
+
}
|
|
1303
|
+
return result.data;
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
catch (error) {
|
|
1307
|
+
throw responseError ?? error;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
async waitForCooldown() {
|
|
1311
|
+
const waitDeadline = Date.now() + MAX_INLINE_COOLDOWN_MS;
|
|
1312
|
+
while (this.cooldownUntil > Date.now()) {
|
|
1313
|
+
if (this.cooldownUntil > waitDeadline)
|
|
1314
|
+
throw new SwapsXyzCooldownError(this.cooldownUntil);
|
|
1315
|
+
await sleep(this.cooldownUntil - Date.now());
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
async withRetry(fn) {
|
|
1319
|
+
let lastError;
|
|
1320
|
+
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
1321
|
+
try {
|
|
1322
|
+
return await fn();
|
|
1323
|
+
}
|
|
1324
|
+
catch (error) {
|
|
1325
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1326
|
+
if (isSwapsXyzTerminalError(lastError)) {
|
|
1327
|
+
this.logger.debug({ error: lastError.message }, 'swaps.xyz terminal error — not retrying');
|
|
1328
|
+
throw lastError;
|
|
1329
|
+
}
|
|
1330
|
+
if (isSwapsXyzDeferredError(lastError))
|
|
1331
|
+
throw lastError;
|
|
1332
|
+
this.logger.warn({ attempt, error: lastError.message }, 'swaps.xyz request failed, retrying');
|
|
1333
|
+
if (attempt < MAX_RETRIES - 1) {
|
|
1334
|
+
await sleep(RETRY_DELAY_MS * (attempt + 1));
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
if (lastError)
|
|
1339
|
+
throw lastError;
|
|
1340
|
+
throw new Error('swaps.xyz request failed without an error');
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
//# sourceMappingURL=SwapsXyzClient.js.map
|
|
1344
|
+
|
|
1345
|
+
/***/ }),
|
|
1346
|
+
|
|
1347
|
+
/***/ 3987:
|
|
1348
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1349
|
+
|
|
1350
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
1351
|
+
/* harmony export */ c: () => (/* binding */ minimumOutputForLoss)
|
|
1352
|
+
/* harmony export */ });
|
|
1353
|
+
/* harmony import */ var _humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21387);
|
|
1354
|
+
|
|
1355
|
+
/** Smallest destination amount satisfying the fixed input's quote-loss budget. */
|
|
1356
|
+
function minimumOutputForLoss(input, sourceDecimals, destinationDecimals, lossBps) {
|
|
1357
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .v)(input > 0n, 'Quote input must be positive');
|
|
1358
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .v)([sourceDecimals, destinationDecimals].every((decimals) => Number.isInteger(decimals) && decimals >= 0 && decimals <= 255), 'Quote decimals must be integers between 0 and 255');
|
|
1359
|
+
(0,_humanode_hyperlane_utils__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .v)(Number.isInteger(lossBps) && lossBps >= 0 && lossBps <= 10_000, 'Quote loss must be an integer between 0 and 10000 bps');
|
|
1360
|
+
const numerator = input * 10n ** BigInt(destinationDecimals) * (10000n - BigInt(lossBps));
|
|
1361
|
+
const denominator = 10n ** BigInt(sourceDecimals) * 10000n;
|
|
1362
|
+
return (numerator + denominator - 1n) / denominator;
|
|
1363
|
+
}
|
|
1364
|
+
//# sourceMappingURL=quoteBudget.js.map
|
|
1365
|
+
|
|
1366
|
+
/***/ })
|
|
1367
|
+
|
|
1368
|
+
};
|