@sodax/sdk 2.2.0-rc.5 → 2.2.0-rc.6
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/README.md +11 -5
- package/dist/index.cjs +1700 -357
- package/dist/index.d.cts +1041 -36
- package/dist/index.d.ts +1041 -36
- package/dist/index.mjs +1695 -367
- package/package.json +5 -4
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getAbiItem, parseAbi, defineChain, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, stringToBytes, fromHex, encodePacked, decodeAbiParameters, parseEventLogs, isHex, maxUint160, maxUint48, fallback } from 'viem';
|
|
1
|
+
import { getAbiItem, parseAbi, defineChain, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, stringToBytes, fromHex, encodePacked, decodeAbiParameters, parseEventLogs, isHex, maxUint160, maxUint48, zeroAddress, isAddressEqual, formatUnits, fallback } from 'viem';
|
|
2
2
|
import { initEccLib, address, networks, Transaction, Psbt, payments, opcodes, script } from 'bitcoinjs-lib';
|
|
3
3
|
import { bcs } from '@mysten/sui/bcs';
|
|
4
4
|
import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram, TransactionMessage, TransactionInstruction } from '@solana/web3.js';
|
|
@@ -18,8 +18,10 @@ import { ChainGrpcWasmApi, IndexerGrpcAccountPortfolioApi, TxGrpcApi, toBase64,
|
|
|
18
18
|
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
|
|
19
19
|
import { getNetworkEndpoints, Network } from '@injectivelabs/networks';
|
|
20
20
|
import * as v from 'valibot';
|
|
21
|
-
import { SwapsApi, SwapsApiError, rawTxSchemaForChainKey
|
|
21
|
+
import { SwapsApi, SwapsApiError, rawTxSchemaForChainKey, makeQuoteResponseSchema, DeadlineResponseSchema, AllowanceCheckResponseSchema, makeApproveResponseSchema, makeCreateIntentResponseSchema, SubmitIntentResponseSchema, StatusResponseSchema, makeCancelIntentResponseSchema, IntentHashResponseSchema, IntentPacketResponseSchema, RelayExtraDataResponseSchema, IntentStateSchema, IntentResponseSchema as IntentResponseSchema$1, GasEstimateResponseSchema, FeeResponseSchema, SubmitTxResponseSchema, SubmitTxStatusResponseSchema } from '@sodax/swaps-api';
|
|
22
22
|
export { SwapsApiError } from '@sodax/swaps-api';
|
|
23
|
+
import { BridgeApi, BridgeApiError } from '@sodax/bridge-api';
|
|
24
|
+
export { BridgeApiError } from '@sodax/bridge-api';
|
|
23
25
|
import BigNumber5, { BigNumber } from 'bignumber.js';
|
|
24
26
|
import { Token, Price } from '@pancakeswap/swap-sdk-core';
|
|
25
27
|
import { sqrtRatioX96ToPrice, PositionMath, tickToPrice, TickMath, maxLiquidityForAmount0Precise, maxLiquidityForAmount1, maxLiquidityForAmounts } from '@pancakeswap/v3-sdk';
|
|
@@ -94,8 +96,8 @@ function serializeCause(cause, depth) {
|
|
|
94
96
|
}
|
|
95
97
|
function sanitizeContext(value, depth) {
|
|
96
98
|
const out = {};
|
|
97
|
-
for (const [key,
|
|
98
|
-
out[key] = sanitizeValue(
|
|
99
|
+
for (const [key, v10] of Object.entries(value)) {
|
|
100
|
+
out[key] = sanitizeValue(v10, depth + 1);
|
|
99
101
|
}
|
|
100
102
|
return out;
|
|
101
103
|
}
|
|
@@ -106,13 +108,13 @@ function sanitizeValue(value, depth) {
|
|
|
106
108
|
if (t === "bigint") return value.toString();
|
|
107
109
|
if (t === "string" || t === "number" || t === "boolean") return value;
|
|
108
110
|
if (t === "function" || t === "symbol") return safeString(value);
|
|
109
|
-
if (Array.isArray(value)) return value.map((
|
|
111
|
+
if (Array.isArray(value)) return value.map((v10) => sanitizeValue(v10, depth + 1));
|
|
110
112
|
if (value instanceof Date) return value.toISOString();
|
|
111
113
|
if (value instanceof Map) {
|
|
112
|
-
return Array.from(value.entries()).map(([k,
|
|
114
|
+
return Array.from(value.entries()).map(([k, v10]) => [sanitizeValue(k, depth + 1), sanitizeValue(v10, depth + 1)]);
|
|
113
115
|
}
|
|
114
116
|
if (value instanceof Set) {
|
|
115
|
-
return Array.from(value.values()).map((
|
|
117
|
+
return Array.from(value.values()).map((v10) => sanitizeValue(v10, depth + 1));
|
|
116
118
|
}
|
|
117
119
|
if (value instanceof Error) return { name: value.name, message: value.message };
|
|
118
120
|
if (t === "object") {
|
|
@@ -124,9 +126,9 @@ function sanitizeValue(value, depth) {
|
|
|
124
126
|
}
|
|
125
127
|
return safeString(value);
|
|
126
128
|
}
|
|
127
|
-
function safeString(
|
|
129
|
+
function safeString(v10) {
|
|
128
130
|
try {
|
|
129
|
-
return String(
|
|
131
|
+
return String(v10);
|
|
130
132
|
} catch {
|
|
131
133
|
return "[unserializable]";
|
|
132
134
|
}
|
|
@@ -1524,6 +1526,15 @@ var baseSupportedTokens = {
|
|
|
1524
1526
|
chainKey: ChainKeys.BASE_MAINNET,
|
|
1525
1527
|
hubAsset: "0x348e086ab6f424dfc575a325c28624ed23973173",
|
|
1526
1528
|
vault: "0x348e086ab6f424dfc575a325c28624ed23973173"
|
|
1529
|
+
},
|
|
1530
|
+
sUSDS: {
|
|
1531
|
+
symbol: "sUSDS",
|
|
1532
|
+
name: "staked USDS",
|
|
1533
|
+
decimals: 18,
|
|
1534
|
+
address: "0x5875eEE11Cf8398102FdAd704C9E96607675467a",
|
|
1535
|
+
chainKey: ChainKeys.BASE_MAINNET,
|
|
1536
|
+
hubAsset: "0x807cC73f69F1aCCC50511a0390A8544cEA71baA9",
|
|
1537
|
+
vault: SodaTokens.sodaSUSDS.address
|
|
1527
1538
|
}
|
|
1528
1539
|
};
|
|
1529
1540
|
var optimismSupportedTokens = {
|
|
@@ -1607,6 +1618,15 @@ var optimismSupportedTokens = {
|
|
|
1607
1618
|
chainKey: ChainKeys.OPTIMISM_MAINNET,
|
|
1608
1619
|
hubAsset: "0xd08375176410febee9cf4591532455a4cdfe4463",
|
|
1609
1620
|
vault: "0xd08375176410febee9cf4591532455a4cdfe4463"
|
|
1621
|
+
},
|
|
1622
|
+
sUSDS: {
|
|
1623
|
+
symbol: "sUSDS",
|
|
1624
|
+
name: "staked USDS",
|
|
1625
|
+
decimals: 18,
|
|
1626
|
+
address: "0xb5B2dc7fd34C249F4be7fB1fCea07950784229e0",
|
|
1627
|
+
chainKey: ChainKeys.OPTIMISM_MAINNET,
|
|
1628
|
+
hubAsset: "0xb9a9cb8A61D30a8F6b7E24491ab83f43E817b0E2",
|
|
1629
|
+
vault: SodaTokens.sodaSUSDS.address
|
|
1610
1630
|
}
|
|
1611
1631
|
};
|
|
1612
1632
|
var bscSupportedTokens = {
|
|
@@ -2961,6 +2981,15 @@ var ethereumSupportedTokens = {
|
|
|
2961
2981
|
chainKey: ChainKeys.ETHEREUM_MAINNET,
|
|
2962
2982
|
hubAsset: "0x40bea4f921355a749f460760ba6f8edd78888164",
|
|
2963
2983
|
vault: "0x40bea4f921355a749f460760ba6f8edd78888164"
|
|
2984
|
+
},
|
|
2985
|
+
sUSDS: {
|
|
2986
|
+
symbol: "sUSDS",
|
|
2987
|
+
name: "staked USDS",
|
|
2988
|
+
decimals: 18,
|
|
2989
|
+
address: "0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD",
|
|
2990
|
+
chainKey: ChainKeys.ETHEREUM_MAINNET,
|
|
2991
|
+
hubAsset: "0x1Bb5128A4837A78cb60bc52cc19079eD3F00A624",
|
|
2992
|
+
vault: SodaTokens.sodaSUSDS.address
|
|
2964
2993
|
}
|
|
2965
2994
|
};
|
|
2966
2995
|
var kaiaSupportedTokens = {
|
|
@@ -4569,7 +4598,8 @@ var moneyMarketSupportedTokens = {
|
|
|
4569
4598
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.cbBTC,
|
|
4570
4599
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.SODA,
|
|
4571
4600
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDT,
|
|
4572
|
-
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDS
|
|
4601
|
+
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDS,
|
|
4602
|
+
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.sUSDS
|
|
4573
4603
|
],
|
|
4574
4604
|
[ChainKeys.OPTIMISM_MAINNET]: [
|
|
4575
4605
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.ETH,
|
|
@@ -4578,7 +4608,8 @@ var moneyMarketSupportedTokens = {
|
|
|
4578
4608
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.wstETH,
|
|
4579
4609
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.weETH,
|
|
4580
4610
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDT,
|
|
4581
|
-
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.SODA
|
|
4611
|
+
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.SODA,
|
|
4612
|
+
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.sUSDS
|
|
4582
4613
|
],
|
|
4583
4614
|
[ChainKeys.POLYGON_MAINNET]: [
|
|
4584
4615
|
spokeChainConfig[ChainKeys.POLYGON_MAINNET].supportedTokens.POL,
|
|
@@ -4700,7 +4731,8 @@ var moneyMarketSupportedTokens = {
|
|
|
4700
4731
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.WBTC,
|
|
4701
4732
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.WBTC_LEGACY,
|
|
4702
4733
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.LL,
|
|
4703
|
-
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDS
|
|
4734
|
+
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDS,
|
|
4735
|
+
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.sUSDS
|
|
4704
4736
|
],
|
|
4705
4737
|
[ChainKeys.REDBELLY_MAINNET]: [
|
|
4706
4738
|
spokeChainConfig[ChainKeys.REDBELLY_MAINNET].supportedTokens.bnUSD,
|
|
@@ -4933,9 +4965,10 @@ var swapSupportedTokens = {
|
|
|
4933
4965
|
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USDT,
|
|
4934
4966
|
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.wS,
|
|
4935
4967
|
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.SODA,
|
|
4936
|
-
|
|
4937
|
-
// Swap membership is per-vault, not every SodaTokens entry:
|
|
4938
|
-
//
|
|
4968
|
+
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USSD,
|
|
4969
|
+
// Swap membership is per-vault, not every SodaTokens entry: sodaUSDS is the one wrapper the
|
|
4970
|
+
// production solver cannot route — a `/quote` against it returns `No path was found`, where
|
|
4971
|
+
// USSD, sodaUSSD and sodaSUSDS all return real prices — so it stays out until a path exists.
|
|
4939
4972
|
SodaTokens.sodaBNB,
|
|
4940
4973
|
SodaTokens.sodaAVAX,
|
|
4941
4974
|
SodaTokens.sodaETH,
|
|
@@ -4960,8 +4993,10 @@ var swapSupportedTokens = {
|
|
|
4960
4993
|
SodaTokens.sodaNEAR,
|
|
4961
4994
|
SodaTokens.sodaKAIA,
|
|
4962
4995
|
SodaTokens.sodaSTX,
|
|
4996
|
+
SodaTokens.sodaSUSDS,
|
|
4963
4997
|
SodaTokens.sodaHBAR,
|
|
4964
4998
|
SodaTokens.sodaJITOSOL,
|
|
4999
|
+
SodaTokens.sodaUSSD,
|
|
4965
5000
|
...Object.values(LsodaTokens),
|
|
4966
5001
|
// Robinhood tokenized equities — swap-only, deliberately absent from the money market.
|
|
4967
5002
|
SodaTokens.SPCX,
|
|
@@ -4995,6 +5030,7 @@ var swapSupportedTokens = {
|
|
|
4995
5030
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.tBTC,
|
|
4996
5031
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.USDC,
|
|
4997
5032
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.USDT,
|
|
5033
|
+
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.sUSDS,
|
|
4998
5034
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.ARB,
|
|
4999
5035
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.AAVE,
|
|
5000
5036
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.LINK,
|
|
@@ -5009,6 +5045,7 @@ var swapSupportedTokens = {
|
|
|
5009
5045
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.ETH,
|
|
5010
5046
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.weETH,
|
|
5011
5047
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDC,
|
|
5048
|
+
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.sUSDS,
|
|
5012
5049
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.wstETH,
|
|
5013
5050
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.cbBTC,
|
|
5014
5051
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.VIRTUAL,
|
|
@@ -5019,6 +5056,7 @@ var swapSupportedTokens = {
|
|
|
5019
5056
|
[ChainKeys.OPTIMISM_MAINNET]: [
|
|
5020
5057
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.ETH,
|
|
5021
5058
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDC,
|
|
5059
|
+
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.sUSDS,
|
|
5022
5060
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.wstETH,
|
|
5023
5061
|
// spokeChainConfig[OPTIMISM_MAINNET_CHAIN_ID].supportedTokens.weETH, // NOTE: Not Implemented
|
|
5024
5062
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDT,
|
|
@@ -5186,6 +5224,7 @@ var swapSupportedTokens = {
|
|
|
5186
5224
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.ETH,
|
|
5187
5225
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.bnUSD,
|
|
5188
5226
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDC,
|
|
5227
|
+
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.sUSDS,
|
|
5189
5228
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDT,
|
|
5190
5229
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.SODA,
|
|
5191
5230
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.LL,
|
|
@@ -5292,7 +5331,7 @@ var swapSupportedTokens = {
|
|
|
5292
5331
|
]
|
|
5293
5332
|
};
|
|
5294
5333
|
var stagingSwapSupportedTokens = {
|
|
5295
|
-
[ChainKeys.SONIC_MAINNET]: [
|
|
5334
|
+
[ChainKeys.SONIC_MAINNET]: [],
|
|
5296
5335
|
[ChainKeys.AVALANCHE_MAINNET]: [],
|
|
5297
5336
|
[ChainKeys.ARBITRUM_MAINNET]: [],
|
|
5298
5337
|
[ChainKeys.BASE_MAINNET]: [
|
|
@@ -5399,7 +5438,8 @@ var leverageYieldVaults = [
|
|
|
5399
5438
|
}
|
|
5400
5439
|
];
|
|
5401
5440
|
var leverageYieldConfig = {
|
|
5402
|
-
vaults: leverageYieldVaults
|
|
5441
|
+
vaults: leverageYieldVaults,
|
|
5442
|
+
positionFactory: "0xF8fB7F200B6545295e1729Cf254482d7c116031C"
|
|
5403
5443
|
};
|
|
5404
5444
|
|
|
5405
5445
|
// ../types/dist/sodax-config/sodax-config.js
|
|
@@ -5632,7 +5672,45 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
5632
5672
|
}
|
|
5633
5673
|
|
|
5634
5674
|
// ../types/dist/index.js
|
|
5635
|
-
var CONFIG_VERSION =
|
|
5675
|
+
var CONFIG_VERSION = 2020006;
|
|
5676
|
+
var RC_STABLE = 99;
|
|
5677
|
+
var MIN_CONFIG_VERSION = 1e6;
|
|
5678
|
+
var MAX_CONFIG_VERSION = 99999999;
|
|
5679
|
+
var VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-rc\.(0|[1-9]\d*))?$/;
|
|
5680
|
+
function configVersionFor(version) {
|
|
5681
|
+
const match = typeof version === "string" ? version.match(VERSION_PATTERN) : null;
|
|
5682
|
+
if (!match)
|
|
5683
|
+
return null;
|
|
5684
|
+
const major = Number(match[1]);
|
|
5685
|
+
const minor = Number(match[2]);
|
|
5686
|
+
const patch = Number(match[3]);
|
|
5687
|
+
const rc = match[4] === void 0 ? null : Number(match[4]);
|
|
5688
|
+
if (major < 1 || major > 99 || minor > 99 || patch > 99)
|
|
5689
|
+
return null;
|
|
5690
|
+
if (rc !== null && rc > 98)
|
|
5691
|
+
return null;
|
|
5692
|
+
return major * 1e6 + minor * 1e4 + patch * 100 + (rc === null ? RC_STABLE : rc);
|
|
5693
|
+
}
|
|
5694
|
+
var unpack = (value) => {
|
|
5695
|
+
const slot = value % 100;
|
|
5696
|
+
return {
|
|
5697
|
+
major: Math.floor(value / 1e6),
|
|
5698
|
+
minor: Math.floor(value / 1e4) % 100,
|
|
5699
|
+
patch: Math.floor(value / 100) % 100,
|
|
5700
|
+
rc: slot === RC_STABLE ? null : slot
|
|
5701
|
+
};
|
|
5702
|
+
};
|
|
5703
|
+
var render = ({ major, minor, patch, rc }) => `${major}.${minor}.${patch}${rc === null ? "" : `-rc.${rc}`}`;
|
|
5704
|
+
function parseConfigVersion(value) {
|
|
5705
|
+
if (!Number.isInteger(value) || value < MIN_CONFIG_VERSION || value > MAX_CONFIG_VERSION)
|
|
5706
|
+
return null;
|
|
5707
|
+
return unpack(value);
|
|
5708
|
+
}
|
|
5709
|
+
function formatConfigVersion(value) {
|
|
5710
|
+
const parsed = parseConfigVersion(value);
|
|
5711
|
+
return parsed === null ? null : render(parsed);
|
|
5712
|
+
}
|
|
5713
|
+
var SDK_VERSION = render(unpack(CONFIG_VERSION));
|
|
5636
5714
|
|
|
5637
5715
|
// src/shared/utils/resolveTimeoutMs.ts
|
|
5638
5716
|
function resolveTimeoutMs(timeout, fallbackMs) {
|
|
@@ -15567,11 +15645,15 @@ var ConfigService = class {
|
|
|
15567
15645
|
isMoneyMarketSupportedToken(chainId, token) {
|
|
15568
15646
|
return this.sodax.moneyMarket.supportedTokens[chainId].some((t) => t.address.toLowerCase() === token.toLowerCase());
|
|
15569
15647
|
}
|
|
15648
|
+
/**
|
|
15649
|
+
* Is `asset` one of the money-market reserve assets?
|
|
15650
|
+
*
|
|
15651
|
+
* The reserve set is built from `moneyMarketHubVaults`, so its members are hub **vault**
|
|
15652
|
+
* addresses. Query it with an `XToken.vault`; an `XToken.hubAsset` only matches for the Sonic
|
|
15653
|
+
* vault shares themselves, where `hubAsset === vault`.
|
|
15654
|
+
*/
|
|
15570
15655
|
isMoneyMarketReserveAsset(asset) {
|
|
15571
|
-
return this.
|
|
15572
|
-
}
|
|
15573
|
-
isMoneyMarketReserveHubAsset(hubAsset) {
|
|
15574
|
-
return this.moneyMarketReserveAssetsSet.has(hubAsset.toLowerCase());
|
|
15656
|
+
return this.moneyMarketReserveAssetsSet.has(asset.toLowerCase());
|
|
15575
15657
|
}
|
|
15576
15658
|
loadSodaxConfigDataStructures(sodaxConfig2) {
|
|
15577
15659
|
this.hubAssetToXTokenMap = new Map(
|
|
@@ -15720,7 +15802,7 @@ function mergeSodaxConfig(base2, override) {
|
|
|
15720
15802
|
}
|
|
15721
15803
|
function encodeContractCalls(calls) {
|
|
15722
15804
|
return encodeAbiParameters(parseAbiParameters("(address,uint256,bytes)[]"), [
|
|
15723
|
-
calls.map((
|
|
15805
|
+
calls.map((v10) => [v10.address, v10.value, v10.data])
|
|
15724
15806
|
]);
|
|
15725
15807
|
}
|
|
15726
15808
|
async function waitForTransactionReceipt(hash, provider) {
|
|
@@ -17983,7 +18065,7 @@ function hexToBytes2(hex) {
|
|
|
17983
18065
|
const al = hl / 2;
|
|
17984
18066
|
if (hl % 2)
|
|
17985
18067
|
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
17986
|
-
const
|
|
18068
|
+
const array3 = new Uint8Array(al);
|
|
17987
18069
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
17988
18070
|
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
17989
18071
|
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
@@ -17991,9 +18073,9 @@ function hexToBytes2(hex) {
|
|
|
17991
18073
|
const char = hex[hi] + hex[hi + 1];
|
|
17992
18074
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
17993
18075
|
}
|
|
17994
|
-
|
|
18076
|
+
array3[ai] = n1 * 16 + n2;
|
|
17995
18077
|
}
|
|
17996
|
-
return
|
|
18078
|
+
return array3;
|
|
17997
18079
|
}
|
|
17998
18080
|
function concatBytes(...arrays) {
|
|
17999
18081
|
let sum = 0;
|
|
@@ -18623,22 +18705,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
18623
18705
|
const byte0 = Uint8Array.of(0);
|
|
18624
18706
|
const byte1 = Uint8Array.of(1);
|
|
18625
18707
|
const _maxDrbgIters = 1e3;
|
|
18626
|
-
let
|
|
18708
|
+
let v10 = u8n(hashLen);
|
|
18627
18709
|
let k = u8n(hashLen);
|
|
18628
18710
|
let i = 0;
|
|
18629
18711
|
const reset = () => {
|
|
18630
|
-
|
|
18712
|
+
v10.fill(1);
|
|
18631
18713
|
k.fill(0);
|
|
18632
18714
|
i = 0;
|
|
18633
18715
|
};
|
|
18634
|
-
const h = (...msgs) => hmacFn(k, concatBytes(
|
|
18716
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v10, ...msgs));
|
|
18635
18717
|
const reseed = (seed = NULL) => {
|
|
18636
18718
|
k = h(byte0, seed);
|
|
18637
|
-
|
|
18719
|
+
v10 = h();
|
|
18638
18720
|
if (seed.length === 0)
|
|
18639
18721
|
return;
|
|
18640
18722
|
k = h(byte1, seed);
|
|
18641
|
-
|
|
18723
|
+
v10 = h();
|
|
18642
18724
|
};
|
|
18643
18725
|
const gen = () => {
|
|
18644
18726
|
if (i++ >= _maxDrbgIters)
|
|
@@ -18646,10 +18728,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
18646
18728
|
let len = 0;
|
|
18647
18729
|
const out = [];
|
|
18648
18730
|
while (len < qByteLen) {
|
|
18649
|
-
|
|
18650
|
-
const sl =
|
|
18731
|
+
v10 = h();
|
|
18732
|
+
const sl = v10.slice();
|
|
18651
18733
|
out.push(sl);
|
|
18652
|
-
len +=
|
|
18734
|
+
len += v10.length;
|
|
18653
18735
|
}
|
|
18654
18736
|
return concatBytes(...out);
|
|
18655
18737
|
};
|
|
@@ -18664,18 +18746,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
18664
18746
|
};
|
|
18665
18747
|
return genUntil;
|
|
18666
18748
|
}
|
|
18667
|
-
function validateObject(
|
|
18668
|
-
if (!
|
|
18749
|
+
function validateObject(object4, fields = {}, optFields = {}) {
|
|
18750
|
+
if (!object4 || typeof object4 !== "object")
|
|
18669
18751
|
throw new Error("expected valid options object");
|
|
18670
18752
|
function checkField(fieldName, expectedType, isOpt) {
|
|
18671
|
-
const val =
|
|
18753
|
+
const val = object4[fieldName];
|
|
18672
18754
|
if (isOpt && val === void 0)
|
|
18673
18755
|
return;
|
|
18674
18756
|
const current = typeof val;
|
|
18675
18757
|
if (current !== expectedType || val === null)
|
|
18676
18758
|
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
18677
18759
|
}
|
|
18678
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k,
|
|
18760
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v10]) => checkField(k, v10, isOpt));
|
|
18679
18761
|
iter(fields, false);
|
|
18680
18762
|
iter(optFields, true);
|
|
18681
18763
|
}
|
|
@@ -18714,12 +18796,12 @@ function pow2(x, power, modulo) {
|
|
|
18714
18796
|
}
|
|
18715
18797
|
return res;
|
|
18716
18798
|
}
|
|
18717
|
-
function invert(
|
|
18718
|
-
if (
|
|
18799
|
+
function invert(number4, modulo) {
|
|
18800
|
+
if (number4 === _0n2)
|
|
18719
18801
|
throw new Error("invert: expected non-zero number");
|
|
18720
18802
|
if (modulo <= _0n2)
|
|
18721
18803
|
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
18722
|
-
let a = mod(
|
|
18804
|
+
let a = mod(number4, modulo);
|
|
18723
18805
|
let b = modulo;
|
|
18724
18806
|
let x = _0n2, u = _1n2;
|
|
18725
18807
|
while (a !== _0n2) {
|
|
@@ -18746,9 +18828,9 @@ function sqrt3mod4(Fp, n) {
|
|
|
18746
18828
|
function sqrt5mod8(Fp, n) {
|
|
18747
18829
|
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
18748
18830
|
const n2 = Fp.mul(n, _2n);
|
|
18749
|
-
const
|
|
18750
|
-
const nv = Fp.mul(n,
|
|
18751
|
-
const i = Fp.mul(Fp.mul(nv, _2n),
|
|
18831
|
+
const v10 = Fp.pow(n2, p5div8);
|
|
18832
|
+
const nv = Fp.mul(n, v10);
|
|
18833
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v10);
|
|
18752
18834
|
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
18753
18835
|
assertIsSquare(Fp, root, n);
|
|
18754
18836
|
return root;
|
|
@@ -19223,27 +19305,27 @@ var wNAF = class {
|
|
|
19223
19305
|
assert0(n);
|
|
19224
19306
|
return acc;
|
|
19225
19307
|
}
|
|
19226
|
-
getPrecomputes(W, point,
|
|
19308
|
+
getPrecomputes(W, point, transform) {
|
|
19227
19309
|
let comp = pointPrecomputes.get(point);
|
|
19228
19310
|
if (!comp) {
|
|
19229
19311
|
comp = this.precomputeWindow(point, W);
|
|
19230
19312
|
if (W !== 1) {
|
|
19231
|
-
if (typeof
|
|
19232
|
-
comp =
|
|
19313
|
+
if (typeof transform === "function")
|
|
19314
|
+
comp = transform(comp);
|
|
19233
19315
|
pointPrecomputes.set(point, comp);
|
|
19234
19316
|
}
|
|
19235
19317
|
}
|
|
19236
19318
|
return comp;
|
|
19237
19319
|
}
|
|
19238
|
-
cached(point, scalar,
|
|
19320
|
+
cached(point, scalar, transform) {
|
|
19239
19321
|
const W = getW(point);
|
|
19240
|
-
return this.wNAF(W, this.getPrecomputes(W, point,
|
|
19322
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
19241
19323
|
}
|
|
19242
|
-
unsafe(point, scalar,
|
|
19324
|
+
unsafe(point, scalar, transform, prev) {
|
|
19243
19325
|
const W = getW(point);
|
|
19244
19326
|
if (W === 1)
|
|
19245
19327
|
return this._unsafeLadder(point, scalar, prev);
|
|
19246
|
-
return this.wNAFUnsafe(W, this.getPrecomputes(W, point,
|
|
19328
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
19247
19329
|
}
|
|
19248
19330
|
// We calculate precomputes for elliptic curve point multiplication
|
|
19249
19331
|
// using windowed method. This specifies window size and
|
|
@@ -19330,9 +19412,9 @@ function edwards(params, extraOpts = {}) {
|
|
|
19330
19412
|
validateObject(extraOpts, {}, { uvRatio: "function" });
|
|
19331
19413
|
const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
|
|
19332
19414
|
const modP = (n) => Fp.create(n);
|
|
19333
|
-
const uvRatio2 = extraOpts.uvRatio || ((u,
|
|
19415
|
+
const uvRatio2 = extraOpts.uvRatio || ((u, v10) => {
|
|
19334
19416
|
try {
|
|
19335
|
-
return { isValid: true, value: Fp.sqrt(Fp.div(u,
|
|
19417
|
+
return { isValid: true, value: Fp.sqrt(Fp.div(u, v10)) };
|
|
19336
19418
|
} catch (e) {
|
|
19337
19419
|
return { isValid: false, value: _0n4 };
|
|
19338
19420
|
}
|
|
@@ -19428,8 +19510,8 @@ function edwards(params, extraOpts = {}) {
|
|
|
19428
19510
|
aInRange("point.y", y, _0n4, max);
|
|
19429
19511
|
const y2 = modP(y * y);
|
|
19430
19512
|
const u = modP(y2 - _1n4);
|
|
19431
|
-
const
|
|
19432
|
-
let { isValid, value: x } = uvRatio2(u,
|
|
19513
|
+
const v10 = modP(d * y2 - a);
|
|
19514
|
+
let { isValid, value: x } = uvRatio2(u, v10);
|
|
19433
19515
|
if (!isValid)
|
|
19434
19516
|
throw new Error("bad point: invalid y coordinate");
|
|
19435
19517
|
const isXOdd = (x & _1n4) === _1n4;
|
|
@@ -19769,13 +19851,13 @@ function adjustScalarBytes(bytes) {
|
|
|
19769
19851
|
return bytes;
|
|
19770
19852
|
}
|
|
19771
19853
|
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
|
|
19772
|
-
function uvRatio(u,
|
|
19854
|
+
function uvRatio(u, v10) {
|
|
19773
19855
|
const P = ed25519_CURVE_p;
|
|
19774
|
-
const v32 = mod(
|
|
19775
|
-
const v72 = mod(v32 * v32 *
|
|
19856
|
+
const v32 = mod(v10 * v10 * v10, P);
|
|
19857
|
+
const v72 = mod(v32 * v32 * v10, P);
|
|
19776
19858
|
const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
|
|
19777
19859
|
let x = mod(u * v32 * pow, P);
|
|
19778
|
-
const vx2 = mod(
|
|
19860
|
+
const vx2 = mod(v10 * x * x, P);
|
|
19779
19861
|
const root1 = x;
|
|
19780
19862
|
const root2 = mod(x * ED25519_SQRT_M1, P);
|
|
19781
19863
|
const useRoot1 = vx2 === u;
|
|
@@ -20106,7 +20188,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
|
|
|
20106
20188
|
return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
|
|
20107
20189
|
}
|
|
20108
20190
|
function findSeatPriceForProtocolBefore49(validators, numSeats) {
|
|
20109
|
-
const stakes = validators.map((
|
|
20191
|
+
const stakes = validators.map((v10) => BigInt(v10.stake)).sort(sortBigIntAsc);
|
|
20110
20192
|
const num = BigInt(numSeats);
|
|
20111
20193
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
20112
20194
|
if (stakesSum < num) {
|
|
@@ -20135,7 +20217,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
|
|
|
20135
20217
|
if (minimumStakeRatio.length != 2) {
|
|
20136
20218
|
throw Error("minimumStakeRatio should have 2 elements");
|
|
20137
20219
|
}
|
|
20138
|
-
const stakes = validators.map((
|
|
20220
|
+
const stakes = validators.map((v10) => BigInt(v10.stake)).sort(sortBigIntAsc);
|
|
20139
20221
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
20140
20222
|
if (validators.length < maxNumberOfSeats) {
|
|
20141
20223
|
return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
|
|
@@ -20307,10 +20389,10 @@ var DER = {
|
|
|
20307
20389
|
if (length < 128)
|
|
20308
20390
|
throw new E("tlv.decode(long): not minimal encoding");
|
|
20309
20391
|
}
|
|
20310
|
-
const
|
|
20311
|
-
if (
|
|
20392
|
+
const v10 = data.subarray(pos, pos + length);
|
|
20393
|
+
if (v10.length !== length)
|
|
20312
20394
|
throw new E("tlv.decode: wrong value length");
|
|
20313
|
-
return { v:
|
|
20395
|
+
return { v: v10, l: data.subarray(pos + length) };
|
|
20314
20396
|
}
|
|
20315
20397
|
},
|
|
20316
20398
|
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
@@ -20878,9 +20960,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
20878
20960
|
extraEntropy: false
|
|
20879
20961
|
};
|
|
20880
20962
|
const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
|
|
20881
|
-
function isBiggerThanHalfOrder(
|
|
20963
|
+
function isBiggerThanHalfOrder(number4) {
|
|
20882
20964
|
const HALF = CURVE_ORDER >> _1n6;
|
|
20883
|
-
return
|
|
20965
|
+
return number4 > HALF;
|
|
20884
20966
|
}
|
|
20885
20967
|
function validateRS(title, num) {
|
|
20886
20968
|
if (!Fn.isValidNot0(num))
|
|
@@ -21063,8 +21145,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
21063
21145
|
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
21064
21146
|
if (R.is0())
|
|
21065
21147
|
return false;
|
|
21066
|
-
const
|
|
21067
|
-
return
|
|
21148
|
+
const v10 = Fn.create(R.x);
|
|
21149
|
+
return v10 === r;
|
|
21068
21150
|
} catch (e) {
|
|
21069
21151
|
return false;
|
|
21070
21152
|
}
|
|
@@ -24956,6 +25038,7 @@ function isTimeoutError(error) {
|
|
|
24956
25038
|
return error instanceof Error && /timed?\s?out|timeout/i.test(error.message);
|
|
24957
25039
|
}
|
|
24958
25040
|
var DEFAULT_GET_COINS_LIMIT = 10;
|
|
25041
|
+
var LATEST_PACKAGE_ID_TIMEOUT_MS = 1e4;
|
|
24959
25042
|
function toSuiObjectOwner(owner) {
|
|
24960
25043
|
switch (owner?.$kind) {
|
|
24961
25044
|
case "AddressOwner":
|
|
@@ -25024,16 +25107,20 @@ var SuiGrpcTransport = class {
|
|
|
25024
25107
|
return effects.gasUsed;
|
|
25025
25108
|
}
|
|
25026
25109
|
async fetchLatestPackageId(objectId) {
|
|
25027
|
-
let
|
|
25110
|
+
let object4;
|
|
25028
25111
|
try {
|
|
25029
|
-
({ object:
|
|
25112
|
+
({ object: object4 } = await this.client.core.getObject({
|
|
25113
|
+
objectId,
|
|
25114
|
+
include: { json: true },
|
|
25115
|
+
signal: AbortSignal.timeout(LATEST_PACKAGE_ID_TIMEOUT_MS)
|
|
25116
|
+
}));
|
|
25030
25117
|
} catch (error) {
|
|
25031
25118
|
throw new Error("Failed to fetch asset manager id", { cause: error });
|
|
25032
25119
|
}
|
|
25033
|
-
if (!
|
|
25120
|
+
if (!object4) {
|
|
25034
25121
|
throw new Error("Asset manager id not found (no data)");
|
|
25035
25122
|
}
|
|
25036
|
-
const fields =
|
|
25123
|
+
const fields = object4.json;
|
|
25037
25124
|
if (!fields) {
|
|
25038
25125
|
throw new Error("Asset manager id not found (not a move object)");
|
|
25039
25126
|
}
|
|
@@ -25070,7 +25157,11 @@ var SuiSpokeService = class {
|
|
|
25070
25157
|
transport;
|
|
25071
25158
|
/** @deprecated Renamed to `transport`, and no longer a raw `@mysten/sui` client. */
|
|
25072
25159
|
publicClient;
|
|
25073
|
-
|
|
25160
|
+
/**
|
|
25161
|
+
* `latest_package_id` reads still in flight, keyed by chain. An entry is dropped as soon as its
|
|
25162
|
+
* read settles, so concurrent callers share one request while a later build always re-reads.
|
|
25163
|
+
*/
|
|
25164
|
+
assetManagerLookups = /* @__PURE__ */ new Map();
|
|
25074
25165
|
pollingIntervalMs;
|
|
25075
25166
|
maxTimeoutMs;
|
|
25076
25167
|
constructor(config) {
|
|
@@ -25132,10 +25223,19 @@ var SuiSpokeService = class {
|
|
|
25132
25223
|
};
|
|
25133
25224
|
}
|
|
25134
25225
|
async getAssetManagerAddress(chainId) {
|
|
25135
|
-
|
|
25136
|
-
|
|
25137
|
-
|
|
25138
|
-
|
|
25226
|
+
const { packageId, moduleId, stateId } = await this.resolveAssetManager(chainId);
|
|
25227
|
+
return `${packageId}::${moduleId}::${stateId}`;
|
|
25228
|
+
}
|
|
25229
|
+
/**
|
|
25230
|
+
* An upgraded Sui package lives at a new address and the superseded one aborts on
|
|
25231
|
+
* `enforce_version`, so the id is read per call and never held between two builds.
|
|
25232
|
+
*/
|
|
25233
|
+
async resolveAssetManager(chainId) {
|
|
25234
|
+
const inFlight = this.assetManagerLookups.get(chainId);
|
|
25235
|
+
if (inFlight) return inFlight;
|
|
25236
|
+
const lookup = this.fetchAssetManagerAddress(chainId).then((address) => this.splitAddress(address)).finally(() => this.assetManagerLookups.delete(chainId));
|
|
25237
|
+
this.assetManagerLookups.set(chainId, lookup);
|
|
25238
|
+
return lookup;
|
|
25139
25239
|
}
|
|
25140
25240
|
async viewContract(tx, packageId, module, functionName, args, typeArgs = [], sender) {
|
|
25141
25241
|
tx.moveCall({
|
|
@@ -25152,12 +25252,27 @@ var SuiSpokeService = class {
|
|
|
25152
25252
|
* @returns {Promise<TxReturnType<SuiChainKey, R>>} A promise that resolves to the transaction hash or raw transaction base64 string.
|
|
25153
25253
|
*/
|
|
25154
25254
|
async deposit(params) {
|
|
25255
|
+
const { tx, assetManager } = await this.buildDepositTransaction(params);
|
|
25256
|
+
if (params.raw === true) {
|
|
25257
|
+
return {
|
|
25258
|
+
from: params.srcAddress,
|
|
25259
|
+
to: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
|
|
25260
|
+
value: params.amount,
|
|
25261
|
+
data: tx.serialize()
|
|
25262
|
+
};
|
|
25263
|
+
}
|
|
25264
|
+
return params.walletProvider.signAndExecuteTxn(tx);
|
|
25265
|
+
}
|
|
25266
|
+
/** Both deposit paths build here, so the asset manager is resolved the same way for each. */
|
|
25267
|
+
async buildDepositTransaction(params) {
|
|
25155
25268
|
const { srcAddress: from, srcChainKey, token, to, amount, data = "0x" } = params;
|
|
25156
25269
|
const isNative = isNativeToken(srcChainKey, token);
|
|
25157
25270
|
const tx = new Transaction$1();
|
|
25158
|
-
const coin = isNative ? await this.getNativeCoin(tx, amount) : await this.getCoin(tx, token, amount, from);
|
|
25159
25271
|
const connection = this.splitAddress(this.config.getChainConfig(srcChainKey).addresses.connection);
|
|
25160
|
-
const assetManager =
|
|
25272
|
+
const [coin, assetManager] = await Promise.all([
|
|
25273
|
+
isNative ? this.getNativeCoin(tx, amount) : this.getCoin(tx, token, amount, from),
|
|
25274
|
+
this.resolveAssetManager(srcChainKey)
|
|
25275
|
+
]);
|
|
25161
25276
|
tx.moveCall({
|
|
25162
25277
|
target: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
|
|
25163
25278
|
typeArguments: [token],
|
|
@@ -25170,15 +25285,7 @@ var SuiSpokeService = class {
|
|
|
25170
25285
|
tx.pure(bcs.vector(bcs.u8()).serialize(fromHex(data, "bytes")))
|
|
25171
25286
|
]
|
|
25172
25287
|
});
|
|
25173
|
-
|
|
25174
|
-
return {
|
|
25175
|
-
from,
|
|
25176
|
-
to: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
|
|
25177
|
-
value: amount,
|
|
25178
|
-
data: tx.serialize()
|
|
25179
|
-
};
|
|
25180
|
-
}
|
|
25181
|
-
return params.walletProvider.signAndExecuteTxn(tx);
|
|
25288
|
+
return { tx, assetManager };
|
|
25182
25289
|
}
|
|
25183
25290
|
async sendMessage(params) {
|
|
25184
25291
|
const { srcAddress: from, srcChainKey, dstChainKey, dstAddress, payload } = params;
|
|
@@ -25218,7 +25325,7 @@ var SuiSpokeService = class {
|
|
|
25218
25325
|
* @returns {Promise<bigint>} The balance of the token.
|
|
25219
25326
|
*/
|
|
25220
25327
|
async getDeposit(params) {
|
|
25221
|
-
const assetmanager =
|
|
25328
|
+
const assetmanager = await this.resolveAssetManager(params.srcChainKey);
|
|
25222
25329
|
const tx = new Transaction$1();
|
|
25223
25330
|
const result = await this.viewContract(
|
|
25224
25331
|
tx,
|
|
@@ -29547,7 +29654,7 @@ function selectSolvedIntentPacket(packets, intentsContract) {
|
|
|
29547
29654
|
|
|
29548
29655
|
// src/swap/speed-tier.ts
|
|
29549
29656
|
var SPEED_TIER_SECONDS = {
|
|
29550
|
-
/** Either token
|
|
29657
|
+
/** Either token's vault is a money-market-reserve (sodaAsset). */
|
|
29551
29658
|
sodaAsset: 15,
|
|
29552
29659
|
/** Anything else / default. */
|
|
29553
29660
|
default: 35,
|
|
@@ -29565,7 +29672,7 @@ var secondsToTier = (seconds) => {
|
|
|
29565
29672
|
return "slow";
|
|
29566
29673
|
};
|
|
29567
29674
|
function estimateSwapSpeedTier({ srcToken, dstToken }, isSodaAssetRelated) {
|
|
29568
|
-
const eitherSodaAsset = isSodaAssetRelated(srcToken.
|
|
29675
|
+
const eitherSodaAsset = isSodaAssetRelated(srcToken.vault) || isSodaAssetRelated(dstToken.vault);
|
|
29569
29676
|
let estimatedSeconds = eitherSodaAsset ? SPEED_TIER_SECONDS.sodaAsset : SPEED_TIER_SECONDS.default;
|
|
29570
29677
|
if (isEthereumToken(srcToken) || isEthereumToken(dstToken)) {
|
|
29571
29678
|
estimatedSeconds += SPEED_TIER_SECONDS.ethereumPenalty;
|
|
@@ -29775,14 +29882,14 @@ var SwapService = class {
|
|
|
29775
29882
|
*/
|
|
29776
29883
|
async getDetailedStatus(params) {
|
|
29777
29884
|
try {
|
|
29778
|
-
const
|
|
29885
|
+
const record = await this.backendApi.swaps.getSubmitTxStatus({
|
|
29779
29886
|
txHash: params.srcTxHash,
|
|
29780
29887
|
srcChainKey: params.srcChainKey
|
|
29781
29888
|
});
|
|
29782
|
-
if (
|
|
29783
|
-
return { ok: true, value: { source: "backend", data:
|
|
29889
|
+
if (record.ok && record.value.success && !isBackendSubmitTxAbandoned(record.value.data)) {
|
|
29890
|
+
return { ok: true, value: { source: "backend", data: record.value.data } };
|
|
29784
29891
|
}
|
|
29785
|
-
const backendAnswered =
|
|
29892
|
+
const backendAnswered = record.ok || isSodaxError(record.error) && record.error.context?.status === 404;
|
|
29786
29893
|
const dstTxHash = await this.resolveHubTxHash(params, backendAnswered);
|
|
29787
29894
|
if (!dstTxHash.ok) return dstTxHash;
|
|
29788
29895
|
const solver = await this.resolveSolverStatus(
|
|
@@ -30924,7 +31031,7 @@ var SwapService = class {
|
|
|
30924
31031
|
/**
|
|
30925
31032
|
* Offline, rule-based estimate of how fast a `srcToken`→`dstToken` swap will settle.
|
|
30926
31033
|
*
|
|
30927
|
-
* Derived purely from SDK config (no network / on-chain / backend call): tokens
|
|
31034
|
+
* Derived purely from SDK config (no network / on-chain / backend call): tokens whose vault is a
|
|
30928
31035
|
* money-market-reserve sodaAsset settle faster, and an Ethereum leg adds a fixed penalty. See
|
|
30929
31036
|
* {@link estimateSwapSpeedTier} for the rules.
|
|
30930
31037
|
*
|
|
@@ -30932,7 +31039,7 @@ var SwapService = class {
|
|
|
30932
31039
|
* @returns the estimated `tier` bucket and `estimatedSeconds`
|
|
30933
31040
|
*/
|
|
30934
31041
|
getSwapSpeedTier(params) {
|
|
30935
|
-
return estimateSwapSpeedTier(params, (
|
|
31042
|
+
return estimateSwapSpeedTier(params, (vault) => this.config.isMoneyMarketReserveAsset(vault));
|
|
30936
31043
|
}
|
|
30937
31044
|
};
|
|
30938
31045
|
|
|
@@ -33432,173 +33539,6 @@ var SponsoringApiService = class {
|
|
|
33432
33539
|
return this.config.baseURL;
|
|
33433
33540
|
}
|
|
33434
33541
|
};
|
|
33435
|
-
var RelayExtraDataResponseSchema = v.object({
|
|
33436
|
-
address: v.string(),
|
|
33437
|
-
payload: v.string()
|
|
33438
|
-
});
|
|
33439
|
-
var BridgeTokenSchema = v.object({
|
|
33440
|
-
symbol: v.string(),
|
|
33441
|
-
name: v.string(),
|
|
33442
|
-
decimals: v.number(),
|
|
33443
|
-
address: v.string(),
|
|
33444
|
-
chainKey: v.string(),
|
|
33445
|
-
hubAsset: v.string(),
|
|
33446
|
-
vault: v.string()
|
|
33447
|
-
});
|
|
33448
|
-
var BridgeTokensResponseSchema = v.record(v.string(), v.array(BridgeTokenSchema));
|
|
33449
|
-
var BridgeTokensByChainResponseSchema = v.array(BridgeTokenSchema);
|
|
33450
|
-
var BridgeAllowanceCheckResponseSchema = v.object({
|
|
33451
|
-
valid: v.boolean()
|
|
33452
|
-
});
|
|
33453
|
-
var makeBridgeApproveResponseSchema = (txSchema) => v.object({ tx: txSchema, resetTx: v.optional(txSchema) });
|
|
33454
|
-
var makeCreateBridgeIntentResponseSchema = (txSchema) => v.object({
|
|
33455
|
-
tx: txSchema,
|
|
33456
|
-
relayData: RelayExtraDataResponseSchema
|
|
33457
|
-
});
|
|
33458
|
-
var BridgeSubmitTxResponseSchema = v.object({
|
|
33459
|
-
success: v.boolean(),
|
|
33460
|
-
data: v.object({
|
|
33461
|
-
status: v.picklist(["inserted", "duplicate"]),
|
|
33462
|
-
message: v.string()
|
|
33463
|
-
})
|
|
33464
|
-
});
|
|
33465
|
-
var BridgePacketDataSchema = v.object({
|
|
33466
|
-
src_chain_id: v.number(),
|
|
33467
|
-
src_tx_hash: v.string(),
|
|
33468
|
-
src_address: v.string(),
|
|
33469
|
-
status: v.picklist(["pending", "validating", "executing", "executed"]),
|
|
33470
|
-
dst_chain_id: v.number(),
|
|
33471
|
-
conn_sn: v.number(),
|
|
33472
|
-
dst_address: v.string(),
|
|
33473
|
-
dst_tx_hash: v.string(),
|
|
33474
|
-
signatures: v.array(v.string()),
|
|
33475
|
-
payload: v.string()
|
|
33476
|
-
});
|
|
33477
|
-
var BridgeSubmitTxStatusResultSchema = v.object({
|
|
33478
|
-
dstIntentTxHash: v.string(),
|
|
33479
|
-
packetData: v.optional(BridgePacketDataSchema)
|
|
33480
|
-
});
|
|
33481
|
-
var BridgeSubmitTxStatusDataSchema = v.object({
|
|
33482
|
-
txHash: v.string(),
|
|
33483
|
-
srcChainKey: v.string(),
|
|
33484
|
-
status: v.string(),
|
|
33485
|
-
failedAtStep: v.optional(v.string()),
|
|
33486
|
-
failureReason: v.optional(v.string()),
|
|
33487
|
-
processingAttempts: v.number(),
|
|
33488
|
-
abandonedAt: v.optional(v.string()),
|
|
33489
|
-
result: v.optional(BridgeSubmitTxStatusResultSchema),
|
|
33490
|
-
userMessage: v.optional(v.string())
|
|
33491
|
-
});
|
|
33492
|
-
var BridgeSubmitTxStatusResponseSchema = v.object({
|
|
33493
|
-
success: v.boolean(),
|
|
33494
|
-
data: BridgeSubmitTxStatusDataSchema
|
|
33495
|
-
});
|
|
33496
|
-
var BridgeFeeResponseSchema = v.object({ fee: v.string() });
|
|
33497
|
-
var BridgeLimitSchema = v.object({
|
|
33498
|
-
amount: v.string(),
|
|
33499
|
-
decimals: v.number(),
|
|
33500
|
-
type: v.picklist(["DEPOSIT_LIMIT", "WITHDRAWAL_LIMIT"])
|
|
33501
|
-
});
|
|
33502
|
-
var BridgeableAmountResponseSchema = v.object({ limit: BridgeLimitSchema });
|
|
33503
|
-
var BridgeableCheckResponseSchema = v.object({ bridgeable: v.boolean() });
|
|
33504
|
-
var AddressSchema2 = v.custom((input) => typeof input === "string");
|
|
33505
|
-
var HexSchema = v.custom((input) => typeof input === "string");
|
|
33506
|
-
var BigintFromString = v.pipe(v.string(), v.toBigint());
|
|
33507
|
-
var BytesFromIndexRecord = v.pipe(
|
|
33508
|
-
v.record(v.string(), v.number()),
|
|
33509
|
-
v.transform((indexed) => Uint8Array.from(Object.values(indexed)))
|
|
33510
|
-
);
|
|
33511
|
-
var EvmRawTxSchema = v.object({
|
|
33512
|
-
from: AddressSchema2,
|
|
33513
|
-
to: AddressSchema2,
|
|
33514
|
-
value: BigintFromString,
|
|
33515
|
-
data: HexSchema
|
|
33516
|
-
});
|
|
33517
|
-
var SolanaRawTxSchema = v.object({
|
|
33518
|
-
from: v.string(),
|
|
33519
|
-
to: v.string(),
|
|
33520
|
-
value: BigintFromString,
|
|
33521
|
-
data: v.string()
|
|
33522
|
-
});
|
|
33523
|
-
var SuiRawTxSchema = v.object({
|
|
33524
|
-
from: HexSchema,
|
|
33525
|
-
to: v.string(),
|
|
33526
|
-
value: BigintFromString,
|
|
33527
|
-
data: v.string()
|
|
33528
|
-
});
|
|
33529
|
-
var StellarRawTxSchema = v.object({
|
|
33530
|
-
from: v.string(),
|
|
33531
|
-
to: v.string(),
|
|
33532
|
-
value: BigintFromString,
|
|
33533
|
-
data: v.string()
|
|
33534
|
-
});
|
|
33535
|
-
var BitcoinRawTxSchema = v.object({
|
|
33536
|
-
from: v.string(),
|
|
33537
|
-
to: v.string(),
|
|
33538
|
-
value: BigintFromString,
|
|
33539
|
-
data: v.string()
|
|
33540
|
-
});
|
|
33541
|
-
var InjectiveRawTxSchema = v.object({
|
|
33542
|
-
from: HexSchema,
|
|
33543
|
-
to: HexSchema,
|
|
33544
|
-
signedDoc: v.object({
|
|
33545
|
-
bodyBytes: BytesFromIndexRecord,
|
|
33546
|
-
authInfoBytes: BytesFromIndexRecord,
|
|
33547
|
-
chainId: v.string(),
|
|
33548
|
-
accountNumber: BigintFromString
|
|
33549
|
-
})
|
|
33550
|
-
});
|
|
33551
|
-
var NearRawTxSchema = v.object({
|
|
33552
|
-
signerId: v.string(),
|
|
33553
|
-
params: v.object({
|
|
33554
|
-
contractId: v.string(),
|
|
33555
|
-
method: v.string(),
|
|
33556
|
-
args: v.custom((input) => typeof input === "object" && input !== null),
|
|
33557
|
-
gas: v.optional(BigintFromString),
|
|
33558
|
-
deposit: v.optional(BigintFromString)
|
|
33559
|
-
})
|
|
33560
|
-
});
|
|
33561
|
-
var IconRawTxSchema = v.record(
|
|
33562
|
-
v.string(),
|
|
33563
|
-
v.union([v.string(), v.custom((input) => typeof input === "object" && input !== null)])
|
|
33564
|
-
);
|
|
33565
|
-
var StacksRawTxSchema = v.object({
|
|
33566
|
-
payload: v.string(),
|
|
33567
|
-
estimatedLength: v.optional(v.number())
|
|
33568
|
-
});
|
|
33569
|
-
var AnyRawTxSchema = v.custom((input) => typeof input === "object" && input !== null);
|
|
33570
|
-
function rawTxSchemaForChainKey(chainKey) {
|
|
33571
|
-
let chainType;
|
|
33572
|
-
try {
|
|
33573
|
-
chainType = getChainType(chainKey);
|
|
33574
|
-
} catch {
|
|
33575
|
-
chainType = void 0;
|
|
33576
|
-
}
|
|
33577
|
-
switch (chainType) {
|
|
33578
|
-
case "EVM":
|
|
33579
|
-
return EvmRawTxSchema;
|
|
33580
|
-
case "SOLANA":
|
|
33581
|
-
return SolanaRawTxSchema;
|
|
33582
|
-
case "SUI":
|
|
33583
|
-
return SuiRawTxSchema;
|
|
33584
|
-
case "STELLAR":
|
|
33585
|
-
return StellarRawTxSchema;
|
|
33586
|
-
case "INJECTIVE":
|
|
33587
|
-
return InjectiveRawTxSchema;
|
|
33588
|
-
case "ICON":
|
|
33589
|
-
return IconRawTxSchema;
|
|
33590
|
-
case "STACKS":
|
|
33591
|
-
return StacksRawTxSchema;
|
|
33592
|
-
case "NEAR":
|
|
33593
|
-
return NearRawTxSchema;
|
|
33594
|
-
case "BITCOIN":
|
|
33595
|
-
return BitcoinRawTxSchema;
|
|
33596
|
-
default:
|
|
33597
|
-
return AnyRawTxSchema;
|
|
33598
|
-
}
|
|
33599
|
-
}
|
|
33600
|
-
|
|
33601
|
-
// src/backendApi/BridgeApiService.ts
|
|
33602
33542
|
function toCreateBridgeIntentParamsV2(params, extras) {
|
|
33603
33543
|
return {
|
|
33604
33544
|
srcChainKey: params.srcChainKey,
|
|
@@ -33623,41 +33563,63 @@ var BridgeApiService = class {
|
|
|
33623
33563
|
trimsLegacyOverrides;
|
|
33624
33564
|
constructor(config, logger = consoleLogger, options = {}) {
|
|
33625
33565
|
this.config = config;
|
|
33626
|
-
this.headers =
|
|
33566
|
+
this.headers = mergeHeaders(config.headers);
|
|
33627
33567
|
this.logger = logger;
|
|
33628
33568
|
this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
|
|
33629
33569
|
}
|
|
33630
33570
|
/**
|
|
33631
|
-
*
|
|
33632
|
-
*
|
|
33633
|
-
*
|
|
33634
|
-
*
|
|
33571
|
+
* Build a `@sodax/bridge-api` client for a single call. Maps the SDK's {@link BaseApiConfig}
|
|
33572
|
+
* (`baseURL`/`timeout`/`headers`) to the package's config (`baseUrl`/`timeout`/`headers`), layering
|
|
33573
|
+
* the optional per-call `RequestOverrideConfig` on top (override wins per field; headers merge).
|
|
33574
|
+
* `timeout` falls back to the backend-API default so a config that omits it still gets a ceiling
|
|
33575
|
+
* rather than an unbounded request. Constructed per call so `setHeaders` mutations and per-call
|
|
33576
|
+
* overrides both take effect without caching stale state.
|
|
33635
33577
|
*/
|
|
33636
|
-
|
|
33578
|
+
buildClient(overrideConfig) {
|
|
33579
|
+
const override = overrideConfig?.baseURL;
|
|
33580
|
+
const baseUrl = override ? this.trimsLegacyOverrides ? stripLegacyBackendMount(override) : override : this.config.baseURL;
|
|
33581
|
+
const timeout = overrideConfig?.timeout ?? this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
|
|
33582
|
+
const headers = mergeHeaders(this.headers, apiKeyHeader(overrideConfig?.apiKey), overrideConfig?.headers);
|
|
33583
|
+
return new BridgeApi({ baseUrl, headers, timeout });
|
|
33584
|
+
}
|
|
33585
|
+
/**
|
|
33586
|
+
* Run one delegated `BridgeApi` call and wrap it in `Result<T>`. A thrown `BridgeApiError`
|
|
33587
|
+
* (network/timeout/HTTP/parse/validation) becomes `{ ok: false }` with a canonical
|
|
33588
|
+
* `SodaxError<'EXTERNAL_API_ERROR'>`; the original error is kept as `cause`, and its
|
|
33589
|
+
* `code`/`status`/`issues` are projected into `context` so consumers can discriminate failure
|
|
33590
|
+
* kinds without unwrapping `cause`. Only a RESPONSE-shape validation failure is tagged
|
|
33591
|
+
* `reason: 'invalid_response_shape'` — a request-side validation error is a caller bug, not a
|
|
33592
|
+
* backend fault.
|
|
33593
|
+
*/
|
|
33594
|
+
async toResult(endpoint, call, overrideConfig) {
|
|
33637
33595
|
try {
|
|
33638
|
-
const
|
|
33639
|
-
|
|
33640
|
-
config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
|
|
33641
|
-
// Normalized like a configured base URL: the override is the gateway root, so a legacy
|
|
33642
|
-
// `/be`-suffixed value must not nest `/bridge/*` under the data API's mount — unless the config
|
|
33643
|
-
// opted out of the legacy trim, in which case the per-call value is left exactly as given.
|
|
33644
|
-
overrideConfig: this.trimsLegacyOverrides ? normalizeOverrideBaseURL(overrideConfig) : overrideConfig,
|
|
33645
|
-
logger: this.logger,
|
|
33646
|
-
serviceLabel: "BridgeApiService"
|
|
33647
|
-
});
|
|
33648
|
-
const parsed = v.safeParse(schema, raw);
|
|
33649
|
-
if (!parsed.success) {
|
|
33650
|
-
return {
|
|
33651
|
-
ok: false,
|
|
33652
|
-
error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from bridge API for ${endpoint}`, {
|
|
33653
|
-
feature: "backend",
|
|
33654
|
-
context: { api: "bridge", endpoint, reason: "invalid_response_shape", issues: v.flatten(parsed.issues) }
|
|
33655
|
-
})
|
|
33656
|
-
};
|
|
33657
|
-
}
|
|
33658
|
-
return { ok: true, value: parsed.output };
|
|
33596
|
+
const value = await call(this.buildClient(overrideConfig));
|
|
33597
|
+
return { ok: true, value };
|
|
33659
33598
|
} catch (error) {
|
|
33660
|
-
|
|
33599
|
+
const context = { api: "bridge", endpoint };
|
|
33600
|
+
if (error instanceof BridgeApiError) {
|
|
33601
|
+
context.code = error.code;
|
|
33602
|
+
if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
|
|
33603
|
+
context.reason = "invalid_response_shape";
|
|
33604
|
+
const issues = error.context.issues;
|
|
33605
|
+
context.issues = issues instanceof v.ValiError ? v.flatten(issues.issues) : issues;
|
|
33606
|
+
}
|
|
33607
|
+
if (error.context.status !== void 0) context.status = error.context.status;
|
|
33608
|
+
if (isAuthStatus(error.context.status)) {
|
|
33609
|
+
this.logger.warn(
|
|
33610
|
+
`[BridgeApiService] ${endpoint} was rejected by the bridge API key guard (${error.context.status}). Configure a valid partner API key \u2014 new Sodax({ apiKey }) \u2014 see docs/CONFIGURE_SDK.md.`
|
|
33611
|
+
);
|
|
33612
|
+
}
|
|
33613
|
+
}
|
|
33614
|
+
this.logger.error(`[BridgeApiService] Request to ${endpoint} failed`, error);
|
|
33615
|
+
return {
|
|
33616
|
+
ok: false,
|
|
33617
|
+
error: new SodaxError(
|
|
33618
|
+
"EXTERNAL_API_ERROR",
|
|
33619
|
+
error instanceof Error ? error.message : `Request to ${endpoint} failed`,
|
|
33620
|
+
{ feature: "backend", cause: error, context }
|
|
33621
|
+
)
|
|
33622
|
+
};
|
|
33661
33623
|
}
|
|
33662
33624
|
}
|
|
33663
33625
|
// ──────────────────────────────────────────────────────────────────────
|
|
@@ -33669,7 +33631,7 @@ var BridgeApiService = class {
|
|
|
33669
33631
|
* @returns `Result<GetBridgeTokensResponseV2>` — map of chain key → token list.
|
|
33670
33632
|
*/
|
|
33671
33633
|
async getTokens(config) {
|
|
33672
|
-
return this.
|
|
33634
|
+
return this.toResult("/bridge/tokens", (c) => c.getTokens(), config);
|
|
33673
33635
|
}
|
|
33674
33636
|
/**
|
|
33675
33637
|
* Fetch supported bridge tokens for a single SpokeChainKey.
|
|
@@ -33678,12 +33640,7 @@ var BridgeApiService = class {
|
|
|
33678
33640
|
* @returns `Result<GetBridgeTokensByChainResponseV2>` — token list for the chain.
|
|
33679
33641
|
*/
|
|
33680
33642
|
async getTokensByChain(chainKey, config) {
|
|
33681
|
-
return this.
|
|
33682
|
-
`/bridge/tokens/${chainKey}`,
|
|
33683
|
-
{ method: "GET" },
|
|
33684
|
-
BridgeTokensByChainResponseSchema,
|
|
33685
|
-
config
|
|
33686
|
-
);
|
|
33643
|
+
return this.toResult(`/bridge/tokens/${chainKey}`, (c) => c.getTokensByChain(chainKey), config);
|
|
33687
33644
|
}
|
|
33688
33645
|
// ──────────────────────────────────────────────────────────────────────
|
|
33689
33646
|
// Allowance · approve · create intent
|
|
@@ -33694,12 +33651,7 @@ var BridgeApiService = class {
|
|
|
33694
33651
|
* @returns `Result<BridgeAllowanceCheckResponseV2>` — `{ valid }`.
|
|
33695
33652
|
*/
|
|
33696
33653
|
async checkAllowance(body, config) {
|
|
33697
|
-
return this.
|
|
33698
|
-
"/bridge/allowance/check",
|
|
33699
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33700
|
-
BridgeAllowanceCheckResponseSchema,
|
|
33701
|
-
config
|
|
33702
|
-
);
|
|
33654
|
+
return this.toResult("/bridge/allowance/check", (c) => c.checkAllowance(body), config);
|
|
33703
33655
|
}
|
|
33704
33656
|
/**
|
|
33705
33657
|
* Build an unsigned token-approval transaction for the source token.
|
|
@@ -33708,13 +33660,7 @@ var BridgeApiService = class {
|
|
|
33708
33660
|
* broadcast and mine `resetTx` first when it is present.
|
|
33709
33661
|
*/
|
|
33710
33662
|
async approve(body, config) {
|
|
33711
|
-
|
|
33712
|
-
return this.request(
|
|
33713
|
-
"/bridge/approve",
|
|
33714
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33715
|
-
makeBridgeApproveResponseSchema(txSchema),
|
|
33716
|
-
config
|
|
33717
|
-
);
|
|
33663
|
+
return this.toResult("/bridge/approve", (c) => c.approve(body), config);
|
|
33718
33664
|
}
|
|
33719
33665
|
/**
|
|
33720
33666
|
* Build an unsigned spoke-deposit (create-bridge-intent) transaction.
|
|
@@ -33722,13 +33668,7 @@ var BridgeApiService = class {
|
|
|
33722
33668
|
* @returns `Result<CreateBridgeIntentResponseV2>` — `{ tx, relayData }` (no intent struct).
|
|
33723
33669
|
*/
|
|
33724
33670
|
async createBridgeIntent(body, config) {
|
|
33725
|
-
|
|
33726
|
-
return this.request(
|
|
33727
|
-
"/bridge/intents",
|
|
33728
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33729
|
-
makeCreateBridgeIntentResponseSchema(txSchema),
|
|
33730
|
-
config
|
|
33731
|
-
);
|
|
33671
|
+
return this.toResult("/bridge/intents", (c) => c.createBridgeIntent(body), config);
|
|
33732
33672
|
}
|
|
33733
33673
|
// ──────────────────────────────────────────────────────────────────────
|
|
33734
33674
|
// Submit-tx state machine
|
|
@@ -33740,12 +33680,7 @@ var BridgeApiService = class {
|
|
|
33740
33680
|
* @returns `Result<BridgeSubmitTxResponseV2>` — `{ success, data: { status, message } }`.
|
|
33741
33681
|
*/
|
|
33742
33682
|
async submitTx(body, config) {
|
|
33743
|
-
return this.
|
|
33744
|
-
"/bridge/submit-tx",
|
|
33745
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33746
|
-
BridgeSubmitTxResponseSchema,
|
|
33747
|
-
config
|
|
33748
|
-
);
|
|
33683
|
+
return this.toResult("/bridge/submit-tx", (c) => c.submitTx(body), config);
|
|
33749
33684
|
}
|
|
33750
33685
|
/**
|
|
33751
33686
|
* Get the processing status of a submitted bridge transaction by `(txHash, srcChainKey)`.
|
|
@@ -33753,13 +33688,7 @@ var BridgeApiService = class {
|
|
|
33753
33688
|
* @returns `Result<BridgeSubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
|
|
33754
33689
|
*/
|
|
33755
33690
|
async getSubmitTxStatus(query, config) {
|
|
33756
|
-
|
|
33757
|
-
return this.request(
|
|
33758
|
-
`/bridge/submit-tx/status?${queryParams.toString()}`,
|
|
33759
|
-
{ method: "GET" },
|
|
33760
|
-
BridgeSubmitTxStatusResponseSchema,
|
|
33761
|
-
config
|
|
33762
|
-
);
|
|
33691
|
+
return this.toResult("/bridge/submit-tx/status", (c) => c.getSubmitTxStatus(query), config);
|
|
33763
33692
|
}
|
|
33764
33693
|
// ──────────────────────────────────────────────────────────────────────
|
|
33765
33694
|
// Fee · bridgeable quote (read-only; mirror the SDK-core client-side methods)
|
|
@@ -33773,12 +33702,7 @@ var BridgeApiService = class {
|
|
|
33773
33702
|
* @returns `Result<BridgeFeeResponseV2>` — `{ fee }` (decimal string).
|
|
33774
33703
|
*/
|
|
33775
33704
|
async getFee(body, config) {
|
|
33776
|
-
return this.
|
|
33777
|
-
"/bridge/fee",
|
|
33778
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33779
|
-
BridgeFeeResponseSchema,
|
|
33780
|
-
config
|
|
33781
|
-
);
|
|
33705
|
+
return this.toResult("/bridge/fee", (c) => c.getFee(body), config);
|
|
33782
33706
|
}
|
|
33783
33707
|
/**
|
|
33784
33708
|
* Deposit capacity / withdrawal liquidity for a (from, to) token pair. Computable client-side in the
|
|
@@ -33787,12 +33711,7 @@ var BridgeApiService = class {
|
|
|
33787
33711
|
* @returns `Result<BridgeableAmountResponseV2>` — `{ limit }`.
|
|
33788
33712
|
*/
|
|
33789
33713
|
async getBridgeableAmount(body, config) {
|
|
33790
|
-
return this.
|
|
33791
|
-
"/bridge/bridgeable-amount",
|
|
33792
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33793
|
-
BridgeableAmountResponseSchema,
|
|
33794
|
-
config
|
|
33795
|
-
);
|
|
33714
|
+
return this.toResult("/bridge/bridgeable-amount", (c) => c.getBridgeableAmount(body), config);
|
|
33796
33715
|
}
|
|
33797
33716
|
/**
|
|
33798
33717
|
* Whether a (from, to) token pair is bridgeable. Computable client-side in the SDK core
|
|
@@ -33801,19 +33720,15 @@ var BridgeApiService = class {
|
|
|
33801
33720
|
* @returns `Result<BridgeableCheckResponseV2>` — `{ bridgeable }`.
|
|
33802
33721
|
*/
|
|
33803
33722
|
async isBridgeable(body, config) {
|
|
33804
|
-
return this.
|
|
33805
|
-
"/bridge/bridgeable/check",
|
|
33806
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33807
|
-
BridgeableCheckResponseSchema,
|
|
33808
|
-
config
|
|
33809
|
-
);
|
|
33723
|
+
return this.toResult("/bridge/bridgeable/check", (c) => c.isBridgeable(body), config);
|
|
33810
33724
|
}
|
|
33811
33725
|
// ──────────────────────────────────────────────────────────────────────
|
|
33812
33726
|
// Utilities (parity with SwapsApiService)
|
|
33813
33727
|
// ──────────────────────────────────────────────────────────────────────
|
|
33814
33728
|
/**
|
|
33815
33729
|
* Merge additional headers into the service's default header set. Existing
|
|
33816
|
-
* keys are overwritten; keys absent from `headers` are preserved.
|
|
33730
|
+
* keys are overwritten; keys absent from `headers` are preserved. Applied to
|
|
33731
|
+
* every subsequent call (the delegated client is rebuilt per call).
|
|
33817
33732
|
*/
|
|
33818
33733
|
setHeaders(headers) {
|
|
33819
33734
|
assignHeaders(this.headers, headers);
|
|
@@ -34146,7 +34061,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34146
34061
|
*/
|
|
34147
34062
|
async getDepositQuote(body, query, config) {
|
|
34148
34063
|
const endpoint = query?.includeTxData ? "/leverage-yield/quote/deposit?includeTxData=true" : "/leverage-yield/quote/deposit";
|
|
34149
|
-
const txSchema = rawTxSchemaForChainKey
|
|
34064
|
+
const txSchema = rawTxSchemaForChainKey(body.tokenSrcChainKey);
|
|
34150
34065
|
return this.request(
|
|
34151
34066
|
endpoint,
|
|
34152
34067
|
{ method: "POST", body: toJsonBody(body) },
|
|
@@ -34163,7 +34078,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34163
34078
|
*/
|
|
34164
34079
|
async getWithdrawQuote(body, query, config) {
|
|
34165
34080
|
const endpoint = query?.includeTxData ? "/leverage-yield/quote/withdraw?includeTxData=true" : "/leverage-yield/quote/withdraw";
|
|
34166
|
-
const txSchema = rawTxSchemaForChainKey
|
|
34081
|
+
const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
|
|
34167
34082
|
return this.request(
|
|
34168
34083
|
endpoint,
|
|
34169
34084
|
{ method: "POST", body: toJsonBody(body) },
|
|
@@ -34209,7 +34124,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34209
34124
|
* @returns `Result<ApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
|
|
34210
34125
|
*/
|
|
34211
34126
|
async approve(body, config) {
|
|
34212
|
-
const txSchema = rawTxSchemaForChainKey
|
|
34127
|
+
const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
|
|
34213
34128
|
return this.request(
|
|
34214
34129
|
"/leverage-yield/approve",
|
|
34215
34130
|
{ method: "POST", body: toJsonBody(body) },
|
|
@@ -34223,7 +34138,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34223
34138
|
* @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
|
|
34224
34139
|
*/
|
|
34225
34140
|
async createDepositIntent(body, config) {
|
|
34226
|
-
const txSchema = rawTxSchemaForChainKey
|
|
34141
|
+
const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
|
|
34227
34142
|
return this.request(
|
|
34228
34143
|
"/leverage-yield/intents/deposit",
|
|
34229
34144
|
{ method: "POST", body: toJsonBody(body) },
|
|
@@ -34238,7 +34153,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34238
34153
|
* @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
|
|
34239
34154
|
*/
|
|
34240
34155
|
async createWithdrawIntent(body, config) {
|
|
34241
|
-
const txSchema = rawTxSchemaForChainKey
|
|
34156
|
+
const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
|
|
34242
34157
|
return this.request(
|
|
34243
34158
|
"/leverage-yield/intents/withdraw",
|
|
34244
34159
|
{ method: "POST", body: toJsonBody(body) },
|
|
@@ -34282,7 +34197,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34282
34197
|
* @returns `Result<CancelIntentResponseV2>` — `{ tx }`.
|
|
34283
34198
|
*/
|
|
34284
34199
|
async cancelIntent(body, config) {
|
|
34285
|
-
const txSchema = rawTxSchemaForChainKey
|
|
34200
|
+
const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
|
|
34286
34201
|
return this.request(
|
|
34287
34202
|
"/leverage-yield/intents/cancel",
|
|
34288
34203
|
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
@@ -34327,7 +34242,7 @@ var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
|
34327
34242
|
return this.request(
|
|
34328
34243
|
"/leverage-yield/intents/extra-data",
|
|
34329
34244
|
{ method: "POST", body: toJsonBody(normalized) },
|
|
34330
|
-
RelayExtraDataResponseSchema
|
|
34245
|
+
RelayExtraDataResponseSchema,
|
|
34331
34246
|
config
|
|
34332
34247
|
);
|
|
34333
34248
|
}
|
|
@@ -43837,6 +43752,24 @@ var isLeverageYieldPostExecutionError = isCodeMember(
|
|
|
43837
43752
|
var isLeverageYieldSwapError = isCodeMember(LEVERAGE_YIELD_SWAP_CODES);
|
|
43838
43753
|
var isLeverageYieldError = isCodeMember(LEVERAGE_YIELD_CODES);
|
|
43839
43754
|
|
|
43755
|
+
// src/leverageYield/positionFunding.ts
|
|
43756
|
+
function resolvePositionFundingAddress(chainKey, hubChainKey, token) {
|
|
43757
|
+
if (chainKey !== hubChainKey) return token?.address ?? "";
|
|
43758
|
+
if (token && isNativeToken(chainKey, token)) return token.address;
|
|
43759
|
+
return token?.hubAsset ?? token?.address ?? "";
|
|
43760
|
+
}
|
|
43761
|
+
|
|
43762
|
+
// src/leverageYield/positionIntent.ts
|
|
43763
|
+
async function reportPositionIntent(notifySolver, txHashes) {
|
|
43764
|
+
const result = await notifySolver({ intent_tx_hash: txHashes.dstChainTxHash }).catch((error2) => ({
|
|
43765
|
+
ok: false,
|
|
43766
|
+
error: error2
|
|
43767
|
+
}));
|
|
43768
|
+
if (result.ok) return { txHashes, notified: true };
|
|
43769
|
+
const { error } = result;
|
|
43770
|
+
return { txHashes, notified: false, notifyError: error instanceof Error ? error.message : String(error) };
|
|
43771
|
+
}
|
|
43772
|
+
|
|
43840
43773
|
// src/leverageYield/LeverageYieldService.ts
|
|
43841
43774
|
var leverageYieldVaultAbi = parseAbi([
|
|
43842
43775
|
"function asset() view returns (address)",
|
|
@@ -43846,7 +43779,31 @@ var leverageYieldVaultAbi = parseAbi([
|
|
|
43846
43779
|
"function borrowToken() view returns (address)",
|
|
43847
43780
|
"function targetLTV() view returns (uint256)"
|
|
43848
43781
|
]);
|
|
43782
|
+
var MAX_POSITION_FEE_BPS = 100;
|
|
43783
|
+
var leveragePositionFactoryAbi = parseAbi([
|
|
43784
|
+
"function positionsOf(address owner) view returns (address[])",
|
|
43785
|
+
"function nextPositionIdFor(address owner) view returns (uint256)",
|
|
43786
|
+
"function predictPosition(address creator, address owner, uint256 positionId) view returns (address)",
|
|
43787
|
+
"function createPositionAndLeverage((address owner, address collateral, address borrowToken, uint8 eModeCategory, uint256 originChainId, bytes originAddress, address originAsset, address feeReceiver, uint16 feeBps) cfg, uint256 initialAssets, uint256 borrowAmount, uint256 minCollateralOut) returns (address)",
|
|
43788
|
+
"function createPositionFromDebtToken((address owner, address collateral, address borrowToken, uint8 eModeCategory, uint256 originChainId, bytes originAddress, address originAsset, address feeReceiver, uint16 feeBps) cfg, uint256 contribution, uint256 totalInput, uint256 minCollateralOut) returns (address)"
|
|
43789
|
+
]);
|
|
43790
|
+
var leveragePositionAbi = parseAbi([
|
|
43791
|
+
"function owner() view returns (address)",
|
|
43792
|
+
"function collateral() view returns (address)",
|
|
43793
|
+
"function borrowToken() view returns (address)",
|
|
43794
|
+
"function eModeCategory() view returns (uint8)",
|
|
43795
|
+
"function feeBps() view returns (uint16)",
|
|
43796
|
+
"function feeReceiver() view returns (address)",
|
|
43797
|
+
"function hasPendingOperation() view returns (bool)",
|
|
43798
|
+
"function pendingKind() view returns (uint8)",
|
|
43799
|
+
"function addLeverage(uint256 borrowAmount, uint256 minCollateralOut)",
|
|
43800
|
+
"function decreaseLeverage(uint256 collateralIn, uint256 minDebtOut, address exitAsset)",
|
|
43801
|
+
"function withdraw(uint256 amount, address to)",
|
|
43802
|
+
"function cancel()",
|
|
43803
|
+
"function settle()"
|
|
43804
|
+
]);
|
|
43849
43805
|
var INTENT_DEADLINE_BUFFER_SECONDS = 5 * 60;
|
|
43806
|
+
var BITCOIN_UNSUPPORTED_MESSAGE = "Bitcoin is not a supported source chain for leverage positions; use a supported spoke or the hub";
|
|
43850
43807
|
var ANY_SOLVER_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
43851
43808
|
var MAX_WITHDRAW_DUST_BUFFER = 1000n;
|
|
43852
43809
|
function pctToRay(aprPct) {
|
|
@@ -43903,7 +43860,7 @@ var LeverageYieldService = class {
|
|
|
43903
43860
|
}
|
|
43904
43861
|
/** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
|
|
43905
43862
|
getVault(name) {
|
|
43906
|
-
return this.listVaults().find((
|
|
43863
|
+
return this.listVaults().find((v10) => v10.name === name);
|
|
43907
43864
|
}
|
|
43908
43865
|
/**
|
|
43909
43866
|
* Looks up a registered vault by its on-chain proxy address (case-insensitive).
|
|
@@ -43911,7 +43868,7 @@ var LeverageYieldService = class {
|
|
|
43911
43868
|
*/
|
|
43912
43869
|
getVaultByAddress(address) {
|
|
43913
43870
|
const normalized = address.toLowerCase();
|
|
43914
|
-
return this.listVaults().find((
|
|
43871
|
+
return this.listVaults().find((v10) => v10.vault.toLowerCase() === normalized);
|
|
43915
43872
|
}
|
|
43916
43873
|
/**
|
|
43917
43874
|
* Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
|
|
@@ -44500,7 +44457,12 @@ var LeverageYieldService = class {
|
|
|
44500
44457
|
}
|
|
44501
44458
|
}
|
|
44502
44459
|
/**
|
|
44503
|
-
* Notifies the solver that
|
|
44460
|
+
* Notifies the solver that an intent landed on the hub, triggering it to fill.
|
|
44461
|
+
*
|
|
44462
|
+
* REQUIRED for anything that creates an intent, not an optimisation. An intent created on the hub
|
|
44463
|
+
* is invisible to the solver until this call puts it in the task pool, so an unnotified intent
|
|
44464
|
+
* simply expires. Leverage positions post their intents on-chain from the position contract, so
|
|
44465
|
+
* the caller that sent the transaction is the only one who can report the hash.
|
|
44504
44466
|
* Leverage-yield copy of the swap domain's `postExecution` — emits only
|
|
44505
44467
|
* `EXECUTION_FAILED` / `EXTERNAL_API_ERROR` / `UNKNOWN` (relay/verify codes appear only
|
|
44506
44468
|
* on {@link LeverageYieldService.vaultSwap}, which owns the verify + relay steps).
|
|
@@ -44545,6 +44507,51 @@ var LeverageYieldService = class {
|
|
|
44545
44507
|
return { ok: false, error: executionFailed("leverageYield", error, { phase: "postExecution" }) };
|
|
44546
44508
|
}
|
|
44547
44509
|
}
|
|
44510
|
+
/**
|
|
44511
|
+
* Polls the solver for the execution status of an intent this service created.
|
|
44512
|
+
*
|
|
44513
|
+
* Pair with {@link LeverageYieldService.notifySolver}: `notifySolver` puts the intent in the
|
|
44514
|
+
* solver's task pool, this reports what became of it. `fill_tx_hash` is set only once
|
|
44515
|
+
* `status === SolverIntentStatusCode.SOLVED`.
|
|
44516
|
+
*
|
|
44517
|
+
* A `NOT_FOUND` status usually means the notification never landed rather than that the intent
|
|
44518
|
+
* does not exist — an intent created on the hub is invisible to the solver until it is told.
|
|
44519
|
+
*
|
|
44520
|
+
* @param request - `{ intent_tx_hash }` — the hub-chain (Sonic) tx hash the intent was
|
|
44521
|
+
* registered in. For a position that is the tx that called the factory or the position.
|
|
44522
|
+
*/
|
|
44523
|
+
async getIntentStatus(request) {
|
|
44524
|
+
try {
|
|
44525
|
+
const result = await SolverApiService.getStatus(
|
|
44526
|
+
request,
|
|
44527
|
+
this.config.solver,
|
|
44528
|
+
this.config.logger,
|
|
44529
|
+
void 0,
|
|
44530
|
+
this.config.apiKey
|
|
44531
|
+
);
|
|
44532
|
+
if (result.ok) return result;
|
|
44533
|
+
const detail = result.error?.detail ?? {
|
|
44534
|
+
code: -999,
|
|
44535
|
+
// SolverIntentErrorCode.UNKNOWN
|
|
44536
|
+
message: "Solver returned malformed error response"
|
|
44537
|
+
};
|
|
44538
|
+
return {
|
|
44539
|
+
ok: false,
|
|
44540
|
+
error: new SodaxError("EXTERNAL_API_ERROR", detail.message, {
|
|
44541
|
+
feature: "leverageYield",
|
|
44542
|
+
context: {
|
|
44543
|
+
phase: "lookup",
|
|
44544
|
+
api: "solver",
|
|
44545
|
+
solverCode: detail.code,
|
|
44546
|
+
solverDetail: detail
|
|
44547
|
+
}
|
|
44548
|
+
})
|
|
44549
|
+
};
|
|
44550
|
+
} catch (error) {
|
|
44551
|
+
if (isLeverageYieldPostExecutionError(error)) return { ok: false, error };
|
|
44552
|
+
return { ok: false, error: executionFailed("leverageYield", error, { phase: "lookup" }) };
|
|
44553
|
+
}
|
|
44554
|
+
}
|
|
44548
44555
|
/**
|
|
44549
44556
|
* Approves the vault's underlying asset to the leverage vault on Sonic. For callers
|
|
44550
44557
|
* interacting with the vault directly on the hub — the swap-style {@link
|
|
@@ -44853,6 +44860,1252 @@ var LeverageYieldService = class {
|
|
|
44853
44860
|
return { ok: false, error: lookupFailed("leverageYield", "getShareBalanceForUser", error, { srcChainKey }) };
|
|
44854
44861
|
}
|
|
44855
44862
|
}
|
|
44863
|
+
// ─── Leverage positions ────────────────────────────────────────────────
|
|
44864
|
+
/**
|
|
44865
|
+
* Resolves the `LeveragePositionFactory` address, or a validation error when it is missing.
|
|
44866
|
+
*
|
|
44867
|
+
* The deployed factory ships in `leverageYieldConfig`, so this only fails when an integrator
|
|
44868
|
+
* overrides it with an empty value — which is what a bad env var produces. Failing closed there is
|
|
44869
|
+
* deliberate: a placeholder address would post real intents at nothing.
|
|
44870
|
+
*/
|
|
44871
|
+
requireFactory(action) {
|
|
44872
|
+
const factory = this.config.sodaxConfig.leverageYield.positionFactory;
|
|
44873
|
+
if (!factory) {
|
|
44874
|
+
return {
|
|
44875
|
+
ok: false,
|
|
44876
|
+
error: lookupFailed(
|
|
44877
|
+
"leverageYield",
|
|
44878
|
+
action,
|
|
44879
|
+
new Error("leverageYield.positionFactory is not configured; supply the deployed factory address")
|
|
44880
|
+
)
|
|
44881
|
+
};
|
|
44882
|
+
}
|
|
44883
|
+
return { ok: true, value: factory };
|
|
44884
|
+
}
|
|
44885
|
+
/** Position clones owned by `owner`, in creation order. Empty when the owner has none. */
|
|
44886
|
+
async listPositions(owner) {
|
|
44887
|
+
const factory = this.requireFactory("listPositions");
|
|
44888
|
+
if (!factory.ok) return factory;
|
|
44889
|
+
try {
|
|
44890
|
+
const value = await this.hubProvider.publicClient.readContract({
|
|
44891
|
+
address: factory.value,
|
|
44892
|
+
abi: leveragePositionFactoryAbi,
|
|
44893
|
+
functionName: "positionsOf",
|
|
44894
|
+
args: [owner]
|
|
44895
|
+
});
|
|
44896
|
+
return { ok: true, value };
|
|
44897
|
+
} catch (error) {
|
|
44898
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
44899
|
+
return { ok: false, error: lookupFailed("leverageYield", "listPositions", error) };
|
|
44900
|
+
}
|
|
44901
|
+
}
|
|
44902
|
+
/**
|
|
44903
|
+
* Positions belonging to a user, resolved by their spoke-side address rather than a hub address.
|
|
44904
|
+
*
|
|
44905
|
+
* Positions are owned by the user's hub wallet, so discovery goes through
|
|
44906
|
+
* `getUserHubWalletAddress` — which returns the wallet router for a Sonic user and the
|
|
44907
|
+
* cross-chain wallet for a spoke user, so the same call works on every chain. Prefer this over
|
|
44908
|
+
* `listPositions` in user-facing code; passing a raw EOA finds nothing.
|
|
44909
|
+
*/
|
|
44910
|
+
async listPositionsForUser(srcChainKey, srcAddress) {
|
|
44911
|
+
try {
|
|
44912
|
+
const hubWallet = await this.hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey);
|
|
44913
|
+
return await this.listPositions(hubWallet);
|
|
44914
|
+
} catch (error) {
|
|
44915
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
44916
|
+
return { ok: false, error: lookupFailed("leverageYield", "listPositionsForUser", error, { srcChainKey }) };
|
|
44917
|
+
}
|
|
44918
|
+
}
|
|
44919
|
+
/** Static descriptor of a position — owner, both legs, and the fixed eMode category. */
|
|
44920
|
+
async getPositionInfo(position) {
|
|
44921
|
+
try {
|
|
44922
|
+
const [owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver] = await Promise.all([
|
|
44923
|
+
this.hubProvider.publicClient.readContract({
|
|
44924
|
+
address: position,
|
|
44925
|
+
abi: leveragePositionAbi,
|
|
44926
|
+
functionName: "owner"
|
|
44927
|
+
}),
|
|
44928
|
+
this.hubProvider.publicClient.readContract({
|
|
44929
|
+
address: position,
|
|
44930
|
+
abi: leveragePositionAbi,
|
|
44931
|
+
functionName: "collateral"
|
|
44932
|
+
}),
|
|
44933
|
+
this.hubProvider.publicClient.readContract({
|
|
44934
|
+
address: position,
|
|
44935
|
+
abi: leveragePositionAbi,
|
|
44936
|
+
functionName: "borrowToken"
|
|
44937
|
+
}),
|
|
44938
|
+
this.hubProvider.publicClient.readContract({
|
|
44939
|
+
address: position,
|
|
44940
|
+
abi: leveragePositionAbi,
|
|
44941
|
+
functionName: "eModeCategory"
|
|
44942
|
+
}),
|
|
44943
|
+
this.hubProvider.publicClient.readContract({
|
|
44944
|
+
address: position,
|
|
44945
|
+
abi: leveragePositionAbi,
|
|
44946
|
+
functionName: "feeBps"
|
|
44947
|
+
}),
|
|
44948
|
+
this.hubProvider.publicClient.readContract({
|
|
44949
|
+
address: position,
|
|
44950
|
+
abi: leveragePositionAbi,
|
|
44951
|
+
functionName: "feeReceiver"
|
|
44952
|
+
})
|
|
44953
|
+
]);
|
|
44954
|
+
return {
|
|
44955
|
+
ok: true,
|
|
44956
|
+
value: {
|
|
44957
|
+
address: position,
|
|
44958
|
+
owner,
|
|
44959
|
+
collateral,
|
|
44960
|
+
borrowToken,
|
|
44961
|
+
eModeCategory,
|
|
44962
|
+
// From the position, not from config: config can change and an open can override it, so
|
|
44963
|
+
// what a NEW position would carry is not what THIS one does.
|
|
44964
|
+
feeBps: Number(feeBps),
|
|
44965
|
+
feeReceiver
|
|
44966
|
+
}
|
|
44967
|
+
};
|
|
44968
|
+
} catch (error) {
|
|
44969
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
44970
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionInfo", error) };
|
|
44971
|
+
}
|
|
44972
|
+
}
|
|
44973
|
+
/**
|
|
44974
|
+
* Live AAVE account snapshot for a position. Read from the pool, not the position: the
|
|
44975
|
+
* position contract keeps no accounting of its own, so collateral, debt and health factor
|
|
44976
|
+
* all come from `getUserAccountData`.
|
|
44977
|
+
*
|
|
44978
|
+
* The pool comes from `moneyMarket.lendingPool` config rather than the position's own
|
|
44979
|
+
* `pool()` getter — same address, one fewer round trip, and it keeps the deployment address
|
|
44980
|
+
* sourced from config like the rest of the SDK.
|
|
44981
|
+
*/
|
|
44982
|
+
async getPositionAccount(position) {
|
|
44983
|
+
try {
|
|
44984
|
+
const [totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor] = await this.hubProvider.publicClient.readContract({
|
|
44985
|
+
address: this.config.sodaxConfig.moneyMarket.lendingPool,
|
|
44986
|
+
abi: poolAbi,
|
|
44987
|
+
functionName: "getUserAccountData",
|
|
44988
|
+
args: [position]
|
|
44989
|
+
});
|
|
44990
|
+
return {
|
|
44991
|
+
ok: true,
|
|
44992
|
+
value: {
|
|
44993
|
+
totalCollateralBase,
|
|
44994
|
+
totalDebtBase,
|
|
44995
|
+
availableBorrowsBase,
|
|
44996
|
+
currentLiquidationThreshold,
|
|
44997
|
+
ltv,
|
|
44998
|
+
healthFactor
|
|
44999
|
+
}
|
|
45000
|
+
};
|
|
45001
|
+
} catch (error) {
|
|
45002
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45003
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionAccount", error) };
|
|
45004
|
+
}
|
|
45005
|
+
}
|
|
45006
|
+
/**
|
|
45007
|
+
* The position's collateral holding, as an exact aToken balance.
|
|
45008
|
+
*
|
|
45009
|
+
* Needed to size a full exit. {@link LeverageYieldService.getPositionAccount} reports collateral
|
|
45010
|
+
* in the oracle's base currency at 8 decimals, which is fine to display but cannot name an amount:
|
|
45011
|
+
* dividing it back out by a price lands near the balance, and a `decreaseLeverage` asking for more
|
|
45012
|
+
* collateral than the position holds does not fail on submission — the hook's `transferFrom`
|
|
45013
|
+
* reverts at fill time, so the intent silently expires instead.
|
|
45014
|
+
*
|
|
45015
|
+
* Safe to act on a slightly stale read: aToken balances only grow, since interest accrues into
|
|
45016
|
+
* them, so a value from a few blocks ago is always still spendable. Selling it leaves interest
|
|
45017
|
+
* dust behind rather than coming up short.
|
|
45018
|
+
*
|
|
45019
|
+
* @param collateral The position's collateral reserve. Read from the position when omitted; pass
|
|
45020
|
+
* it if you already hold a {@link LeveragePosition} to save the round trip.
|
|
45021
|
+
*/
|
|
45022
|
+
async getPositionCollateralBalance(position, collateral) {
|
|
45023
|
+
try {
|
|
45024
|
+
const asset = collateral ?? await this.hubProvider.publicClient.readContract({
|
|
45025
|
+
address: position,
|
|
45026
|
+
abi: leveragePositionAbi,
|
|
45027
|
+
functionName: "collateral"
|
|
45028
|
+
});
|
|
45029
|
+
const reserve = await this.hubProvider.publicClient.readContract({
|
|
45030
|
+
address: this.config.sodaxConfig.moneyMarket.lendingPool,
|
|
45031
|
+
abi: poolAbi,
|
|
45032
|
+
functionName: "getReserveData",
|
|
45033
|
+
args: [asset]
|
|
45034
|
+
});
|
|
45035
|
+
const aToken = reserve.aTokenAddress;
|
|
45036
|
+
const balance = await this.hubProvider.publicClient.readContract({
|
|
45037
|
+
address: aToken,
|
|
45038
|
+
abi: erc20Abi$1,
|
|
45039
|
+
functionName: "balanceOf",
|
|
45040
|
+
args: [position]
|
|
45041
|
+
});
|
|
45042
|
+
return { ok: true, value: { aToken, balance } };
|
|
45043
|
+
} catch (error) {
|
|
45044
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45045
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionCollateralBalance", error) };
|
|
45046
|
+
}
|
|
45047
|
+
}
|
|
45048
|
+
/**
|
|
45049
|
+
* The position's operation slot: which operation it recorded, and whether that intent is still
|
|
45050
|
+
* live on `Intents`.
|
|
45051
|
+
*
|
|
45052
|
+
* Both are needed, because the interesting state is when they disagree. `isLive` false with a
|
|
45053
|
+
* non-zero `kind` means the intent resolved — filled, expired, or cancelled by someone else — but
|
|
45054
|
+
* the position has not been told, so its grant is still open and any debt-side contribution is
|
|
45055
|
+
* still sitting there. That is what `needsSettle` flags, and `buildSettlePosition` clears. A live
|
|
45056
|
+
* intent instead blocks any second operation until it resolves.
|
|
45057
|
+
*/
|
|
45058
|
+
async getPositionPendingState(position) {
|
|
45059
|
+
try {
|
|
45060
|
+
const [isLive, kind] = await Promise.all([
|
|
45061
|
+
this.hubProvider.publicClient.readContract({
|
|
45062
|
+
address: position,
|
|
45063
|
+
abi: leveragePositionAbi,
|
|
45064
|
+
functionName: "hasPendingOperation"
|
|
45065
|
+
}),
|
|
45066
|
+
this.hubProvider.publicClient.readContract({
|
|
45067
|
+
address: position,
|
|
45068
|
+
abi: leveragePositionAbi,
|
|
45069
|
+
functionName: "pendingKind"
|
|
45070
|
+
})
|
|
45071
|
+
]);
|
|
45072
|
+
return { ok: true, value: { kind, isLive, needsSettle: kind !== 0 && !isLive } };
|
|
45073
|
+
} catch (error) {
|
|
45074
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45075
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionPendingState", error) };
|
|
45076
|
+
}
|
|
45077
|
+
}
|
|
45078
|
+
/** Deterministic clone address for the next position a given creator opens for `owner`. */
|
|
45079
|
+
async predictPosition(creator, owner, positionId) {
|
|
45080
|
+
const factory = this.requireFactory("predictPosition");
|
|
45081
|
+
if (!factory.ok) return factory;
|
|
45082
|
+
try {
|
|
45083
|
+
const id = positionId ?? await this.hubProvider.publicClient.readContract({
|
|
45084
|
+
address: factory.value,
|
|
45085
|
+
abi: leveragePositionFactoryAbi,
|
|
45086
|
+
functionName: "nextPositionIdFor",
|
|
45087
|
+
args: [owner]
|
|
45088
|
+
});
|
|
45089
|
+
const value = await this.hubProvider.publicClient.readContract({
|
|
45090
|
+
address: factory.value,
|
|
45091
|
+
abi: leveragePositionFactoryAbi,
|
|
45092
|
+
functionName: "predictPosition",
|
|
45093
|
+
args: [creator, owner, id]
|
|
45094
|
+
});
|
|
45095
|
+
return { ok: true, value };
|
|
45096
|
+
} catch (error) {
|
|
45097
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45098
|
+
return { ok: false, error: lookupFailed("leverageYield", "predictPosition", error) };
|
|
45099
|
+
}
|
|
45100
|
+
}
|
|
45101
|
+
// ─── Position transaction builders ─────────────────────────────────────
|
|
45102
|
+
//
|
|
45103
|
+
// Positions are driven by direct Sonic calls, not intents, so these return raw transactions
|
|
45104
|
+
// for the caller to sign with a hub wallet provider. The leverage and deleverage calls only
|
|
45105
|
+
// *post* an intent — a solver fills it afterwards, so poll `getPositionPendingState`
|
|
45106
|
+
// rather than treating the receipt as completion.
|
|
45107
|
+
/**
|
|
45108
|
+
* Opens a new position and requests leverage on it in the same transaction — the standard way
|
|
45109
|
+
* to open a leveraged position: one approve, then this.
|
|
45110
|
+
*
|
|
45111
|
+
* `initialAssets` of `collateral` is pulled from the signer, so the factory needs an allowance
|
|
45112
|
+
* first. Control is assigned to `owner`, which may differ from the signer — pass a user's hub
|
|
45113
|
+
* wallet address to have the existing cross-chain path drive the position.
|
|
45114
|
+
*
|
|
45115
|
+
* The leverage is still asynchronous: this posts the intent and a solver fills it afterwards,
|
|
45116
|
+
* so on confirmation the position is funded with the request outstanding, not yet levered. If
|
|
45117
|
+
* no solver fills it, `buildCancelPositionOperation` returns the deposit to the owner.
|
|
45118
|
+
*/
|
|
45119
|
+
/**
|
|
45120
|
+
* Turns a {@link PositionOrigin} into the tuple the factory takes, and refuses the combinations the
|
|
45121
|
+
* contract would refuse anyway — better a rejected build than a transaction that reverts.
|
|
45122
|
+
*/
|
|
45123
|
+
resolveOrigin(origin, method) {
|
|
45124
|
+
const chainId = getIntentRelayChainId(origin.chainKey);
|
|
45125
|
+
if (chainId === void 0) {
|
|
45126
|
+
return {
|
|
45127
|
+
ok: false,
|
|
45128
|
+
error: lookupFailed(
|
|
45129
|
+
"leverageYield",
|
|
45130
|
+
method,
|
|
45131
|
+
new Error(`no relay chain id for origin chain ${origin.chainKey}`)
|
|
45132
|
+
)
|
|
45133
|
+
};
|
|
45134
|
+
}
|
|
45135
|
+
const isHub = origin.chainKey === this.hubProvider.chainConfig.chain.key;
|
|
45136
|
+
if (!isHub && !origin.asset) {
|
|
45137
|
+
return {
|
|
45138
|
+
ok: false,
|
|
45139
|
+
error: lookupFailed(
|
|
45140
|
+
"leverageYield",
|
|
45141
|
+
method,
|
|
45142
|
+
new Error(`origin.asset is required for a refund to ${origin.chainKey}`)
|
|
45143
|
+
)
|
|
45144
|
+
};
|
|
45145
|
+
}
|
|
45146
|
+
return {
|
|
45147
|
+
ok: true,
|
|
45148
|
+
value: {
|
|
45149
|
+
chainId,
|
|
45150
|
+
// The chain's own encoding, not a 0x-prefixed string. `originAddress` is `bytes` on-chain and
|
|
45151
|
+
// is handed to the AssetManager as the refund destination, so a Solana or Stellar address has
|
|
45152
|
+
// to arrive in the form that chain's spoke expects — prefixing `0x` would produce a refund
|
|
45153
|
+
// address that is merely well-formed hex. EVM addresses pass through unchanged.
|
|
45154
|
+
address: encodeAddress(origin.chainKey, origin.address),
|
|
45155
|
+
// Named on the hub as well, not just off it. The asset decides what a cancellation pays back,
|
|
45156
|
+
// and zeroing it here is why someone who funded with USSD was refunded `sodaUSSD`. Callers pass
|
|
45157
|
+
// the asset only when a wrap actually happened — when the reserve IS what was deposited there is
|
|
45158
|
+
// nothing to unwrap and `address(0)` is the correct answer.
|
|
45159
|
+
asset: origin.asset ?? zeroAddress
|
|
45160
|
+
}
|
|
45161
|
+
};
|
|
45162
|
+
}
|
|
45163
|
+
/**
|
|
45164
|
+
* Partner fee for a position, in the shape `PositionConfig` takes.
|
|
45165
|
+
*
|
|
45166
|
+
* Only the PERCENTAGE variant of `PartnerFee` maps: the contract stores basis points and derives
|
|
45167
|
+
* the amount per operation (`_feeFor`), so a fixed-amount fee has nowhere to go and is rejected
|
|
45168
|
+
* rather than silently dropped. Same precedence as the vault flows — per-call, then
|
|
45169
|
+
* `leverageYield.partnerFee`, then none.
|
|
45170
|
+
*
|
|
45171
|
+
* The fee is FIXED AT CREATION on-chain, so this is read when a position is created and never
|
|
45172
|
+
* again; changing the config later does not re-price positions already open.
|
|
45173
|
+
*/
|
|
45174
|
+
/**
|
|
45175
|
+
* The fee a position created NOW would carry, in basis points, plus who receives it.
|
|
45176
|
+
*
|
|
45177
|
+
* Public because a caller cannot project a position correctly without it and cannot derive it:
|
|
45178
|
+
* the fee resolves from `leverageYield.partnerFee`, then the global fee, then none, and it is
|
|
45179
|
+
* FIXED AT CREATION on-chain. Feed `feeBps` to {@link projectLeverageLeg} — the hooks require
|
|
45180
|
+
* `inputAmount + fee`, so a leverage-up borrows the fee ON TOP of what the solver is paid. Leaving
|
|
45181
|
+
* it out understates LTV and overstates the ceiling, which is the Aave `'36'` failure at fill time
|
|
45182
|
+
* this module exists to prevent: 50 bp takes a debt-side ceiling from 9.88x to about 9.44x.
|
|
45183
|
+
*
|
|
45184
|
+
* Pass the same `override` here as to the open call, or omit it on both.
|
|
45185
|
+
*/
|
|
45186
|
+
getEffectivePositionFee(override) {
|
|
45187
|
+
return this.resolvePositionFee(override, "getEffectivePositionFee");
|
|
45188
|
+
}
|
|
45189
|
+
resolvePositionFee(override, method) {
|
|
45190
|
+
const fee = override ?? this.config.leverageYieldPartnerFee;
|
|
45191
|
+
if (!fee) return { ok: true, value: { feeReceiver: zeroAddress, feeBps: 0 } };
|
|
45192
|
+
if (!isPartnerFeePercentage(fee)) {
|
|
45193
|
+
return {
|
|
45194
|
+
ok: false,
|
|
45195
|
+
error: lookupFailed(
|
|
45196
|
+
"leverageYield",
|
|
45197
|
+
method,
|
|
45198
|
+
new Error("a position partner fee must be the percentage variant; PositionConfig stores basis points")
|
|
45199
|
+
)
|
|
45200
|
+
};
|
|
45201
|
+
}
|
|
45202
|
+
if (!Number.isInteger(fee.percentage) || fee.percentage < 0 || fee.percentage > MAX_POSITION_FEE_BPS) {
|
|
45203
|
+
return {
|
|
45204
|
+
ok: false,
|
|
45205
|
+
error: lookupFailed(
|
|
45206
|
+
"leverageYield",
|
|
45207
|
+
method,
|
|
45208
|
+
new Error(
|
|
45209
|
+
`a position partner fee must be a whole number of basis points between 0 and MAX_POSITION_FEE_BPS (${MAX_POSITION_FEE_BPS}) (got ${fee.percentage})`
|
|
45210
|
+
)
|
|
45211
|
+
)
|
|
45212
|
+
};
|
|
45213
|
+
}
|
|
45214
|
+
if (fee.percentage === 0 !== isAddressEqual(fee.address, zeroAddress)) {
|
|
45215
|
+
return {
|
|
45216
|
+
ok: false,
|
|
45217
|
+
error: lookupFailed(
|
|
45218
|
+
"leverageYield",
|
|
45219
|
+
method,
|
|
45220
|
+
new Error(
|
|
45221
|
+
`a position partner fee needs a rate and a receiver together, or neither (got ${fee.percentage} bps for ${fee.address})`
|
|
45222
|
+
)
|
|
45223
|
+
)
|
|
45224
|
+
};
|
|
45225
|
+
}
|
|
45226
|
+
return { ok: true, value: { feeReceiver: fee.address, feeBps: fee.percentage } };
|
|
45227
|
+
}
|
|
45228
|
+
/** A hub transaction. Every builder below produces this shape and none of them sends value. */
|
|
45229
|
+
// Generic so a builder's declared return type applies its own brand. The cast is the single one
|
|
45230
|
+
// the pattern needs — a brand is type-only and erased at runtime — and keeping it here means no
|
|
45231
|
+
// builder carries one of its own.
|
|
45232
|
+
hubTx(from, to, data) {
|
|
45233
|
+
return { from, to, value: 0n, data };
|
|
45234
|
+
}
|
|
45235
|
+
/**
|
|
45236
|
+
* The `PositionConfig` struct both factory entry points take, assembled from a resolved origin.
|
|
45237
|
+
*
|
|
45238
|
+
* Shared so the two create paths cannot drift: which side the funded reserve goes on is their only
|
|
45239
|
+
* real difference, and a field silently spelled differently in one of them would be a
|
|
45240
|
+
* mis-recorded refund destination rather than a compile error.
|
|
45241
|
+
*/
|
|
45242
|
+
positionConfig(args) {
|
|
45243
|
+
return {
|
|
45244
|
+
owner: args.owner,
|
|
45245
|
+
collateral: args.collateral,
|
|
45246
|
+
borrowToken: args.borrowToken,
|
|
45247
|
+
eModeCategory: args.eModeCategory,
|
|
45248
|
+
originChainId: args.origin.chainId,
|
|
45249
|
+
originAddress: args.origin.address,
|
|
45250
|
+
originAsset: args.origin.asset,
|
|
45251
|
+
feeReceiver: args.fee?.feeReceiver ?? zeroAddress,
|
|
45252
|
+
feeBps: args.fee?.feeBps ?? 0
|
|
45253
|
+
};
|
|
45254
|
+
}
|
|
45255
|
+
buildCreatePositionAndLeverage(params) {
|
|
45256
|
+
const method = "buildCreatePositionAndLeverage";
|
|
45257
|
+
const factory = this.requireFactory(method);
|
|
45258
|
+
if (!factory.ok) return factory;
|
|
45259
|
+
const fee = this.resolvePositionFee(params.partnerFee, method);
|
|
45260
|
+
if (!fee.ok) return fee;
|
|
45261
|
+
const origin = this.resolveOrigin(params.origin, method);
|
|
45262
|
+
if (!origin.ok) return origin;
|
|
45263
|
+
return {
|
|
45264
|
+
ok: true,
|
|
45265
|
+
value: this.hubTx(
|
|
45266
|
+
params.from,
|
|
45267
|
+
factory.value,
|
|
45268
|
+
encodeFunctionData({
|
|
45269
|
+
abi: leveragePositionFactoryAbi,
|
|
45270
|
+
functionName: "createPositionAndLeverage",
|
|
45271
|
+
args: [
|
|
45272
|
+
this.positionConfig({ ...params, origin: origin.value, fee: fee.value }),
|
|
45273
|
+
params.initialAssets,
|
|
45274
|
+
params.borrowAmount,
|
|
45275
|
+
params.minCollateralOut
|
|
45276
|
+
]
|
|
45277
|
+
})
|
|
45278
|
+
)
|
|
45279
|
+
};
|
|
45280
|
+
}
|
|
45281
|
+
/**
|
|
45282
|
+
* Opens a levered position starting from the **debt** token, with no collateral of your own.
|
|
45283
|
+
*
|
|
45284
|
+
* Pulls `contribution` of `borrowToken` from the signer — not the collateral. On fill the hook
|
|
45285
|
+
* supplies the solver's collateral, adds the contribution, borrows `totalInput - contribution`,
|
|
45286
|
+
* and pays the solver the total, so a holder of the debt asset lands in a levered collateral
|
|
45287
|
+
* position having never owned collateral. Requires the deployment's implementation to have a
|
|
45288
|
+
* debt-side hook configured; otherwise the position reverts with `DebtSideHookUnavailable`.
|
|
45289
|
+
*/
|
|
45290
|
+
buildCreatePositionFromDebtToken(params) {
|
|
45291
|
+
const method = "buildCreatePositionFromDebtToken";
|
|
45292
|
+
const factory = this.requireFactory(method);
|
|
45293
|
+
if (!factory.ok) return factory;
|
|
45294
|
+
const fee = this.resolvePositionFee(params.partnerFee, method);
|
|
45295
|
+
if (!fee.ok) return fee;
|
|
45296
|
+
const origin = this.resolveOrigin(params.origin, method);
|
|
45297
|
+
if (!origin.ok) return origin;
|
|
45298
|
+
return {
|
|
45299
|
+
ok: true,
|
|
45300
|
+
value: this.hubTx(
|
|
45301
|
+
params.from,
|
|
45302
|
+
factory.value,
|
|
45303
|
+
encodeFunctionData({
|
|
45304
|
+
abi: leveragePositionFactoryAbi,
|
|
45305
|
+
functionName: "createPositionFromDebtToken",
|
|
45306
|
+
args: [
|
|
45307
|
+
this.positionConfig({ ...params, origin: origin.value, fee: fee.value }),
|
|
45308
|
+
params.contribution,
|
|
45309
|
+
params.totalInput,
|
|
45310
|
+
params.minCollateralOut
|
|
45311
|
+
]
|
|
45312
|
+
})
|
|
45313
|
+
)
|
|
45314
|
+
};
|
|
45315
|
+
}
|
|
45316
|
+
/** Borrows `borrowAmount` and swaps it into more collateral. `minCollateralOut` is the slippage floor. */
|
|
45317
|
+
buildAddLeverage(params) {
|
|
45318
|
+
return this.hubTx(
|
|
45319
|
+
params.from,
|
|
45320
|
+
params.position,
|
|
45321
|
+
encodeFunctionData({
|
|
45322
|
+
abi: leveragePositionAbi,
|
|
45323
|
+
functionName: "addLeverage",
|
|
45324
|
+
args: [params.borrowAmount, params.minCollateralOut]
|
|
45325
|
+
})
|
|
45326
|
+
);
|
|
45327
|
+
}
|
|
45328
|
+
/**
|
|
45329
|
+
* Gives up `collateralIn` of collateral to repay debt. `minDebtOut` is the slippage floor.
|
|
45330
|
+
*
|
|
45331
|
+
* CLOSING INTO THE DEBT TOKEN is this call with the position's collateral balance, less the fee a
|
|
45332
|
+
* non-zero `feeBps` gives up on top of the input (`balance x 10_000 / (10_000 + feeBps)`) — there is
|
|
45333
|
+
* no separate close entry point, because selling everything is the same operation as selling part.
|
|
45334
|
+
* Size it with {@link LeverageYieldService.getPositionCollateralBalance}, never off
|
|
45335
|
+
* `totalCollateralBase`, and quote the full amount so `minDebtOut` reflects what the solver will
|
|
45336
|
+
* actually pay for all of it.
|
|
45337
|
+
*
|
|
45338
|
+
* What that leaves behind is worth knowing. The solver delivers more debt token than is owed, so
|
|
45339
|
+
* the hook repays the debt and hands the surplus to the position, which is the owner's equity now
|
|
45340
|
+
* denominated in the debt asset. It sits in the position until someone calls
|
|
45341
|
+
* {@link LeverageYieldService.buildSettlePosition} — that sweep is what actually delivers it, and
|
|
45342
|
+
* it goes to the position's `owner` (the hub wallet), not to whoever signed. Exiting into the
|
|
45343
|
+
* *collateral* instead means repaying only the debt and then calling
|
|
45344
|
+
* {@link LeverageYieldService.buildPositionWithdraw}, which can pay out to any address.
|
|
45345
|
+
*/
|
|
45346
|
+
buildDecreaseLeverage(params) {
|
|
45347
|
+
return this.hubTx(
|
|
45348
|
+
params.from,
|
|
45349
|
+
params.position,
|
|
45350
|
+
encodeFunctionData({
|
|
45351
|
+
abi: leveragePositionAbi,
|
|
45352
|
+
functionName: "decreaseLeverage",
|
|
45353
|
+
args: [params.collateralIn, params.minDebtOut, params.exitAsset ?? zeroAddress]
|
|
45354
|
+
})
|
|
45355
|
+
);
|
|
45356
|
+
}
|
|
45357
|
+
/**
|
|
45358
|
+
* Withdraws collateral out of the position. The pool rejects a withdrawal that would drop
|
|
45359
|
+
* the position below its liquidation threshold, so no client-side health check is applied
|
|
45360
|
+
* here — but note that bound is health factor 1, not a safety buffer above it.
|
|
45361
|
+
*/
|
|
45362
|
+
buildPositionWithdraw(params) {
|
|
45363
|
+
return this.hubTx(
|
|
45364
|
+
params.from,
|
|
45365
|
+
params.position,
|
|
45366
|
+
encodeFunctionData({
|
|
45367
|
+
abi: leveragePositionAbi,
|
|
45368
|
+
functionName: "withdraw",
|
|
45369
|
+
args: [params.amount, params.to]
|
|
45370
|
+
})
|
|
45371
|
+
);
|
|
45372
|
+
}
|
|
45373
|
+
/**
|
|
45374
|
+
* Clears an operation that has already resolved and returns anything the position is holding
|
|
45375
|
+
* loose to its owner.
|
|
45376
|
+
*
|
|
45377
|
+
* PERMISSIONLESS, and deliberately so: it only ever tightens state, so a stranded balance can be
|
|
45378
|
+
* pushed back by anyone rather than waiting on the owner to notice. That matters because an intent
|
|
45379
|
+
* can be cancelled by a third party once past its deadline, which leaves the position resolved but
|
|
45380
|
+
* un-swept if the hook's notification did not land.
|
|
45381
|
+
*
|
|
45382
|
+
* Reverts while the intent is still live — use {@link LeverageYieldService.buildCancelPositionOperation}
|
|
45383
|
+
* to end one that has not resolved yet.
|
|
45384
|
+
*/
|
|
45385
|
+
buildSettlePosition(params) {
|
|
45386
|
+
return this.hubTx(
|
|
45387
|
+
params.from,
|
|
45388
|
+
params.position,
|
|
45389
|
+
encodeFunctionData({ abi: leveragePositionAbi, functionName: "settle" })
|
|
45390
|
+
);
|
|
45391
|
+
}
|
|
45392
|
+
/**
|
|
45393
|
+
* Cancels the in-flight operation and returns the deposit.
|
|
45394
|
+
*
|
|
45395
|
+
* Nothing is escrowed when an intent is posted, so cancelling recovers nothing by itself — but
|
|
45396
|
+
* a position carrying no debt withdraws its whole collateral balance back to the owner, which
|
|
45397
|
+
* is what a leveraged open whose intent never filled needs. With debt outstanding the
|
|
45398
|
+
* collateral stays put: the pool would reject the withdrawal on its health-factor check.
|
|
45399
|
+
*/
|
|
45400
|
+
buildCancelPositionOperation(params) {
|
|
45401
|
+
return this.hubTx(
|
|
45402
|
+
params.from,
|
|
45403
|
+
params.position,
|
|
45404
|
+
encodeFunctionData({ abi: leveragePositionAbi, functionName: "cancel" })
|
|
45405
|
+
);
|
|
45406
|
+
}
|
|
45407
|
+
// ─── Positions from any chain ──────────────────────────────────────────
|
|
45408
|
+
//
|
|
45409
|
+
// The builders above produce a transaction sent straight to the hub. That only works for a user
|
|
45410
|
+
// signing on the hub, and even there it has to be routed so `msg.sender` is their hub wallet —
|
|
45411
|
+
// a position's `onlyOwner` is that wallet, and an EOA cannot send as another address.
|
|
45412
|
+
//
|
|
45413
|
+
// These take over from there: the calls are encoded as a hub-wallet payload and carried by the
|
|
45414
|
+
// spoke transport, which routes them locally on the hub and relays them from anywhere else. So one
|
|
45415
|
+
// code path covers every chain, and the hub is not a special case.
|
|
45416
|
+
/**
|
|
45417
|
+
* Encodes position calls as a hub-wallet payload.
|
|
45418
|
+
*
|
|
45419
|
+
* Takes the raw transactions from the builders above and produces the `(address,uint256,bytes)[]`
|
|
45420
|
+
* payload the hub wallet executes. Public because that payload is the unit the transport takes:
|
|
45421
|
+
* pass it to `spoke.deposit` / `spoke.sendMessage` yourself when you want manual relay control,
|
|
45422
|
+
* or use {@link LeverageYieldService.openPosition} / {@link LeverageYieldService.operatePosition},
|
|
45423
|
+
* which do it for you.
|
|
45424
|
+
*/
|
|
45425
|
+
encodePositionCalls(txs) {
|
|
45426
|
+
return encodeContractCalls(
|
|
45427
|
+
txs.map((tx) => ({ address: tx.to, value: tx.value ?? 0n, data: tx.data }))
|
|
45428
|
+
);
|
|
45429
|
+
}
|
|
45430
|
+
/**
|
|
45431
|
+
* Resolves the hub reserve a spoke token funds, and the hub asset it arrives as.
|
|
45432
|
+
*
|
|
45433
|
+
* Three addresses per token and they are not interchangeable: `hubAsset` is what lands in the hub
|
|
45434
|
+
* wallet, `vault` is the 18-decimal money-market reserve a position actually uses, and the spoke
|
|
45435
|
+
* `address` is neither. Getting this wrong is silent — the wrong one is still a valid ERC-20.
|
|
45436
|
+
*/
|
|
45437
|
+
resolveFunding(srcChainKey, token, method) {
|
|
45438
|
+
const spokeToken = this.config.getSpokeTokenFromOriginalAssetAddress(srcChainKey, token) ?? this.config.getXTokenFromHubAsset(token);
|
|
45439
|
+
if (!spokeToken) {
|
|
45440
|
+
return {
|
|
45441
|
+
ok: false,
|
|
45442
|
+
error: lookupFailed(
|
|
45443
|
+
"leverageYield",
|
|
45444
|
+
method,
|
|
45445
|
+
new Error(`no hub asset registered for ${token} on ${srcChainKey}`),
|
|
45446
|
+
{ srcChainKey }
|
|
45447
|
+
)
|
|
45448
|
+
};
|
|
45449
|
+
}
|
|
45450
|
+
return {
|
|
45451
|
+
ok: true,
|
|
45452
|
+
value: {
|
|
45453
|
+
hubAsset: spokeToken.hubAsset,
|
|
45454
|
+
vault: spokeToken.vault,
|
|
45455
|
+
decimals: spokeToken.decimals
|
|
45456
|
+
}
|
|
45457
|
+
};
|
|
45458
|
+
}
|
|
45459
|
+
/**
|
|
45460
|
+
* What a refund should pay back: the asset the user actually funded with, or `undefined` when that IS
|
|
45461
|
+
* the reserve and there is nothing to unwrap.
|
|
45462
|
+
*
|
|
45463
|
+
* A named asset makes `IntentRefund` unwrap before paying, on the hub as well as off it — so someone
|
|
45464
|
+
* who deposited USSD is refunded USSD rather than `sodaUSSD`.
|
|
45465
|
+
*/
|
|
45466
|
+
refundAsset(funding) {
|
|
45467
|
+
return funding.hubAsset.toLowerCase() === funding.vault.toLowerCase() ? void 0 : funding.hubAsset;
|
|
45468
|
+
}
|
|
45469
|
+
/**
|
|
45470
|
+
* Encodes the wrap of an arriving deposit into its money-market reserve, and returns the reserve
|
|
45471
|
+
* amount that produces.
|
|
45472
|
+
*
|
|
45473
|
+
* A hub asset that is already a soda vault token IS the reserve, so nothing is wrapped. Otherwise
|
|
45474
|
+
* the vault mints 18-decimal shares one-for-one with the asset, which is what
|
|
45475
|
+
* `translateIncomingDecimals` computes — the same conversion the asset manager applies to a spoke
|
|
45476
|
+
* deposit, rather than a second implementation of it. A reserve carrying a non-zero deposit fee
|
|
45477
|
+
* would mint fewer shares than this predicts and the factory's pull would revert; both reserves in
|
|
45478
|
+
* use today are fee-free.
|
|
45479
|
+
*/
|
|
45480
|
+
encodeWrapIntoReserve(funding, amount) {
|
|
45481
|
+
if (this.config.isSodaVaultHubAsset(funding.hubAsset)) {
|
|
45482
|
+
return { calls: [], reserveAmount: amount };
|
|
45483
|
+
}
|
|
45484
|
+
return {
|
|
45485
|
+
calls: [
|
|
45486
|
+
Erc20Service.encodeApprove(funding.hubAsset, funding.vault, amount),
|
|
45487
|
+
EvmVaultTokenService.encodeDeposit(funding.vault, funding.hubAsset, amount)
|
|
45488
|
+
],
|
|
45489
|
+
reserveAmount: EvmVaultTokenService.translateIncomingDecimals(funding.decimals, amount)
|
|
45490
|
+
};
|
|
45491
|
+
}
|
|
45492
|
+
/**
|
|
45493
|
+
* Everything both opens do before they diverge: resolve the factory, the funding token's hub asset
|
|
45494
|
+
* and reserve, and the origin to refund to; predict the address the position will be created at;
|
|
45495
|
+
* and encode the wrap plus the transfer that funds it.
|
|
45496
|
+
*
|
|
45497
|
+
* Only the factory call itself differs between the collateral side and the debt side — which side
|
|
45498
|
+
* the funded reserve lands on, and the two amounts — so everything up to that point lives here
|
|
45499
|
+
* once. `calls` is returned ready to be appended to.
|
|
45500
|
+
*/
|
|
45501
|
+
async prepareOpen(params, method) {
|
|
45502
|
+
const factory = this.requireFactory(method);
|
|
45503
|
+
if (!factory.ok) return factory;
|
|
45504
|
+
const fee = this.resolvePositionFee(params.partnerFee, method);
|
|
45505
|
+
if (!fee.ok) return fee;
|
|
45506
|
+
const funding = this.resolveFunding(params.srcChainKey, params.token, method);
|
|
45507
|
+
if (!funding.ok) return funding;
|
|
45508
|
+
const origin = this.resolveOrigin(
|
|
45509
|
+
{ chainKey: params.srcChainKey, address: params.srcAddress, asset: this.refundAsset(funding.value) },
|
|
45510
|
+
method
|
|
45511
|
+
);
|
|
45512
|
+
if (!origin.ok) return origin;
|
|
45513
|
+
const predicted = await this.predictPosition(params.owner, params.owner);
|
|
45514
|
+
if (!predicted.ok) return predicted;
|
|
45515
|
+
const { calls, reserveAmount } = this.encodeWrapIntoReserve(funding.value, params.amount);
|
|
45516
|
+
calls.push(Erc20Service.encodeTransfer(funding.value.vault, predicted.value, reserveAmount));
|
|
45517
|
+
return {
|
|
45518
|
+
ok: true,
|
|
45519
|
+
value: {
|
|
45520
|
+
factory: factory.value,
|
|
45521
|
+
funding: funding.value,
|
|
45522
|
+
calls,
|
|
45523
|
+
reserveAmount,
|
|
45524
|
+
origin: origin.value,
|
|
45525
|
+
fee: fee.value
|
|
45526
|
+
}
|
|
45527
|
+
};
|
|
45528
|
+
}
|
|
45529
|
+
/**
|
|
45530
|
+
* Hub-side payload for opening a position from the collateral side.
|
|
45531
|
+
*
|
|
45532
|
+
* Wrap the arriving deposit into its reserve, TRANSFER it to the address the position will be
|
|
45533
|
+
* created at, create the position and post its leverage intent — one batch, executed by the user's
|
|
45534
|
+
* hub wallet. The position's collateral is the reserve behind `params.token`; `borrowToken` is
|
|
45535
|
+
* borrowed against it.
|
|
45536
|
+
*
|
|
45537
|
+
* Nothing is ever approved to the factory: it holds no allowance and pulls from nobody, so funding
|
|
45538
|
+
* is a transfer to `predictPosition(creator, owner, nextPositionIdFor(owner))` and the clone supplies
|
|
45539
|
+
* whatever it finds. The id is per-owner, so an unrelated user creating a position cannot move the
|
|
45540
|
+
* address out from under this batch — and because the transfer and the create are in the same batch,
|
|
45541
|
+
* a stale prediction reverts both rather than stranding the tokens.
|
|
45542
|
+
*
|
|
45543
|
+
* The owner's OWN concurrent opens are the one thing that can still advance the id between building
|
|
45544
|
+
* this payload and executing it. On the hub that reverts atomically and nothing is lost; funded from
|
|
45545
|
+
* a spoke the deposit has already landed in the user's hub wallet when the batch reverts, and is
|
|
45546
|
+
* recovered with `sodax.recovery` (see RECOVERY.md). Do not open two positions for one owner at once.
|
|
45547
|
+
*
|
|
45548
|
+
* The origin recorded on the position is `srcChainKey` / `srcAddress` / the deposited hub asset,
|
|
45549
|
+
* so a leverage intent that never fills refunds to the user on the chain they funded from — not to
|
|
45550
|
+
* the position, and not to the hub wallet.
|
|
45551
|
+
*/
|
|
45552
|
+
async buildOpenPositionData(params) {
|
|
45553
|
+
const prep = await this.prepareOpen(params, "buildOpenPositionData");
|
|
45554
|
+
if (!prep.ok) return prep;
|
|
45555
|
+
const { factory, funding, calls, reserveAmount, origin, fee } = prep.value;
|
|
45556
|
+
calls.push({
|
|
45557
|
+
address: factory,
|
|
45558
|
+
value: 0n,
|
|
45559
|
+
data: encodeFunctionData({
|
|
45560
|
+
abi: leveragePositionFactoryAbi,
|
|
45561
|
+
functionName: "createPositionAndLeverage",
|
|
45562
|
+
args: [
|
|
45563
|
+
this.positionConfig({
|
|
45564
|
+
owner: params.owner,
|
|
45565
|
+
collateral: funding.vault,
|
|
45566
|
+
borrowToken: params.borrowToken,
|
|
45567
|
+
eModeCategory: params.eModeCategory ?? 0,
|
|
45568
|
+
origin,
|
|
45569
|
+
fee
|
|
45570
|
+
}),
|
|
45571
|
+
reserveAmount,
|
|
45572
|
+
params.borrowAmount,
|
|
45573
|
+
params.minCollateralOut
|
|
45574
|
+
]
|
|
45575
|
+
})
|
|
45576
|
+
});
|
|
45577
|
+
return { ok: true, value: encodeContractCalls(calls) };
|
|
45578
|
+
}
|
|
45579
|
+
/**
|
|
45580
|
+
* Hub-side payload for opening a position from the debt side.
|
|
45581
|
+
*
|
|
45582
|
+
* The mirror of {@link LeverageYieldService.buildOpenPositionData}: here the deposit is the
|
|
45583
|
+
* position's *debt* token, contributed rather than supplied, and `collateral` is the reserve the
|
|
45584
|
+
* position ends up long. The hook supplies the solver's collateral on fill and borrows only the
|
|
45585
|
+
* shortfall, so the position legitimately starts with no collateral of its own.
|
|
45586
|
+
*/
|
|
45587
|
+
async buildOpenPositionFromDebtTokenData(params) {
|
|
45588
|
+
const prep = await this.prepareOpen(params, "buildOpenPositionFromDebtTokenData");
|
|
45589
|
+
if (!prep.ok) return prep;
|
|
45590
|
+
const { factory, funding, calls, reserveAmount, origin, fee } = prep.value;
|
|
45591
|
+
calls.push({
|
|
45592
|
+
address: factory,
|
|
45593
|
+
value: 0n,
|
|
45594
|
+
data: encodeFunctionData({
|
|
45595
|
+
abi: leveragePositionFactoryAbi,
|
|
45596
|
+
functionName: "createPositionFromDebtToken",
|
|
45597
|
+
args: [
|
|
45598
|
+
this.positionConfig({
|
|
45599
|
+
owner: params.owner,
|
|
45600
|
+
collateral: params.collateral,
|
|
45601
|
+
// The deposited token IS the debt side, so its reserve is the borrow token.
|
|
45602
|
+
borrowToken: funding.vault,
|
|
45603
|
+
eModeCategory: params.eModeCategory ?? 0,
|
|
45604
|
+
origin,
|
|
45605
|
+
fee
|
|
45606
|
+
}),
|
|
45607
|
+
reserveAmount,
|
|
45608
|
+
params.totalInput,
|
|
45609
|
+
params.minCollateralOut
|
|
45610
|
+
]
|
|
45611
|
+
})
|
|
45612
|
+
});
|
|
45613
|
+
return { ok: true, value: encodeContractCalls(calls) };
|
|
45614
|
+
}
|
|
45615
|
+
/**
|
|
45616
|
+
* Whether the funding token is already approved for an open from `srcChainKey`.
|
|
45617
|
+
*
|
|
45618
|
+
* The spender differs by chain and neither choice is guessable: on the hub the deposit is pulled
|
|
45619
|
+
* by the user's own hub wallet, executing inside the routed batch; on an EVM spoke it is pulled by
|
|
45620
|
+
* that spoke's asset manager. Chains with no allowance concept report `true`, and Stellar reports
|
|
45621
|
+
* whether the trustline covers the amount.
|
|
45622
|
+
*/
|
|
45623
|
+
async isPositionFundingAllowanceValid(params) {
|
|
45624
|
+
const baseCtx = { srcChainKey: params.srcChainKey, action: "allowanceCheck" };
|
|
45625
|
+
try {
|
|
45626
|
+
leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
|
|
45627
|
+
const srcChainKey = params.srcChainKey;
|
|
45628
|
+
const inner = isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey) ? await this.spoke.isAllowanceValid({
|
|
45629
|
+
srcChainKey,
|
|
45630
|
+
token: params.token,
|
|
45631
|
+
amount: params.amount,
|
|
45632
|
+
owner: params.srcAddress,
|
|
45633
|
+
spender: await this.resolveFundingSpender(srcChainKey, params.srcAddress)
|
|
45634
|
+
}) : await this.spoke.isAllowanceValid({
|
|
45635
|
+
srcChainKey,
|
|
45636
|
+
token: params.token,
|
|
45637
|
+
amount: params.amount,
|
|
45638
|
+
owner: params.srcAddress
|
|
45639
|
+
});
|
|
45640
|
+
if (inner.ok) return inner;
|
|
45641
|
+
return { ok: false, error: allowanceCheckFailed("leverageYield", inner.error, baseCtx) };
|
|
45642
|
+
} catch (error) {
|
|
45643
|
+
if (isLeverageYieldAllowanceCheckError(error)) return { ok: false, error };
|
|
45644
|
+
return { ok: false, error: allowanceCheckFailed("leverageYield", error, baseCtx) };
|
|
45645
|
+
}
|
|
45646
|
+
}
|
|
45647
|
+
/**
|
|
45648
|
+
* Approves the funding token for an open, against the spender that chain's deposit actually uses —
|
|
45649
|
+
* see {@link LeverageYieldService.isPositionFundingAllowanceValid} for which that is.
|
|
45650
|
+
*
|
|
45651
|
+
* WAITS FOR THE APPROVAL TO LAND before returning. `Erc20Service.approve` resolves with the hash the
|
|
45652
|
+
* moment it is broadcast, so a caller that immediately re-reads the allowance sees the value from
|
|
45653
|
+
* BEFORE the approval — a UI then keeps showing "approve" and the user signs a second, pointless
|
|
45654
|
+
* approval. Returning early from a helper whose whole purpose is "the allowance is now sufficient" is
|
|
45655
|
+
* a footgun, so the wait lives here rather than in each caller.
|
|
45656
|
+
*/
|
|
45657
|
+
async approvePositionFunding(params) {
|
|
45658
|
+
const baseCtx = { srcChainKey: params.srcChainKey, action: "approve" };
|
|
45659
|
+
try {
|
|
45660
|
+
leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
|
|
45661
|
+
const srcChainKey = params.srcChainKey;
|
|
45662
|
+
let inner = {
|
|
45663
|
+
ok: false,
|
|
45664
|
+
error: new Error(`[LeverageYieldService.approvePositionFunding] approve is unsupported on ${srcChainKey}`)
|
|
45665
|
+
};
|
|
45666
|
+
if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
|
|
45667
|
+
leverageYieldInvariant(isAddress(params.token), "Invalid token address", { ...baseCtx, field: "token" });
|
|
45668
|
+
inner = await this.spoke.approve({
|
|
45669
|
+
srcChainKey,
|
|
45670
|
+
token: params.token,
|
|
45671
|
+
amount: params.amount,
|
|
45672
|
+
owner: params.srcAddress,
|
|
45673
|
+
spender: await this.resolveFundingSpender(srcChainKey, params.srcAddress),
|
|
45674
|
+
raw: false,
|
|
45675
|
+
// `K` stays open here, so the provider is only checkable against the chain key inside `spoke.approve`.
|
|
45676
|
+
walletProvider: params.walletProvider
|
|
45677
|
+
});
|
|
45678
|
+
} else if (isStellarChainKeyType(srcChainKey)) {
|
|
45679
|
+
inner = await this.spoke.approve({
|
|
45680
|
+
srcChainKey,
|
|
45681
|
+
token: params.token,
|
|
45682
|
+
amount: params.amount,
|
|
45683
|
+
owner: params.srcAddress,
|
|
45684
|
+
raw: false,
|
|
45685
|
+
walletProvider: params.walletProvider
|
|
45686
|
+
});
|
|
45687
|
+
}
|
|
45688
|
+
if (!inner.ok) return { ok: false, error: approveFailed("leverageYield", inner.error, baseCtx) };
|
|
45689
|
+
if (params.walletProvider && isEvmWalletProviderType(params.walletProvider)) {
|
|
45690
|
+
const receipt = await params.walletProvider.waitForTransactionReceipt(
|
|
45691
|
+
inner.value
|
|
45692
|
+
);
|
|
45693
|
+
if (receipt.status !== "success") {
|
|
45694
|
+
return { ok: false, error: approveFailed("leverageYield", "transaction reverted", baseCtx) };
|
|
45695
|
+
}
|
|
45696
|
+
} else {
|
|
45697
|
+
const landed = await this.spoke.verifyTxHash({ txHash: inner.value, chainKey: params.srcChainKey });
|
|
45698
|
+
if (!landed.ok) return { ok: false, error: approveFailed("leverageYield", landed.error, baseCtx) };
|
|
45699
|
+
}
|
|
45700
|
+
return inner;
|
|
45701
|
+
} catch (error) {
|
|
45702
|
+
if (isLeverageYieldApproveError(error)) return { ok: false, error };
|
|
45703
|
+
return { ok: false, error: approveFailed("leverageYield", error, baseCtx) };
|
|
45704
|
+
}
|
|
45705
|
+
}
|
|
45706
|
+
/**
|
|
45707
|
+
* Who pulls the deposit on an EVM source chain.
|
|
45708
|
+
*
|
|
45709
|
+
* On the hub the pull happens inside the routed batch, so the spender is the user's own hub wallet
|
|
45710
|
+
* rather than any protocol contract; on an EVM spoke it is that spoke's asset manager. Chains with
|
|
45711
|
+
* no ERC-20 allowance never reach here.
|
|
45712
|
+
*/
|
|
45713
|
+
async resolveFundingSpender(srcChainKey, srcAddress) {
|
|
45714
|
+
if (isHubChainKeyType(srcChainKey)) return await this.hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey);
|
|
45715
|
+
return this.config.getChainConfig(srcChainKey).addresses.assetManager;
|
|
45716
|
+
}
|
|
45717
|
+
/**
|
|
45718
|
+
* Opens a leveraged position, funded from any chain, in one signature.
|
|
45719
|
+
*
|
|
45720
|
+
* The deposit is carried to the user's hub wallet and the position is created from inside that
|
|
45721
|
+
* same batch, so there is no window in which the funds sit on the hub unattached to a position.
|
|
45722
|
+
* On the hub this routes locally; from a spoke it relays and this waits for the hub side to land.
|
|
45723
|
+
*
|
|
45724
|
+
* WHAT IS AND IS NOT DONE WHEN THIS RESOLVES: the position exists and its leverage intent is
|
|
45725
|
+
* posted. The leverage itself is not applied — a solver fills that intent afterwards. And an
|
|
45726
|
+
* intent is invisible to the solver until its hub transaction hash is reported, so pass the
|
|
45727
|
+
* returned `dstChainTxHash` to {@link LeverageYieldService.notifySolver}; an unreported intent
|
|
45728
|
+
* simply expires and the deposit comes back.
|
|
45729
|
+
*
|
|
45730
|
+
* Spoke tokens need the spoke asset manager approved first, the same as any other deposit.
|
|
45731
|
+
*
|
|
45732
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
|
|
45733
|
+
* end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
|
|
45734
|
+
* replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
|
|
45735
|
+
* delivering the underlying back to the spoke it came from — has never run on mainnet.
|
|
45736
|
+
* Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
|
|
45737
|
+
* outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
|
|
45738
|
+
*/
|
|
45739
|
+
async openPosition(_params) {
|
|
45740
|
+
return this.runPositionOpen(
|
|
45741
|
+
_params,
|
|
45742
|
+
"openPosition",
|
|
45743
|
+
(owner, params) => this.buildOpenPositionData({ ...params, owner })
|
|
45744
|
+
);
|
|
45745
|
+
}
|
|
45746
|
+
/**
|
|
45747
|
+
* Opens a leveraged position from the **debt** token, funded from any chain.
|
|
45748
|
+
*
|
|
45749
|
+
* Same transport and the same asynchronous settlement as
|
|
45750
|
+
* {@link LeverageYieldService.openPosition} — see there for what is and is not done when this
|
|
45751
|
+
* resolves. The difference is only which side the user funds: here they hand over debt token and
|
|
45752
|
+
* end up long collateral they never held.
|
|
45753
|
+
*
|
|
45754
|
+
* Requires the deployed implementation to have a debt-side hook configured; without one the
|
|
45755
|
+
* position reverts `DebtSideHookUnavailable`.
|
|
45756
|
+
*
|
|
45757
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
|
|
45758
|
+
* end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
|
|
45759
|
+
* replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
|
|
45760
|
+
* delivering the underlying back to the spoke it came from — has never run on mainnet.
|
|
45761
|
+
* Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
|
|
45762
|
+
* outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
|
|
45763
|
+
*/
|
|
45764
|
+
async openPositionFromDebtToken(_params) {
|
|
45765
|
+
return this.runPositionOpen(
|
|
45766
|
+
_params,
|
|
45767
|
+
"openPositionFromDebtToken",
|
|
45768
|
+
(owner, params) => this.buildOpenPositionFromDebtTokenData({ ...params, owner })
|
|
45769
|
+
);
|
|
45770
|
+
}
|
|
45771
|
+
/**
|
|
45772
|
+
* Shared body of the two open paths. They differ only in which factory call the payload ends with,
|
|
45773
|
+
* so everything around it — owner resolution, deposit, verify, relay — lives here rather than
|
|
45774
|
+
* being written twice and drifting.
|
|
45775
|
+
*/
|
|
45776
|
+
/**
|
|
45777
|
+
* Instrumentation for both opens. Wrapping the shared runner rather than each entry point keeps
|
|
45778
|
+
* `openPosition` and `openPositionFromDebtToken` from drifting, and `action` is already threaded
|
|
45779
|
+
* through for the error context, so it doubles as the analytics action.
|
|
45780
|
+
*
|
|
45781
|
+
* `start` carries only the fields common to both param shapes — the funding side's token and
|
|
45782
|
+
* amount. The side-specific ones (`borrowToken`/`borrowAmount` vs `collateral`/`totalInput`) are
|
|
45783
|
+
* not on `PositionFundingParams`, and inventing a cast to reach them would be worse than omitting
|
|
45784
|
+
* them.
|
|
45785
|
+
*/
|
|
45786
|
+
async runPositionOpen(_params, action, build) {
|
|
45787
|
+
return this.config.analytics.trackResult(
|
|
45788
|
+
"leverageYield",
|
|
45789
|
+
action,
|
|
45790
|
+
() => this.executePositionOpen(_params, action, build),
|
|
45791
|
+
{
|
|
45792
|
+
start: () => ({
|
|
45793
|
+
srcChainKey: _params.params.srcChainKey,
|
|
45794
|
+
srcAddress: _params.params.srcAddress,
|
|
45795
|
+
inputToken: _params.params.token,
|
|
45796
|
+
inputAmount: _params.params.amount,
|
|
45797
|
+
eModeCategory: _params.params.eModeCategory
|
|
45798
|
+
}),
|
|
45799
|
+
success: (value) => ({ srcTxHash: value.srcChainTxHash, dstTxHash: value.dstChainTxHash }),
|
|
45800
|
+
failure: (error) => ({ code: error.code })
|
|
45801
|
+
}
|
|
45802
|
+
);
|
|
45803
|
+
}
|
|
45804
|
+
async executePositionOpen(_params, action, buildData) {
|
|
45805
|
+
const { params, timeout = DEFAULT_RELAY_TX_TIMEOUT } = _params;
|
|
45806
|
+
const baseCtx = {
|
|
45807
|
+
srcChainKey: params.srcChainKey,
|
|
45808
|
+
action
|
|
45809
|
+
};
|
|
45810
|
+
try {
|
|
45811
|
+
leverageYieldInvariant(!isBitcoinChainKeyType(params.srcChainKey), BITCOIN_UNSUPPORTED_MESSAGE, {
|
|
45812
|
+
...baseCtx,
|
|
45813
|
+
field: "srcChainKey"
|
|
45814
|
+
});
|
|
45815
|
+
leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
|
|
45816
|
+
leverageYieldInvariant(params.minCollateralOut > 0n, "minCollateralOut must be greater than 0", {
|
|
45817
|
+
...baseCtx,
|
|
45818
|
+
field: "minCollateralOut"
|
|
45819
|
+
});
|
|
45820
|
+
leverageYieldInvariant(
|
|
45821
|
+
isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
|
|
45822
|
+
`Invalid wallet provider for chain key: ${params.srcChainKey}`,
|
|
45823
|
+
{ ...baseCtx, field: "walletProvider" }
|
|
45824
|
+
);
|
|
45825
|
+
const hubWallet = await this.hubProvider.getUserHubWalletAddress(params.srcAddress, params.srcChainKey);
|
|
45826
|
+
const data = await buildData(hubWallet, params);
|
|
45827
|
+
if (!data.ok) return data;
|
|
45828
|
+
const txResult = await this.spoke.deposit({
|
|
45829
|
+
srcChainKey: params.srcChainKey,
|
|
45830
|
+
srcAddress: params.srcAddress,
|
|
45831
|
+
to: hubWallet,
|
|
45832
|
+
token: params.token,
|
|
45833
|
+
amount: params.amount,
|
|
45834
|
+
data: data.value,
|
|
45835
|
+
skipSimulation: _params.skipSimulation ?? false,
|
|
45836
|
+
raw: false,
|
|
45837
|
+
walletProvider: _params.walletProvider
|
|
45838
|
+
});
|
|
45839
|
+
if (!txResult.ok) {
|
|
45840
|
+
if (isLeverageYieldCreateIntentError(txResult.error)) return { ok: false, error: txResult.error };
|
|
45841
|
+
return { ok: false, error: intentCreationFailed("leverageYield", txResult.error, baseCtx) };
|
|
45842
|
+
}
|
|
45843
|
+
return await this.settleHubWalletMessage(txResult.value, { address: hubWallet, payload: data.value }, baseCtx, {
|
|
45844
|
+
timeout
|
|
45845
|
+
});
|
|
45846
|
+
} catch (error) {
|
|
45847
|
+
if (isLeverageYieldSwapError(error)) return { ok: false, error };
|
|
45848
|
+
return { ok: false, error: executionFailed("leverageYield", error, { ...baseCtx, phase: "intentCreation" }) };
|
|
45849
|
+
}
|
|
45850
|
+
}
|
|
45851
|
+
/**
|
|
45852
|
+
* Which address actually funds a position from `chainKey` — what a balance must be read against,
|
|
45853
|
+
* and what the deposit is built from.
|
|
45854
|
+
*
|
|
45855
|
+
* ONE ANSWER FOR BOTH, because two answers cost an open on mainnet: the balance was read from the
|
|
45856
|
+
* registry `address` while the deposit rewrote it to `hubAsset`, so for Sonic's native S the form
|
|
45857
|
+
* showed 42 S and the batch then called `wS.transferFrom(user, hubWallet, 5e18)` against a wS
|
|
45858
|
+
* balance of zero. The approval was correct; the revert surfaced as nothing but "External call
|
|
45859
|
+
* failed". Any integrator reading a balance for a position deposit needs this same answer.
|
|
45860
|
+
*
|
|
45861
|
+
* Three addresses hang off a registry entry and they are not interchangeable:
|
|
45862
|
+
*
|
|
45863
|
+
* `address` the spoke-side original; for a bridged entry it can name another chain entirely
|
|
45864
|
+
* `hubAsset` what the user holds ON THE HUB, and the vault's deposit input
|
|
45865
|
+
* `vault` the hub money-market reserve the position ends up in
|
|
45866
|
+
*
|
|
45867
|
+
* Off the hub the answer is always `address` — that is the chain the user is on. On the hub it is
|
|
45868
|
+
* `hubAsset`, EXCEPT for a native entry: `EvmSpokeService.deposit` keys on the chain's own
|
|
45869
|
+
* `nativeToken` to send `msg.value` rather than an ERC-20 `transferFrom`, and the native entry
|
|
45870
|
+
* carries exactly that sentinel as its `address`. Rewriting that to the wrapper asks for a token
|
|
45871
|
+
* the wallet does not hold.
|
|
45872
|
+
*
|
|
45873
|
+
* @returns The funding address, or `undefined` when the token is not supported on `chainKey`.
|
|
45874
|
+
*/
|
|
45875
|
+
resolvePositionFunding(chainKey, token) {
|
|
45876
|
+
const address = resolvePositionFundingAddress(chainKey, this.hubProvider.chainConfig.chain.key, token);
|
|
45877
|
+
return address === "" ? void 0 : address;
|
|
45878
|
+
}
|
|
45879
|
+
/**
|
|
45880
|
+
* Quotes one leg of a position operation: the borrowed side when levering up, the collateral when
|
|
45881
|
+
* levering down or exiting.
|
|
45882
|
+
*
|
|
45883
|
+
* Use this rather than {@link LeverageYieldService.getQuote} for a position. Both hit the same
|
|
45884
|
+
* endpoint, but this one names the hub reserves as the pair the intent actually swaps and quotes
|
|
45885
|
+
* GROSS — see `positionLegQuote.ts` for why either alone gets the floor wrong. Feed `quotedAmount`
|
|
45886
|
+
* to {@link projectLeverageLeg}.
|
|
45887
|
+
*
|
|
45888
|
+
* A refusal is not always a dead pair: {@link isNoRouteRefusal} is also what the solver answers
|
|
45889
|
+
* for a leg that is only too small, and telling the two apart means quoting again at a healthy
|
|
45890
|
+
* notional. That size is priced, so it is the caller's to choose.
|
|
45891
|
+
*/
|
|
45892
|
+
async getPositionLegQuote(params) {
|
|
45893
|
+
const hubChainKey = this.hubProvider.chainConfig.chain.key;
|
|
45894
|
+
const quote = await this.getQuote({
|
|
45895
|
+
token_src: params.inputHubToken,
|
|
45896
|
+
token_src_blockchain_id: hubChainKey,
|
|
45897
|
+
token_dst: params.outputHubToken,
|
|
45898
|
+
token_dst_blockchain_id: hubChainKey,
|
|
45899
|
+
amount: params.amount,
|
|
45900
|
+
quote_type: "exact_input",
|
|
45901
|
+
// Explicit, not omitted: omitting it applies the configured leverage-yield fee.
|
|
45902
|
+
partnerFee: { address: zeroAddress, percentage: 0 }
|
|
45903
|
+
});
|
|
45904
|
+
if (!quote.ok) return quote;
|
|
45905
|
+
return { ok: true, value: { quotedAmount: quote.value.quoted_amount } };
|
|
45906
|
+
}
|
|
45907
|
+
/**
|
|
45908
|
+
* Opens a leveraged position AND reports the intent it posts. Prefer this to
|
|
45909
|
+
* {@link LeverageYieldService.openPosition} / {@link LeverageYieldService.openPositionFromDebtToken}.
|
|
45910
|
+
*
|
|
45911
|
+
* Those two only post the intent. Reporting it is a separate call that must not be skipped — an
|
|
45912
|
+
* unreported intent expires unfilled, so the owner is left funded with leverage that never arrives
|
|
45913
|
+
* and nothing said so. Pairing them here is the difference between an API that works and one that
|
|
45914
|
+
* works only if you read the docs.
|
|
45915
|
+
*
|
|
45916
|
+
* `side` picks which asset funds the open: `'collateral'` supplies the deposit and borrows against
|
|
45917
|
+
* it, `'debt'` hands the deposit to the solver and ends up long collateral never held.
|
|
45918
|
+
*
|
|
45919
|
+
* RESOLVING MEANS THE INTENT IS LIVE, not that the position is open, and a failed notification is
|
|
45920
|
+
* still `ok: true` — see {@link LeveragePositionIntentResult}.
|
|
45921
|
+
*
|
|
45922
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN — see `operatePosition`.
|
|
45923
|
+
*/
|
|
45924
|
+
async openLeveragePosition(_params) {
|
|
45925
|
+
return this.config.analytics.trackResult(
|
|
45926
|
+
"leverageYield",
|
|
45927
|
+
"openLeveragePosition",
|
|
45928
|
+
async () => {
|
|
45929
|
+
const { side, ...rest } = _params;
|
|
45930
|
+
const opened = side === "debt" ? await this.openPositionFromDebtToken(
|
|
45931
|
+
rest
|
|
45932
|
+
) : await this.openPosition(rest);
|
|
45933
|
+
if (!opened.ok) return opened;
|
|
45934
|
+
return { ok: true, value: await reportPositionIntent(this.notifyIntent, opened.value) };
|
|
45935
|
+
},
|
|
45936
|
+
{
|
|
45937
|
+
start: () => ({ srcChainKey: _params.params.srcChainKey, side: _params.side ?? "collateral" }),
|
|
45938
|
+
success: (result) => ({ ...result.txHashes, notified: result.notified }),
|
|
45939
|
+
failure: (error) => ({ code: error.code })
|
|
45940
|
+
}
|
|
45941
|
+
);
|
|
45942
|
+
}
|
|
45943
|
+
/**
|
|
45944
|
+
* Runs position calls that POST A SOLVER INTENT — `addLeverage` and `decreaseLeverage` — and
|
|
45945
|
+
* reports it. Prefer this to {@link LeverageYieldService.operatePosition} for those two.
|
|
45946
|
+
*
|
|
45947
|
+
* USE {@link LeverageYieldService.runLeveragePositionOperation} FOR `withdraw`, `settle` AND
|
|
45948
|
+
* `cancel`. Those are synchronous on the hub and need no notification, and the split is not
|
|
45949
|
+
* cosmetic: sending a leverage change through the route-only path leaves an intent nothing will
|
|
45950
|
+
* fill, and it expires without a word. The other direction is merely noisy.
|
|
45951
|
+
*
|
|
45952
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN — see `operatePosition`.
|
|
45953
|
+
*/
|
|
45954
|
+
async submitLeveragePositionIntent(_params) {
|
|
45955
|
+
return this.config.analytics.trackResult(
|
|
45956
|
+
"leverageYield",
|
|
45957
|
+
"submitLeveragePositionIntent",
|
|
45958
|
+
async () => {
|
|
45959
|
+
const routed = await this.operatePosition(_params);
|
|
45960
|
+
if (!routed.ok) return routed;
|
|
45961
|
+
return { ok: true, value: await reportPositionIntent(this.notifyIntent, routed.value) };
|
|
45962
|
+
},
|
|
45963
|
+
{
|
|
45964
|
+
start: () => ({ srcChainKey: _params.params.srcChainKey, calls: _params.params.calls.length }),
|
|
45965
|
+
success: (result) => ({ ...result.txHashes, notified: result.notified }),
|
|
45966
|
+
failure: (error) => ({ code: error.code })
|
|
45967
|
+
}
|
|
45968
|
+
);
|
|
45969
|
+
}
|
|
45970
|
+
/**
|
|
45971
|
+
* Runs position calls that do NOT post an intent — `withdraw`, `settle` and `cancel` — as the
|
|
45972
|
+
* owning hub wallet. They are synchronous on the hub, so resolving means the work is done.
|
|
45973
|
+
*
|
|
45974
|
+
* Still routed, never sent directly: the position's `onlyOwner` is the hub wallet, so a builder's
|
|
45975
|
+
* transaction sent from the signer reverts `NotOwner`. Use
|
|
45976
|
+
* {@link LeverageYieldService.submitLeveragePositionIntent} for `addLeverage` and
|
|
45977
|
+
* `decreaseLeverage`, which this deliberately does not report.
|
|
45978
|
+
*
|
|
45979
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN, and this path carries the worst of
|
|
45980
|
+
* it: an exit or cancellation delivering the underlying back to the spoke it came from
|
|
45981
|
+
* has never run on mainnet.
|
|
45982
|
+
*/
|
|
45983
|
+
async runLeveragePositionOperation(_params) {
|
|
45984
|
+
return this.operatePosition(_params);
|
|
45985
|
+
}
|
|
45986
|
+
/** Bound once so the notify half can be handed around without losing `this`. */
|
|
45987
|
+
notifyIntent = (request) => this.notifySolver(request);
|
|
45988
|
+
/**
|
|
45989
|
+
* Runs position calls as the user's hub wallet, from any chain.
|
|
45990
|
+
*
|
|
45991
|
+
* The write counterpart to the read hooks: add or decrease leverage, withdraw, settle, cancel. No
|
|
45992
|
+
* funds move, so this is a bare message rather than a deposit — on the hub it routes locally, from
|
|
45993
|
+
* a spoke it relays and this waits for the hub side to land.
|
|
45994
|
+
*
|
|
45995
|
+
* The leverage calls only *post* an intent, so a resolved promise means the intent is live, not
|
|
45996
|
+
* that leverage moved. Report the returned `dstChainTxHash` to
|
|
45997
|
+
* {@link LeverageYieldService.notifySolver} for those two; `withdraw`, `settle` and `cancel` are
|
|
45998
|
+
* synchronous on the hub and need no notification.
|
|
45999
|
+
*
|
|
46000
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
|
|
46001
|
+
* end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
|
|
46002
|
+
* replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
|
|
46003
|
+
* delivering the underlying back to the spoke it came from — has never run on mainnet.
|
|
46004
|
+
* Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
|
|
46005
|
+
* outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
|
|
46006
|
+
*/
|
|
46007
|
+
async operatePosition(_params) {
|
|
46008
|
+
return this.config.analytics.trackResult(
|
|
46009
|
+
"leverageYield",
|
|
46010
|
+
"operatePosition",
|
|
46011
|
+
() => this.executePositionOperation(_params),
|
|
46012
|
+
{
|
|
46013
|
+
// The calls themselves are not emitted — they are arbitrary hub calldata. The count is
|
|
46014
|
+
// enough to tell a batched adjust from a single write.
|
|
46015
|
+
start: () => ({
|
|
46016
|
+
srcChainKey: _params.params.srcChainKey,
|
|
46017
|
+
srcAddress: _params.params.srcAddress,
|
|
46018
|
+
callCount: _params.params.calls.length
|
|
46019
|
+
}),
|
|
46020
|
+
success: (value) => ({ srcTxHash: value.srcChainTxHash, dstTxHash: value.dstChainTxHash }),
|
|
46021
|
+
failure: (error) => ({ code: error.code })
|
|
46022
|
+
}
|
|
46023
|
+
);
|
|
46024
|
+
}
|
|
46025
|
+
async executePositionOperation(_params) {
|
|
46026
|
+
const { params, timeout = DEFAULT_RELAY_TX_TIMEOUT } = _params;
|
|
46027
|
+
const baseCtx = {
|
|
46028
|
+
srcChainKey: params.srcChainKey,
|
|
46029
|
+
action: "operatePosition"
|
|
46030
|
+
};
|
|
46031
|
+
try {
|
|
46032
|
+
leverageYieldInvariant(!isBitcoinChainKeyType(params.srcChainKey), BITCOIN_UNSUPPORTED_MESSAGE, {
|
|
46033
|
+
...baseCtx,
|
|
46034
|
+
field: "srcChainKey"
|
|
46035
|
+
});
|
|
46036
|
+
leverageYieldInvariant(params.calls.length > 0, "at least one call is required", {
|
|
46037
|
+
...baseCtx,
|
|
46038
|
+
field: "calls"
|
|
46039
|
+
});
|
|
46040
|
+
leverageYieldInvariant(
|
|
46041
|
+
isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
|
|
46042
|
+
`Invalid wallet provider for chain key: ${params.srcChainKey}`,
|
|
46043
|
+
{ ...baseCtx, field: "walletProvider" }
|
|
46044
|
+
);
|
|
46045
|
+
const hubWallet = await this.hubProvider.getUserHubWalletAddress(params.srcAddress, params.srcChainKey);
|
|
46046
|
+
const payload = this.encodePositionCalls(params.calls);
|
|
46047
|
+
const txResult = await this.spoke.sendMessage({
|
|
46048
|
+
srcChainKey: params.srcChainKey,
|
|
46049
|
+
srcAddress: params.srcAddress,
|
|
46050
|
+
dstChainKey: HUB_CHAIN_KEY,
|
|
46051
|
+
dstAddress: hubWallet,
|
|
46052
|
+
payload,
|
|
46053
|
+
skipSimulation: _params.skipSimulation ?? false,
|
|
46054
|
+
raw: false,
|
|
46055
|
+
walletProvider: _params.walletProvider
|
|
46056
|
+
});
|
|
46057
|
+
if (!txResult.ok) {
|
|
46058
|
+
if (isLeverageYieldCreateIntentError(txResult.error)) return { ok: false, error: txResult.error };
|
|
46059
|
+
return { ok: false, error: intentCreationFailed("leverageYield", txResult.error, baseCtx) };
|
|
46060
|
+
}
|
|
46061
|
+
return await this.settleHubWalletMessage(txResult.value, { address: hubWallet, payload }, baseCtx, { timeout });
|
|
46062
|
+
} catch (error) {
|
|
46063
|
+
if (isLeverageYieldSwapError(error)) return { ok: false, error };
|
|
46064
|
+
return { ok: false, error: executionFailed("leverageYield", error, { ...baseCtx, phase: "intentCreation" }) };
|
|
46065
|
+
}
|
|
46066
|
+
}
|
|
46067
|
+
/**
|
|
46068
|
+
* Verifies a submitted source transaction and, off the hub, relays it and waits for the hub side.
|
|
46069
|
+
*
|
|
46070
|
+
* Shared by both write paths because the tail is identical whether funds moved or not. The hub
|
|
46071
|
+
* short-circuit is not an optimisation: a hub transaction has already executed the calls, so there
|
|
46072
|
+
* is nothing to relay, and both hashes are the same transaction.
|
|
46073
|
+
*/
|
|
46074
|
+
async settleHubWalletMessage(srcTxHash, relayData, baseCtx, opts) {
|
|
46075
|
+
const verify = await this.spoke.verifyTxHash({ txHash: srcTxHash, chainKey: baseCtx.srcChainKey });
|
|
46076
|
+
if (!verify.ok) return { ok: false, error: verifyFailed("leverageYield", verify.error, baseCtx) };
|
|
46077
|
+
if (isHubChainKeyType(baseCtx.srcChainKey)) {
|
|
46078
|
+
const receipt = await this.hubProvider.publicClient.waitForTransactionReceipt({
|
|
46079
|
+
hash: srcTxHash,
|
|
46080
|
+
timeout: opts.timeout
|
|
46081
|
+
});
|
|
46082
|
+
if (receipt.status !== "success") {
|
|
46083
|
+
return {
|
|
46084
|
+
ok: false,
|
|
46085
|
+
error: verifyFailed("leverageYield", new Error(`hub transaction ${srcTxHash} reverted`), baseCtx)
|
|
46086
|
+
};
|
|
46087
|
+
}
|
|
46088
|
+
return { ok: true, value: { srcChainTxHash: srcTxHash, dstChainTxHash: srcTxHash } };
|
|
46089
|
+
}
|
|
46090
|
+
const packet = await relayTxAndWaitPacket({
|
|
46091
|
+
srcTxHash,
|
|
46092
|
+
data: relayData,
|
|
46093
|
+
chainKey: baseCtx.srcChainKey,
|
|
46094
|
+
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
46095
|
+
timeout: opts.timeout
|
|
46096
|
+
});
|
|
46097
|
+
if (!packet.ok) {
|
|
46098
|
+
return {
|
|
46099
|
+
ok: false,
|
|
46100
|
+
error: mapRelayFailure(packet.error, {
|
|
46101
|
+
feature: "leverageYield",
|
|
46102
|
+
action: baseCtx.action,
|
|
46103
|
+
srcChainKey: baseCtx.srcChainKey
|
|
46104
|
+
})
|
|
46105
|
+
};
|
|
46106
|
+
}
|
|
46107
|
+
return { ok: true, value: { srcChainTxHash: srcTxHash, dstChainTxHash: packet.value.dst_tx_hash } };
|
|
46108
|
+
}
|
|
44856
46109
|
};
|
|
44857
46110
|
|
|
44858
46111
|
// src/sponsoring/errors.ts
|
|
@@ -44880,12 +46133,12 @@ function toDomainCode(value) {
|
|
|
44880
46133
|
}
|
|
44881
46134
|
function readErrorBody(body) {
|
|
44882
46135
|
if (typeof body !== "object" || body === null) return {};
|
|
44883
|
-
const
|
|
44884
|
-
const retryAfterSeconds = typeof
|
|
44885
|
-
const sponsorSequence = typeof
|
|
46136
|
+
const record = body;
|
|
46137
|
+
const retryAfterSeconds = typeof record.retryAfterSeconds === "number" && Number.isFinite(record.retryAfterSeconds) && record.retryAfterSeconds > 0 ? record.retryAfterSeconds : void 0;
|
|
46138
|
+
const sponsorSequence = typeof record.sponsorSequence === "string" && /^\d+$/.test(record.sponsorSequence) ? record.sponsorSequence : void 0;
|
|
44886
46139
|
return {
|
|
44887
|
-
message: typeof
|
|
44888
|
-
code: toDomainCode(
|
|
46140
|
+
message: typeof record.message === "string" ? record.message : void 0,
|
|
46141
|
+
code: toDomainCode(record.error),
|
|
44889
46142
|
retryAfterSeconds,
|
|
44890
46143
|
sponsorSequence
|
|
44891
46144
|
};
|
|
@@ -45541,6 +46794,81 @@ var PARTNER_CODES = /* @__PURE__ */ new Set([
|
|
|
45541
46794
|
"UNKNOWN"
|
|
45542
46795
|
]);
|
|
45543
46796
|
var isPartnerError = isCodeMember(PARTNER_CODES);
|
|
46797
|
+
function sizeLeverageBorrow(request) {
|
|
46798
|
+
const { side, deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd, borrowDecimals, leverage } = request;
|
|
46799
|
+
const depositTokens = Number(formatUnits(deposit, depositDecimals));
|
|
46800
|
+
const depositUsd = depositTokens * (side === "debt" ? borrowPriceUsd : collateralPriceUsd);
|
|
46801
|
+
const RATIO_SCALE = 1000000000n;
|
|
46802
|
+
const ratio = borrowPriceUsd > 0 && depositTokens > 0 ? depositUsd * Math.max(leverage - 1, 0) / borrowPriceUsd / depositTokens : 0;
|
|
46803
|
+
const borrowAmount = deposit * BigInt(Math.floor(ratio * Number(RATIO_SCALE))) * 10n ** BigInt(borrowDecimals) / (RATIO_SCALE * 10n ** BigInt(depositDecimals));
|
|
46804
|
+
const depositInBorrowUnits = deposit * 10n ** BigInt(borrowDecimals) / 10n ** BigInt(depositDecimals);
|
|
46805
|
+
const intentInput = side === "debt" ? borrowAmount + depositInBorrowUnits : borrowAmount;
|
|
46806
|
+
const feeAmount = request.feeBps ? intentInput * BigInt(Math.round(request.feeBps)) / 10000n : 0n;
|
|
46807
|
+
const borrowUsd = Number(formatUnits(borrowAmount, borrowDecimals)) * borrowPriceUsd;
|
|
46808
|
+
const feeUsd = Number(formatUnits(feeAmount, borrowDecimals)) * borrowPriceUsd;
|
|
46809
|
+
return {
|
|
46810
|
+
borrowAmount,
|
|
46811
|
+
intentInput,
|
|
46812
|
+
depositUsd,
|
|
46813
|
+
// Taken from the amount actually being borrowed, so the projection cannot disagree with the
|
|
46814
|
+
// transaction by the rounding above.
|
|
46815
|
+
borrowUsd,
|
|
46816
|
+
feeAmount,
|
|
46817
|
+
// The fee is borrowed on top on a leverage-up, so it is debt even though the solver never sees it.
|
|
46818
|
+
debtUsd: borrowUsd + feeUsd
|
|
46819
|
+
};
|
|
46820
|
+
}
|
|
46821
|
+
function projectLeverageLeg(request, quote, risk, slippagePct) {
|
|
46822
|
+
const { side, collateralPriceUsd, leverage } = request;
|
|
46823
|
+
const sized = sizeLeverageBorrow(request);
|
|
46824
|
+
const { depositUsd, borrowUsd } = sized;
|
|
46825
|
+
const floor = quote.quotedCollateral * BigInt(Math.round((100 - slippagePct) * 100)) / 10000n;
|
|
46826
|
+
const minCollateralOut = floor > 0n ? floor : 1n;
|
|
46827
|
+
const floorUsd = Number(formatUnits(minCollateralOut, quote.collateralDecimals)) * collateralPriceUsd;
|
|
46828
|
+
const quotedUsd = Number(formatUnits(quote.quotedCollateral, quote.collateralDecimals)) * collateralPriceUsd;
|
|
46829
|
+
const inputUsd = side === "debt" ? depositUsd * leverage : borrowUsd;
|
|
46830
|
+
const f = inputUsd > 0 ? floorUsd / inputUsd : 0;
|
|
46831
|
+
const haircut = inputUsd > 0 ? 1 - quotedUsd / inputUsd : 0;
|
|
46832
|
+
const collateralUsd = (side === "debt" ? 0 : depositUsd) + floorUsd;
|
|
46833
|
+
const debtUsd = sized.debtUsd;
|
|
46834
|
+
const ltv = collateralUsd > 0 ? debtUsd / collateralUsd : 0;
|
|
46835
|
+
const ltvF = risk.ltv * f;
|
|
46836
|
+
const phi = (request.feeBps ?? 0) / 1e4;
|
|
46837
|
+
const denominator = 1 + phi - ltvF;
|
|
46838
|
+
const usableMaxLeverage = risk.ltv <= 0 ? 1 : denominator <= 0 ? Number.POSITIVE_INFINITY : side === "debt" ? 1 / denominator : 1 + risk.ltv / denominator;
|
|
46839
|
+
const equityUsd = collateralUsd - debtUsd;
|
|
46840
|
+
return {
|
|
46841
|
+
minCollateralOut,
|
|
46842
|
+
collateralUsd,
|
|
46843
|
+
debtUsd,
|
|
46844
|
+
exposureLeverage: equityUsd > 0 ? collateralUsd / equityUsd : Number.POSITIVE_INFINITY,
|
|
46845
|
+
ltv,
|
|
46846
|
+
healthFactor: debtUsd > 0 ? collateralUsd * risk.liquidationThreshold / debtUsd : Number.POSITIVE_INFINITY,
|
|
46847
|
+
exceedsMaxLtv: ltv > risk.ltv,
|
|
46848
|
+
haircut,
|
|
46849
|
+
inputUsd,
|
|
46850
|
+
costUsd: inputUsd * haircut + sized.debtUsd - borrowUsd,
|
|
46851
|
+
usableMaxLeverage
|
|
46852
|
+
};
|
|
46853
|
+
}
|
|
46854
|
+
|
|
46855
|
+
// src/leverageYield/positionApyMath.ts
|
|
46856
|
+
function leveragedNetApyPct(supplyApyPct, borrowApyPct, leverage) {
|
|
46857
|
+
return supplyApyPct * leverage - borrowApyPct * (leverage - 1);
|
|
46858
|
+
}
|
|
46859
|
+
function timeToBreakevenYears(supplyApyPct, borrowApyPct, toLeverage, { costUsd, equityUsd, fromLeverage }) {
|
|
46860
|
+
if (!(equityUsd > 0) || !Number.isFinite(costUsd)) return void 0;
|
|
46861
|
+
if (costUsd <= 0) return "immediate";
|
|
46862
|
+
const incrementalPct = leveragedNetApyPct(supplyApyPct, borrowApyPct, toLeverage) - leveragedNetApyPct(supplyApyPct, borrowApyPct, fromLeverage);
|
|
46863
|
+
if (!(incrementalPct > 0)) return "never";
|
|
46864
|
+
return costUsd / (equityUsd * (incrementalPct / 100));
|
|
46865
|
+
}
|
|
46866
|
+
|
|
46867
|
+
// src/leverageYield/positionLegQuote.ts
|
|
46868
|
+
function isNoRouteRefusal(error) {
|
|
46869
|
+
const message = typeof error === "object" && error !== null && "detail" in error ? error.detail?.message : error instanceof Error ? error.message : void 0;
|
|
46870
|
+
return /no path was found/i.test(message ?? "");
|
|
46871
|
+
}
|
|
45544
46872
|
/*! Bundled license information:
|
|
45545
46873
|
|
|
45546
46874
|
@noble/hashes/utils.js:
|
|
@@ -45559,4 +46887,4 @@ var isPartnerError = isCodeMember(PARTNER_CODES);
|
|
|
45559
46887
|
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
45560
46888
|
*/
|
|
45561
46889
|
|
|
45562
|
-
export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BACKEND_API_BASE_PATH, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BITCOIN_DUST_SATS, BOUND_API_HOST, BOUND_COMPANION_HOSTS, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BackendHttpError, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeApiService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_API_BASE_URL, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DEFAULT_SPONSORING_API_ENDPOINT, DEPRECATED_BOUND_HOSTS, DETAILED_STATUS_NOT_DELIVERED, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldApiService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, ORACLE_CANDLE_INTERVALS, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RELAY_FALLBACK_FLOOR_MS, RELAY_REQUEST_TIMEOUT_MS, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, SPEED_TIER_SECONDS, SPEED_TIER_THRESHOLDS, SPONSORING_API_ERROR_CODES, SPONSORING_API_STELLAR_BASE_PATH, SPONSOR_CONFIG_TTL_MS, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_BASE_RESERVE_TTL_MS, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, SponsoringApiService, SponsoringService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiGrpcTransport, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, canonicalizeBitcoinAddress, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, classifySponsorError, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createBalanceCollector, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, encodeTokenIdentifier, erc20Abi, erc4626Abi, estimateBitcoinTxSize, estimateSwapSpeedTier, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isApprovalSupportedChainKeyType, isAuthFailure, isAuthStatus, isBackendHttpError, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isFillEvent, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeBitcoinToken, isNativeBitcoinTransfer, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isOracleCandleInterval, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRealWorldAsset, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isSponsoringConfigError, isSponsoringLookupError, isSponsoringOrchestrationError, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidBitcoinAddress, isValidInjectiveAddress, isValidNearAccountId, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, robinhoodChain, robinhoodSupportedTokens, serializeAddressData, settleWalletBalances, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, sponsoringInvariant, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, toCreateBridgeIntentParamsV2, toSuiExecutionResult, toSuiExecutionStatus, toSuiPaginatedCoins, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
|
|
46890
|
+
export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BACKEND_API_BASE_PATH, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BITCOIN_DUST_SATS, BOUND_API_HOST, BOUND_COMPANION_HOSTS, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BackendHttpError, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeApiService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_API_BASE_URL, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DEFAULT_SPONSORING_API_ENDPOINT, DEPRECATED_BOUND_HOSTS, DETAILED_STATUS_NOT_DELIVERED, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldApiService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_POSITION_FEE_BPS, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, ORACLE_CANDLE_INTERVALS, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RELAY_FALLBACK_FLOOR_MS, RELAY_REQUEST_TIMEOUT_MS, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SDK_VERSION, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, SPEED_TIER_SECONDS, SPEED_TIER_THRESHOLDS, SPONSORING_API_ERROR_CODES, SPONSORING_API_STELLAR_BASE_PATH, SPONSOR_CONFIG_TTL_MS, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_BASE_RESERVE_TTL_MS, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, SponsoringApiService, SponsoringService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiGrpcTransport, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, canonicalizeBitcoinAddress, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, classifySponsorError, concentratedLiquidityConfig, configVersionFor, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createBalanceCollector, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, encodeTokenIdentifier, erc20Abi, erc4626Abi, estimateBitcoinTxSize, estimateSwapSpeedTier, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatConfigVersion, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isApprovalSupportedChainKeyType, isAuthFailure, isAuthStatus, isBackendHttpError, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isFillEvent, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeBitcoinToken, isNativeBitcoinTransfer, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isNoRouteRefusal, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isOracleCandleInterval, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRealWorldAsset, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isSponsoringConfigError, isSponsoringLookupError, isSponsoringOrchestrationError, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidBitcoinAddress, isValidInjectiveAddress, isValidNearAccountId, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, leveragedNetApyPct, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseConfigVersion, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, projectLeverageLeg, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, reportPositionIntent, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, resolvePositionFundingAddress, retry, reverseEncodeAddress, robinhoodChain, robinhoodSupportedTokens, serializeAddressData, settleWalletBalances, silentLogger, sizeLeverageBorrow, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, sponsoringInvariant, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, timeToBreakevenYears, toCreateBridgeIntentParamsV2, toSuiExecutionResult, toSuiExecutionStatus, toSuiPaginatedCoins, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
|