@sodax/sdk 2.1.0-rc.2 → 2.1.0-rc.4
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/dist/index.cjs +682 -173
- package/dist/index.d.cts +340 -62
- package/dist/index.d.ts +340 -62
- package/dist/index.mjs +682 -173
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -3337,7 +3337,7 @@ var spokeChainConfig = {
|
|
|
3337
3337
|
supportedTokens: suiSupportedTokens,
|
|
3338
3338
|
nativeToken: "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
|
|
3339
3339
|
bnUSD: "0xff4de2b2b57dd7611d2812d231a467d007b702a101fd5c7ad3b278257cddb507::bnusd::BNUSD",
|
|
3340
|
-
rpc_url: "https://
|
|
3340
|
+
rpc_url: "https://sui-rpc.publicnode.com",
|
|
3341
3341
|
chain: baseChainInfo[ChainKeys.SUI_MAINNET],
|
|
3342
3342
|
pollingConfig: {
|
|
3343
3343
|
pollingIntervalMs: 500,
|
|
@@ -4272,7 +4272,13 @@ var BTC_ADDRESS_TYPES = ["P2PKH", "P2SH", "P2WPKH", "P2TR"];
|
|
|
4272
4272
|
// ../types/dist/hooks/hooks.js
|
|
4273
4273
|
var HookKind = {
|
|
4274
4274
|
/** Deposits delivered USDC into the recipient's HyperCore perps account (HyperEVM). */
|
|
4275
|
-
HYPERCORE_DEPOSIT: "hyperCoreDeposit"
|
|
4275
|
+
HYPERCORE_DEPOSIT: "hyperCoreDeposit",
|
|
4276
|
+
/**
|
|
4277
|
+
* Requests an ERC-7540 deposit of delivered USDC into the Flint RWA vault (Ethereum), with the
|
|
4278
|
+
* recipient as the request's controller. Asynchronous: the request mints no shares — Flint's
|
|
4279
|
+
* curator settles a NAV and then claims the shares on the controller's behalf.
|
|
4280
|
+
*/
|
|
4281
|
+
FLINT_DEPOSIT: "flintDeposit"
|
|
4276
4282
|
};
|
|
4277
4283
|
var spokeHooks = {
|
|
4278
4284
|
[ChainKeys.HYPEREVM_MAINNET]: [
|
|
@@ -4283,6 +4289,20 @@ var spokeHooks = {
|
|
|
4283
4289
|
// USDC on HyperEVM
|
|
4284
4290
|
}
|
|
4285
4291
|
]
|
|
4292
|
+
// HookKind.FLINT_DEPOSIT is not registered yet: FlintDepositHook is not deployed to Ethereum
|
|
4293
|
+
// mainnet (icon-project/sodax-contracts#693). Registering it with a placeholder address would
|
|
4294
|
+
// route real intent output to that address, so the entry lands with the deployment:
|
|
4295
|
+
//
|
|
4296
|
+
// [ChainKeys.ETHEREUM_MAINNET]: [
|
|
4297
|
+
// {
|
|
4298
|
+
// kind: HookKind.FLINT_DEPOSIT,
|
|
4299
|
+
// address: '0x…',
|
|
4300
|
+
// supportedTokens: [spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDC.address],
|
|
4301
|
+
// },
|
|
4302
|
+
// ],
|
|
4303
|
+
//
|
|
4304
|
+
// Until then `getSpokeHook` returns undefined and `resolveDeliveryHook` throws, which is the
|
|
4305
|
+
// correct behaviour for a hook that does not exist on chain.
|
|
4286
4306
|
};
|
|
4287
4307
|
var getSpokeHook = (chainKey, kind) => spokeHooks[chainKey]?.find((h) => h.kind === kind);
|
|
4288
4308
|
var getSpokeHooks = (chainKey) => spokeHooks[chainKey] ?? [];
|
|
@@ -4408,7 +4428,13 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
4408
4428
|
}
|
|
4409
4429
|
|
|
4410
4430
|
// ../types/dist/index.js
|
|
4411
|
-
var CONFIG_VERSION =
|
|
4431
|
+
var CONFIG_VERSION = 224;
|
|
4432
|
+
|
|
4433
|
+
// src/shared/utils/resolveTimeoutMs.ts
|
|
4434
|
+
function resolveTimeoutMs(timeout, fallbackMs) {
|
|
4435
|
+
if (timeout === void 0 || !Number.isFinite(timeout)) return fallbackMs;
|
|
4436
|
+
return Math.max(0, timeout);
|
|
4437
|
+
}
|
|
4412
4438
|
function isEvmSpokeChainConfig(value) {
|
|
4413
4439
|
return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
|
|
4414
4440
|
}
|
|
@@ -4835,7 +4861,7 @@ async function pollForExecutedPacket(payload, deadline) {
|
|
|
4835
4861
|
}
|
|
4836
4862
|
async function waitUntilIntentExecuted(payload) {
|
|
4837
4863
|
try {
|
|
4838
|
-
const timeout = payload.timeout
|
|
4864
|
+
const timeout = resolveTimeoutMs(payload.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
4839
4865
|
const startTime = Date.now();
|
|
4840
4866
|
const deadline = startTime + timeout;
|
|
4841
4867
|
let lastPollingError;
|
|
@@ -4868,7 +4894,8 @@ async function waitUntilIntentExecuted(payload) {
|
|
|
4868
4894
|
}
|
|
4869
4895
|
async function relayTxAndWaitPacket(params) {
|
|
4870
4896
|
try {
|
|
4871
|
-
const { srcTxHash, data, chainKey, relayerApiEndpoint,
|
|
4897
|
+
const { srcTxHash, data, chainKey, relayerApiEndpoint, pollTxHash } = params;
|
|
4898
|
+
const timeout = resolveTimeoutMs(params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
4872
4899
|
const intentRelayChainId = getIntentRelayChainId(chainKey).toString();
|
|
4873
4900
|
const isSplitTxChain = isSolanaChainKeyType(chainKey) || isBitcoinChainKeyType(chainKey);
|
|
4874
4901
|
invariant(!isSplitTxChain || data !== void 0, "Data is required for Solana and Bitcoin chain keys");
|
|
@@ -14276,6 +14303,17 @@ var ConfigService = class {
|
|
|
14276
14303
|
get leverageYieldPartnerFee() {
|
|
14277
14304
|
return this.leverageYield.partnerFee ?? this.fee;
|
|
14278
14305
|
}
|
|
14306
|
+
// Effective backend submit-tx toggle per feature. Read live off the same `swaps` / `bridge` slots as
|
|
14307
|
+
// `partnerFee` so an omitted flag resolves to the ON default here, in one place, instead of leaving
|
|
14308
|
+
// `config.swaps.useBackendSubmitTx === undefined` while the backend path is actually active.
|
|
14309
|
+
// The deprecated `swapsOptions` / `bridgeOptions` keys are still honoured as a second-precedence
|
|
14310
|
+
// fallback, so a pre-existing explicit opt-out keeps the client-side path instead of silently flipping.
|
|
14311
|
+
get swapUseBackendSubmitTx() {
|
|
14312
|
+
return this.swaps.useBackendSubmitTx ?? this.sodax.swapsOptions?.useBackendSubmitTx ?? true;
|
|
14313
|
+
}
|
|
14314
|
+
get bridgeUseBackendSubmitTx() {
|
|
14315
|
+
return this.bridge.useBackendSubmitTx ?? this.sodax.bridgeOptions?.useBackendSubmitTx ?? true;
|
|
14316
|
+
}
|
|
14279
14317
|
get dex() {
|
|
14280
14318
|
return this.sodax.dex;
|
|
14281
14319
|
}
|
|
@@ -14603,7 +14641,7 @@ var EvmVaultTokenService = class {
|
|
|
14603
14641
|
return amount * BigInt(10 ** (decimals - 18));
|
|
14604
14642
|
}
|
|
14605
14643
|
};
|
|
14606
|
-
var Erc20Service = class {
|
|
14644
|
+
var Erc20Service = class _Erc20Service {
|
|
14607
14645
|
constructor() {
|
|
14608
14646
|
}
|
|
14609
14647
|
static async getErc20Token(token, publicClient) {
|
|
@@ -14629,6 +14667,19 @@ var Erc20Service = class {
|
|
|
14629
14667
|
});
|
|
14630
14668
|
return { name, symbol, decimals, address: token };
|
|
14631
14669
|
}
|
|
14670
|
+
/**
|
|
14671
|
+
* Read the current on-chain allowance of `spender` over `owner`'s balance.
|
|
14672
|
+
* @param params - Token, owner, spender, and publicClient for the chain.
|
|
14673
|
+
* @returns The raw allowance.
|
|
14674
|
+
*/
|
|
14675
|
+
static async getAllowance(params) {
|
|
14676
|
+
return params.publicClient.readContract({
|
|
14677
|
+
address: params.token,
|
|
14678
|
+
abi: erc20Abi$1,
|
|
14679
|
+
functionName: "allowance",
|
|
14680
|
+
args: [params.owner, params.spender]
|
|
14681
|
+
});
|
|
14682
|
+
}
|
|
14632
14683
|
/**
|
|
14633
14684
|
* Check if spender has enough ERC20 allowance for given amount.
|
|
14634
14685
|
* @param params - Token, amount, owner, spender, chainKey, and publicClient for the chain.
|
|
@@ -14642,12 +14693,7 @@ var Erc20Service = class {
|
|
|
14642
14693
|
value: true
|
|
14643
14694
|
};
|
|
14644
14695
|
}
|
|
14645
|
-
const allowedAmount = await
|
|
14646
|
-
address: params.token,
|
|
14647
|
-
abi: erc20Abi$1,
|
|
14648
|
-
functionName: "allowance",
|
|
14649
|
-
args: [params.owner, params.spender]
|
|
14650
|
-
});
|
|
14696
|
+
const allowedAmount = await _Erc20Service.getAllowance(params);
|
|
14651
14697
|
return {
|
|
14652
14698
|
ok: true,
|
|
14653
14699
|
value: allowedAmount >= params.amount
|
|
@@ -14659,6 +14705,59 @@ var Erc20Service = class {
|
|
|
14659
14705
|
};
|
|
14660
14706
|
}
|
|
14661
14707
|
}
|
|
14708
|
+
/**
|
|
14709
|
+
* Decide how many approve transactions this token needs for `amount`.
|
|
14710
|
+
*
|
|
14711
|
+
* Tokens of the 2017 TetherToken lineage reject an allowance change from one non-zero value to
|
|
14712
|
+
* another, so a wallet holding a stale allowance can never approve — every retry reverts the same
|
|
14713
|
+
* way. Such a token needs `approve(0)` first.
|
|
14714
|
+
*
|
|
14715
|
+
* Detection is behavioural: a simulated approve either reverts or it does not. That answers the
|
|
14716
|
+
* question that actually matters ("will this approve revert?") instead of "is this token USDT?",
|
|
14717
|
+
* so a token listed later, or upgraded later behind the same address, is covered without a code
|
|
14718
|
+
* change — and no token list is hardcoded.
|
|
14719
|
+
*
|
|
14720
|
+
* The probes only run once an allowance is already set. The common path (nothing approved yet)
|
|
14721
|
+
* costs a single read.
|
|
14722
|
+
*/
|
|
14723
|
+
static async planApproval(params) {
|
|
14724
|
+
const single = (reason) => ({ approveAmount: params.amount, reason });
|
|
14725
|
+
if (params.token.toLowerCase() === params.nativeToken.toLowerCase()) {
|
|
14726
|
+
return single("native-token");
|
|
14727
|
+
}
|
|
14728
|
+
let allowance;
|
|
14729
|
+
try {
|
|
14730
|
+
allowance = await _Erc20Service.getAllowance(params);
|
|
14731
|
+
} catch {
|
|
14732
|
+
return single("allowance-read-failed");
|
|
14733
|
+
}
|
|
14734
|
+
if (allowance === 0n) {
|
|
14735
|
+
return single("zero-allowance");
|
|
14736
|
+
}
|
|
14737
|
+
if (await _Erc20Service.canApprove(params, params.amount)) {
|
|
14738
|
+
return single("probe-passed");
|
|
14739
|
+
}
|
|
14740
|
+
if (!await _Erc20Service.canApprove(params, 0n)) {
|
|
14741
|
+
return single("reset-not-viable");
|
|
14742
|
+
}
|
|
14743
|
+
return { resetAmount: 0n, approveAmount: params.amount, reason: "reset-required" };
|
|
14744
|
+
}
|
|
14745
|
+
/**
|
|
14746
|
+
* Simulate `approve(spender, amount)` as `owner`.
|
|
14747
|
+
*
|
|
14748
|
+
* `call` rather than `simulateContract`, because a TetherToken-lineage `approve` returns no value
|
|
14749
|
+
* and ABI decoding would fail even on a successful call. `account` is required: the guard reads
|
|
14750
|
+
* `allowed[msg.sender][spender]`.
|
|
14751
|
+
*/
|
|
14752
|
+
static async canApprove(params, amount) {
|
|
14753
|
+
const { data } = _Erc20Service.encodeApprove(params.token, params.spender, amount);
|
|
14754
|
+
try {
|
|
14755
|
+
await params.publicClient.call({ account: params.owner, to: params.token, data });
|
|
14756
|
+
return true;
|
|
14757
|
+
} catch {
|
|
14758
|
+
return false;
|
|
14759
|
+
}
|
|
14760
|
+
}
|
|
14662
14761
|
/**
|
|
14663
14762
|
* Approve ERC20 amount spending
|
|
14664
14763
|
* @param token - ERC20 token address
|
|
@@ -22415,7 +22514,17 @@ var IntentDataType = /* @__PURE__ */ ((IntentDataType2) => {
|
|
|
22415
22514
|
})(IntentDataType || {});
|
|
22416
22515
|
var HOOK_DELIVERY_ABI = {
|
|
22417
22516
|
// HyperCoreDepositHook expects `abi.encode(address)` — the HyperCore account to credit.
|
|
22418
|
-
[HookKind.HYPERCORE_DEPOSIT]: [{ name: "recipient", type: "address" }]
|
|
22517
|
+
[HookKind.HYPERCORE_DEPOSIT]: [{ name: "recipient", type: "address" }],
|
|
22518
|
+
// FlintDepositHook expects `abi.encode(address)` — the ERC-7540 controller the deposit request is
|
|
22519
|
+
// recorded against, i.e. the account that ends up owning the resulting flUSD shares. Same shape as
|
|
22520
|
+
// HyperCore's today; kept as its own entry so the two can diverge without touching each other.
|
|
22521
|
+
[HookKind.FLINT_DEPOSIT]: [{ name: "recipient", type: "address" }]
|
|
22522
|
+
};
|
|
22523
|
+
var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
22524
|
+
var assertUnsupportedHook = (request) => {
|
|
22525
|
+
throw new Error(
|
|
22526
|
+
`[HookService.encodeDeliveryData] Unsupported delivery hook kind: ${request.kind}`
|
|
22527
|
+
);
|
|
22419
22528
|
};
|
|
22420
22529
|
var HookService = class _HookService {
|
|
22421
22530
|
constructor() {
|
|
@@ -22424,17 +22533,28 @@ var HookService = class _HookService {
|
|
|
22424
22533
|
* Encodes a hook's `deliveryData` payload. One common entry point for all hooks — the encoding is
|
|
22425
22534
|
* selected by {@link HookRequest.kind} and uses that hook's schema from {@link HOOK_DELIVERY_ABI}.
|
|
22426
22535
|
*
|
|
22536
|
+
* Rejects the zero address. Every hook treats its recipient as the account to credit, and a
|
|
22537
|
+
* zero recipient is unrecoverable on arrival: the receiver reverts, which rolls back the whole
|
|
22538
|
+
* cross-chain withdrawal inside `SpokeAssetManager.recvMessage` and leaves the message wedged —
|
|
22539
|
+
* every retry hits the same revert. Failing here keeps that mistake client-side, before an intent
|
|
22540
|
+
* exists. Malformed and non-EVM addresses already throw inside viem's encoder.
|
|
22541
|
+
*
|
|
22427
22542
|
* @param request - The hook selection (and any hook-specific params).
|
|
22428
22543
|
* @param recipient - The end recipient the hook should credit (the intent's `dstAddress`).
|
|
22429
22544
|
*/
|
|
22430
22545
|
static encodeDeliveryData(request, recipient) {
|
|
22546
|
+
invariant(
|
|
22547
|
+
recipient.toLowerCase() !== ZERO_ADDRESS,
|
|
22548
|
+
"[HookService.encodeDeliveryData] recipient (dstAddress) must not be the zero address"
|
|
22549
|
+
);
|
|
22431
22550
|
switch (request.kind) {
|
|
22432
22551
|
case HookKind.HYPERCORE_DEPOSIT:
|
|
22433
22552
|
return encodeAbiParameters(HOOK_DELIVERY_ABI[HookKind.HYPERCORE_DEPOSIT], [recipient]);
|
|
22553
|
+
case HookKind.FLINT_DEPOSIT:
|
|
22554
|
+
return encodeAbiParameters(HOOK_DELIVERY_ABI[HookKind.FLINT_DEPOSIT], [recipient]);
|
|
22555
|
+
default:
|
|
22556
|
+
return assertUnsupportedHook(request);
|
|
22434
22557
|
}
|
|
22435
|
-
throw new Error(
|
|
22436
|
-
`[HookService.encodeDeliveryData] Unsupported delivery hook kind: ${request.kind}`
|
|
22437
|
-
);
|
|
22438
22558
|
}
|
|
22439
22559
|
/**
|
|
22440
22560
|
* Resolves a high-level {@link HookRequest} to the on-chain delivery pair: the deployed hook address
|
|
@@ -24802,6 +24922,12 @@ var SpokeService = class _SpokeService {
|
|
|
24802
24922
|
/**
|
|
24803
24923
|
* Approve ERC-20 spending on hub / EVM spoke or request a Stellar trustline using unified params.
|
|
24804
24924
|
* Feature services map their action payloads into {@link SpokeApproveParams}.
|
|
24925
|
+
*
|
|
24926
|
+
* A signed ERC-20 approval can take **two** transactions: a token of the TetherToken lineage
|
|
24927
|
+
* rejects an allowance change from one non-zero value to another, so a stale allowance is zeroed
|
|
24928
|
+
* first and the user signs twice. The returned hash is always the last transaction's, so the
|
|
24929
|
+
* contract callers see is unchanged. An unsigned caller still gets exactly one transaction — use
|
|
24930
|
+
* {@link SpokeService.buildApproveTxs} to get the whole plan.
|
|
24805
24931
|
*/
|
|
24806
24932
|
async approve(params) {
|
|
24807
24933
|
try {
|
|
@@ -24809,53 +24935,168 @@ var SpokeService = class _SpokeService {
|
|
|
24809
24935
|
isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, params.walletProvider),
|
|
24810
24936
|
`Invalid wallet provider for chain key: ${params.srcChainKey}, walletProvider.chainType: ${params.walletProvider?.chainType}`
|
|
24811
24937
|
);
|
|
24812
|
-
if (isSpokeApproveParamsHub(params)) {
|
|
24813
|
-
|
|
24814
|
-
|
|
24815
|
-
|
|
24816
|
-
|
|
24817
|
-
|
|
24818
|
-
|
|
24819
|
-
|
|
24938
|
+
if (isSpokeApproveParamsHub(params) || isSpokeApproveParamsEvmSpoke(params)) {
|
|
24939
|
+
if (params.raw) {
|
|
24940
|
+
const tx = await Erc20Service.approve({
|
|
24941
|
+
...params,
|
|
24942
|
+
token: params.token,
|
|
24943
|
+
amount: params.amount,
|
|
24944
|
+
from: params.owner,
|
|
24945
|
+
spender: params.spender
|
|
24946
|
+
});
|
|
24947
|
+
return { ok: true, value: tx };
|
|
24948
|
+
}
|
|
24949
|
+
const result = await this.executeErc20ApprovalPlan(params);
|
|
24950
|
+
if (!result.ok) {
|
|
24951
|
+
return result;
|
|
24952
|
+
}
|
|
24820
24953
|
return {
|
|
24821
24954
|
ok: true,
|
|
24822
|
-
value: result
|
|
24955
|
+
value: result.value
|
|
24823
24956
|
};
|
|
24824
24957
|
}
|
|
24825
|
-
if (
|
|
24826
|
-
const result = await
|
|
24827
|
-
...params,
|
|
24828
|
-
token: params.token,
|
|
24829
|
-
amount: params.amount,
|
|
24830
|
-
from: params.owner,
|
|
24831
|
-
spender: params.spender
|
|
24832
|
-
});
|
|
24958
|
+
if (isSpokeApproveParamsStellar(params)) {
|
|
24959
|
+
const result = await this.requestTrustlineForApproval(params);
|
|
24833
24960
|
return {
|
|
24834
24961
|
ok: true,
|
|
24835
24962
|
value: result
|
|
24836
24963
|
};
|
|
24837
24964
|
}
|
|
24838
|
-
|
|
24839
|
-
|
|
24840
|
-
|
|
24841
|
-
|
|
24842
|
-
|
|
24965
|
+
return {
|
|
24966
|
+
ok: false,
|
|
24967
|
+
error: new Error("[SpokeService.approve] Only hub (Sonic), EVM spokes, and Stellar are supported")
|
|
24968
|
+
};
|
|
24969
|
+
} catch (error) {
|
|
24970
|
+
return { ok: false, error };
|
|
24971
|
+
}
|
|
24972
|
+
}
|
|
24973
|
+
/**
|
|
24974
|
+
* The unsigned approval transactions, named rather than ordered (see {@link ApprovalTxs}).
|
|
24975
|
+
*
|
|
24976
|
+
* `resetTx` is present only when the token needs its stale allowance cleared first (see
|
|
24977
|
+
* {@link Erc20Service.planApproval}); broadcast it and wait for it to be mined before `approveTx`,
|
|
24978
|
+
* which is not valid until the reset has landed. Unsigned callers — the swaps API and the apps
|
|
24979
|
+
* built on it — need this, because {@link SpokeService.approve} can only hand back a single `tx`.
|
|
24980
|
+
*
|
|
24981
|
+
* Deliberately separate from {@link SpokeService.approve} rather than a mode of it: the two return
|
|
24982
|
+
* genuinely different shapes, and folding them together would put a union in the return type of
|
|
24983
|
+
* the method every feature approves through.
|
|
24984
|
+
*/
|
|
24985
|
+
async buildApproveTxs(params) {
|
|
24986
|
+
try {
|
|
24987
|
+
if (isSpokeApproveParamsHub(params) || isSpokeApproveParamsEvmSpoke(params)) {
|
|
24988
|
+
const plan = await this.planErc20Approval(params, "buildApproveTxs");
|
|
24989
|
+
const encode3 = (amount) => Erc20Service.approve({
|
|
24843
24990
|
token: params.token,
|
|
24844
|
-
amount
|
|
24991
|
+
amount,
|
|
24992
|
+
from: params.owner,
|
|
24993
|
+
spender: params.spender,
|
|
24994
|
+
raw: true
|
|
24845
24995
|
});
|
|
24996
|
+
const resetTx = plan.resetAmount === void 0 ? void 0 : await encode3(plan.resetAmount);
|
|
24997
|
+
const approveTx = await encode3(plan.approveAmount);
|
|
24998
|
+
return { ok: true, value: resetTx === void 0 ? { approveTx } : { resetTx, approveTx } };
|
|
24999
|
+
}
|
|
25000
|
+
if (isSpokeApproveParamsStellar(params)) {
|
|
25001
|
+
const tx = await this.requestTrustlineForApproval({ ...params, raw: true });
|
|
24846
25002
|
return {
|
|
24847
25003
|
ok: true,
|
|
24848
|
-
value:
|
|
25004
|
+
value: { approveTx: tx }
|
|
24849
25005
|
};
|
|
24850
25006
|
}
|
|
24851
25007
|
return {
|
|
24852
25008
|
ok: false,
|
|
24853
|
-
error: new Error("[SpokeService.
|
|
25009
|
+
error: new Error("[SpokeService.buildApproveTxs] Only hub (Sonic), EVM spokes, and Stellar are supported")
|
|
24854
25010
|
};
|
|
24855
25011
|
} catch (error) {
|
|
24856
25012
|
return { ok: false, error };
|
|
24857
25013
|
}
|
|
24858
25014
|
}
|
|
25015
|
+
/**
|
|
25016
|
+
* Sign and broadcast the approval plan for an ERC-20 on the hub or an EVM spoke.
|
|
25017
|
+
*
|
|
25018
|
+
* A token of the TetherToken lineage rejects an allowance change from one non-zero value to
|
|
25019
|
+
* another, so a wallet holding a stale allowance needs `approve(0)` first. The transactions cannot
|
|
25020
|
+
* be batched: each one is only valid once its predecessor has been mined. The hash of the last is
|
|
25021
|
+
* returned, so the contract callers see is unchanged.
|
|
25022
|
+
*/
|
|
25023
|
+
async executeErc20ApprovalPlan(params) {
|
|
25024
|
+
const { walletProvider } = params;
|
|
25025
|
+
invariant(
|
|
25026
|
+
walletProvider !== void 0 && isEvmWalletProviderType(walletProvider),
|
|
25027
|
+
"[SpokeService.approve] Expected an EVM wallet provider for a signed approval"
|
|
25028
|
+
);
|
|
25029
|
+
const plan = await this.planErc20Approval(params, "approve");
|
|
25030
|
+
const sendApprove = (amount) => Erc20Service.approve({
|
|
25031
|
+
token: params.token,
|
|
25032
|
+
amount,
|
|
25033
|
+
from: params.owner,
|
|
25034
|
+
spender: params.spender,
|
|
25035
|
+
raw: false,
|
|
25036
|
+
walletProvider
|
|
25037
|
+
});
|
|
25038
|
+
if (plan.resetAmount !== void 0) {
|
|
25039
|
+
const resetHash = await sendApprove(plan.resetAmount);
|
|
25040
|
+
const receipt = await this.waitForTxReceipt({ txHash: resetHash, chainKey: params.srcChainKey });
|
|
25041
|
+
if (!receipt.ok || receipt.value.status !== "success") {
|
|
25042
|
+
return {
|
|
25043
|
+
ok: false,
|
|
25044
|
+
error: new Error(
|
|
25045
|
+
`[SpokeService.approve] allowance reset transaction ${resetHash} did not confirm. Retry the approval \u2014 once the reset has landed it takes a single transaction.`
|
|
25046
|
+
)
|
|
25047
|
+
};
|
|
25048
|
+
}
|
|
25049
|
+
}
|
|
25050
|
+
const txHash = await sendApprove(plan.approveAmount);
|
|
25051
|
+
return { ok: true, value: txHash };
|
|
25052
|
+
}
|
|
25053
|
+
/**
|
|
25054
|
+
* Stellar approves by adding a trustline — always a single transaction, with no allowance to plan
|
|
25055
|
+
* around. Shared by both entry points so the param mapping and its cast live in one place.
|
|
25056
|
+
*/
|
|
25057
|
+
requestTrustlineForApproval(params) {
|
|
25058
|
+
return this.stellar.requestTrustline({
|
|
25059
|
+
...params,
|
|
25060
|
+
srcAddress: params.owner,
|
|
25061
|
+
srcChainKey: params.srcChainKey,
|
|
25062
|
+
token: params.token,
|
|
25063
|
+
amount: params.amount
|
|
25064
|
+
});
|
|
25065
|
+
}
|
|
25066
|
+
/** Resolve the chain-specific inputs {@link Erc20Service.planApproval} needs, and record the plan. */
|
|
25067
|
+
async planErc20Approval(params, caller) {
|
|
25068
|
+
const plan = await Erc20Service.planApproval({
|
|
25069
|
+
token: params.token,
|
|
25070
|
+
owner: params.owner,
|
|
25071
|
+
spender: params.spender,
|
|
25072
|
+
amount: params.amount,
|
|
25073
|
+
nativeToken: this.config.getChainConfig(params.srcChainKey).nativeToken,
|
|
25074
|
+
publicClient: this.getEvmPublicClient(params.srcChainKey)
|
|
25075
|
+
});
|
|
25076
|
+
this.logApprovalPlan(caller, params.srcChainKey, params.token, plan);
|
|
25077
|
+
return plan;
|
|
25078
|
+
}
|
|
25079
|
+
/** The read client for an EVM chain, whether it is the hub or a spoke. */
|
|
25080
|
+
getEvmPublicClient(chainKey) {
|
|
25081
|
+
return isHubChainKeyType(chainKey) ? this.sonic.publicClient : this.evm.getPublicClient(chainKey);
|
|
25082
|
+
}
|
|
25083
|
+
/**
|
|
25084
|
+
* Log a plan only when it says something: an extra transaction the user will have to sign, or a
|
|
25085
|
+
* probe that could not reach a verdict. The ordinary single approve is the vast majority of calls
|
|
25086
|
+
* and stays silent.
|
|
25087
|
+
*/
|
|
25088
|
+
logApprovalPlan(caller, chainKey, token, plan) {
|
|
25089
|
+
const isNoteworthy = plan.resetAmount !== void 0 || plan.reason === "reset-not-viable" || plan.reason === "allowance-read-failed";
|
|
25090
|
+
if (!isNoteworthy) {
|
|
25091
|
+
return;
|
|
25092
|
+
}
|
|
25093
|
+
this.config.logger.debug(`[SpokeService.${caller}] approval plan`, {
|
|
25094
|
+
chainKey,
|
|
25095
|
+
token,
|
|
25096
|
+
needsReset: plan.resetAmount !== void 0,
|
|
25097
|
+
reason: plan.reason
|
|
25098
|
+
});
|
|
25099
|
+
}
|
|
24859
25100
|
/**
|
|
24860
25101
|
* Estimate the gas for a raw transaction.
|
|
24861
25102
|
* @param {TxReturnType<T, true>} params - The parameters for the raw transaction.
|
|
@@ -26696,19 +26937,20 @@ var SolverApiService = class {
|
|
|
26696
26937
|
|
|
26697
26938
|
// src/backendApi/pollBackendSubmitTx.ts
|
|
26698
26939
|
async function pollBackendSubmitTx({
|
|
26699
|
-
|
|
26940
|
+
attempt,
|
|
26700
26941
|
terminalStatus,
|
|
26701
26942
|
getStatus,
|
|
26702
26943
|
onExecuted,
|
|
26703
26944
|
intervalMs = 1e3,
|
|
26704
26945
|
requestTimeoutMs
|
|
26705
26946
|
}) {
|
|
26706
|
-
|
|
26707
|
-
|
|
26708
|
-
|
|
26709
|
-
|
|
26710
|
-
const statusResult = await getStatus(
|
|
26947
|
+
let polls = 0;
|
|
26948
|
+
let lastStatusError;
|
|
26949
|
+
for (let requestTimeout = attempt.requestTimeout(requestTimeoutMs); requestTimeout !== null; requestTimeout = attempt.requestTimeout(requestTimeoutMs)) {
|
|
26950
|
+
polls += 1;
|
|
26951
|
+
const statusResult = await getStatus({ timeout: requestTimeout });
|
|
26711
26952
|
if (statusResult.ok) {
|
|
26953
|
+
lastStatusError = void 0;
|
|
26712
26954
|
const { status, result, failureReason, abandonedAt } = statusResult.value.data;
|
|
26713
26955
|
if (status === terminalStatus) {
|
|
26714
26956
|
const value = onExecuted(result);
|
|
@@ -26718,11 +26960,70 @@ async function pollBackendSubmitTx({
|
|
|
26718
26960
|
const reason = failureReason ? `: ${failureReason}` : "";
|
|
26719
26961
|
return { ok: false, cause: new Error(`backend submit-tx ${status}${reason}`) };
|
|
26720
26962
|
}
|
|
26963
|
+
} else {
|
|
26964
|
+
lastStatusError = statusResult.error;
|
|
26721
26965
|
}
|
|
26722
|
-
|
|
26966
|
+
if (attempt.remaining() <= intervalMs) break;
|
|
26967
|
+
await sleep(intervalMs);
|
|
26968
|
+
}
|
|
26969
|
+
if (polls === 0) {
|
|
26970
|
+
return { ok: false, cause: new Error("backend submit-tx submitted, but no budget was left to poll for status") };
|
|
26971
|
+
}
|
|
26972
|
+
if (lastStatusError !== void 0) {
|
|
26973
|
+
return {
|
|
26974
|
+
ok: false,
|
|
26975
|
+
cause: new Error(`backend submit-tx status polling failed before reaching ${terminalStatus}`, {
|
|
26976
|
+
cause: lastStatusError
|
|
26977
|
+
})
|
|
26978
|
+
};
|
|
26723
26979
|
}
|
|
26724
26980
|
return { ok: false, cause: new Error(`backend submit-tx polling timed out before reaching ${terminalStatus}`) };
|
|
26725
26981
|
}
|
|
26982
|
+
|
|
26983
|
+
// src/backendApi/submitTxAttempt.ts
|
|
26984
|
+
function noRequestBudgetCause(serviceTimeoutMs) {
|
|
26985
|
+
return serviceTimeoutMs > 0 ? new Error("backend submit-tx skipped: the caller timeout left no budget for the attempt") : new Error(`backend submit-tx skipped: api timeout must be a positive number, got ${serviceTimeoutMs}`);
|
|
26986
|
+
}
|
|
26987
|
+
function createSubmitTxAttempt(callerTimeoutMs) {
|
|
26988
|
+
const deadline = Date.now() + resolveTimeoutMs(callerTimeoutMs, 0);
|
|
26989
|
+
const remaining = () => Math.max(0, deadline - Date.now());
|
|
26990
|
+
return {
|
|
26991
|
+
remaining,
|
|
26992
|
+
requestTimeout: (serviceTimeoutMs) => {
|
|
26993
|
+
const timeout = Math.min(remaining(), serviceTimeoutMs);
|
|
26994
|
+
return timeout > 0 ? timeout : null;
|
|
26995
|
+
}
|
|
26996
|
+
};
|
|
26997
|
+
}
|
|
26998
|
+
|
|
26999
|
+
// src/backendApi/runBackendSubmitTx.ts
|
|
27000
|
+
async function runBackendSubmitTx({
|
|
27001
|
+
attempt,
|
|
27002
|
+
api,
|
|
27003
|
+
body,
|
|
27004
|
+
statusQuery,
|
|
27005
|
+
terminalStatus,
|
|
27006
|
+
onExecuted
|
|
27007
|
+
}) {
|
|
27008
|
+
const serviceTimeoutMs = api.getTimeout();
|
|
27009
|
+
const requestTimeout = attempt.requestTimeout(serviceTimeoutMs);
|
|
27010
|
+
if (requestTimeout === null) return { ok: false, cause: noRequestBudgetCause(serviceTimeoutMs) };
|
|
27011
|
+
const submitted = await api.submitTx(body, { timeout: requestTimeout });
|
|
27012
|
+
if (!submitted.ok) return { ok: false, cause: submitted.error };
|
|
27013
|
+
if (!submitted.value.success) {
|
|
27014
|
+
return { ok: false, cause: new Error(`backend submit-tx not accepted: ${submitted.value.data.message}`) };
|
|
27015
|
+
}
|
|
27016
|
+
const polled = await pollBackendSubmitTx({
|
|
27017
|
+
attempt,
|
|
27018
|
+
terminalStatus,
|
|
27019
|
+
getStatus: (override) => api.getSubmitTxStatus(statusQuery, override),
|
|
27020
|
+
onExecuted,
|
|
27021
|
+
// While this ceiling is the smaller bound the poll retries within the attempt; once the attempt's
|
|
27022
|
+
// remainder falls below it, one stalled request can spend the rest.
|
|
27023
|
+
requestTimeoutMs: serviceTimeoutMs
|
|
27024
|
+
});
|
|
27025
|
+
return polled.ok ? { ok: true, value: polled.value } : { ok: false, cause: polled.cause };
|
|
27026
|
+
}
|
|
26726
27027
|
function decodePacketIntentTarget(payload) {
|
|
26727
27028
|
try {
|
|
26728
27029
|
const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
|
|
@@ -26773,20 +27074,33 @@ var SwapService = class {
|
|
|
26773
27074
|
spoke;
|
|
26774
27075
|
// swap config
|
|
26775
27076
|
solver;
|
|
26776
|
-
partnerFee;
|
|
26777
27077
|
relayerApiEndpoint;
|
|
26778
|
-
// backend swaps-API client
|
|
27078
|
+
// backend swaps-API client
|
|
26779
27079
|
backendApi;
|
|
26780
|
-
|
|
26781
|
-
|
|
27080
|
+
/**
|
|
27081
|
+
* Effective 2-step submit-tx flow (`swaps.useBackendSubmitTx`, default on). Read live off
|
|
27082
|
+
* `ConfigService`, like {@link SwapService.partnerFee}, so the config object and the behavior can
|
|
27083
|
+
* never disagree.
|
|
27084
|
+
*/
|
|
27085
|
+
get useBackendSubmitTx() {
|
|
27086
|
+
return this.config.swapUseBackendSubmitTx;
|
|
27087
|
+
}
|
|
27088
|
+
/**
|
|
27089
|
+
* Effective swap partner fee (`swaps.partnerFee`, else the global `fee`). Read live off
|
|
27090
|
+
* `ConfigService` rather than snapshotted in the constructor, so it cannot diverge from
|
|
27091
|
+
* `config.swapPartnerFee` if the config object is ever replaced (see `ConfigService.initialize`).
|
|
27092
|
+
* `BridgeService` and `LeverageYieldService` resolve their fees the same way.
|
|
27093
|
+
*/
|
|
27094
|
+
get partnerFee() {
|
|
27095
|
+
return this.config.swapPartnerFee;
|
|
27096
|
+
}
|
|
27097
|
+
constructor({ config, hubProvider, spoke, backendApi }) {
|
|
26782
27098
|
this.solver = config.solver;
|
|
26783
|
-
this.partnerFee = config.swapPartnerFee;
|
|
26784
27099
|
this.relayerApiEndpoint = config.relay.relayerApiEndpoint;
|
|
26785
27100
|
this.config = config;
|
|
26786
27101
|
this.hubProvider = hubProvider;
|
|
26787
27102
|
this.spoke = spoke;
|
|
26788
27103
|
this.backendApi = backendApi;
|
|
26789
|
-
this.useBackendSubmitTx = useBackendSubmitTx ?? false;
|
|
26790
27104
|
}
|
|
26791
27105
|
/**
|
|
26792
27106
|
* Estimates the gas cost for a raw (unsigned) transaction on a spoke chain.
|
|
@@ -26931,21 +27245,26 @@ var SwapService = class {
|
|
|
26931
27245
|
* Executes a full end-to-end cross-chain swap.
|
|
26932
27246
|
*
|
|
26933
27247
|
* Orchestrates the complete swap lifecycle. `createIntent` first submits the intent transaction on
|
|
26934
|
-
* the source spoke chain; completion then runs via one of two paths,
|
|
26935
|
-
*
|
|
26936
|
-
*
|
|
26937
|
-
* - **Client-side (
|
|
26938
|
-
* relays it to the hub (Sonic) and waits for the packet — skipped when
|
|
26939
|
-
* where the spoke tx already is the hub tx — then calls `postExecution` to
|
|
26940
|
-
* triggering it to fill the intent.
|
|
26941
|
-
* - **Backend 2-step (
|
|
27248
|
+
* the source spoke chain; completion then runs via one of two paths, each bounded by its own `timeout`
|
|
27249
|
+
* budget:
|
|
27250
|
+
*
|
|
27251
|
+
* - **Client-side (opt-out via `swaps.useBackendSubmitTx: false`), {@link fallbackSwapSteps}:** verifies
|
|
27252
|
+
* the spoke tx landed on-chain, relays it to the hub (Sonic) and waits for the packet — skipped when
|
|
27253
|
+
* `srcChainKey` is the hub, where the spoke tx already is the hub tx — then calls `postExecution` to
|
|
27254
|
+
* notify the solver, triggering it to fill the intent.
|
|
27255
|
+
* - **Backend 2-step (default via `swaps.useBackendSubmitTx`), {@link submitTx}:** hands the
|
|
26942
27256
|
* broadcast tx to the swaps API, which verifies, relays and post-executes server-side, then polls
|
|
26943
27257
|
* for completion. On ANY non-success it transparently falls back to the client-side path above —
|
|
26944
27258
|
* safe because re-relaying / re-posting an already-processed swap is idempotent (no double-fill).
|
|
26945
27259
|
*
|
|
26946
27260
|
* @param _params - Swap action params including intent parameters, wallet provider, and an optional
|
|
26947
|
-
* `timeout` —
|
|
26948
|
-
*
|
|
27261
|
+
* `timeout` — a PER-ATTEMPT budget, not an end-to-end one. The backend attempt (submit POST + status
|
|
27262
|
+
* poll) gets it, and if that attempt does not complete the client-side relay wait gets a fresh one
|
|
27263
|
+
* starting after verification, so neither a stalled backend nor a slow source-chain confirmation can
|
|
27264
|
+
* shorten it. Worst-case wall-clock is `createIntent + timeout + verification +
|
|
27265
|
+
* max(timeout, RELAY_FALLBACK_FLOOR_MS) + postExecution`, where verification is bounded by the source
|
|
27266
|
+
* chain's `pollingConfig.maxTimeoutMs` and the first and last terms are not bounded by `timeout` at
|
|
27267
|
+
* all. See `docs/SWAPS.md` § How `timeout` bounds each attempt.
|
|
26949
27268
|
* @returns A `Result<SwapResponse, SwapError>`. On success:
|
|
26950
27269
|
* - `solverExecutionResponse` — solver acknowledgement (`{ answer: 'OK', intent_hash }`).
|
|
26951
27270
|
* - `intent` — the on-chain intent object that was created.
|
|
@@ -26979,9 +27298,9 @@ var SwapService = class {
|
|
|
26979
27298
|
return { ok: false, error: createIntentResult.error };
|
|
26980
27299
|
}
|
|
26981
27300
|
const created = createIntentResult.value;
|
|
26982
|
-
const
|
|
27301
|
+
const timeoutMs = resolveTimeoutMs(_params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
26983
27302
|
if (this.useBackendSubmitTx) {
|
|
26984
|
-
const submitted = await this.submitTx(_params, created,
|
|
27303
|
+
const submitted = await this.submitTx(_params, created, createSubmitTxAttempt(timeoutMs));
|
|
26985
27304
|
if (submitted.ok) return submitted;
|
|
26986
27305
|
this.config.logger.warn(
|
|
26987
27306
|
"[swap] backend submit-tx did not complete; falling back to the client-side relay",
|
|
@@ -26990,7 +27309,7 @@ var SwapService = class {
|
|
|
26990
27309
|
}
|
|
26991
27310
|
);
|
|
26992
27311
|
}
|
|
26993
|
-
return this.fallbackSwapSteps(_params, created,
|
|
27312
|
+
return this.fallbackSwapSteps(_params, created, timeoutMs);
|
|
26994
27313
|
} catch (error) {
|
|
26995
27314
|
if (isSwapError(error)) return { ok: false, error };
|
|
26996
27315
|
return {
|
|
@@ -27017,12 +27336,16 @@ var SwapService = class {
|
|
|
27017
27336
|
);
|
|
27018
27337
|
}
|
|
27019
27338
|
/**
|
|
27020
|
-
* Client-side swap completion (
|
|
27021
|
-
* use it directly when the source IS the hub — then notify the
|
|
27022
|
-
* build the {@link SwapResponse}. Extracted verbatim from `swap()` so the
|
|
27023
|
-
* path ({@link submitTx}) can fall back to it on any non-success.
|
|
27339
|
+
* Client-side swap completion (opt-out via `swaps.useBackendSubmitTx: false`): verify the broadcast intent
|
|
27340
|
+
* tx landed, then relay it to the hub — or use it directly when the source IS the hub — then notify the
|
|
27341
|
+
* solver via post-execution and build the {@link SwapResponse}. Extracted verbatim from `swap()` so the
|
|
27342
|
+
* backend 2-step path ({@link submitTx}) can fall back to it on any non-success.
|
|
27343
|
+
*
|
|
27344
|
+
* Verification belongs to THIS path only: the backend runs its own, so verifying before handing over
|
|
27345
|
+
* would delay every backend success by the source chain's confirmation wait and could fail a swap the
|
|
27346
|
+
* backend would have completed.
|
|
27024
27347
|
*/
|
|
27025
|
-
async fallbackSwapSteps(_params, created,
|
|
27348
|
+
async fallbackSwapSteps(_params, created, timeoutMs) {
|
|
27026
27349
|
const { params } = _params;
|
|
27027
27350
|
const srcChainKey = params.srcChainKey;
|
|
27028
27351
|
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
|
|
@@ -27043,9 +27366,12 @@ var SwapService = class {
|
|
|
27043
27366
|
data: relayData,
|
|
27044
27367
|
chainKey: srcChainKey,
|
|
27045
27368
|
relayerApiEndpoint: this.relayerApiEndpoint,
|
|
27046
|
-
//
|
|
27047
|
-
//
|
|
27048
|
-
|
|
27369
|
+
// The caller's full `timeout`, starting HERE — after verification, and whether this runs as the
|
|
27370
|
+
// only path or as the backend's fallback. Neither a stalled backend attempt nor a slow source-chain
|
|
27371
|
+
// confirmation may shorten the relay wait. The floor covers a sub-floor caller `timeout`:
|
|
27372
|
+
// `relayTxAndWaitPacket` SUBMITS before `timeout` bounds anything, so a zero budget would strand an
|
|
27373
|
+
// already-landed tx unrelayed. Re-relay is idempotent, so spending it is safe.
|
|
27374
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS)
|
|
27049
27375
|
});
|
|
27050
27376
|
if (!packet.ok) {
|
|
27051
27377
|
return { ok: false, error: mapRelayFailure(packet.error, { feature: "swap", action: "swap", ...baseCtx }) };
|
|
@@ -27075,7 +27401,7 @@ var SwapService = class {
|
|
|
27075
27401
|
};
|
|
27076
27402
|
}
|
|
27077
27403
|
/**
|
|
27078
|
-
* Backend 2-step swap path (
|
|
27404
|
+
* Backend 2-step swap path (default via `swaps.useBackendSubmitTx`): hand the broadcast
|
|
27079
27405
|
* intent tx to the swaps API (`POST /swaps/submit-tx`); the backend relays + post-executes
|
|
27080
27406
|
* server-side. Polls `getSubmitTxStatus` until `solved`, then reconstructs the same
|
|
27081
27407
|
* {@link SwapResponse} the client-side path returns (`result.dstIntentTxHash` → delivery info,
|
|
@@ -27086,32 +27412,36 @@ var SwapService = class {
|
|
|
27086
27412
|
*
|
|
27087
27413
|
* Falling back is safe: re-relaying / re-posting an already-processed swap is idempotent — the
|
|
27088
27414
|
* relay dedups and returns the existing `executed` packet, and the solver re-affirms the intent
|
|
27089
|
-
* (no double-fill). Verified live by `e2e-tests/e2e-relay.test.ts`.
|
|
27090
|
-
*
|
|
27415
|
+
* (no double-fill). Verified live by `e2e-tests/e2e-relay.test.ts`. It is also load-bearing rather
|
|
27416
|
+
* than belt-and-braces: the backend keeps processing after this attempt gives up, so the fallback's
|
|
27417
|
+
* relay can race the backend's own.
|
|
27418
|
+
*
|
|
27419
|
+
* The attempt itself — POST, budget clamps, status poll — is {@link runBackendSubmitTx}, shared with
|
|
27420
|
+
* bridge. What is swap-specific and lives here: the request body, the `solved` terminal status, the
|
|
27421
|
+
* mapping from a terminal result to a {@link SwapResponse}, and the swap error taxonomy.
|
|
27422
|
+
*
|
|
27423
|
+
* `attempt` bounds this attempt alone — the POST and every status request draw on it, and the
|
|
27424
|
+
* client-side fallback holds a separate fresh `timeout`.
|
|
27091
27425
|
*/
|
|
27092
|
-
async submitTx(_params, created,
|
|
27426
|
+
async submitTx(_params, created, attempt) {
|
|
27093
27427
|
const { params } = _params;
|
|
27094
27428
|
const srcChainKey = params.srcChainKey;
|
|
27095
27429
|
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
|
|
27096
27430
|
const { tx: spokeTxHash, intent, relayData } = created;
|
|
27097
|
-
const submitTxFailed = (cause) => ({
|
|
27098
|
-
ok: false,
|
|
27099
|
-
error: executionFailed("swap", cause, { ...baseCtx, action: "swap" })
|
|
27100
|
-
});
|
|
27101
27431
|
try {
|
|
27102
|
-
const
|
|
27103
|
-
|
|
27104
|
-
|
|
27105
|
-
|
|
27106
|
-
|
|
27107
|
-
|
|
27108
|
-
|
|
27109
|
-
|
|
27110
|
-
|
|
27111
|
-
|
|
27432
|
+
const outcome = await runBackendSubmitTx({
|
|
27433
|
+
attempt,
|
|
27434
|
+
api: this.backendApi.swaps,
|
|
27435
|
+
body: {
|
|
27436
|
+
txHash: spokeTxHash,
|
|
27437
|
+
srcChainKey,
|
|
27438
|
+
walletAddress: params.srcAddress,
|
|
27439
|
+
intent,
|
|
27440
|
+
relayData: relayData.payload
|
|
27441
|
+
},
|
|
27442
|
+
statusQuery: { txHash: spokeTxHash, srcChainKey },
|
|
27112
27443
|
// Swaps terminal success is `solved` (solver filled) — not the bridge `executed`.
|
|
27113
27444
|
terminalStatus: "solved",
|
|
27114
|
-
getStatus: () => this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }),
|
|
27115
27445
|
onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
|
|
27116
27446
|
// Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
|
|
27117
27447
|
solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
|
|
@@ -27126,7 +27456,7 @@ var SwapService = class {
|
|
|
27126
27456
|
}
|
|
27127
27457
|
} : void 0
|
|
27128
27458
|
});
|
|
27129
|
-
return
|
|
27459
|
+
return outcome.ok ? { ok: true, value: outcome.value } : { ok: false, error: executionFailed("swap", outcome.cause, { ...baseCtx, action: "swap" }) };
|
|
27130
27460
|
} catch (error) {
|
|
27131
27461
|
return { ok: false, error: unknownFailed("swap", error, { ...baseCtx, action: "swap" }) };
|
|
27132
27462
|
}
|
|
@@ -27188,9 +27518,13 @@ var SwapService = class {
|
|
|
27188
27518
|
* - Stellar: approves the trustline (adds/increases it).
|
|
27189
27519
|
* - Other chain types: returns an error — approval is not supported.
|
|
27190
27520
|
*
|
|
27191
|
-
* When `raw: true`, returns unsigned transaction data instead of broadcasting.
|
|
27521
|
+
* When `raw: true`, returns unsigned transaction data instead of broadcasting. That is always a
|
|
27522
|
+
* single transaction, which cannot express the two-step approval a TetherToken-lineage token
|
|
27523
|
+
* needs when a stale allowance already exists — use {@link SwapService.buildApproveTxs} for the
|
|
27524
|
+
* whole plan.
|
|
27192
27525
|
* When `raw: false`, a matching wallet provider for `K` must be supplied and the transaction
|
|
27193
|
-
* is signed and broadcast immediately.
|
|
27526
|
+
* is signed and broadcast immediately. Such an approval can take **two** transactions, so the
|
|
27527
|
+
* user may sign twice; the returned hash is the last one's.
|
|
27194
27528
|
*
|
|
27195
27529
|
* @param _params - Swap action params including the source chain key, input token, amount, and wallet provider.
|
|
27196
27530
|
* @returns A `Result` wrapping the chain-specific transaction return type (`TxReturnType<K, Raw>`).
|
|
@@ -27260,6 +27594,62 @@ var SwapService = class {
|
|
|
27260
27594
|
return { ok: false, error };
|
|
27261
27595
|
}
|
|
27262
27596
|
}
|
|
27597
|
+
/**
|
|
27598
|
+
* The unsigned approval transactions for the swap's source token, in the order they must be
|
|
27599
|
+
* broadcast.
|
|
27600
|
+
*
|
|
27601
|
+
* Two transactions when the source token needs its stale allowance cleared first, one otherwise.
|
|
27602
|
+
* {@link SwapService.approve} is unchanged and still returns a single transaction; this is the
|
|
27603
|
+
* entry point for unsigned callers that need to handle the two-step case. When `resetTx` is
|
|
27604
|
+
* present, broadcast it and wait for it to be mined first — `approveTx` is not valid until the
|
|
27605
|
+
* reset has landed.
|
|
27606
|
+
*/
|
|
27607
|
+
async buildApproveTxs(_params) {
|
|
27608
|
+
const { params } = _params;
|
|
27609
|
+
const wrapApproveFailure = (cause) => approveFailed("swap", cause);
|
|
27610
|
+
try {
|
|
27611
|
+
if (isHubChainKeyType(params.srcChainKey) || isEvmSpokeOnlyChainKeyType(params.srcChainKey)) {
|
|
27612
|
+
const spender = isHubChainKeyType(params.srcChainKey) ? this.solver.intentsContract : this.config.getChainConfig(params.srcChainKey).addresses.assetManager;
|
|
27613
|
+
const result = await this.spoke.buildApproveTxs({
|
|
27614
|
+
srcChainKey: params.srcChainKey,
|
|
27615
|
+
owner: params.srcAddress,
|
|
27616
|
+
token: params.inputToken,
|
|
27617
|
+
amount: params.inputAmount,
|
|
27618
|
+
spender,
|
|
27619
|
+
raw: true
|
|
27620
|
+
});
|
|
27621
|
+
if (!result.ok) {
|
|
27622
|
+
return { ok: false, error: wrapApproveFailure(result.error) };
|
|
27623
|
+
}
|
|
27624
|
+
return {
|
|
27625
|
+
ok: true,
|
|
27626
|
+
value: result.value
|
|
27627
|
+
};
|
|
27628
|
+
}
|
|
27629
|
+
if (isStellarChainKeyType(params.srcChainKey)) {
|
|
27630
|
+
const result = await this.spoke.buildApproveTxs({
|
|
27631
|
+
srcChainKey: params.srcChainKey,
|
|
27632
|
+
token: params.inputToken,
|
|
27633
|
+
amount: params.inputAmount,
|
|
27634
|
+
owner: params.srcAddress,
|
|
27635
|
+
raw: true
|
|
27636
|
+
});
|
|
27637
|
+
if (!result.ok) {
|
|
27638
|
+
return { ok: false, error: wrapApproveFailure(result.error) };
|
|
27639
|
+
}
|
|
27640
|
+
return {
|
|
27641
|
+
ok: true,
|
|
27642
|
+
value: result.value
|
|
27643
|
+
};
|
|
27644
|
+
}
|
|
27645
|
+
return {
|
|
27646
|
+
ok: false,
|
|
27647
|
+
error: new Error("Approve only supported for hub (Sonic), EVM spokes, and Stellar")
|
|
27648
|
+
};
|
|
27649
|
+
} catch (error) {
|
|
27650
|
+
return { ok: false, error };
|
|
27651
|
+
}
|
|
27652
|
+
}
|
|
27263
27653
|
/**
|
|
27264
27654
|
* Creates a swap intent on the user's source spoke chain without submitting it to the solver.
|
|
27265
27655
|
*
|
|
@@ -29915,7 +30305,6 @@ async function makeRequest(params) {
|
|
|
29915
30305
|
body: config.body,
|
|
29916
30306
|
signal: controller.signal
|
|
29917
30307
|
});
|
|
29918
|
-
clearTimeout(timeoutId);
|
|
29919
30308
|
if (!response.ok) {
|
|
29920
30309
|
const errorText = await response.text();
|
|
29921
30310
|
throw new BackendHttpError(response.status, errorText);
|
|
@@ -29923,7 +30312,6 @@ async function makeRequest(params) {
|
|
|
29923
30312
|
const data = await response.json();
|
|
29924
30313
|
return data;
|
|
29925
30314
|
} catch (error) {
|
|
29926
|
-
clearTimeout(timeoutId);
|
|
29927
30315
|
if (error instanceof Error) {
|
|
29928
30316
|
if (error.name === "AbortError") {
|
|
29929
30317
|
throw new Error("REQUEST_TIMEOUT", { cause: new Error(`Request timeout after ${timeout}ms`) });
|
|
@@ -29933,6 +30321,8 @@ async function makeRequest(params) {
|
|
|
29933
30321
|
}
|
|
29934
30322
|
logger.error(`[${serviceLabel}] Unknown error`, error);
|
|
29935
30323
|
throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
|
|
30324
|
+
} finally {
|
|
30325
|
+
clearTimeout(timeoutId);
|
|
29936
30326
|
}
|
|
29937
30327
|
}
|
|
29938
30328
|
function resolveRequestConfig(config, defaults) {
|
|
@@ -30137,7 +30527,9 @@ var SwapsApiService = class _SwapsApiService {
|
|
|
30137
30527
|
// ──────────────────────────────────────────────────────────────────────
|
|
30138
30528
|
// Submit-tx state machine
|
|
30139
30529
|
// ──────────────────────────────────────────────────────────────────────
|
|
30140
|
-
/** Submit a swap transaction to be processed (relay, post-execution, etc.). Idempotent on `(txHash, srcChainKey)`.
|
|
30530
|
+
/** Submit a swap transaction to be processed (relay, post-execution, etc.). Idempotent on `(txHash, srcChainKey)`.
|
|
30531
|
+
* Response is immediate after successful submission. Use getSubmitTxStatus to poll the status of the submission.
|
|
30532
|
+
*/
|
|
30141
30533
|
async submitTx(body, config) {
|
|
30142
30534
|
return this.toResult(
|
|
30143
30535
|
"/swaps/submit-tx",
|
|
@@ -30166,6 +30558,18 @@ var SwapsApiService = class _SwapsApiService {
|
|
|
30166
30558
|
getBaseURL() {
|
|
30167
30559
|
return this.config.baseURL;
|
|
30168
30560
|
}
|
|
30561
|
+
/**
|
|
30562
|
+
* Return the effective per-request timeout (ms) — the same value {@link buildClient} resolves, so
|
|
30563
|
+
* `SwapsApiConfig.timeout` being optional never leaks an `undefined` ceiling.
|
|
30564
|
+
*
|
|
30565
|
+
* Callers bounding a request tighter than this need it as the CEILING, because a
|
|
30566
|
+
* `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it: an override
|
|
30567
|
+
* derived from a caller budget alone would raise the bound whenever that budget is the larger of the
|
|
30568
|
+
* two. `SubmitTxAttempt.requestTimeout` clamps against both (`min(budget left in the attempt, this)`).
|
|
30569
|
+
*/
|
|
30570
|
+
getTimeout() {
|
|
30571
|
+
return this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
|
|
30572
|
+
}
|
|
30169
30573
|
};
|
|
30170
30574
|
var StellarSponsorConfigSchema = v7.object({
|
|
30171
30575
|
sponsorAccount: v7.string(),
|
|
@@ -30652,9 +31056,12 @@ var BridgeApiService = class {
|
|
|
30652
31056
|
return this.config.baseURL;
|
|
30653
31057
|
}
|
|
30654
31058
|
/**
|
|
30655
|
-
* Return the effective per-request timeout (ms).
|
|
30656
|
-
*
|
|
30657
|
-
*
|
|
31059
|
+
* Return the effective per-request timeout (ms).
|
|
31060
|
+
*
|
|
31061
|
+
* Callers bounding a request tighter than this need it as the CEILING, because a
|
|
31062
|
+
* `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it: an override
|
|
31063
|
+
* derived from a caller budget alone would raise the bound whenever that budget is the larger of the
|
|
31064
|
+
* two. `SubmitTxAttempt.requestTimeout` clamps against both (`min(budget left in the attempt, this)`).
|
|
30658
31065
|
*/
|
|
30659
31066
|
getTimeout() {
|
|
30660
31067
|
return this.config.timeout;
|
|
@@ -31266,15 +31673,20 @@ var BridgeService = class {
|
|
|
31266
31673
|
hubProvider;
|
|
31267
31674
|
config;
|
|
31268
31675
|
spoke;
|
|
31269
|
-
// backend bridge-API client
|
|
31676
|
+
// backend bridge-API client
|
|
31270
31677
|
backendApi;
|
|
31271
|
-
|
|
31272
|
-
|
|
31678
|
+
/**
|
|
31679
|
+
* Effective backend submit-tx flow (`bridge.useBackendSubmitTx`, default on). Read live off
|
|
31680
|
+
* `ConfigService` like `bridgePartnerFee`, so the config object and the behavior can never disagree.
|
|
31681
|
+
*/
|
|
31682
|
+
get useBackendSubmitTx() {
|
|
31683
|
+
return this.config.bridgeUseBackendSubmitTx;
|
|
31684
|
+
}
|
|
31685
|
+
constructor({ hubProvider, config, spoke, backendApi }) {
|
|
31273
31686
|
this.config = config;
|
|
31274
31687
|
this.hubProvider = hubProvider;
|
|
31275
31688
|
this.spoke = spoke;
|
|
31276
31689
|
this.backendApi = backendApi;
|
|
31277
|
-
this.useBackendSubmitTx = useBackendSubmitTx ?? false;
|
|
31278
31690
|
}
|
|
31279
31691
|
/**
|
|
31280
31692
|
* Calculates the partner fee deducted from a given bridge input amount.
|
|
@@ -31439,15 +31851,27 @@ var BridgeService = class {
|
|
|
31439
31851
|
/**
|
|
31440
31852
|
* Executes a full end-to-end bridge transfer: spoke deposit → relay → hub settlement.
|
|
31441
31853
|
*
|
|
31442
|
-
* Internally calls `createBridgeIntent()` to submit the spoke-side deposit transaction,
|
|
31443
|
-
*
|
|
31444
|
-
*
|
|
31854
|
+
* Internally calls `createBridgeIntent()` to submit the spoke-side deposit transaction, then
|
|
31855
|
+
* completes the transfer via one of two paths. Use this method for the typical "fire and wait" UX.
|
|
31856
|
+
*
|
|
31857
|
+
* - **Backend submit-tx (default, `bridge.useBackendSubmitTx`), {@link submitTx}:** hands the deposit
|
|
31858
|
+
* to the bridge API, which relays server-side, and polls until `executed`. On ANY non-success it
|
|
31859
|
+
* falls back to the path below — safe because re-relaying is idempotent.
|
|
31860
|
+
* - **Client-side (opt-out with `useBackendSubmitTx: false`), {@link fallbackBridgeSteps}:** verifies
|
|
31861
|
+
* the deposit landed on-chain, then relays it and waits for the settlement packet. `verifyTxHash`
|
|
31862
|
+
* runs on this path only; the backend runs its own.
|
|
31445
31863
|
*
|
|
31446
31864
|
* For manual relay control (e.g. monitoring or batching), use `createBridgeIntent()` directly
|
|
31447
31865
|
* and handle the relay step yourself.
|
|
31448
31866
|
*
|
|
31449
31867
|
* @param _params - Bridge parameters including source/destination chain keys, token addresses,
|
|
31450
|
-
* amount, recipient address, wallet provider, and optional timeout
|
|
31868
|
+
* amount, recipient address, wallet provider, and an optional `timeout` — a PER-ATTEMPT budget,
|
|
31869
|
+
* not an end-to-end one. The backend attempt gets it, and if that attempt does not complete the
|
|
31870
|
+
* client-side relay wait gets a fresh one starting after verification, so neither a stalled backend
|
|
31871
|
+
* nor a slow source-chain confirmation can shorten it. Worst-case wall-clock is
|
|
31872
|
+
* `createBridgeIntent + timeout + verification + max(timeout, RELAY_FALLBACK_FLOOR_MS)`, where
|
|
31873
|
+
* verification is bounded by the source chain's `pollingConfig.maxTimeoutMs` and intent creation is
|
|
31874
|
+
* not bounded by `timeout` at all. See `docs/BRIDGE.md` § Completion paths and `timeout`.
|
|
31451
31875
|
* @returns `Result<TxHashPair>` — `{ srcChainTxHash, dstChainTxHash }` on success,
|
|
31452
31876
|
* where `srcChainTxHash` is the spoke deposit tx and `dstChainTxHash` is the hub settlement tx.
|
|
31453
31877
|
*
|
|
@@ -31481,16 +31905,16 @@ var BridgeService = class {
|
|
|
31481
31905
|
try {
|
|
31482
31906
|
const created = await this.createBridgeIntent(_params);
|
|
31483
31907
|
if (!created.ok) return { ok: false, error: created.error };
|
|
31484
|
-
const
|
|
31908
|
+
const timeoutMs = resolveTimeoutMs(_params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
31485
31909
|
if (this.useBackendSubmitTx) {
|
|
31486
|
-
const submitted = await this.submitTx(_params, created.value,
|
|
31910
|
+
const submitted = await this.submitTx(_params, created.value, createSubmitTxAttempt(timeoutMs));
|
|
31487
31911
|
if (submitted.ok) return submitted;
|
|
31488
31912
|
this.config.logger.warn(
|
|
31489
31913
|
"[bridge] backend submit-tx did not complete; falling back to the client-side relay",
|
|
31490
31914
|
{ error: submitted.error }
|
|
31491
31915
|
);
|
|
31492
31916
|
}
|
|
31493
|
-
return this.fallbackBridgeSteps(_params, created.value,
|
|
31917
|
+
return this.fallbackBridgeSteps(_params, created.value, timeoutMs);
|
|
31494
31918
|
} catch (error) {
|
|
31495
31919
|
if (isBridgeOrchestrationError(error)) return { ok: false, error };
|
|
31496
31920
|
return {
|
|
@@ -31518,12 +31942,16 @@ var BridgeService = class {
|
|
|
31518
31942
|
);
|
|
31519
31943
|
}
|
|
31520
31944
|
/**
|
|
31521
|
-
* Client-side bridge completion (
|
|
31522
|
-
* relay it to the hub and wait for the settlement packet. Extracted verbatim from
|
|
31523
|
-
*
|
|
31524
|
-
* always relays — there is no hub-source short-circuit.
|
|
31945
|
+
* Client-side bridge completion (opt-out via `bridge.useBackendSubmitTx: false`): verify the broadcast
|
|
31946
|
+
* spoke-deposit tx, then relay it to the hub and wait for the settlement packet. Extracted verbatim from
|
|
31947
|
+
* `bridge()` so the backend submit-tx path ({@link submitTx}) can fall back to it on any non-success.
|
|
31948
|
+
* Bridge always relays — there is no hub-source short-circuit.
|
|
31949
|
+
*
|
|
31950
|
+
* Verification belongs to THIS path only: the backend runs its own, so verifying before handing over
|
|
31951
|
+
* would delay every backend success by the source chain's confirmation wait and could fail a bridge the
|
|
31952
|
+
* backend would have completed.
|
|
31525
31953
|
*/
|
|
31526
|
-
async fallbackBridgeSteps(_params, created,
|
|
31954
|
+
async fallbackBridgeSteps(_params, created, timeoutMs) {
|
|
31527
31955
|
const { params } = _params;
|
|
31528
31956
|
const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
|
|
31529
31957
|
const verifyTxHashResult = await this.spoke.verifyTxHash({
|
|
@@ -31538,13 +31966,13 @@ var BridgeService = class {
|
|
|
31538
31966
|
data: created.relayData,
|
|
31539
31967
|
chainKey: params.srcChainKey,
|
|
31540
31968
|
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
31541
|
-
//
|
|
31542
|
-
// or the
|
|
31543
|
-
//
|
|
31544
|
-
//
|
|
31545
|
-
//
|
|
31546
|
-
//
|
|
31547
|
-
timeout: Math.max(
|
|
31969
|
+
// The caller's full `timeout`, starting HERE — after verification, and whether this runs as the only
|
|
31970
|
+
// path or as the backend's fallback. Neither a stalled backend attempt nor a slow source-chain
|
|
31971
|
+
// confirmation (Stacks polls for up to its full 120s `maxTimeoutMs`) may shorten the relay wait. The
|
|
31972
|
+
// floor covers a sub-floor caller `timeout`: `relayTxAndWaitPacket` SUBMITS the tx to the relay
|
|
31973
|
+
// before `timeout` bounds anything, so a zero budget would strand an already-landed deposit
|
|
31974
|
+
// unrelayed. Re-relay is idempotent, so always spending the floor is safe.
|
|
31975
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS)
|
|
31548
31976
|
});
|
|
31549
31977
|
if (!packetResult.ok) {
|
|
31550
31978
|
return {
|
|
@@ -31563,7 +31991,7 @@ var BridgeService = class {
|
|
|
31563
31991
|
};
|
|
31564
31992
|
}
|
|
31565
31993
|
/**
|
|
31566
|
-
* Backend bridge path (
|
|
31994
|
+
* Backend bridge path (default via `bridge.useBackendSubmitTx`): hand the broadcast
|
|
31567
31995
|
* spoke-deposit tx to the bridge API (`POST /bridge/submit-tx`) with the FULL `relayData`
|
|
31568
31996
|
* envelope; the backend relays server-side. Polls `getSubmitTxStatus` until `executed`, then
|
|
31569
31997
|
* returns the same {@link TxHashPair} the client-side path returns (`result.dstIntentTxHash` →
|
|
@@ -31572,39 +32000,39 @@ var BridgeService = class {
|
|
|
31572
32000
|
* Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, terminal `failed` /
|
|
31573
32001
|
* abandoned, or poll timeout) so `bridge()` falls back to {@link fallbackBridgeSteps}. Falling back
|
|
31574
32002
|
* is safe: re-relaying an already-relayed bridge tx is idempotent — the relay dedups and returns the
|
|
31575
|
-
* existing `executed` packet.
|
|
31576
|
-
*
|
|
32003
|
+
* existing `executed` packet. It is also load-bearing rather than belt-and-braces: the backend keeps
|
|
32004
|
+
* processing after this attempt gives up, so the fallback's relay can race the backend's own.
|
|
32005
|
+
*
|
|
32006
|
+
* The attempt itself — POST, budget clamps, status poll — is {@link runBackendSubmitTx}, shared with
|
|
32007
|
+
* swaps. What is bridge-specific and lives here: the request body (the FULL `relayData` envelope), the
|
|
32008
|
+
* `executed` terminal status, the mapping to a {@link TxHashPair}, and the bridge error taxonomy.
|
|
32009
|
+
*
|
|
32010
|
+
* `attempt` bounds this attempt alone — the POST and every status request draw on it, and the
|
|
32011
|
+
* client-side fallback holds a separate fresh `timeout`.
|
|
31577
32012
|
*/
|
|
31578
|
-
async submitTx(_params, created,
|
|
32013
|
+
async submitTx(_params, created, attempt) {
|
|
31579
32014
|
const { params } = _params;
|
|
31580
32015
|
const srcChainKey = params.srcChainKey;
|
|
31581
32016
|
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
|
|
31582
32017
|
const { tx: spokeTxHash, relayData } = created;
|
|
31583
|
-
const submitTxFailed = (cause) => ({
|
|
31584
|
-
ok: false,
|
|
31585
|
-
error: executionFailed("bridge", cause, { ...baseCtx, action: "bridge" })
|
|
31586
|
-
});
|
|
31587
32018
|
try {
|
|
31588
|
-
const
|
|
31589
|
-
|
|
31590
|
-
|
|
31591
|
-
|
|
31592
|
-
|
|
31593
|
-
|
|
31594
|
-
|
|
31595
|
-
|
|
31596
|
-
|
|
31597
|
-
|
|
31598
|
-
|
|
32019
|
+
const outcome = await runBackendSubmitTx({
|
|
32020
|
+
attempt,
|
|
32021
|
+
api: this.backendApi.bridge,
|
|
32022
|
+
body: {
|
|
32023
|
+
txHash: spokeTxHash,
|
|
32024
|
+
srcChainKey,
|
|
32025
|
+
walletAddress: params.srcAddress,
|
|
32026
|
+
// Send the FULL { address, payload } envelope — bridge has no intent.creator for the backend
|
|
32027
|
+
// to rebuild the relay address, so dropping it would break split-tx-chain relay.
|
|
32028
|
+
relayData
|
|
32029
|
+
},
|
|
32030
|
+
statusQuery: { txHash: spokeTxHash, srcChainKey },
|
|
31599
32031
|
// Bridge terminal success is `executed` (hub-settled) — not the swaps `solved`.
|
|
31600
32032
|
terminalStatus: "executed",
|
|
31601
|
-
|
|
31602
|
-
onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0,
|
|
31603
|
-
// Bound each status request by the poll cutoff, never above the service default — so a stalled
|
|
31604
|
-
// request can neither eat the fallback's reserve nor consume the window in one attempt.
|
|
31605
|
-
requestTimeoutMs: this.backendApi.bridge.getTimeout()
|
|
32033
|
+
onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0
|
|
31606
32034
|
});
|
|
31607
|
-
return
|
|
32035
|
+
return outcome.ok ? { ok: true, value: outcome.value } : { ok: false, error: executionFailed("bridge", outcome.cause, { ...baseCtx, action: "bridge" }) };
|
|
31608
32036
|
} catch (error) {
|
|
31609
32037
|
return { ok: false, error: unknownFailed("bridge", error, { ...baseCtx, action: "bridge" }) };
|
|
31610
32038
|
}
|
|
@@ -37778,15 +38206,25 @@ var MoneyMarketService = class _MoneyMarketService {
|
|
|
37778
38206
|
config;
|
|
37779
38207
|
spoke;
|
|
37780
38208
|
// money market config (hoisted from config for ergonomics, mirrors SwapService)
|
|
37781
|
-
partnerFee;
|
|
37782
38209
|
relayerApiEndpoint;
|
|
37783
38210
|
// sub-service
|
|
37784
38211
|
data;
|
|
38212
|
+
/**
|
|
38213
|
+
* Effective money-market partner fee (`moneyMarket.partnerFee`, else the global `fee`). Read live
|
|
38214
|
+
* off `ConfigService` rather than snapshotted in the constructor, so it cannot diverge from
|
|
38215
|
+
* `config.moneyMarketPartnerFee` if the config object is ever replaced. Mirrors
|
|
38216
|
+
* {@link SwapService.partnerFee}.
|
|
38217
|
+
*
|
|
38218
|
+
* Money market has no per-action override: unlike swap / bridge / leverage-yield, every flow here
|
|
38219
|
+
* charges this configured fee.
|
|
38220
|
+
*/
|
|
38221
|
+
get partnerFee() {
|
|
38222
|
+
return this.config.moneyMarketPartnerFee;
|
|
38223
|
+
}
|
|
37785
38224
|
constructor({ config, hubProvider, spoke }) {
|
|
37786
38225
|
this.config = config;
|
|
37787
38226
|
this.hubProvider = hubProvider;
|
|
37788
38227
|
this.spoke = spoke;
|
|
37789
|
-
this.partnerFee = config.moneyMarketPartnerFee;
|
|
37790
38228
|
this.relayerApiEndpoint = config.relay.relayerApiEndpoint;
|
|
37791
38229
|
this.data = new MoneyMarketDataService({ hubProvider, config });
|
|
37792
38230
|
}
|
|
@@ -40099,6 +40537,68 @@ var LeverageYieldService = class {
|
|
|
40099
40537
|
return { ok: false, error: lookupFailed("leverageYield", "resolveDeadline", error, { srcChainKey }) };
|
|
40100
40538
|
}
|
|
40101
40539
|
}
|
|
40540
|
+
/**
|
|
40541
|
+
* Quotes a vault deposit or withdraw. Vault shares are solver-tradeable, so this is the
|
|
40542
|
+
* generic solver quote with one difference that matters: the fee deducted before quoting is
|
|
40543
|
+
* the effective **leverage-yield** fee, matching what {@link LeverageYieldService.createVaultIntent}
|
|
40544
|
+
* will charge. `sodax.swaps.getQuote` deducts the effective *swap* fee instead, so quoting a
|
|
40545
|
+
* vault flow through it makes the quote and the intent disagree whenever the two feature fees
|
|
40546
|
+
* differ. Quoting a vault flow through the swap service can be made to agree — pass the same fee
|
|
40547
|
+
* explicitly, using a zero fee (`{ address, percentage: 0 }`) where the effective leverage-yield
|
|
40548
|
+
* fee is `undefined`, since an explicit `undefined` there falls back to the swap fee — but this
|
|
40549
|
+
* method resolves it for you and is the canonical way to quote a vault flow.
|
|
40550
|
+
*
|
|
40551
|
+
* Pass the vault address as `token_dst` to quote a deposit, or as `token_src` to quote a
|
|
40552
|
+
* withdraw; subtract your slippage tolerance from `quoted_amount` to get `minOutputAmount`.
|
|
40553
|
+
* When overriding the fee per intent, pass the same `partnerFee` here and to whichever builder
|
|
40554
|
+
* you use ({@link LeverageYieldService.deposit}, {@link LeverageYieldService.withdraw}) or
|
|
40555
|
+
* directly to {@link LeverageYieldService.vaultSwap} — omitting it everywhere is equally safe,
|
|
40556
|
+
* since each side then resolves the same effective leverage-yield fee. Both directions are
|
|
40557
|
+
* charged, so this applies to withdrawals as much as deposits.
|
|
40558
|
+
*
|
|
40559
|
+
* @returns `SolverIntentQuoteResponse` on success. On failure `result.error` is either the
|
|
40560
|
+
* solver's own `SolverErrorResponse` (no path, insufficient liquidity, …) or a SodaxError
|
|
40561
|
+
* with `VALIDATION_FAILED` (bad `amount`, or a partner fee that leaves nothing to quote),
|
|
40562
|
+
* `LOOKUP_FAILED` (unsupported token — the solver payload could not be assembled) or
|
|
40563
|
+
* `UNKNOWN`. Discriminate with `isSodaxError(error)`.
|
|
40564
|
+
*/
|
|
40565
|
+
async getQuote(payload) {
|
|
40566
|
+
const { partnerFee = this.config.leverageYieldPartnerFee, ...request } = payload;
|
|
40567
|
+
const baseCtx = {
|
|
40568
|
+
method: "getQuote",
|
|
40569
|
+
tokenSrcChainKey: request.token_src_blockchain_id,
|
|
40570
|
+
tokenDstChainKey: request.token_dst_blockchain_id
|
|
40571
|
+
};
|
|
40572
|
+
try {
|
|
40573
|
+
leverageYieldInvariant(request.amount > 0n, "amount must be greater than 0", {
|
|
40574
|
+
...baseCtx,
|
|
40575
|
+
field: "amount"
|
|
40576
|
+
});
|
|
40577
|
+
if (isPartnerFeeAmount(partnerFee)) {
|
|
40578
|
+
leverageYieldInvariant(
|
|
40579
|
+
partnerFee.amount < request.amount,
|
|
40580
|
+
`partnerFee amount (${partnerFee.amount}) must be less than the quote amount (${request.amount})`,
|
|
40581
|
+
{ ...baseCtx, field: "partnerFee" }
|
|
40582
|
+
);
|
|
40583
|
+
} else if (isPartnerFeePercentage(partnerFee)) {
|
|
40584
|
+
leverageYieldInvariant(
|
|
40585
|
+
Number.isInteger(partnerFee.percentage) && partnerFee.percentage >= 0 && partnerFee.percentage <= Number(FEE_PERCENTAGE_SCALE),
|
|
40586
|
+
`partnerFee percentage must be a whole number of basis points between 0 and ${FEE_PERCENTAGE_SCALE} (got ${partnerFee.percentage})`,
|
|
40587
|
+
{ ...baseCtx, field: "partnerFee" }
|
|
40588
|
+
);
|
|
40589
|
+
}
|
|
40590
|
+
const netAmount = adjustAmountByFee(request.amount, partnerFee, request.quote_type);
|
|
40591
|
+
leverageYieldInvariant(netAmount > 0n, "amount net of the partner fee must be greater than 0", {
|
|
40592
|
+
...baseCtx,
|
|
40593
|
+
field: "partnerFee"
|
|
40594
|
+
});
|
|
40595
|
+
const adjustedPayload = { ...request, amount: netAmount };
|
|
40596
|
+
return await SolverApiService.getQuote(adjustedPayload, this.config.solver, this.config);
|
|
40597
|
+
} catch (error) {
|
|
40598
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
40599
|
+
return { ok: false, error: lookupFailed("leverageYield", "getQuote", error, baseCtx) };
|
|
40600
|
+
}
|
|
40601
|
+
}
|
|
40102
40602
|
/**
|
|
40103
40603
|
* Builds the {@link LeverageYieldSwapPayload} for a leverage-yield deposit (any token → lsoda*).
|
|
40104
40604
|
* The lsoda* output is delivered to the user's hub wallet on Sonic so a later
|
|
@@ -40106,9 +40606,8 @@ var LeverageYieldService = class {
|
|
|
40106
40606
|
* {@link LeverageYieldService.vaultSwap}: `vaultSwap({ ...payload, walletProvider })`.
|
|
40107
40607
|
* An optional `partnerFee` is forwarded on the payload as the per-intent fee override.
|
|
40108
40608
|
*
|
|
40109
|
-
* For `minOutputAmount`, quote via
|
|
40110
|
-
* destination token (`token_dst`)
|
|
40111
|
-
* quote applies; then subtract your slippage tolerance.
|
|
40609
|
+
* For `minOutputAmount`, quote via {@link LeverageYieldService.getQuote} with the vault
|
|
40610
|
+
* address as the destination token (`token_dst`), then subtract your slippage tolerance.
|
|
40112
40611
|
*/
|
|
40113
40612
|
async deposit(params) {
|
|
40114
40613
|
const baseCtx = { srcChainKey: params.srcChainKey, action: "deposit" };
|
|
@@ -40161,9 +40660,13 @@ var LeverageYieldService = class {
|
|
|
40161
40660
|
* a call shape uniform with {@link LeverageYieldService.deposit}; async because the default
|
|
40162
40661
|
* `deadline` is read from the hub block timestamp.
|
|
40163
40662
|
*
|
|
40164
|
-
*
|
|
40165
|
-
*
|
|
40166
|
-
*
|
|
40663
|
+
* An optional `partnerFee` is forwarded on the payload as the per-intent fee override; omit it
|
|
40664
|
+
* and the configured leverage-yield fee applies. Withdrawals **are** charged — the fee comes out
|
|
40665
|
+
* of `inputAmount`, which for a withdraw is the vault's own shares, so the receiver accrues
|
|
40666
|
+
* lsoda\* rather than the output token.
|
|
40667
|
+
*
|
|
40668
|
+
* For `minOutputAmount`, quote via {@link LeverageYieldService.getQuote} with the vault
|
|
40669
|
+
* address as the source token (`token_src`), then subtract your slippage tolerance.
|
|
40167
40670
|
*/
|
|
40168
40671
|
async withdraw(params) {
|
|
40169
40672
|
const baseCtx = { srcChainKey: params.srcChainKey, action: "withdraw" };
|
|
@@ -40197,7 +40700,10 @@ var LeverageYieldService = class {
|
|
|
40197
40700
|
solver: params.solver ?? ANY_SOLVER_ADDRESS,
|
|
40198
40701
|
data: "0x"
|
|
40199
40702
|
},
|
|
40200
|
-
hubWalletSwap: true
|
|
40703
|
+
hubWalletSwap: true,
|
|
40704
|
+
// Per-intent fee override — only included when the caller supplies one, so the
|
|
40705
|
+
// payload stays free of undefined-valued keys (mirrors `deposit`).
|
|
40706
|
+
...params.partnerFee !== void 0 && { partnerFee: params.partnerFee }
|
|
40201
40707
|
}
|
|
40202
40708
|
};
|
|
40203
40709
|
} catch (error) {
|
|
@@ -40230,7 +40736,7 @@ var LeverageYieldService = class {
|
|
|
40230
40736
|
* `UNKNOWN` (defensive fallback).
|
|
40231
40737
|
*/
|
|
40232
40738
|
async createVaultIntent(_params) {
|
|
40233
|
-
const { params, skipSimulation, hubWalletSwap, partnerFee = this.config.
|
|
40739
|
+
const { params, skipSimulation, hubWalletSwap, partnerFee = this.config.leverageYieldPartnerFee } = _params;
|
|
40234
40740
|
const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
|
|
40235
40741
|
try {
|
|
40236
40742
|
leverageYieldInvariant(
|
|
@@ -40575,15 +41081,22 @@ var LeverageYieldService = class {
|
|
|
40575
41081
|
spender: params.vault
|
|
40576
41082
|
};
|
|
40577
41083
|
if (params.raw) {
|
|
40578
|
-
const
|
|
40579
|
-
return { ok: true, value:
|
|
40580
|
-
}
|
|
40581
|
-
const
|
|
40582
|
-
|
|
41084
|
+
const tx = await Erc20Service.approve({ ...baseApprove, raw: true });
|
|
41085
|
+
return { ok: true, value: tx };
|
|
41086
|
+
}
|
|
41087
|
+
const result = await this.spoke.approve({
|
|
41088
|
+
srcChainKey: this.hubProvider.chainConfig.chain.key,
|
|
41089
|
+
token: baseApprove.token,
|
|
41090
|
+
amount: baseApprove.amount,
|
|
41091
|
+
owner: from,
|
|
41092
|
+
spender: baseApprove.spender,
|
|
40583
41093
|
raw: false,
|
|
40584
41094
|
walletProvider: params.walletProvider
|
|
40585
41095
|
});
|
|
40586
|
-
|
|
41096
|
+
if (!result.ok) {
|
|
41097
|
+
return { ok: false, error: approveFailed("leverageYield", result.error, baseCtx) };
|
|
41098
|
+
}
|
|
41099
|
+
return { ok: true, value: result.value };
|
|
40587
41100
|
} catch (error) {
|
|
40588
41101
|
if (isLeverageYieldApproveError(error)) return { ok: false, error };
|
|
40589
41102
|
return { ok: false, error: approveFailed("leverageYield", error, baseCtx) };
|
|
@@ -41453,8 +41966,6 @@ var Sodax = class {
|
|
|
41453
41966
|
const analytics = resolveAnalytics(options?.analytics);
|
|
41454
41967
|
const fee = options?.fee;
|
|
41455
41968
|
const radfiSigner = options?.radfi?.signRequest;
|
|
41456
|
-
const useBackendSubmitTx = options?.swapsOptions?.useBackendSubmitTx ?? false;
|
|
41457
|
-
const bridgeUseBackendSubmitTx = options?.bridgeOptions?.useBackendSubmitTx ?? false;
|
|
41458
41969
|
this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
|
|
41459
41970
|
this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
|
|
41460
41971
|
this.api = this.backendApi;
|
|
@@ -41473,8 +41984,7 @@ var Sodax = class {
|
|
|
41473
41984
|
config: this.config,
|
|
41474
41985
|
hubProvider: this.hubProvider,
|
|
41475
41986
|
spoke: this.spoke,
|
|
41476
|
-
backendApi: this.backendApi
|
|
41477
|
-
useBackendSubmitTx
|
|
41987
|
+
backendApi: this.backendApi
|
|
41478
41988
|
});
|
|
41479
41989
|
this.moneyMarket = new MoneyMarketService({
|
|
41480
41990
|
config: this.config,
|
|
@@ -41495,8 +42005,7 @@ var Sodax = class {
|
|
|
41495
42005
|
hubProvider: this.hubProvider,
|
|
41496
42006
|
config: this.config,
|
|
41497
42007
|
spoke: this.spoke,
|
|
41498
|
-
backendApi: this.backendApi
|
|
41499
|
-
useBackendSubmitTx: bridgeUseBackendSubmitTx
|
|
42008
|
+
backendApi: this.backendApi
|
|
41500
42009
|
});
|
|
41501
42010
|
this.staking = new StakingService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
|
|
41502
42011
|
this.partners = new PartnerService({
|