@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.cjs
CHANGED
|
@@ -3365,7 +3365,7 @@ var spokeChainConfig = {
|
|
|
3365
3365
|
supportedTokens: suiSupportedTokens,
|
|
3366
3366
|
nativeToken: "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
|
|
3367
3367
|
bnUSD: "0xff4de2b2b57dd7611d2812d231a467d007b702a101fd5c7ad3b278257cddb507::bnusd::BNUSD",
|
|
3368
|
-
rpc_url: "https://
|
|
3368
|
+
rpc_url: "https://sui-rpc.publicnode.com",
|
|
3369
3369
|
chain: baseChainInfo[ChainKeys.SUI_MAINNET],
|
|
3370
3370
|
pollingConfig: {
|
|
3371
3371
|
pollingIntervalMs: 500,
|
|
@@ -4300,7 +4300,13 @@ var BTC_ADDRESS_TYPES = ["P2PKH", "P2SH", "P2WPKH", "P2TR"];
|
|
|
4300
4300
|
// ../types/dist/hooks/hooks.js
|
|
4301
4301
|
var HookKind = {
|
|
4302
4302
|
/** Deposits delivered USDC into the recipient's HyperCore perps account (HyperEVM). */
|
|
4303
|
-
HYPERCORE_DEPOSIT: "hyperCoreDeposit"
|
|
4303
|
+
HYPERCORE_DEPOSIT: "hyperCoreDeposit",
|
|
4304
|
+
/**
|
|
4305
|
+
* Requests an ERC-7540 deposit of delivered USDC into the Flint RWA vault (Ethereum), with the
|
|
4306
|
+
* recipient as the request's controller. Asynchronous: the request mints no shares — Flint's
|
|
4307
|
+
* curator settles a NAV and then claims the shares on the controller's behalf.
|
|
4308
|
+
*/
|
|
4309
|
+
FLINT_DEPOSIT: "flintDeposit"
|
|
4304
4310
|
};
|
|
4305
4311
|
var spokeHooks = {
|
|
4306
4312
|
[ChainKeys.HYPEREVM_MAINNET]: [
|
|
@@ -4311,6 +4317,20 @@ var spokeHooks = {
|
|
|
4311
4317
|
// USDC on HyperEVM
|
|
4312
4318
|
}
|
|
4313
4319
|
]
|
|
4320
|
+
// HookKind.FLINT_DEPOSIT is not registered yet: FlintDepositHook is not deployed to Ethereum
|
|
4321
|
+
// mainnet (icon-project/sodax-contracts#693). Registering it with a placeholder address would
|
|
4322
|
+
// route real intent output to that address, so the entry lands with the deployment:
|
|
4323
|
+
//
|
|
4324
|
+
// [ChainKeys.ETHEREUM_MAINNET]: [
|
|
4325
|
+
// {
|
|
4326
|
+
// kind: HookKind.FLINT_DEPOSIT,
|
|
4327
|
+
// address: '0x…',
|
|
4328
|
+
// supportedTokens: [spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDC.address],
|
|
4329
|
+
// },
|
|
4330
|
+
// ],
|
|
4331
|
+
//
|
|
4332
|
+
// Until then `getSpokeHook` returns undefined and `resolveDeliveryHook` throws, which is the
|
|
4333
|
+
// correct behaviour for a hook that does not exist on chain.
|
|
4314
4334
|
};
|
|
4315
4335
|
var getSpokeHook = (chainKey, kind) => spokeHooks[chainKey]?.find((h) => h.kind === kind);
|
|
4316
4336
|
var getSpokeHooks = (chainKey) => spokeHooks[chainKey] ?? [];
|
|
@@ -4436,7 +4456,13 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
4436
4456
|
}
|
|
4437
4457
|
|
|
4438
4458
|
// ../types/dist/index.js
|
|
4439
|
-
var CONFIG_VERSION =
|
|
4459
|
+
var CONFIG_VERSION = 224;
|
|
4460
|
+
|
|
4461
|
+
// src/shared/utils/resolveTimeoutMs.ts
|
|
4462
|
+
function resolveTimeoutMs(timeout, fallbackMs) {
|
|
4463
|
+
if (timeout === void 0 || !Number.isFinite(timeout)) return fallbackMs;
|
|
4464
|
+
return Math.max(0, timeout);
|
|
4465
|
+
}
|
|
4440
4466
|
function isEvmSpokeChainConfig(value) {
|
|
4441
4467
|
return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
|
|
4442
4468
|
}
|
|
@@ -4863,7 +4889,7 @@ async function pollForExecutedPacket(payload, deadline) {
|
|
|
4863
4889
|
}
|
|
4864
4890
|
async function waitUntilIntentExecuted(payload) {
|
|
4865
4891
|
try {
|
|
4866
|
-
const timeout = payload.timeout
|
|
4892
|
+
const timeout = resolveTimeoutMs(payload.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
4867
4893
|
const startTime = Date.now();
|
|
4868
4894
|
const deadline = startTime + timeout;
|
|
4869
4895
|
let lastPollingError;
|
|
@@ -4896,7 +4922,8 @@ async function waitUntilIntentExecuted(payload) {
|
|
|
4896
4922
|
}
|
|
4897
4923
|
async function relayTxAndWaitPacket(params) {
|
|
4898
4924
|
try {
|
|
4899
|
-
const { srcTxHash, data, chainKey, relayerApiEndpoint,
|
|
4925
|
+
const { srcTxHash, data, chainKey, relayerApiEndpoint, pollTxHash } = params;
|
|
4926
|
+
const timeout = resolveTimeoutMs(params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
4900
4927
|
const intentRelayChainId = getIntentRelayChainId(chainKey).toString();
|
|
4901
4928
|
const isSplitTxChain = isSolanaChainKeyType(chainKey) || isBitcoinChainKeyType(chainKey);
|
|
4902
4929
|
invariant(!isSplitTxChain || data !== void 0, "Data is required for Solana and Bitcoin chain keys");
|
|
@@ -14304,6 +14331,17 @@ var ConfigService = class {
|
|
|
14304
14331
|
get leverageYieldPartnerFee() {
|
|
14305
14332
|
return this.leverageYield.partnerFee ?? this.fee;
|
|
14306
14333
|
}
|
|
14334
|
+
// Effective backend submit-tx toggle per feature. Read live off the same `swaps` / `bridge` slots as
|
|
14335
|
+
// `partnerFee` so an omitted flag resolves to the ON default here, in one place, instead of leaving
|
|
14336
|
+
// `config.swaps.useBackendSubmitTx === undefined` while the backend path is actually active.
|
|
14337
|
+
// The deprecated `swapsOptions` / `bridgeOptions` keys are still honoured as a second-precedence
|
|
14338
|
+
// fallback, so a pre-existing explicit opt-out keeps the client-side path instead of silently flipping.
|
|
14339
|
+
get swapUseBackendSubmitTx() {
|
|
14340
|
+
return this.swaps.useBackendSubmitTx ?? this.sodax.swapsOptions?.useBackendSubmitTx ?? true;
|
|
14341
|
+
}
|
|
14342
|
+
get bridgeUseBackendSubmitTx() {
|
|
14343
|
+
return this.bridge.useBackendSubmitTx ?? this.sodax.bridgeOptions?.useBackendSubmitTx ?? true;
|
|
14344
|
+
}
|
|
14307
14345
|
get dex() {
|
|
14308
14346
|
return this.sodax.dex;
|
|
14309
14347
|
}
|
|
@@ -14631,7 +14669,7 @@ var EvmVaultTokenService = class {
|
|
|
14631
14669
|
return amount * BigInt(10 ** (decimals - 18));
|
|
14632
14670
|
}
|
|
14633
14671
|
};
|
|
14634
|
-
var Erc20Service = class {
|
|
14672
|
+
var Erc20Service = class _Erc20Service {
|
|
14635
14673
|
constructor() {
|
|
14636
14674
|
}
|
|
14637
14675
|
static async getErc20Token(token, publicClient) {
|
|
@@ -14657,6 +14695,19 @@ var Erc20Service = class {
|
|
|
14657
14695
|
});
|
|
14658
14696
|
return { name, symbol, decimals, address: token };
|
|
14659
14697
|
}
|
|
14698
|
+
/**
|
|
14699
|
+
* Read the current on-chain allowance of `spender` over `owner`'s balance.
|
|
14700
|
+
* @param params - Token, owner, spender, and publicClient for the chain.
|
|
14701
|
+
* @returns The raw allowance.
|
|
14702
|
+
*/
|
|
14703
|
+
static async getAllowance(params) {
|
|
14704
|
+
return params.publicClient.readContract({
|
|
14705
|
+
address: params.token,
|
|
14706
|
+
abi: viem.erc20Abi,
|
|
14707
|
+
functionName: "allowance",
|
|
14708
|
+
args: [params.owner, params.spender]
|
|
14709
|
+
});
|
|
14710
|
+
}
|
|
14660
14711
|
/**
|
|
14661
14712
|
* Check if spender has enough ERC20 allowance for given amount.
|
|
14662
14713
|
* @param params - Token, amount, owner, spender, chainKey, and publicClient for the chain.
|
|
@@ -14670,12 +14721,7 @@ var Erc20Service = class {
|
|
|
14670
14721
|
value: true
|
|
14671
14722
|
};
|
|
14672
14723
|
}
|
|
14673
|
-
const allowedAmount = await
|
|
14674
|
-
address: params.token,
|
|
14675
|
-
abi: viem.erc20Abi,
|
|
14676
|
-
functionName: "allowance",
|
|
14677
|
-
args: [params.owner, params.spender]
|
|
14678
|
-
});
|
|
14724
|
+
const allowedAmount = await _Erc20Service.getAllowance(params);
|
|
14679
14725
|
return {
|
|
14680
14726
|
ok: true,
|
|
14681
14727
|
value: allowedAmount >= params.amount
|
|
@@ -14687,6 +14733,59 @@ var Erc20Service = class {
|
|
|
14687
14733
|
};
|
|
14688
14734
|
}
|
|
14689
14735
|
}
|
|
14736
|
+
/**
|
|
14737
|
+
* Decide how many approve transactions this token needs for `amount`.
|
|
14738
|
+
*
|
|
14739
|
+
* Tokens of the 2017 TetherToken lineage reject an allowance change from one non-zero value to
|
|
14740
|
+
* another, so a wallet holding a stale allowance can never approve — every retry reverts the same
|
|
14741
|
+
* way. Such a token needs `approve(0)` first.
|
|
14742
|
+
*
|
|
14743
|
+
* Detection is behavioural: a simulated approve either reverts or it does not. That answers the
|
|
14744
|
+
* question that actually matters ("will this approve revert?") instead of "is this token USDT?",
|
|
14745
|
+
* so a token listed later, or upgraded later behind the same address, is covered without a code
|
|
14746
|
+
* change — and no token list is hardcoded.
|
|
14747
|
+
*
|
|
14748
|
+
* The probes only run once an allowance is already set. The common path (nothing approved yet)
|
|
14749
|
+
* costs a single read.
|
|
14750
|
+
*/
|
|
14751
|
+
static async planApproval(params) {
|
|
14752
|
+
const single = (reason) => ({ approveAmount: params.amount, reason });
|
|
14753
|
+
if (params.token.toLowerCase() === params.nativeToken.toLowerCase()) {
|
|
14754
|
+
return single("native-token");
|
|
14755
|
+
}
|
|
14756
|
+
let allowance;
|
|
14757
|
+
try {
|
|
14758
|
+
allowance = await _Erc20Service.getAllowance(params);
|
|
14759
|
+
} catch {
|
|
14760
|
+
return single("allowance-read-failed");
|
|
14761
|
+
}
|
|
14762
|
+
if (allowance === 0n) {
|
|
14763
|
+
return single("zero-allowance");
|
|
14764
|
+
}
|
|
14765
|
+
if (await _Erc20Service.canApprove(params, params.amount)) {
|
|
14766
|
+
return single("probe-passed");
|
|
14767
|
+
}
|
|
14768
|
+
if (!await _Erc20Service.canApprove(params, 0n)) {
|
|
14769
|
+
return single("reset-not-viable");
|
|
14770
|
+
}
|
|
14771
|
+
return { resetAmount: 0n, approveAmount: params.amount, reason: "reset-required" };
|
|
14772
|
+
}
|
|
14773
|
+
/**
|
|
14774
|
+
* Simulate `approve(spender, amount)` as `owner`.
|
|
14775
|
+
*
|
|
14776
|
+
* `call` rather than `simulateContract`, because a TetherToken-lineage `approve` returns no value
|
|
14777
|
+
* and ABI decoding would fail even on a successful call. `account` is required: the guard reads
|
|
14778
|
+
* `allowed[msg.sender][spender]`.
|
|
14779
|
+
*/
|
|
14780
|
+
static async canApprove(params, amount) {
|
|
14781
|
+
const { data } = _Erc20Service.encodeApprove(params.token, params.spender, amount);
|
|
14782
|
+
try {
|
|
14783
|
+
await params.publicClient.call({ account: params.owner, to: params.token, data });
|
|
14784
|
+
return true;
|
|
14785
|
+
} catch {
|
|
14786
|
+
return false;
|
|
14787
|
+
}
|
|
14788
|
+
}
|
|
14690
14789
|
/**
|
|
14691
14790
|
* Approve ERC20 amount spending
|
|
14692
14791
|
* @param token - ERC20 token address
|
|
@@ -22443,7 +22542,17 @@ var IntentDataType = /* @__PURE__ */ ((IntentDataType2) => {
|
|
|
22443
22542
|
})(IntentDataType || {});
|
|
22444
22543
|
var HOOK_DELIVERY_ABI = {
|
|
22445
22544
|
// HyperCoreDepositHook expects `abi.encode(address)` — the HyperCore account to credit.
|
|
22446
|
-
[HookKind.HYPERCORE_DEPOSIT]: [{ name: "recipient", type: "address" }]
|
|
22545
|
+
[HookKind.HYPERCORE_DEPOSIT]: [{ name: "recipient", type: "address" }],
|
|
22546
|
+
// FlintDepositHook expects `abi.encode(address)` — the ERC-7540 controller the deposit request is
|
|
22547
|
+
// recorded against, i.e. the account that ends up owning the resulting flUSD shares. Same shape as
|
|
22548
|
+
// HyperCore's today; kept as its own entry so the two can diverge without touching each other.
|
|
22549
|
+
[HookKind.FLINT_DEPOSIT]: [{ name: "recipient", type: "address" }]
|
|
22550
|
+
};
|
|
22551
|
+
var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
22552
|
+
var assertUnsupportedHook = (request) => {
|
|
22553
|
+
throw new Error(
|
|
22554
|
+
`[HookService.encodeDeliveryData] Unsupported delivery hook kind: ${request.kind}`
|
|
22555
|
+
);
|
|
22447
22556
|
};
|
|
22448
22557
|
var HookService = class _HookService {
|
|
22449
22558
|
constructor() {
|
|
@@ -22452,17 +22561,28 @@ var HookService = class _HookService {
|
|
|
22452
22561
|
* Encodes a hook's `deliveryData` payload. One common entry point for all hooks — the encoding is
|
|
22453
22562
|
* selected by {@link HookRequest.kind} and uses that hook's schema from {@link HOOK_DELIVERY_ABI}.
|
|
22454
22563
|
*
|
|
22564
|
+
* Rejects the zero address. Every hook treats its recipient as the account to credit, and a
|
|
22565
|
+
* zero recipient is unrecoverable on arrival: the receiver reverts, which rolls back the whole
|
|
22566
|
+
* cross-chain withdrawal inside `SpokeAssetManager.recvMessage` and leaves the message wedged —
|
|
22567
|
+
* every retry hits the same revert. Failing here keeps that mistake client-side, before an intent
|
|
22568
|
+
* exists. Malformed and non-EVM addresses already throw inside viem's encoder.
|
|
22569
|
+
*
|
|
22455
22570
|
* @param request - The hook selection (and any hook-specific params).
|
|
22456
22571
|
* @param recipient - The end recipient the hook should credit (the intent's `dstAddress`).
|
|
22457
22572
|
*/
|
|
22458
22573
|
static encodeDeliveryData(request, recipient) {
|
|
22574
|
+
invariant(
|
|
22575
|
+
recipient.toLowerCase() !== ZERO_ADDRESS,
|
|
22576
|
+
"[HookService.encodeDeliveryData] recipient (dstAddress) must not be the zero address"
|
|
22577
|
+
);
|
|
22459
22578
|
switch (request.kind) {
|
|
22460
22579
|
case HookKind.HYPERCORE_DEPOSIT:
|
|
22461
22580
|
return viem.encodeAbiParameters(HOOK_DELIVERY_ABI[HookKind.HYPERCORE_DEPOSIT], [recipient]);
|
|
22581
|
+
case HookKind.FLINT_DEPOSIT:
|
|
22582
|
+
return viem.encodeAbiParameters(HOOK_DELIVERY_ABI[HookKind.FLINT_DEPOSIT], [recipient]);
|
|
22583
|
+
default:
|
|
22584
|
+
return assertUnsupportedHook(request);
|
|
22462
22585
|
}
|
|
22463
|
-
throw new Error(
|
|
22464
|
-
`[HookService.encodeDeliveryData] Unsupported delivery hook kind: ${request.kind}`
|
|
22465
|
-
);
|
|
22466
22586
|
}
|
|
22467
22587
|
/**
|
|
22468
22588
|
* Resolves a high-level {@link HookRequest} to the on-chain delivery pair: the deployed hook address
|
|
@@ -24830,6 +24950,12 @@ var SpokeService = class _SpokeService {
|
|
|
24830
24950
|
/**
|
|
24831
24951
|
* Approve ERC-20 spending on hub / EVM spoke or request a Stellar trustline using unified params.
|
|
24832
24952
|
* Feature services map their action payloads into {@link SpokeApproveParams}.
|
|
24953
|
+
*
|
|
24954
|
+
* A signed ERC-20 approval can take **two** transactions: a token of the TetherToken lineage
|
|
24955
|
+
* rejects an allowance change from one non-zero value to another, so a stale allowance is zeroed
|
|
24956
|
+
* first and the user signs twice. The returned hash is always the last transaction's, so the
|
|
24957
|
+
* contract callers see is unchanged. An unsigned caller still gets exactly one transaction — use
|
|
24958
|
+
* {@link SpokeService.buildApproveTxs} to get the whole plan.
|
|
24833
24959
|
*/
|
|
24834
24960
|
async approve(params) {
|
|
24835
24961
|
try {
|
|
@@ -24837,53 +24963,168 @@ var SpokeService = class _SpokeService {
|
|
|
24837
24963
|
isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, params.walletProvider),
|
|
24838
24964
|
`Invalid wallet provider for chain key: ${params.srcChainKey}, walletProvider.chainType: ${params.walletProvider?.chainType}`
|
|
24839
24965
|
);
|
|
24840
|
-
if (isSpokeApproveParamsHub(params)) {
|
|
24841
|
-
|
|
24842
|
-
|
|
24843
|
-
|
|
24844
|
-
|
|
24845
|
-
|
|
24846
|
-
|
|
24847
|
-
|
|
24966
|
+
if (isSpokeApproveParamsHub(params) || isSpokeApproveParamsEvmSpoke(params)) {
|
|
24967
|
+
if (params.raw) {
|
|
24968
|
+
const tx = await Erc20Service.approve({
|
|
24969
|
+
...params,
|
|
24970
|
+
token: params.token,
|
|
24971
|
+
amount: params.amount,
|
|
24972
|
+
from: params.owner,
|
|
24973
|
+
spender: params.spender
|
|
24974
|
+
});
|
|
24975
|
+
return { ok: true, value: tx };
|
|
24976
|
+
}
|
|
24977
|
+
const result = await this.executeErc20ApprovalPlan(params);
|
|
24978
|
+
if (!result.ok) {
|
|
24979
|
+
return result;
|
|
24980
|
+
}
|
|
24848
24981
|
return {
|
|
24849
24982
|
ok: true,
|
|
24850
|
-
value: result
|
|
24983
|
+
value: result.value
|
|
24851
24984
|
};
|
|
24852
24985
|
}
|
|
24853
|
-
if (
|
|
24854
|
-
const result = await
|
|
24855
|
-
...params,
|
|
24856
|
-
token: params.token,
|
|
24857
|
-
amount: params.amount,
|
|
24858
|
-
from: params.owner,
|
|
24859
|
-
spender: params.spender
|
|
24860
|
-
});
|
|
24986
|
+
if (isSpokeApproveParamsStellar(params)) {
|
|
24987
|
+
const result = await this.requestTrustlineForApproval(params);
|
|
24861
24988
|
return {
|
|
24862
24989
|
ok: true,
|
|
24863
24990
|
value: result
|
|
24864
24991
|
};
|
|
24865
24992
|
}
|
|
24866
|
-
|
|
24867
|
-
|
|
24868
|
-
|
|
24869
|
-
|
|
24870
|
-
|
|
24993
|
+
return {
|
|
24994
|
+
ok: false,
|
|
24995
|
+
error: new Error("[SpokeService.approve] Only hub (Sonic), EVM spokes, and Stellar are supported")
|
|
24996
|
+
};
|
|
24997
|
+
} catch (error) {
|
|
24998
|
+
return { ok: false, error };
|
|
24999
|
+
}
|
|
25000
|
+
}
|
|
25001
|
+
/**
|
|
25002
|
+
* The unsigned approval transactions, named rather than ordered (see {@link ApprovalTxs}).
|
|
25003
|
+
*
|
|
25004
|
+
* `resetTx` is present only when the token needs its stale allowance cleared first (see
|
|
25005
|
+
* {@link Erc20Service.planApproval}); broadcast it and wait for it to be mined before `approveTx`,
|
|
25006
|
+
* which is not valid until the reset has landed. Unsigned callers — the swaps API and the apps
|
|
25007
|
+
* built on it — need this, because {@link SpokeService.approve} can only hand back a single `tx`.
|
|
25008
|
+
*
|
|
25009
|
+
* Deliberately separate from {@link SpokeService.approve} rather than a mode of it: the two return
|
|
25010
|
+
* genuinely different shapes, and folding them together would put a union in the return type of
|
|
25011
|
+
* the method every feature approves through.
|
|
25012
|
+
*/
|
|
25013
|
+
async buildApproveTxs(params) {
|
|
25014
|
+
try {
|
|
25015
|
+
if (isSpokeApproveParamsHub(params) || isSpokeApproveParamsEvmSpoke(params)) {
|
|
25016
|
+
const plan = await this.planErc20Approval(params, "buildApproveTxs");
|
|
25017
|
+
const encode3 = (amount) => Erc20Service.approve({
|
|
24871
25018
|
token: params.token,
|
|
24872
|
-
amount
|
|
25019
|
+
amount,
|
|
25020
|
+
from: params.owner,
|
|
25021
|
+
spender: params.spender,
|
|
25022
|
+
raw: true
|
|
24873
25023
|
});
|
|
25024
|
+
const resetTx = plan.resetAmount === void 0 ? void 0 : await encode3(plan.resetAmount);
|
|
25025
|
+
const approveTx = await encode3(plan.approveAmount);
|
|
25026
|
+
return { ok: true, value: resetTx === void 0 ? { approveTx } : { resetTx, approveTx } };
|
|
25027
|
+
}
|
|
25028
|
+
if (isSpokeApproveParamsStellar(params)) {
|
|
25029
|
+
const tx = await this.requestTrustlineForApproval({ ...params, raw: true });
|
|
24874
25030
|
return {
|
|
24875
25031
|
ok: true,
|
|
24876
|
-
value:
|
|
25032
|
+
value: { approveTx: tx }
|
|
24877
25033
|
};
|
|
24878
25034
|
}
|
|
24879
25035
|
return {
|
|
24880
25036
|
ok: false,
|
|
24881
|
-
error: new Error("[SpokeService.
|
|
25037
|
+
error: new Error("[SpokeService.buildApproveTxs] Only hub (Sonic), EVM spokes, and Stellar are supported")
|
|
24882
25038
|
};
|
|
24883
25039
|
} catch (error) {
|
|
24884
25040
|
return { ok: false, error };
|
|
24885
25041
|
}
|
|
24886
25042
|
}
|
|
25043
|
+
/**
|
|
25044
|
+
* Sign and broadcast the approval plan for an ERC-20 on the hub or an EVM spoke.
|
|
25045
|
+
*
|
|
25046
|
+
* A token of the TetherToken lineage rejects an allowance change from one non-zero value to
|
|
25047
|
+
* another, so a wallet holding a stale allowance needs `approve(0)` first. The transactions cannot
|
|
25048
|
+
* be batched: each one is only valid once its predecessor has been mined. The hash of the last is
|
|
25049
|
+
* returned, so the contract callers see is unchanged.
|
|
25050
|
+
*/
|
|
25051
|
+
async executeErc20ApprovalPlan(params) {
|
|
25052
|
+
const { walletProvider } = params;
|
|
25053
|
+
invariant(
|
|
25054
|
+
walletProvider !== void 0 && isEvmWalletProviderType(walletProvider),
|
|
25055
|
+
"[SpokeService.approve] Expected an EVM wallet provider for a signed approval"
|
|
25056
|
+
);
|
|
25057
|
+
const plan = await this.planErc20Approval(params, "approve");
|
|
25058
|
+
const sendApprove = (amount) => Erc20Service.approve({
|
|
25059
|
+
token: params.token,
|
|
25060
|
+
amount,
|
|
25061
|
+
from: params.owner,
|
|
25062
|
+
spender: params.spender,
|
|
25063
|
+
raw: false,
|
|
25064
|
+
walletProvider
|
|
25065
|
+
});
|
|
25066
|
+
if (plan.resetAmount !== void 0) {
|
|
25067
|
+
const resetHash = await sendApprove(plan.resetAmount);
|
|
25068
|
+
const receipt = await this.waitForTxReceipt({ txHash: resetHash, chainKey: params.srcChainKey });
|
|
25069
|
+
if (!receipt.ok || receipt.value.status !== "success") {
|
|
25070
|
+
return {
|
|
25071
|
+
ok: false,
|
|
25072
|
+
error: new Error(
|
|
25073
|
+
`[SpokeService.approve] allowance reset transaction ${resetHash} did not confirm. Retry the approval \u2014 once the reset has landed it takes a single transaction.`
|
|
25074
|
+
)
|
|
25075
|
+
};
|
|
25076
|
+
}
|
|
25077
|
+
}
|
|
25078
|
+
const txHash = await sendApprove(plan.approveAmount);
|
|
25079
|
+
return { ok: true, value: txHash };
|
|
25080
|
+
}
|
|
25081
|
+
/**
|
|
25082
|
+
* Stellar approves by adding a trustline — always a single transaction, with no allowance to plan
|
|
25083
|
+
* around. Shared by both entry points so the param mapping and its cast live in one place.
|
|
25084
|
+
*/
|
|
25085
|
+
requestTrustlineForApproval(params) {
|
|
25086
|
+
return this.stellar.requestTrustline({
|
|
25087
|
+
...params,
|
|
25088
|
+
srcAddress: params.owner,
|
|
25089
|
+
srcChainKey: params.srcChainKey,
|
|
25090
|
+
token: params.token,
|
|
25091
|
+
amount: params.amount
|
|
25092
|
+
});
|
|
25093
|
+
}
|
|
25094
|
+
/** Resolve the chain-specific inputs {@link Erc20Service.planApproval} needs, and record the plan. */
|
|
25095
|
+
async planErc20Approval(params, caller) {
|
|
25096
|
+
const plan = await Erc20Service.planApproval({
|
|
25097
|
+
token: params.token,
|
|
25098
|
+
owner: params.owner,
|
|
25099
|
+
spender: params.spender,
|
|
25100
|
+
amount: params.amount,
|
|
25101
|
+
nativeToken: this.config.getChainConfig(params.srcChainKey).nativeToken,
|
|
25102
|
+
publicClient: this.getEvmPublicClient(params.srcChainKey)
|
|
25103
|
+
});
|
|
25104
|
+
this.logApprovalPlan(caller, params.srcChainKey, params.token, plan);
|
|
25105
|
+
return plan;
|
|
25106
|
+
}
|
|
25107
|
+
/** The read client for an EVM chain, whether it is the hub or a spoke. */
|
|
25108
|
+
getEvmPublicClient(chainKey) {
|
|
25109
|
+
return isHubChainKeyType(chainKey) ? this.sonic.publicClient : this.evm.getPublicClient(chainKey);
|
|
25110
|
+
}
|
|
25111
|
+
/**
|
|
25112
|
+
* Log a plan only when it says something: an extra transaction the user will have to sign, or a
|
|
25113
|
+
* probe that could not reach a verdict. The ordinary single approve is the vast majority of calls
|
|
25114
|
+
* and stays silent.
|
|
25115
|
+
*/
|
|
25116
|
+
logApprovalPlan(caller, chainKey, token, plan) {
|
|
25117
|
+
const isNoteworthy = plan.resetAmount !== void 0 || plan.reason === "reset-not-viable" || plan.reason === "allowance-read-failed";
|
|
25118
|
+
if (!isNoteworthy) {
|
|
25119
|
+
return;
|
|
25120
|
+
}
|
|
25121
|
+
this.config.logger.debug(`[SpokeService.${caller}] approval plan`, {
|
|
25122
|
+
chainKey,
|
|
25123
|
+
token,
|
|
25124
|
+
needsReset: plan.resetAmount !== void 0,
|
|
25125
|
+
reason: plan.reason
|
|
25126
|
+
});
|
|
25127
|
+
}
|
|
24887
25128
|
/**
|
|
24888
25129
|
* Estimate the gas for a raw transaction.
|
|
24889
25130
|
* @param {TxReturnType<T, true>} params - The parameters for the raw transaction.
|
|
@@ -26724,19 +26965,20 @@ var SolverApiService = class {
|
|
|
26724
26965
|
|
|
26725
26966
|
// src/backendApi/pollBackendSubmitTx.ts
|
|
26726
26967
|
async function pollBackendSubmitTx({
|
|
26727
|
-
|
|
26968
|
+
attempt,
|
|
26728
26969
|
terminalStatus,
|
|
26729
26970
|
getStatus,
|
|
26730
26971
|
onExecuted,
|
|
26731
26972
|
intervalMs = 1e3,
|
|
26732
26973
|
requestTimeoutMs
|
|
26733
26974
|
}) {
|
|
26734
|
-
|
|
26735
|
-
|
|
26736
|
-
|
|
26737
|
-
|
|
26738
|
-
const statusResult = await getStatus(
|
|
26975
|
+
let polls = 0;
|
|
26976
|
+
let lastStatusError;
|
|
26977
|
+
for (let requestTimeout = attempt.requestTimeout(requestTimeoutMs); requestTimeout !== null; requestTimeout = attempt.requestTimeout(requestTimeoutMs)) {
|
|
26978
|
+
polls += 1;
|
|
26979
|
+
const statusResult = await getStatus({ timeout: requestTimeout });
|
|
26739
26980
|
if (statusResult.ok) {
|
|
26981
|
+
lastStatusError = void 0;
|
|
26740
26982
|
const { status, result, failureReason, abandonedAt } = statusResult.value.data;
|
|
26741
26983
|
if (status === terminalStatus) {
|
|
26742
26984
|
const value = onExecuted(result);
|
|
@@ -26746,11 +26988,70 @@ async function pollBackendSubmitTx({
|
|
|
26746
26988
|
const reason = failureReason ? `: ${failureReason}` : "";
|
|
26747
26989
|
return { ok: false, cause: new Error(`backend submit-tx ${status}${reason}`) };
|
|
26748
26990
|
}
|
|
26991
|
+
} else {
|
|
26992
|
+
lastStatusError = statusResult.error;
|
|
26749
26993
|
}
|
|
26750
|
-
|
|
26994
|
+
if (attempt.remaining() <= intervalMs) break;
|
|
26995
|
+
await sleep(intervalMs);
|
|
26996
|
+
}
|
|
26997
|
+
if (polls === 0) {
|
|
26998
|
+
return { ok: false, cause: new Error("backend submit-tx submitted, but no budget was left to poll for status") };
|
|
26999
|
+
}
|
|
27000
|
+
if (lastStatusError !== void 0) {
|
|
27001
|
+
return {
|
|
27002
|
+
ok: false,
|
|
27003
|
+
cause: new Error(`backend submit-tx status polling failed before reaching ${terminalStatus}`, {
|
|
27004
|
+
cause: lastStatusError
|
|
27005
|
+
})
|
|
27006
|
+
};
|
|
26751
27007
|
}
|
|
26752
27008
|
return { ok: false, cause: new Error(`backend submit-tx polling timed out before reaching ${terminalStatus}`) };
|
|
26753
27009
|
}
|
|
27010
|
+
|
|
27011
|
+
// src/backendApi/submitTxAttempt.ts
|
|
27012
|
+
function noRequestBudgetCause(serviceTimeoutMs) {
|
|
27013
|
+
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}`);
|
|
27014
|
+
}
|
|
27015
|
+
function createSubmitTxAttempt(callerTimeoutMs) {
|
|
27016
|
+
const deadline = Date.now() + resolveTimeoutMs(callerTimeoutMs, 0);
|
|
27017
|
+
const remaining = () => Math.max(0, deadline - Date.now());
|
|
27018
|
+
return {
|
|
27019
|
+
remaining,
|
|
27020
|
+
requestTimeout: (serviceTimeoutMs) => {
|
|
27021
|
+
const timeout = Math.min(remaining(), serviceTimeoutMs);
|
|
27022
|
+
return timeout > 0 ? timeout : null;
|
|
27023
|
+
}
|
|
27024
|
+
};
|
|
27025
|
+
}
|
|
27026
|
+
|
|
27027
|
+
// src/backendApi/runBackendSubmitTx.ts
|
|
27028
|
+
async function runBackendSubmitTx({
|
|
27029
|
+
attempt,
|
|
27030
|
+
api,
|
|
27031
|
+
body,
|
|
27032
|
+
statusQuery,
|
|
27033
|
+
terminalStatus,
|
|
27034
|
+
onExecuted
|
|
27035
|
+
}) {
|
|
27036
|
+
const serviceTimeoutMs = api.getTimeout();
|
|
27037
|
+
const requestTimeout = attempt.requestTimeout(serviceTimeoutMs);
|
|
27038
|
+
if (requestTimeout === null) return { ok: false, cause: noRequestBudgetCause(serviceTimeoutMs) };
|
|
27039
|
+
const submitted = await api.submitTx(body, { timeout: requestTimeout });
|
|
27040
|
+
if (!submitted.ok) return { ok: false, cause: submitted.error };
|
|
27041
|
+
if (!submitted.value.success) {
|
|
27042
|
+
return { ok: false, cause: new Error(`backend submit-tx not accepted: ${submitted.value.data.message}`) };
|
|
27043
|
+
}
|
|
27044
|
+
const polled = await pollBackendSubmitTx({
|
|
27045
|
+
attempt,
|
|
27046
|
+
terminalStatus,
|
|
27047
|
+
getStatus: (override) => api.getSubmitTxStatus(statusQuery, override),
|
|
27048
|
+
onExecuted,
|
|
27049
|
+
// While this ceiling is the smaller bound the poll retries within the attempt; once the attempt's
|
|
27050
|
+
// remainder falls below it, one stalled request can spend the rest.
|
|
27051
|
+
requestTimeoutMs: serviceTimeoutMs
|
|
27052
|
+
});
|
|
27053
|
+
return polled.ok ? { ok: true, value: polled.value } : { ok: false, cause: polled.cause };
|
|
27054
|
+
}
|
|
26754
27055
|
function decodePacketIntentTarget(payload) {
|
|
26755
27056
|
try {
|
|
26756
27057
|
const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
|
|
@@ -26801,20 +27102,33 @@ var SwapService = class {
|
|
|
26801
27102
|
spoke;
|
|
26802
27103
|
// swap config
|
|
26803
27104
|
solver;
|
|
26804
|
-
partnerFee;
|
|
26805
27105
|
relayerApiEndpoint;
|
|
26806
|
-
// backend swaps-API client
|
|
27106
|
+
// backend swaps-API client
|
|
26807
27107
|
backendApi;
|
|
26808
|
-
|
|
26809
|
-
|
|
27108
|
+
/**
|
|
27109
|
+
* Effective 2-step submit-tx flow (`swaps.useBackendSubmitTx`, default on). Read live off
|
|
27110
|
+
* `ConfigService`, like {@link SwapService.partnerFee}, so the config object and the behavior can
|
|
27111
|
+
* never disagree.
|
|
27112
|
+
*/
|
|
27113
|
+
get useBackendSubmitTx() {
|
|
27114
|
+
return this.config.swapUseBackendSubmitTx;
|
|
27115
|
+
}
|
|
27116
|
+
/**
|
|
27117
|
+
* Effective swap partner fee (`swaps.partnerFee`, else the global `fee`). Read live off
|
|
27118
|
+
* `ConfigService` rather than snapshotted in the constructor, so it cannot diverge from
|
|
27119
|
+
* `config.swapPartnerFee` if the config object is ever replaced (see `ConfigService.initialize`).
|
|
27120
|
+
* `BridgeService` and `LeverageYieldService` resolve their fees the same way.
|
|
27121
|
+
*/
|
|
27122
|
+
get partnerFee() {
|
|
27123
|
+
return this.config.swapPartnerFee;
|
|
27124
|
+
}
|
|
27125
|
+
constructor({ config, hubProvider, spoke, backendApi }) {
|
|
26810
27126
|
this.solver = config.solver;
|
|
26811
|
-
this.partnerFee = config.swapPartnerFee;
|
|
26812
27127
|
this.relayerApiEndpoint = config.relay.relayerApiEndpoint;
|
|
26813
27128
|
this.config = config;
|
|
26814
27129
|
this.hubProvider = hubProvider;
|
|
26815
27130
|
this.spoke = spoke;
|
|
26816
27131
|
this.backendApi = backendApi;
|
|
26817
|
-
this.useBackendSubmitTx = useBackendSubmitTx ?? false;
|
|
26818
27132
|
}
|
|
26819
27133
|
/**
|
|
26820
27134
|
* Estimates the gas cost for a raw (unsigned) transaction on a spoke chain.
|
|
@@ -26959,21 +27273,26 @@ var SwapService = class {
|
|
|
26959
27273
|
* Executes a full end-to-end cross-chain swap.
|
|
26960
27274
|
*
|
|
26961
27275
|
* Orchestrates the complete swap lifecycle. `createIntent` first submits the intent transaction on
|
|
26962
|
-
* the source spoke chain; completion then runs via one of two paths,
|
|
26963
|
-
*
|
|
26964
|
-
*
|
|
26965
|
-
* - **Client-side (
|
|
26966
|
-
* relays it to the hub (Sonic) and waits for the packet — skipped when
|
|
26967
|
-
* where the spoke tx already is the hub tx — then calls `postExecution` to
|
|
26968
|
-
* triggering it to fill the intent.
|
|
26969
|
-
* - **Backend 2-step (
|
|
27276
|
+
* the source spoke chain; completion then runs via one of two paths, each bounded by its own `timeout`
|
|
27277
|
+
* budget:
|
|
27278
|
+
*
|
|
27279
|
+
* - **Client-side (opt-out via `swaps.useBackendSubmitTx: false`), {@link fallbackSwapSteps}:** verifies
|
|
27280
|
+
* the spoke tx landed on-chain, relays it to the hub (Sonic) and waits for the packet — skipped when
|
|
27281
|
+
* `srcChainKey` is the hub, where the spoke tx already is the hub tx — then calls `postExecution` to
|
|
27282
|
+
* notify the solver, triggering it to fill the intent.
|
|
27283
|
+
* - **Backend 2-step (default via `swaps.useBackendSubmitTx`), {@link submitTx}:** hands the
|
|
26970
27284
|
* broadcast tx to the swaps API, which verifies, relays and post-executes server-side, then polls
|
|
26971
27285
|
* for completion. On ANY non-success it transparently falls back to the client-side path above —
|
|
26972
27286
|
* safe because re-relaying / re-posting an already-processed swap is idempotent (no double-fill).
|
|
26973
27287
|
*
|
|
26974
27288
|
* @param _params - Swap action params including intent parameters, wallet provider, and an optional
|
|
26975
|
-
* `timeout` —
|
|
26976
|
-
*
|
|
27289
|
+
* `timeout` — a PER-ATTEMPT budget, not an end-to-end one. The backend attempt (submit POST + status
|
|
27290
|
+
* poll) gets it, and if that attempt does not complete the client-side relay wait gets a fresh one
|
|
27291
|
+
* starting after verification, so neither a stalled backend nor a slow source-chain confirmation can
|
|
27292
|
+
* shorten it. Worst-case wall-clock is `createIntent + timeout + verification +
|
|
27293
|
+
* max(timeout, RELAY_FALLBACK_FLOOR_MS) + postExecution`, where verification is bounded by the source
|
|
27294
|
+
* chain's `pollingConfig.maxTimeoutMs` and the first and last terms are not bounded by `timeout` at
|
|
27295
|
+
* all. See `docs/SWAPS.md` § How `timeout` bounds each attempt.
|
|
26977
27296
|
* @returns A `Result<SwapResponse, SwapError>`. On success:
|
|
26978
27297
|
* - `solverExecutionResponse` — solver acknowledgement (`{ answer: 'OK', intent_hash }`).
|
|
26979
27298
|
* - `intent` — the on-chain intent object that was created.
|
|
@@ -27007,9 +27326,9 @@ var SwapService = class {
|
|
|
27007
27326
|
return { ok: false, error: createIntentResult.error };
|
|
27008
27327
|
}
|
|
27009
27328
|
const created = createIntentResult.value;
|
|
27010
|
-
const
|
|
27329
|
+
const timeoutMs = resolveTimeoutMs(_params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
27011
27330
|
if (this.useBackendSubmitTx) {
|
|
27012
|
-
const submitted = await this.submitTx(_params, created,
|
|
27331
|
+
const submitted = await this.submitTx(_params, created, createSubmitTxAttempt(timeoutMs));
|
|
27013
27332
|
if (submitted.ok) return submitted;
|
|
27014
27333
|
this.config.logger.warn(
|
|
27015
27334
|
"[swap] backend submit-tx did not complete; falling back to the client-side relay",
|
|
@@ -27018,7 +27337,7 @@ var SwapService = class {
|
|
|
27018
27337
|
}
|
|
27019
27338
|
);
|
|
27020
27339
|
}
|
|
27021
|
-
return this.fallbackSwapSteps(_params, created,
|
|
27340
|
+
return this.fallbackSwapSteps(_params, created, timeoutMs);
|
|
27022
27341
|
} catch (error) {
|
|
27023
27342
|
if (isSwapError(error)) return { ok: false, error };
|
|
27024
27343
|
return {
|
|
@@ -27045,12 +27364,16 @@ var SwapService = class {
|
|
|
27045
27364
|
);
|
|
27046
27365
|
}
|
|
27047
27366
|
/**
|
|
27048
|
-
* Client-side swap completion (
|
|
27049
|
-
* use it directly when the source IS the hub — then notify the
|
|
27050
|
-
* build the {@link SwapResponse}. Extracted verbatim from `swap()` so the
|
|
27051
|
-
* path ({@link submitTx}) can fall back to it on any non-success.
|
|
27367
|
+
* Client-side swap completion (opt-out via `swaps.useBackendSubmitTx: false`): verify the broadcast intent
|
|
27368
|
+
* tx landed, then relay it to the hub — or use it directly when the source IS the hub — then notify the
|
|
27369
|
+
* solver via post-execution and build the {@link SwapResponse}. Extracted verbatim from `swap()` so the
|
|
27370
|
+
* backend 2-step path ({@link submitTx}) can fall back to it on any non-success.
|
|
27371
|
+
*
|
|
27372
|
+
* Verification belongs to THIS path only: the backend runs its own, so verifying before handing over
|
|
27373
|
+
* would delay every backend success by the source chain's confirmation wait and could fail a swap the
|
|
27374
|
+
* backend would have completed.
|
|
27052
27375
|
*/
|
|
27053
|
-
async fallbackSwapSteps(_params, created,
|
|
27376
|
+
async fallbackSwapSteps(_params, created, timeoutMs) {
|
|
27054
27377
|
const { params } = _params;
|
|
27055
27378
|
const srcChainKey = params.srcChainKey;
|
|
27056
27379
|
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
|
|
@@ -27071,9 +27394,12 @@ var SwapService = class {
|
|
|
27071
27394
|
data: relayData,
|
|
27072
27395
|
chainKey: srcChainKey,
|
|
27073
27396
|
relayerApiEndpoint: this.relayerApiEndpoint,
|
|
27074
|
-
//
|
|
27075
|
-
//
|
|
27076
|
-
|
|
27397
|
+
// The caller's full `timeout`, starting HERE — after verification, and whether this runs as the
|
|
27398
|
+
// only path or as the backend's fallback. Neither a stalled backend attempt nor a slow source-chain
|
|
27399
|
+
// confirmation may shorten the relay wait. The floor covers a sub-floor caller `timeout`:
|
|
27400
|
+
// `relayTxAndWaitPacket` SUBMITS before `timeout` bounds anything, so a zero budget would strand an
|
|
27401
|
+
// already-landed tx unrelayed. Re-relay is idempotent, so spending it is safe.
|
|
27402
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS)
|
|
27077
27403
|
});
|
|
27078
27404
|
if (!packet.ok) {
|
|
27079
27405
|
return { ok: false, error: mapRelayFailure(packet.error, { feature: "swap", action: "swap", ...baseCtx }) };
|
|
@@ -27103,7 +27429,7 @@ var SwapService = class {
|
|
|
27103
27429
|
};
|
|
27104
27430
|
}
|
|
27105
27431
|
/**
|
|
27106
|
-
* Backend 2-step swap path (
|
|
27432
|
+
* Backend 2-step swap path (default via `swaps.useBackendSubmitTx`): hand the broadcast
|
|
27107
27433
|
* intent tx to the swaps API (`POST /swaps/submit-tx`); the backend relays + post-executes
|
|
27108
27434
|
* server-side. Polls `getSubmitTxStatus` until `solved`, then reconstructs the same
|
|
27109
27435
|
* {@link SwapResponse} the client-side path returns (`result.dstIntentTxHash` → delivery info,
|
|
@@ -27114,32 +27440,36 @@ var SwapService = class {
|
|
|
27114
27440
|
*
|
|
27115
27441
|
* Falling back is safe: re-relaying / re-posting an already-processed swap is idempotent — the
|
|
27116
27442
|
* relay dedups and returns the existing `executed` packet, and the solver re-affirms the intent
|
|
27117
|
-
* (no double-fill). Verified live by `e2e-tests/e2e-relay.test.ts`.
|
|
27118
|
-
*
|
|
27443
|
+
* (no double-fill). Verified live by `e2e-tests/e2e-relay.test.ts`. It is also load-bearing rather
|
|
27444
|
+
* than belt-and-braces: the backend keeps processing after this attempt gives up, so the fallback's
|
|
27445
|
+
* relay can race the backend's own.
|
|
27446
|
+
*
|
|
27447
|
+
* The attempt itself — POST, budget clamps, status poll — is {@link runBackendSubmitTx}, shared with
|
|
27448
|
+
* bridge. What is swap-specific and lives here: the request body, the `solved` terminal status, the
|
|
27449
|
+
* mapping from a terminal result to a {@link SwapResponse}, and the swap error taxonomy.
|
|
27450
|
+
*
|
|
27451
|
+
* `attempt` bounds this attempt alone — the POST and every status request draw on it, and the
|
|
27452
|
+
* client-side fallback holds a separate fresh `timeout`.
|
|
27119
27453
|
*/
|
|
27120
|
-
async submitTx(_params, created,
|
|
27454
|
+
async submitTx(_params, created, attempt) {
|
|
27121
27455
|
const { params } = _params;
|
|
27122
27456
|
const srcChainKey = params.srcChainKey;
|
|
27123
27457
|
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
|
|
27124
27458
|
const { tx: spokeTxHash, intent, relayData } = created;
|
|
27125
|
-
const submitTxFailed = (cause) => ({
|
|
27126
|
-
ok: false,
|
|
27127
|
-
error: executionFailed("swap", cause, { ...baseCtx, action: "swap" })
|
|
27128
|
-
});
|
|
27129
27459
|
try {
|
|
27130
|
-
const
|
|
27131
|
-
|
|
27132
|
-
|
|
27133
|
-
|
|
27134
|
-
|
|
27135
|
-
|
|
27136
|
-
|
|
27137
|
-
|
|
27138
|
-
|
|
27139
|
-
|
|
27460
|
+
const outcome = await runBackendSubmitTx({
|
|
27461
|
+
attempt,
|
|
27462
|
+
api: this.backendApi.swaps,
|
|
27463
|
+
body: {
|
|
27464
|
+
txHash: spokeTxHash,
|
|
27465
|
+
srcChainKey,
|
|
27466
|
+
walletAddress: params.srcAddress,
|
|
27467
|
+
intent,
|
|
27468
|
+
relayData: relayData.payload
|
|
27469
|
+
},
|
|
27470
|
+
statusQuery: { txHash: spokeTxHash, srcChainKey },
|
|
27140
27471
|
// Swaps terminal success is `solved` (solver filled) — not the bridge `executed`.
|
|
27141
27472
|
terminalStatus: "solved",
|
|
27142
|
-
getStatus: () => this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }),
|
|
27143
27473
|
onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
|
|
27144
27474
|
// Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
|
|
27145
27475
|
solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
|
|
@@ -27154,7 +27484,7 @@ var SwapService = class {
|
|
|
27154
27484
|
}
|
|
27155
27485
|
} : void 0
|
|
27156
27486
|
});
|
|
27157
|
-
return
|
|
27487
|
+
return outcome.ok ? { ok: true, value: outcome.value } : { ok: false, error: executionFailed("swap", outcome.cause, { ...baseCtx, action: "swap" }) };
|
|
27158
27488
|
} catch (error) {
|
|
27159
27489
|
return { ok: false, error: unknownFailed("swap", error, { ...baseCtx, action: "swap" }) };
|
|
27160
27490
|
}
|
|
@@ -27216,9 +27546,13 @@ var SwapService = class {
|
|
|
27216
27546
|
* - Stellar: approves the trustline (adds/increases it).
|
|
27217
27547
|
* - Other chain types: returns an error — approval is not supported.
|
|
27218
27548
|
*
|
|
27219
|
-
* When `raw: true`, returns unsigned transaction data instead of broadcasting.
|
|
27549
|
+
* When `raw: true`, returns unsigned transaction data instead of broadcasting. That is always a
|
|
27550
|
+
* single transaction, which cannot express the two-step approval a TetherToken-lineage token
|
|
27551
|
+
* needs when a stale allowance already exists — use {@link SwapService.buildApproveTxs} for the
|
|
27552
|
+
* whole plan.
|
|
27220
27553
|
* When `raw: false`, a matching wallet provider for `K` must be supplied and the transaction
|
|
27221
|
-
* is signed and broadcast immediately.
|
|
27554
|
+
* is signed and broadcast immediately. Such an approval can take **two** transactions, so the
|
|
27555
|
+
* user may sign twice; the returned hash is the last one's.
|
|
27222
27556
|
*
|
|
27223
27557
|
* @param _params - Swap action params including the source chain key, input token, amount, and wallet provider.
|
|
27224
27558
|
* @returns A `Result` wrapping the chain-specific transaction return type (`TxReturnType<K, Raw>`).
|
|
@@ -27288,6 +27622,62 @@ var SwapService = class {
|
|
|
27288
27622
|
return { ok: false, error };
|
|
27289
27623
|
}
|
|
27290
27624
|
}
|
|
27625
|
+
/**
|
|
27626
|
+
* The unsigned approval transactions for the swap's source token, in the order they must be
|
|
27627
|
+
* broadcast.
|
|
27628
|
+
*
|
|
27629
|
+
* Two transactions when the source token needs its stale allowance cleared first, one otherwise.
|
|
27630
|
+
* {@link SwapService.approve} is unchanged and still returns a single transaction; this is the
|
|
27631
|
+
* entry point for unsigned callers that need to handle the two-step case. When `resetTx` is
|
|
27632
|
+
* present, broadcast it and wait for it to be mined first — `approveTx` is not valid until the
|
|
27633
|
+
* reset has landed.
|
|
27634
|
+
*/
|
|
27635
|
+
async buildApproveTxs(_params) {
|
|
27636
|
+
const { params } = _params;
|
|
27637
|
+
const wrapApproveFailure = (cause) => approveFailed("swap", cause);
|
|
27638
|
+
try {
|
|
27639
|
+
if (isHubChainKeyType(params.srcChainKey) || isEvmSpokeOnlyChainKeyType(params.srcChainKey)) {
|
|
27640
|
+
const spender = isHubChainKeyType(params.srcChainKey) ? this.solver.intentsContract : this.config.getChainConfig(params.srcChainKey).addresses.assetManager;
|
|
27641
|
+
const result = await this.spoke.buildApproveTxs({
|
|
27642
|
+
srcChainKey: params.srcChainKey,
|
|
27643
|
+
owner: params.srcAddress,
|
|
27644
|
+
token: params.inputToken,
|
|
27645
|
+
amount: params.inputAmount,
|
|
27646
|
+
spender,
|
|
27647
|
+
raw: true
|
|
27648
|
+
});
|
|
27649
|
+
if (!result.ok) {
|
|
27650
|
+
return { ok: false, error: wrapApproveFailure(result.error) };
|
|
27651
|
+
}
|
|
27652
|
+
return {
|
|
27653
|
+
ok: true,
|
|
27654
|
+
value: result.value
|
|
27655
|
+
};
|
|
27656
|
+
}
|
|
27657
|
+
if (isStellarChainKeyType(params.srcChainKey)) {
|
|
27658
|
+
const result = await this.spoke.buildApproveTxs({
|
|
27659
|
+
srcChainKey: params.srcChainKey,
|
|
27660
|
+
token: params.inputToken,
|
|
27661
|
+
amount: params.inputAmount,
|
|
27662
|
+
owner: params.srcAddress,
|
|
27663
|
+
raw: true
|
|
27664
|
+
});
|
|
27665
|
+
if (!result.ok) {
|
|
27666
|
+
return { ok: false, error: wrapApproveFailure(result.error) };
|
|
27667
|
+
}
|
|
27668
|
+
return {
|
|
27669
|
+
ok: true,
|
|
27670
|
+
value: result.value
|
|
27671
|
+
};
|
|
27672
|
+
}
|
|
27673
|
+
return {
|
|
27674
|
+
ok: false,
|
|
27675
|
+
error: new Error("Approve only supported for hub (Sonic), EVM spokes, and Stellar")
|
|
27676
|
+
};
|
|
27677
|
+
} catch (error) {
|
|
27678
|
+
return { ok: false, error };
|
|
27679
|
+
}
|
|
27680
|
+
}
|
|
27291
27681
|
/**
|
|
27292
27682
|
* Creates a swap intent on the user's source spoke chain without submitting it to the solver.
|
|
27293
27683
|
*
|
|
@@ -29943,7 +30333,6 @@ async function makeRequest(params) {
|
|
|
29943
30333
|
body: config.body,
|
|
29944
30334
|
signal: controller.signal
|
|
29945
30335
|
});
|
|
29946
|
-
clearTimeout(timeoutId);
|
|
29947
30336
|
if (!response.ok) {
|
|
29948
30337
|
const errorText = await response.text();
|
|
29949
30338
|
throw new BackendHttpError(response.status, errorText);
|
|
@@ -29951,7 +30340,6 @@ async function makeRequest(params) {
|
|
|
29951
30340
|
const data = await response.json();
|
|
29952
30341
|
return data;
|
|
29953
30342
|
} catch (error) {
|
|
29954
|
-
clearTimeout(timeoutId);
|
|
29955
30343
|
if (error instanceof Error) {
|
|
29956
30344
|
if (error.name === "AbortError") {
|
|
29957
30345
|
throw new Error("REQUEST_TIMEOUT", { cause: new Error(`Request timeout after ${timeout}ms`) });
|
|
@@ -29961,6 +30349,8 @@ async function makeRequest(params) {
|
|
|
29961
30349
|
}
|
|
29962
30350
|
logger.error(`[${serviceLabel}] Unknown error`, error);
|
|
29963
30351
|
throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
|
|
30352
|
+
} finally {
|
|
30353
|
+
clearTimeout(timeoutId);
|
|
29964
30354
|
}
|
|
29965
30355
|
}
|
|
29966
30356
|
function resolveRequestConfig(config, defaults) {
|
|
@@ -30165,7 +30555,9 @@ var SwapsApiService = class _SwapsApiService {
|
|
|
30165
30555
|
// ──────────────────────────────────────────────────────────────────────
|
|
30166
30556
|
// Submit-tx state machine
|
|
30167
30557
|
// ──────────────────────────────────────────────────────────────────────
|
|
30168
|
-
/** Submit a swap transaction to be processed (relay, post-execution, etc.). Idempotent on `(txHash, srcChainKey)`.
|
|
30558
|
+
/** Submit a swap transaction to be processed (relay, post-execution, etc.). Idempotent on `(txHash, srcChainKey)`.
|
|
30559
|
+
* Response is immediate after successful submission. Use getSubmitTxStatus to poll the status of the submission.
|
|
30560
|
+
*/
|
|
30169
30561
|
async submitTx(body, config) {
|
|
30170
30562
|
return this.toResult(
|
|
30171
30563
|
"/swaps/submit-tx",
|
|
@@ -30194,6 +30586,18 @@ var SwapsApiService = class _SwapsApiService {
|
|
|
30194
30586
|
getBaseURL() {
|
|
30195
30587
|
return this.config.baseURL;
|
|
30196
30588
|
}
|
|
30589
|
+
/**
|
|
30590
|
+
* Return the effective per-request timeout (ms) — the same value {@link buildClient} resolves, so
|
|
30591
|
+
* `SwapsApiConfig.timeout` being optional never leaks an `undefined` ceiling.
|
|
30592
|
+
*
|
|
30593
|
+
* Callers bounding a request tighter than this need it as the CEILING, because a
|
|
30594
|
+
* `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it: an override
|
|
30595
|
+
* derived from a caller budget alone would raise the bound whenever that budget is the larger of the
|
|
30596
|
+
* two. `SubmitTxAttempt.requestTimeout` clamps against both (`min(budget left in the attempt, this)`).
|
|
30597
|
+
*/
|
|
30598
|
+
getTimeout() {
|
|
30599
|
+
return this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
|
|
30600
|
+
}
|
|
30197
30601
|
};
|
|
30198
30602
|
var StellarSponsorConfigSchema = v7__namespace.object({
|
|
30199
30603
|
sponsorAccount: v7__namespace.string(),
|
|
@@ -30680,9 +31084,12 @@ var BridgeApiService = class {
|
|
|
30680
31084
|
return this.config.baseURL;
|
|
30681
31085
|
}
|
|
30682
31086
|
/**
|
|
30683
|
-
* Return the effective per-request timeout (ms).
|
|
30684
|
-
*
|
|
30685
|
-
*
|
|
31087
|
+
* Return the effective per-request timeout (ms).
|
|
31088
|
+
*
|
|
31089
|
+
* Callers bounding a request tighter than this need it as the CEILING, because a
|
|
31090
|
+
* `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it: an override
|
|
31091
|
+
* derived from a caller budget alone would raise the bound whenever that budget is the larger of the
|
|
31092
|
+
* two. `SubmitTxAttempt.requestTimeout` clamps against both (`min(budget left in the attempt, this)`).
|
|
30686
31093
|
*/
|
|
30687
31094
|
getTimeout() {
|
|
30688
31095
|
return this.config.timeout;
|
|
@@ -31294,15 +31701,20 @@ var BridgeService = class {
|
|
|
31294
31701
|
hubProvider;
|
|
31295
31702
|
config;
|
|
31296
31703
|
spoke;
|
|
31297
|
-
// backend bridge-API client
|
|
31704
|
+
// backend bridge-API client
|
|
31298
31705
|
backendApi;
|
|
31299
|
-
|
|
31300
|
-
|
|
31706
|
+
/**
|
|
31707
|
+
* Effective backend submit-tx flow (`bridge.useBackendSubmitTx`, default on). Read live off
|
|
31708
|
+
* `ConfigService` like `bridgePartnerFee`, so the config object and the behavior can never disagree.
|
|
31709
|
+
*/
|
|
31710
|
+
get useBackendSubmitTx() {
|
|
31711
|
+
return this.config.bridgeUseBackendSubmitTx;
|
|
31712
|
+
}
|
|
31713
|
+
constructor({ hubProvider, config, spoke, backendApi }) {
|
|
31301
31714
|
this.config = config;
|
|
31302
31715
|
this.hubProvider = hubProvider;
|
|
31303
31716
|
this.spoke = spoke;
|
|
31304
31717
|
this.backendApi = backendApi;
|
|
31305
|
-
this.useBackendSubmitTx = useBackendSubmitTx ?? false;
|
|
31306
31718
|
}
|
|
31307
31719
|
/**
|
|
31308
31720
|
* Calculates the partner fee deducted from a given bridge input amount.
|
|
@@ -31467,15 +31879,27 @@ var BridgeService = class {
|
|
|
31467
31879
|
/**
|
|
31468
31880
|
* Executes a full end-to-end bridge transfer: spoke deposit → relay → hub settlement.
|
|
31469
31881
|
*
|
|
31470
|
-
* Internally calls `createBridgeIntent()` to submit the spoke-side deposit transaction,
|
|
31471
|
-
*
|
|
31472
|
-
*
|
|
31882
|
+
* Internally calls `createBridgeIntent()` to submit the spoke-side deposit transaction, then
|
|
31883
|
+
* completes the transfer via one of two paths. Use this method for the typical "fire and wait" UX.
|
|
31884
|
+
*
|
|
31885
|
+
* - **Backend submit-tx (default, `bridge.useBackendSubmitTx`), {@link submitTx}:** hands the deposit
|
|
31886
|
+
* to the bridge API, which relays server-side, and polls until `executed`. On ANY non-success it
|
|
31887
|
+
* falls back to the path below — safe because re-relaying is idempotent.
|
|
31888
|
+
* - **Client-side (opt-out with `useBackendSubmitTx: false`), {@link fallbackBridgeSteps}:** verifies
|
|
31889
|
+
* the deposit landed on-chain, then relays it and waits for the settlement packet. `verifyTxHash`
|
|
31890
|
+
* runs on this path only; the backend runs its own.
|
|
31473
31891
|
*
|
|
31474
31892
|
* For manual relay control (e.g. monitoring or batching), use `createBridgeIntent()` directly
|
|
31475
31893
|
* and handle the relay step yourself.
|
|
31476
31894
|
*
|
|
31477
31895
|
* @param _params - Bridge parameters including source/destination chain keys, token addresses,
|
|
31478
|
-
* amount, recipient address, wallet provider, and optional timeout
|
|
31896
|
+
* amount, recipient address, wallet provider, and an optional `timeout` — a PER-ATTEMPT budget,
|
|
31897
|
+
* not an end-to-end one. The backend attempt gets it, and if that attempt does not complete the
|
|
31898
|
+
* client-side relay wait gets a fresh one starting after verification, so neither a stalled backend
|
|
31899
|
+
* nor a slow source-chain confirmation can shorten it. Worst-case wall-clock is
|
|
31900
|
+
* `createBridgeIntent + timeout + verification + max(timeout, RELAY_FALLBACK_FLOOR_MS)`, where
|
|
31901
|
+
* verification is bounded by the source chain's `pollingConfig.maxTimeoutMs` and intent creation is
|
|
31902
|
+
* not bounded by `timeout` at all. See `docs/BRIDGE.md` § Completion paths and `timeout`.
|
|
31479
31903
|
* @returns `Result<TxHashPair>` — `{ srcChainTxHash, dstChainTxHash }` on success,
|
|
31480
31904
|
* where `srcChainTxHash` is the spoke deposit tx and `dstChainTxHash` is the hub settlement tx.
|
|
31481
31905
|
*
|
|
@@ -31509,16 +31933,16 @@ var BridgeService = class {
|
|
|
31509
31933
|
try {
|
|
31510
31934
|
const created = await this.createBridgeIntent(_params);
|
|
31511
31935
|
if (!created.ok) return { ok: false, error: created.error };
|
|
31512
|
-
const
|
|
31936
|
+
const timeoutMs = resolveTimeoutMs(_params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
31513
31937
|
if (this.useBackendSubmitTx) {
|
|
31514
|
-
const submitted = await this.submitTx(_params, created.value,
|
|
31938
|
+
const submitted = await this.submitTx(_params, created.value, createSubmitTxAttempt(timeoutMs));
|
|
31515
31939
|
if (submitted.ok) return submitted;
|
|
31516
31940
|
this.config.logger.warn(
|
|
31517
31941
|
"[bridge] backend submit-tx did not complete; falling back to the client-side relay",
|
|
31518
31942
|
{ error: submitted.error }
|
|
31519
31943
|
);
|
|
31520
31944
|
}
|
|
31521
|
-
return this.fallbackBridgeSteps(_params, created.value,
|
|
31945
|
+
return this.fallbackBridgeSteps(_params, created.value, timeoutMs);
|
|
31522
31946
|
} catch (error) {
|
|
31523
31947
|
if (isBridgeOrchestrationError(error)) return { ok: false, error };
|
|
31524
31948
|
return {
|
|
@@ -31546,12 +31970,16 @@ var BridgeService = class {
|
|
|
31546
31970
|
);
|
|
31547
31971
|
}
|
|
31548
31972
|
/**
|
|
31549
|
-
* Client-side bridge completion (
|
|
31550
|
-
* relay it to the hub and wait for the settlement packet. Extracted verbatim from
|
|
31551
|
-
*
|
|
31552
|
-
* always relays — there is no hub-source short-circuit.
|
|
31973
|
+
* Client-side bridge completion (opt-out via `bridge.useBackendSubmitTx: false`): verify the broadcast
|
|
31974
|
+
* spoke-deposit tx, then relay it to the hub and wait for the settlement packet. Extracted verbatim from
|
|
31975
|
+
* `bridge()` so the backend submit-tx path ({@link submitTx}) can fall back to it on any non-success.
|
|
31976
|
+
* Bridge always relays — there is no hub-source short-circuit.
|
|
31977
|
+
*
|
|
31978
|
+
* Verification belongs to THIS path only: the backend runs its own, so verifying before handing over
|
|
31979
|
+
* would delay every backend success by the source chain's confirmation wait and could fail a bridge the
|
|
31980
|
+
* backend would have completed.
|
|
31553
31981
|
*/
|
|
31554
|
-
async fallbackBridgeSteps(_params, created,
|
|
31982
|
+
async fallbackBridgeSteps(_params, created, timeoutMs) {
|
|
31555
31983
|
const { params } = _params;
|
|
31556
31984
|
const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
|
|
31557
31985
|
const verifyTxHashResult = await this.spoke.verifyTxHash({
|
|
@@ -31566,13 +31994,13 @@ var BridgeService = class {
|
|
|
31566
31994
|
data: created.relayData,
|
|
31567
31995
|
chainKey: params.srcChainKey,
|
|
31568
31996
|
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
31569
|
-
//
|
|
31570
|
-
// or the
|
|
31571
|
-
//
|
|
31572
|
-
//
|
|
31573
|
-
//
|
|
31574
|
-
//
|
|
31575
|
-
timeout: Math.max(
|
|
31997
|
+
// The caller's full `timeout`, starting HERE — after verification, and whether this runs as the only
|
|
31998
|
+
// path or as the backend's fallback. Neither a stalled backend attempt nor a slow source-chain
|
|
31999
|
+
// confirmation (Stacks polls for up to its full 120s `maxTimeoutMs`) may shorten the relay wait. The
|
|
32000
|
+
// floor covers a sub-floor caller `timeout`: `relayTxAndWaitPacket` SUBMITS the tx to the relay
|
|
32001
|
+
// before `timeout` bounds anything, so a zero budget would strand an already-landed deposit
|
|
32002
|
+
// unrelayed. Re-relay is idempotent, so always spending the floor is safe.
|
|
32003
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS)
|
|
31576
32004
|
});
|
|
31577
32005
|
if (!packetResult.ok) {
|
|
31578
32006
|
return {
|
|
@@ -31591,7 +32019,7 @@ var BridgeService = class {
|
|
|
31591
32019
|
};
|
|
31592
32020
|
}
|
|
31593
32021
|
/**
|
|
31594
|
-
* Backend bridge path (
|
|
32022
|
+
* Backend bridge path (default via `bridge.useBackendSubmitTx`): hand the broadcast
|
|
31595
32023
|
* spoke-deposit tx to the bridge API (`POST /bridge/submit-tx`) with the FULL `relayData`
|
|
31596
32024
|
* envelope; the backend relays server-side. Polls `getSubmitTxStatus` until `executed`, then
|
|
31597
32025
|
* returns the same {@link TxHashPair} the client-side path returns (`result.dstIntentTxHash` →
|
|
@@ -31600,39 +32028,39 @@ var BridgeService = class {
|
|
|
31600
32028
|
* Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, terminal `failed` /
|
|
31601
32029
|
* abandoned, or poll timeout) so `bridge()` falls back to {@link fallbackBridgeSteps}. Falling back
|
|
31602
32030
|
* is safe: re-relaying an already-relayed bridge tx is idempotent — the relay dedups and returns the
|
|
31603
|
-
* existing `executed` packet.
|
|
31604
|
-
*
|
|
32031
|
+
* existing `executed` packet. It is also load-bearing rather than belt-and-braces: the backend keeps
|
|
32032
|
+
* processing after this attempt gives up, so the fallback's relay can race the backend's own.
|
|
32033
|
+
*
|
|
32034
|
+
* The attempt itself — POST, budget clamps, status poll — is {@link runBackendSubmitTx}, shared with
|
|
32035
|
+
* swaps. What is bridge-specific and lives here: the request body (the FULL `relayData` envelope), the
|
|
32036
|
+
* `executed` terminal status, the mapping to a {@link TxHashPair}, and the bridge error taxonomy.
|
|
32037
|
+
*
|
|
32038
|
+
* `attempt` bounds this attempt alone — the POST and every status request draw on it, and the
|
|
32039
|
+
* client-side fallback holds a separate fresh `timeout`.
|
|
31605
32040
|
*/
|
|
31606
|
-
async submitTx(_params, created,
|
|
32041
|
+
async submitTx(_params, created, attempt) {
|
|
31607
32042
|
const { params } = _params;
|
|
31608
32043
|
const srcChainKey = params.srcChainKey;
|
|
31609
32044
|
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
|
|
31610
32045
|
const { tx: spokeTxHash, relayData } = created;
|
|
31611
|
-
const submitTxFailed = (cause) => ({
|
|
31612
|
-
ok: false,
|
|
31613
|
-
error: executionFailed("bridge", cause, { ...baseCtx, action: "bridge" })
|
|
31614
|
-
});
|
|
31615
32046
|
try {
|
|
31616
|
-
const
|
|
31617
|
-
|
|
31618
|
-
|
|
31619
|
-
|
|
31620
|
-
|
|
31621
|
-
|
|
31622
|
-
|
|
31623
|
-
|
|
31624
|
-
|
|
31625
|
-
|
|
31626
|
-
|
|
32047
|
+
const outcome = await runBackendSubmitTx({
|
|
32048
|
+
attempt,
|
|
32049
|
+
api: this.backendApi.bridge,
|
|
32050
|
+
body: {
|
|
32051
|
+
txHash: spokeTxHash,
|
|
32052
|
+
srcChainKey,
|
|
32053
|
+
walletAddress: params.srcAddress,
|
|
32054
|
+
// Send the FULL { address, payload } envelope — bridge has no intent.creator for the backend
|
|
32055
|
+
// to rebuild the relay address, so dropping it would break split-tx-chain relay.
|
|
32056
|
+
relayData
|
|
32057
|
+
},
|
|
32058
|
+
statusQuery: { txHash: spokeTxHash, srcChainKey },
|
|
31627
32059
|
// Bridge terminal success is `executed` (hub-settled) — not the swaps `solved`.
|
|
31628
32060
|
terminalStatus: "executed",
|
|
31629
|
-
|
|
31630
|
-
onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0,
|
|
31631
|
-
// Bound each status request by the poll cutoff, never above the service default — so a stalled
|
|
31632
|
-
// request can neither eat the fallback's reserve nor consume the window in one attempt.
|
|
31633
|
-
requestTimeoutMs: this.backendApi.bridge.getTimeout()
|
|
32061
|
+
onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0
|
|
31634
32062
|
});
|
|
31635
|
-
return
|
|
32063
|
+
return outcome.ok ? { ok: true, value: outcome.value } : { ok: false, error: executionFailed("bridge", outcome.cause, { ...baseCtx, action: "bridge" }) };
|
|
31636
32064
|
} catch (error) {
|
|
31637
32065
|
return { ok: false, error: unknownFailed("bridge", error, { ...baseCtx, action: "bridge" }) };
|
|
31638
32066
|
}
|
|
@@ -37806,15 +38234,25 @@ var MoneyMarketService = class _MoneyMarketService {
|
|
|
37806
38234
|
config;
|
|
37807
38235
|
spoke;
|
|
37808
38236
|
// money market config (hoisted from config for ergonomics, mirrors SwapService)
|
|
37809
|
-
partnerFee;
|
|
37810
38237
|
relayerApiEndpoint;
|
|
37811
38238
|
// sub-service
|
|
37812
38239
|
data;
|
|
38240
|
+
/**
|
|
38241
|
+
* Effective money-market partner fee (`moneyMarket.partnerFee`, else the global `fee`). Read live
|
|
38242
|
+
* off `ConfigService` rather than snapshotted in the constructor, so it cannot diverge from
|
|
38243
|
+
* `config.moneyMarketPartnerFee` if the config object is ever replaced. Mirrors
|
|
38244
|
+
* {@link SwapService.partnerFee}.
|
|
38245
|
+
*
|
|
38246
|
+
* Money market has no per-action override: unlike swap / bridge / leverage-yield, every flow here
|
|
38247
|
+
* charges this configured fee.
|
|
38248
|
+
*/
|
|
38249
|
+
get partnerFee() {
|
|
38250
|
+
return this.config.moneyMarketPartnerFee;
|
|
38251
|
+
}
|
|
37813
38252
|
constructor({ config, hubProvider, spoke }) {
|
|
37814
38253
|
this.config = config;
|
|
37815
38254
|
this.hubProvider = hubProvider;
|
|
37816
38255
|
this.spoke = spoke;
|
|
37817
|
-
this.partnerFee = config.moneyMarketPartnerFee;
|
|
37818
38256
|
this.relayerApiEndpoint = config.relay.relayerApiEndpoint;
|
|
37819
38257
|
this.data = new MoneyMarketDataService({ hubProvider, config });
|
|
37820
38258
|
}
|
|
@@ -40127,6 +40565,68 @@ var LeverageYieldService = class {
|
|
|
40127
40565
|
return { ok: false, error: lookupFailed("leverageYield", "resolveDeadline", error, { srcChainKey }) };
|
|
40128
40566
|
}
|
|
40129
40567
|
}
|
|
40568
|
+
/**
|
|
40569
|
+
* Quotes a vault deposit or withdraw. Vault shares are solver-tradeable, so this is the
|
|
40570
|
+
* generic solver quote with one difference that matters: the fee deducted before quoting is
|
|
40571
|
+
* the effective **leverage-yield** fee, matching what {@link LeverageYieldService.createVaultIntent}
|
|
40572
|
+
* will charge. `sodax.swaps.getQuote` deducts the effective *swap* fee instead, so quoting a
|
|
40573
|
+
* vault flow through it makes the quote and the intent disagree whenever the two feature fees
|
|
40574
|
+
* differ. Quoting a vault flow through the swap service can be made to agree — pass the same fee
|
|
40575
|
+
* explicitly, using a zero fee (`{ address, percentage: 0 }`) where the effective leverage-yield
|
|
40576
|
+
* fee is `undefined`, since an explicit `undefined` there falls back to the swap fee — but this
|
|
40577
|
+
* method resolves it for you and is the canonical way to quote a vault flow.
|
|
40578
|
+
*
|
|
40579
|
+
* Pass the vault address as `token_dst` to quote a deposit, or as `token_src` to quote a
|
|
40580
|
+
* withdraw; subtract your slippage tolerance from `quoted_amount` to get `minOutputAmount`.
|
|
40581
|
+
* When overriding the fee per intent, pass the same `partnerFee` here and to whichever builder
|
|
40582
|
+
* you use ({@link LeverageYieldService.deposit}, {@link LeverageYieldService.withdraw}) or
|
|
40583
|
+
* directly to {@link LeverageYieldService.vaultSwap} — omitting it everywhere is equally safe,
|
|
40584
|
+
* since each side then resolves the same effective leverage-yield fee. Both directions are
|
|
40585
|
+
* charged, so this applies to withdrawals as much as deposits.
|
|
40586
|
+
*
|
|
40587
|
+
* @returns `SolverIntentQuoteResponse` on success. On failure `result.error` is either the
|
|
40588
|
+
* solver's own `SolverErrorResponse` (no path, insufficient liquidity, …) or a SodaxError
|
|
40589
|
+
* with `VALIDATION_FAILED` (bad `amount`, or a partner fee that leaves nothing to quote),
|
|
40590
|
+
* `LOOKUP_FAILED` (unsupported token — the solver payload could not be assembled) or
|
|
40591
|
+
* `UNKNOWN`. Discriminate with `isSodaxError(error)`.
|
|
40592
|
+
*/
|
|
40593
|
+
async getQuote(payload) {
|
|
40594
|
+
const { partnerFee = this.config.leverageYieldPartnerFee, ...request } = payload;
|
|
40595
|
+
const baseCtx = {
|
|
40596
|
+
method: "getQuote",
|
|
40597
|
+
tokenSrcChainKey: request.token_src_blockchain_id,
|
|
40598
|
+
tokenDstChainKey: request.token_dst_blockchain_id
|
|
40599
|
+
};
|
|
40600
|
+
try {
|
|
40601
|
+
leverageYieldInvariant(request.amount > 0n, "amount must be greater than 0", {
|
|
40602
|
+
...baseCtx,
|
|
40603
|
+
field: "amount"
|
|
40604
|
+
});
|
|
40605
|
+
if (isPartnerFeeAmount(partnerFee)) {
|
|
40606
|
+
leverageYieldInvariant(
|
|
40607
|
+
partnerFee.amount < request.amount,
|
|
40608
|
+
`partnerFee amount (${partnerFee.amount}) must be less than the quote amount (${request.amount})`,
|
|
40609
|
+
{ ...baseCtx, field: "partnerFee" }
|
|
40610
|
+
);
|
|
40611
|
+
} else if (isPartnerFeePercentage(partnerFee)) {
|
|
40612
|
+
leverageYieldInvariant(
|
|
40613
|
+
Number.isInteger(partnerFee.percentage) && partnerFee.percentage >= 0 && partnerFee.percentage <= Number(FEE_PERCENTAGE_SCALE),
|
|
40614
|
+
`partnerFee percentage must be a whole number of basis points between 0 and ${FEE_PERCENTAGE_SCALE} (got ${partnerFee.percentage})`,
|
|
40615
|
+
{ ...baseCtx, field: "partnerFee" }
|
|
40616
|
+
);
|
|
40617
|
+
}
|
|
40618
|
+
const netAmount = adjustAmountByFee(request.amount, partnerFee, request.quote_type);
|
|
40619
|
+
leverageYieldInvariant(netAmount > 0n, "amount net of the partner fee must be greater than 0", {
|
|
40620
|
+
...baseCtx,
|
|
40621
|
+
field: "partnerFee"
|
|
40622
|
+
});
|
|
40623
|
+
const adjustedPayload = { ...request, amount: netAmount };
|
|
40624
|
+
return await SolverApiService.getQuote(adjustedPayload, this.config.solver, this.config);
|
|
40625
|
+
} catch (error) {
|
|
40626
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
40627
|
+
return { ok: false, error: lookupFailed("leverageYield", "getQuote", error, baseCtx) };
|
|
40628
|
+
}
|
|
40629
|
+
}
|
|
40130
40630
|
/**
|
|
40131
40631
|
* Builds the {@link LeverageYieldSwapPayload} for a leverage-yield deposit (any token → lsoda*).
|
|
40132
40632
|
* The lsoda* output is delivered to the user's hub wallet on Sonic so a later
|
|
@@ -40134,9 +40634,8 @@ var LeverageYieldService = class {
|
|
|
40134
40634
|
* {@link LeverageYieldService.vaultSwap}: `vaultSwap({ ...payload, walletProvider })`.
|
|
40135
40635
|
* An optional `partnerFee` is forwarded on the payload as the per-intent fee override.
|
|
40136
40636
|
*
|
|
40137
|
-
* For `minOutputAmount`, quote via
|
|
40138
|
-
* destination token (`token_dst`)
|
|
40139
|
-
* quote applies; then subtract your slippage tolerance.
|
|
40637
|
+
* For `minOutputAmount`, quote via {@link LeverageYieldService.getQuote} with the vault
|
|
40638
|
+
* address as the destination token (`token_dst`), then subtract your slippage tolerance.
|
|
40140
40639
|
*/
|
|
40141
40640
|
async deposit(params) {
|
|
40142
40641
|
const baseCtx = { srcChainKey: params.srcChainKey, action: "deposit" };
|
|
@@ -40189,9 +40688,13 @@ var LeverageYieldService = class {
|
|
|
40189
40688
|
* a call shape uniform with {@link LeverageYieldService.deposit}; async because the default
|
|
40190
40689
|
* `deadline` is read from the hub block timestamp.
|
|
40191
40690
|
*
|
|
40192
|
-
*
|
|
40193
|
-
*
|
|
40194
|
-
*
|
|
40691
|
+
* An optional `partnerFee` is forwarded on the payload as the per-intent fee override; omit it
|
|
40692
|
+
* and the configured leverage-yield fee applies. Withdrawals **are** charged — the fee comes out
|
|
40693
|
+
* of `inputAmount`, which for a withdraw is the vault's own shares, so the receiver accrues
|
|
40694
|
+
* lsoda\* rather than the output token.
|
|
40695
|
+
*
|
|
40696
|
+
* For `minOutputAmount`, quote via {@link LeverageYieldService.getQuote} with the vault
|
|
40697
|
+
* address as the source token (`token_src`), then subtract your slippage tolerance.
|
|
40195
40698
|
*/
|
|
40196
40699
|
async withdraw(params) {
|
|
40197
40700
|
const baseCtx = { srcChainKey: params.srcChainKey, action: "withdraw" };
|
|
@@ -40225,7 +40728,10 @@ var LeverageYieldService = class {
|
|
|
40225
40728
|
solver: params.solver ?? ANY_SOLVER_ADDRESS,
|
|
40226
40729
|
data: "0x"
|
|
40227
40730
|
},
|
|
40228
|
-
hubWalletSwap: true
|
|
40731
|
+
hubWalletSwap: true,
|
|
40732
|
+
// Per-intent fee override — only included when the caller supplies one, so the
|
|
40733
|
+
// payload stays free of undefined-valued keys (mirrors `deposit`).
|
|
40734
|
+
...params.partnerFee !== void 0 && { partnerFee: params.partnerFee }
|
|
40229
40735
|
}
|
|
40230
40736
|
};
|
|
40231
40737
|
} catch (error) {
|
|
@@ -40258,7 +40764,7 @@ var LeverageYieldService = class {
|
|
|
40258
40764
|
* `UNKNOWN` (defensive fallback).
|
|
40259
40765
|
*/
|
|
40260
40766
|
async createVaultIntent(_params) {
|
|
40261
|
-
const { params, skipSimulation, hubWalletSwap, partnerFee = this.config.
|
|
40767
|
+
const { params, skipSimulation, hubWalletSwap, partnerFee = this.config.leverageYieldPartnerFee } = _params;
|
|
40262
40768
|
const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
|
|
40263
40769
|
try {
|
|
40264
40770
|
leverageYieldInvariant(
|
|
@@ -40603,15 +41109,22 @@ var LeverageYieldService = class {
|
|
|
40603
41109
|
spender: params.vault
|
|
40604
41110
|
};
|
|
40605
41111
|
if (params.raw) {
|
|
40606
|
-
const
|
|
40607
|
-
return { ok: true, value:
|
|
40608
|
-
}
|
|
40609
|
-
const
|
|
40610
|
-
|
|
41112
|
+
const tx = await Erc20Service.approve({ ...baseApprove, raw: true });
|
|
41113
|
+
return { ok: true, value: tx };
|
|
41114
|
+
}
|
|
41115
|
+
const result = await this.spoke.approve({
|
|
41116
|
+
srcChainKey: this.hubProvider.chainConfig.chain.key,
|
|
41117
|
+
token: baseApprove.token,
|
|
41118
|
+
amount: baseApprove.amount,
|
|
41119
|
+
owner: from,
|
|
41120
|
+
spender: baseApprove.spender,
|
|
40611
41121
|
raw: false,
|
|
40612
41122
|
walletProvider: params.walletProvider
|
|
40613
41123
|
});
|
|
40614
|
-
|
|
41124
|
+
if (!result.ok) {
|
|
41125
|
+
return { ok: false, error: approveFailed("leverageYield", result.error, baseCtx) };
|
|
41126
|
+
}
|
|
41127
|
+
return { ok: true, value: result.value };
|
|
40615
41128
|
} catch (error) {
|
|
40616
41129
|
if (isLeverageYieldApproveError(error)) return { ok: false, error };
|
|
40617
41130
|
return { ok: false, error: approveFailed("leverageYield", error, baseCtx) };
|
|
@@ -41481,8 +41994,6 @@ var Sodax = class {
|
|
|
41481
41994
|
const analytics = resolveAnalytics(options?.analytics);
|
|
41482
41995
|
const fee = options?.fee;
|
|
41483
41996
|
const radfiSigner = options?.radfi?.signRequest;
|
|
41484
|
-
const useBackendSubmitTx = options?.swapsOptions?.useBackendSubmitTx ?? false;
|
|
41485
|
-
const bridgeUseBackendSubmitTx = options?.bridgeOptions?.useBackendSubmitTx ?? false;
|
|
41486
41997
|
this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
|
|
41487
41998
|
this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
|
|
41488
41999
|
this.api = this.backendApi;
|
|
@@ -41501,8 +42012,7 @@ var Sodax = class {
|
|
|
41501
42012
|
config: this.config,
|
|
41502
42013
|
hubProvider: this.hubProvider,
|
|
41503
42014
|
spoke: this.spoke,
|
|
41504
|
-
backendApi: this.backendApi
|
|
41505
|
-
useBackendSubmitTx
|
|
42015
|
+
backendApi: this.backendApi
|
|
41506
42016
|
});
|
|
41507
42017
|
this.moneyMarket = new MoneyMarketService({
|
|
41508
42018
|
config: this.config,
|
|
@@ -41523,8 +42033,7 @@ var Sodax = class {
|
|
|
41523
42033
|
hubProvider: this.hubProvider,
|
|
41524
42034
|
config: this.config,
|
|
41525
42035
|
spoke: this.spoke,
|
|
41526
|
-
backendApi: this.backendApi
|
|
41527
|
-
useBackendSubmitTx: bridgeUseBackendSubmitTx
|
|
42036
|
+
backendApi: this.backendApi
|
|
41528
42037
|
});
|
|
41529
42038
|
this.staking = new StakingService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
|
|
41530
42039
|
this.partners = new PartnerService({
|