@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.cjs
CHANGED
|
@@ -21,6 +21,7 @@ var tx_js = require('cosmjs-types/cosmos/tx/v1beta1/tx.js');
|
|
|
21
21
|
var networks = require('@injectivelabs/networks');
|
|
22
22
|
var v = require('valibot');
|
|
23
23
|
var swapsApi = require('@sodax/swaps-api');
|
|
24
|
+
var bridgeApi = require('@sodax/bridge-api');
|
|
24
25
|
var BigNumber5 = require('bignumber.js');
|
|
25
26
|
var swapSdkCore = require('@pancakeswap/swap-sdk-core');
|
|
26
27
|
var v3Sdk = require('@pancakeswap/v3-sdk');
|
|
@@ -122,8 +123,8 @@ function serializeCause(cause, depth) {
|
|
|
122
123
|
}
|
|
123
124
|
function sanitizeContext(value, depth) {
|
|
124
125
|
const out = {};
|
|
125
|
-
for (const [key,
|
|
126
|
-
out[key] = sanitizeValue(
|
|
126
|
+
for (const [key, v10] of Object.entries(value)) {
|
|
127
|
+
out[key] = sanitizeValue(v10, depth + 1);
|
|
127
128
|
}
|
|
128
129
|
return out;
|
|
129
130
|
}
|
|
@@ -134,13 +135,13 @@ function sanitizeValue(value, depth) {
|
|
|
134
135
|
if (t === "bigint") return value.toString();
|
|
135
136
|
if (t === "string" || t === "number" || t === "boolean") return value;
|
|
136
137
|
if (t === "function" || t === "symbol") return safeString(value);
|
|
137
|
-
if (Array.isArray(value)) return value.map((
|
|
138
|
+
if (Array.isArray(value)) return value.map((v10) => sanitizeValue(v10, depth + 1));
|
|
138
139
|
if (value instanceof Date) return value.toISOString();
|
|
139
140
|
if (value instanceof Map) {
|
|
140
|
-
return Array.from(value.entries()).map(([k,
|
|
141
|
+
return Array.from(value.entries()).map(([k, v10]) => [sanitizeValue(k, depth + 1), sanitizeValue(v10, depth + 1)]);
|
|
141
142
|
}
|
|
142
143
|
if (value instanceof Set) {
|
|
143
|
-
return Array.from(value.values()).map((
|
|
144
|
+
return Array.from(value.values()).map((v10) => sanitizeValue(v10, depth + 1));
|
|
144
145
|
}
|
|
145
146
|
if (value instanceof Error) return { name: value.name, message: value.message };
|
|
146
147
|
if (t === "object") {
|
|
@@ -152,9 +153,9 @@ function sanitizeValue(value, depth) {
|
|
|
152
153
|
}
|
|
153
154
|
return safeString(value);
|
|
154
155
|
}
|
|
155
|
-
function safeString(
|
|
156
|
+
function safeString(v10) {
|
|
156
157
|
try {
|
|
157
|
-
return String(
|
|
158
|
+
return String(v10);
|
|
158
159
|
} catch {
|
|
159
160
|
return "[unserializable]";
|
|
160
161
|
}
|
|
@@ -1552,6 +1553,15 @@ var baseSupportedTokens = {
|
|
|
1552
1553
|
chainKey: ChainKeys.BASE_MAINNET,
|
|
1553
1554
|
hubAsset: "0x348e086ab6f424dfc575a325c28624ed23973173",
|
|
1554
1555
|
vault: "0x348e086ab6f424dfc575a325c28624ed23973173"
|
|
1556
|
+
},
|
|
1557
|
+
sUSDS: {
|
|
1558
|
+
symbol: "sUSDS",
|
|
1559
|
+
name: "staked USDS",
|
|
1560
|
+
decimals: 18,
|
|
1561
|
+
address: "0x5875eEE11Cf8398102FdAd704C9E96607675467a",
|
|
1562
|
+
chainKey: ChainKeys.BASE_MAINNET,
|
|
1563
|
+
hubAsset: "0x807cC73f69F1aCCC50511a0390A8544cEA71baA9",
|
|
1564
|
+
vault: SodaTokens.sodaSUSDS.address
|
|
1555
1565
|
}
|
|
1556
1566
|
};
|
|
1557
1567
|
var optimismSupportedTokens = {
|
|
@@ -1635,6 +1645,15 @@ var optimismSupportedTokens = {
|
|
|
1635
1645
|
chainKey: ChainKeys.OPTIMISM_MAINNET,
|
|
1636
1646
|
hubAsset: "0xd08375176410febee9cf4591532455a4cdfe4463",
|
|
1637
1647
|
vault: "0xd08375176410febee9cf4591532455a4cdfe4463"
|
|
1648
|
+
},
|
|
1649
|
+
sUSDS: {
|
|
1650
|
+
symbol: "sUSDS",
|
|
1651
|
+
name: "staked USDS",
|
|
1652
|
+
decimals: 18,
|
|
1653
|
+
address: "0xb5B2dc7fd34C249F4be7fB1fCea07950784229e0",
|
|
1654
|
+
chainKey: ChainKeys.OPTIMISM_MAINNET,
|
|
1655
|
+
hubAsset: "0xb9a9cb8A61D30a8F6b7E24491ab83f43E817b0E2",
|
|
1656
|
+
vault: SodaTokens.sodaSUSDS.address
|
|
1638
1657
|
}
|
|
1639
1658
|
};
|
|
1640
1659
|
var bscSupportedTokens = {
|
|
@@ -2989,6 +3008,15 @@ var ethereumSupportedTokens = {
|
|
|
2989
3008
|
chainKey: ChainKeys.ETHEREUM_MAINNET,
|
|
2990
3009
|
hubAsset: "0x40bea4f921355a749f460760ba6f8edd78888164",
|
|
2991
3010
|
vault: "0x40bea4f921355a749f460760ba6f8edd78888164"
|
|
3011
|
+
},
|
|
3012
|
+
sUSDS: {
|
|
3013
|
+
symbol: "sUSDS",
|
|
3014
|
+
name: "staked USDS",
|
|
3015
|
+
decimals: 18,
|
|
3016
|
+
address: "0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD",
|
|
3017
|
+
chainKey: ChainKeys.ETHEREUM_MAINNET,
|
|
3018
|
+
hubAsset: "0x1Bb5128A4837A78cb60bc52cc19079eD3F00A624",
|
|
3019
|
+
vault: SodaTokens.sodaSUSDS.address
|
|
2992
3020
|
}
|
|
2993
3021
|
};
|
|
2994
3022
|
var kaiaSupportedTokens = {
|
|
@@ -4597,7 +4625,8 @@ var moneyMarketSupportedTokens = {
|
|
|
4597
4625
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.cbBTC,
|
|
4598
4626
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.SODA,
|
|
4599
4627
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDT,
|
|
4600
|
-
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDS
|
|
4628
|
+
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDS,
|
|
4629
|
+
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.sUSDS
|
|
4601
4630
|
],
|
|
4602
4631
|
[ChainKeys.OPTIMISM_MAINNET]: [
|
|
4603
4632
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.ETH,
|
|
@@ -4606,7 +4635,8 @@ var moneyMarketSupportedTokens = {
|
|
|
4606
4635
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.wstETH,
|
|
4607
4636
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.weETH,
|
|
4608
4637
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDT,
|
|
4609
|
-
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.SODA
|
|
4638
|
+
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.SODA,
|
|
4639
|
+
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.sUSDS
|
|
4610
4640
|
],
|
|
4611
4641
|
[ChainKeys.POLYGON_MAINNET]: [
|
|
4612
4642
|
spokeChainConfig[ChainKeys.POLYGON_MAINNET].supportedTokens.POL,
|
|
@@ -4728,7 +4758,8 @@ var moneyMarketSupportedTokens = {
|
|
|
4728
4758
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.WBTC,
|
|
4729
4759
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.WBTC_LEGACY,
|
|
4730
4760
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.LL,
|
|
4731
|
-
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDS
|
|
4761
|
+
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDS,
|
|
4762
|
+
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.sUSDS
|
|
4732
4763
|
],
|
|
4733
4764
|
[ChainKeys.REDBELLY_MAINNET]: [
|
|
4734
4765
|
spokeChainConfig[ChainKeys.REDBELLY_MAINNET].supportedTokens.bnUSD,
|
|
@@ -4961,9 +4992,10 @@ var swapSupportedTokens = {
|
|
|
4961
4992
|
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USDT,
|
|
4962
4993
|
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.wS,
|
|
4963
4994
|
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.SODA,
|
|
4964
|
-
|
|
4965
|
-
// Swap membership is per-vault, not every SodaTokens entry:
|
|
4966
|
-
//
|
|
4995
|
+
spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USSD,
|
|
4996
|
+
// Swap membership is per-vault, not every SodaTokens entry: sodaUSDS is the one wrapper the
|
|
4997
|
+
// production solver cannot route — a `/quote` against it returns `No path was found`, where
|
|
4998
|
+
// USSD, sodaUSSD and sodaSUSDS all return real prices — so it stays out until a path exists.
|
|
4967
4999
|
SodaTokens.sodaBNB,
|
|
4968
5000
|
SodaTokens.sodaAVAX,
|
|
4969
5001
|
SodaTokens.sodaETH,
|
|
@@ -4988,8 +5020,10 @@ var swapSupportedTokens = {
|
|
|
4988
5020
|
SodaTokens.sodaNEAR,
|
|
4989
5021
|
SodaTokens.sodaKAIA,
|
|
4990
5022
|
SodaTokens.sodaSTX,
|
|
5023
|
+
SodaTokens.sodaSUSDS,
|
|
4991
5024
|
SodaTokens.sodaHBAR,
|
|
4992
5025
|
SodaTokens.sodaJITOSOL,
|
|
5026
|
+
SodaTokens.sodaUSSD,
|
|
4993
5027
|
...Object.values(LsodaTokens),
|
|
4994
5028
|
// Robinhood tokenized equities — swap-only, deliberately absent from the money market.
|
|
4995
5029
|
SodaTokens.SPCX,
|
|
@@ -5023,6 +5057,7 @@ var swapSupportedTokens = {
|
|
|
5023
5057
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.tBTC,
|
|
5024
5058
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.USDC,
|
|
5025
5059
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.USDT,
|
|
5060
|
+
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.sUSDS,
|
|
5026
5061
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.ARB,
|
|
5027
5062
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.AAVE,
|
|
5028
5063
|
spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.LINK,
|
|
@@ -5037,6 +5072,7 @@ var swapSupportedTokens = {
|
|
|
5037
5072
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.ETH,
|
|
5038
5073
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.weETH,
|
|
5039
5074
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDC,
|
|
5075
|
+
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.sUSDS,
|
|
5040
5076
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.wstETH,
|
|
5041
5077
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.cbBTC,
|
|
5042
5078
|
spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.VIRTUAL,
|
|
@@ -5047,6 +5083,7 @@ var swapSupportedTokens = {
|
|
|
5047
5083
|
[ChainKeys.OPTIMISM_MAINNET]: [
|
|
5048
5084
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.ETH,
|
|
5049
5085
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDC,
|
|
5086
|
+
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.sUSDS,
|
|
5050
5087
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.wstETH,
|
|
5051
5088
|
// spokeChainConfig[OPTIMISM_MAINNET_CHAIN_ID].supportedTokens.weETH, // NOTE: Not Implemented
|
|
5052
5089
|
spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDT,
|
|
@@ -5214,6 +5251,7 @@ var swapSupportedTokens = {
|
|
|
5214
5251
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.ETH,
|
|
5215
5252
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.bnUSD,
|
|
5216
5253
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDC,
|
|
5254
|
+
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.sUSDS,
|
|
5217
5255
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDT,
|
|
5218
5256
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.SODA,
|
|
5219
5257
|
spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.LL,
|
|
@@ -5320,7 +5358,7 @@ var swapSupportedTokens = {
|
|
|
5320
5358
|
]
|
|
5321
5359
|
};
|
|
5322
5360
|
var stagingSwapSupportedTokens = {
|
|
5323
|
-
[ChainKeys.SONIC_MAINNET]: [
|
|
5361
|
+
[ChainKeys.SONIC_MAINNET]: [],
|
|
5324
5362
|
[ChainKeys.AVALANCHE_MAINNET]: [],
|
|
5325
5363
|
[ChainKeys.ARBITRUM_MAINNET]: [],
|
|
5326
5364
|
[ChainKeys.BASE_MAINNET]: [
|
|
@@ -5427,7 +5465,8 @@ var leverageYieldVaults = [
|
|
|
5427
5465
|
}
|
|
5428
5466
|
];
|
|
5429
5467
|
var leverageYieldConfig = {
|
|
5430
|
-
vaults: leverageYieldVaults
|
|
5468
|
+
vaults: leverageYieldVaults,
|
|
5469
|
+
positionFactory: "0xF8fB7F200B6545295e1729Cf254482d7c116031C"
|
|
5431
5470
|
};
|
|
5432
5471
|
|
|
5433
5472
|
// ../types/dist/sodax-config/sodax-config.js
|
|
@@ -5660,7 +5699,45 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
5660
5699
|
}
|
|
5661
5700
|
|
|
5662
5701
|
// ../types/dist/index.js
|
|
5663
|
-
var CONFIG_VERSION =
|
|
5702
|
+
var CONFIG_VERSION = 2020006;
|
|
5703
|
+
var RC_STABLE = 99;
|
|
5704
|
+
var MIN_CONFIG_VERSION = 1e6;
|
|
5705
|
+
var MAX_CONFIG_VERSION = 99999999;
|
|
5706
|
+
var VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-rc\.(0|[1-9]\d*))?$/;
|
|
5707
|
+
function configVersionFor(version) {
|
|
5708
|
+
const match = typeof version === "string" ? version.match(VERSION_PATTERN) : null;
|
|
5709
|
+
if (!match)
|
|
5710
|
+
return null;
|
|
5711
|
+
const major = Number(match[1]);
|
|
5712
|
+
const minor = Number(match[2]);
|
|
5713
|
+
const patch = Number(match[3]);
|
|
5714
|
+
const rc = match[4] === void 0 ? null : Number(match[4]);
|
|
5715
|
+
if (major < 1 || major > 99 || minor > 99 || patch > 99)
|
|
5716
|
+
return null;
|
|
5717
|
+
if (rc !== null && rc > 98)
|
|
5718
|
+
return null;
|
|
5719
|
+
return major * 1e6 + minor * 1e4 + patch * 100 + (rc === null ? RC_STABLE : rc);
|
|
5720
|
+
}
|
|
5721
|
+
var unpack = (value) => {
|
|
5722
|
+
const slot = value % 100;
|
|
5723
|
+
return {
|
|
5724
|
+
major: Math.floor(value / 1e6),
|
|
5725
|
+
minor: Math.floor(value / 1e4) % 100,
|
|
5726
|
+
patch: Math.floor(value / 100) % 100,
|
|
5727
|
+
rc: slot === RC_STABLE ? null : slot
|
|
5728
|
+
};
|
|
5729
|
+
};
|
|
5730
|
+
var render = ({ major, minor, patch, rc }) => `${major}.${minor}.${patch}${rc === null ? "" : `-rc.${rc}`}`;
|
|
5731
|
+
function parseConfigVersion(value) {
|
|
5732
|
+
if (!Number.isInteger(value) || value < MIN_CONFIG_VERSION || value > MAX_CONFIG_VERSION)
|
|
5733
|
+
return null;
|
|
5734
|
+
return unpack(value);
|
|
5735
|
+
}
|
|
5736
|
+
function formatConfigVersion(value) {
|
|
5737
|
+
const parsed = parseConfigVersion(value);
|
|
5738
|
+
return parsed === null ? null : render(parsed);
|
|
5739
|
+
}
|
|
5740
|
+
var SDK_VERSION = render(unpack(CONFIG_VERSION));
|
|
5664
5741
|
|
|
5665
5742
|
// src/shared/utils/resolveTimeoutMs.ts
|
|
5666
5743
|
function resolveTimeoutMs(timeout, fallbackMs) {
|
|
@@ -15595,11 +15672,15 @@ var ConfigService = class {
|
|
|
15595
15672
|
isMoneyMarketSupportedToken(chainId, token) {
|
|
15596
15673
|
return this.sodax.moneyMarket.supportedTokens[chainId].some((t) => t.address.toLowerCase() === token.toLowerCase());
|
|
15597
15674
|
}
|
|
15675
|
+
/**
|
|
15676
|
+
* Is `asset` one of the money-market reserve assets?
|
|
15677
|
+
*
|
|
15678
|
+
* The reserve set is built from `moneyMarketHubVaults`, so its members are hub **vault**
|
|
15679
|
+
* addresses. Query it with an `XToken.vault`; an `XToken.hubAsset` only matches for the Sonic
|
|
15680
|
+
* vault shares themselves, where `hubAsset === vault`.
|
|
15681
|
+
*/
|
|
15598
15682
|
isMoneyMarketReserveAsset(asset) {
|
|
15599
|
-
return this.
|
|
15600
|
-
}
|
|
15601
|
-
isMoneyMarketReserveHubAsset(hubAsset) {
|
|
15602
|
-
return this.moneyMarketReserveAssetsSet.has(hubAsset.toLowerCase());
|
|
15683
|
+
return this.moneyMarketReserveAssetsSet.has(asset.toLowerCase());
|
|
15603
15684
|
}
|
|
15604
15685
|
loadSodaxConfigDataStructures(sodaxConfig2) {
|
|
15605
15686
|
this.hubAssetToXTokenMap = new Map(
|
|
@@ -15748,7 +15829,7 @@ function mergeSodaxConfig(base2, override) {
|
|
|
15748
15829
|
}
|
|
15749
15830
|
function encodeContractCalls(calls) {
|
|
15750
15831
|
return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
|
|
15751
|
-
calls.map((
|
|
15832
|
+
calls.map((v10) => [v10.address, v10.value, v10.data])
|
|
15752
15833
|
]);
|
|
15753
15834
|
}
|
|
15754
15835
|
async function waitForTransactionReceipt(hash, provider) {
|
|
@@ -18011,7 +18092,7 @@ function hexToBytes2(hex) {
|
|
|
18011
18092
|
const al = hl / 2;
|
|
18012
18093
|
if (hl % 2)
|
|
18013
18094
|
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
18014
|
-
const
|
|
18095
|
+
const array3 = new Uint8Array(al);
|
|
18015
18096
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
18016
18097
|
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
18017
18098
|
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
@@ -18019,9 +18100,9 @@ function hexToBytes2(hex) {
|
|
|
18019
18100
|
const char = hex[hi] + hex[hi + 1];
|
|
18020
18101
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
18021
18102
|
}
|
|
18022
|
-
|
|
18103
|
+
array3[ai] = n1 * 16 + n2;
|
|
18023
18104
|
}
|
|
18024
|
-
return
|
|
18105
|
+
return array3;
|
|
18025
18106
|
}
|
|
18026
18107
|
function concatBytes(...arrays) {
|
|
18027
18108
|
let sum = 0;
|
|
@@ -18651,22 +18732,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
18651
18732
|
const byte0 = Uint8Array.of(0);
|
|
18652
18733
|
const byte1 = Uint8Array.of(1);
|
|
18653
18734
|
const _maxDrbgIters = 1e3;
|
|
18654
|
-
let
|
|
18735
|
+
let v10 = u8n(hashLen);
|
|
18655
18736
|
let k = u8n(hashLen);
|
|
18656
18737
|
let i = 0;
|
|
18657
18738
|
const reset = () => {
|
|
18658
|
-
|
|
18739
|
+
v10.fill(1);
|
|
18659
18740
|
k.fill(0);
|
|
18660
18741
|
i = 0;
|
|
18661
18742
|
};
|
|
18662
|
-
const h = (...msgs) => hmacFn(k, concatBytes(
|
|
18743
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v10, ...msgs));
|
|
18663
18744
|
const reseed = (seed = NULL) => {
|
|
18664
18745
|
k = h(byte0, seed);
|
|
18665
|
-
|
|
18746
|
+
v10 = h();
|
|
18666
18747
|
if (seed.length === 0)
|
|
18667
18748
|
return;
|
|
18668
18749
|
k = h(byte1, seed);
|
|
18669
|
-
|
|
18750
|
+
v10 = h();
|
|
18670
18751
|
};
|
|
18671
18752
|
const gen = () => {
|
|
18672
18753
|
if (i++ >= _maxDrbgIters)
|
|
@@ -18674,10 +18755,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
18674
18755
|
let len = 0;
|
|
18675
18756
|
const out = [];
|
|
18676
18757
|
while (len < qByteLen) {
|
|
18677
|
-
|
|
18678
|
-
const sl =
|
|
18758
|
+
v10 = h();
|
|
18759
|
+
const sl = v10.slice();
|
|
18679
18760
|
out.push(sl);
|
|
18680
|
-
len +=
|
|
18761
|
+
len += v10.length;
|
|
18681
18762
|
}
|
|
18682
18763
|
return concatBytes(...out);
|
|
18683
18764
|
};
|
|
@@ -18692,18 +18773,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
18692
18773
|
};
|
|
18693
18774
|
return genUntil;
|
|
18694
18775
|
}
|
|
18695
|
-
function validateObject(
|
|
18696
|
-
if (!
|
|
18776
|
+
function validateObject(object4, fields = {}, optFields = {}) {
|
|
18777
|
+
if (!object4 || typeof object4 !== "object")
|
|
18697
18778
|
throw new Error("expected valid options object");
|
|
18698
18779
|
function checkField(fieldName, expectedType, isOpt) {
|
|
18699
|
-
const val =
|
|
18780
|
+
const val = object4[fieldName];
|
|
18700
18781
|
if (isOpt && val === void 0)
|
|
18701
18782
|
return;
|
|
18702
18783
|
const current = typeof val;
|
|
18703
18784
|
if (current !== expectedType || val === null)
|
|
18704
18785
|
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
18705
18786
|
}
|
|
18706
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k,
|
|
18787
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v10]) => checkField(k, v10, isOpt));
|
|
18707
18788
|
iter(fields, false);
|
|
18708
18789
|
iter(optFields, true);
|
|
18709
18790
|
}
|
|
@@ -18742,12 +18823,12 @@ function pow2(x, power, modulo) {
|
|
|
18742
18823
|
}
|
|
18743
18824
|
return res;
|
|
18744
18825
|
}
|
|
18745
|
-
function invert(
|
|
18746
|
-
if (
|
|
18826
|
+
function invert(number4, modulo) {
|
|
18827
|
+
if (number4 === _0n2)
|
|
18747
18828
|
throw new Error("invert: expected non-zero number");
|
|
18748
18829
|
if (modulo <= _0n2)
|
|
18749
18830
|
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
18750
|
-
let a = mod(
|
|
18831
|
+
let a = mod(number4, modulo);
|
|
18751
18832
|
let b = modulo;
|
|
18752
18833
|
let x = _0n2, u = _1n2;
|
|
18753
18834
|
while (a !== _0n2) {
|
|
@@ -18774,9 +18855,9 @@ function sqrt3mod4(Fp, n) {
|
|
|
18774
18855
|
function sqrt5mod8(Fp, n) {
|
|
18775
18856
|
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
18776
18857
|
const n2 = Fp.mul(n, _2n);
|
|
18777
|
-
const
|
|
18778
|
-
const nv = Fp.mul(n,
|
|
18779
|
-
const i = Fp.mul(Fp.mul(nv, _2n),
|
|
18858
|
+
const v10 = Fp.pow(n2, p5div8);
|
|
18859
|
+
const nv = Fp.mul(n, v10);
|
|
18860
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v10);
|
|
18780
18861
|
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
18781
18862
|
assertIsSquare(Fp, root, n);
|
|
18782
18863
|
return root;
|
|
@@ -19251,27 +19332,27 @@ var wNAF = class {
|
|
|
19251
19332
|
assert0(n);
|
|
19252
19333
|
return acc;
|
|
19253
19334
|
}
|
|
19254
|
-
getPrecomputes(W, point,
|
|
19335
|
+
getPrecomputes(W, point, transform) {
|
|
19255
19336
|
let comp = pointPrecomputes.get(point);
|
|
19256
19337
|
if (!comp) {
|
|
19257
19338
|
comp = this.precomputeWindow(point, W);
|
|
19258
19339
|
if (W !== 1) {
|
|
19259
|
-
if (typeof
|
|
19260
|
-
comp =
|
|
19340
|
+
if (typeof transform === "function")
|
|
19341
|
+
comp = transform(comp);
|
|
19261
19342
|
pointPrecomputes.set(point, comp);
|
|
19262
19343
|
}
|
|
19263
19344
|
}
|
|
19264
19345
|
return comp;
|
|
19265
19346
|
}
|
|
19266
|
-
cached(point, scalar,
|
|
19347
|
+
cached(point, scalar, transform) {
|
|
19267
19348
|
const W = getW(point);
|
|
19268
|
-
return this.wNAF(W, this.getPrecomputes(W, point,
|
|
19349
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
19269
19350
|
}
|
|
19270
|
-
unsafe(point, scalar,
|
|
19351
|
+
unsafe(point, scalar, transform, prev) {
|
|
19271
19352
|
const W = getW(point);
|
|
19272
19353
|
if (W === 1)
|
|
19273
19354
|
return this._unsafeLadder(point, scalar, prev);
|
|
19274
|
-
return this.wNAFUnsafe(W, this.getPrecomputes(W, point,
|
|
19355
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
19275
19356
|
}
|
|
19276
19357
|
// We calculate precomputes for elliptic curve point multiplication
|
|
19277
19358
|
// using windowed method. This specifies window size and
|
|
@@ -19358,9 +19439,9 @@ function edwards(params, extraOpts = {}) {
|
|
|
19358
19439
|
validateObject(extraOpts, {}, { uvRatio: "function" });
|
|
19359
19440
|
const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
|
|
19360
19441
|
const modP = (n) => Fp.create(n);
|
|
19361
|
-
const uvRatio2 = extraOpts.uvRatio || ((u,
|
|
19442
|
+
const uvRatio2 = extraOpts.uvRatio || ((u, v10) => {
|
|
19362
19443
|
try {
|
|
19363
|
-
return { isValid: true, value: Fp.sqrt(Fp.div(u,
|
|
19444
|
+
return { isValid: true, value: Fp.sqrt(Fp.div(u, v10)) };
|
|
19364
19445
|
} catch (e) {
|
|
19365
19446
|
return { isValid: false, value: _0n4 };
|
|
19366
19447
|
}
|
|
@@ -19456,8 +19537,8 @@ function edwards(params, extraOpts = {}) {
|
|
|
19456
19537
|
aInRange("point.y", y, _0n4, max);
|
|
19457
19538
|
const y2 = modP(y * y);
|
|
19458
19539
|
const u = modP(y2 - _1n4);
|
|
19459
|
-
const
|
|
19460
|
-
let { isValid, value: x } = uvRatio2(u,
|
|
19540
|
+
const v10 = modP(d * y2 - a);
|
|
19541
|
+
let { isValid, value: x } = uvRatio2(u, v10);
|
|
19461
19542
|
if (!isValid)
|
|
19462
19543
|
throw new Error("bad point: invalid y coordinate");
|
|
19463
19544
|
const isXOdd = (x & _1n4) === _1n4;
|
|
@@ -19797,13 +19878,13 @@ function adjustScalarBytes(bytes) {
|
|
|
19797
19878
|
return bytes;
|
|
19798
19879
|
}
|
|
19799
19880
|
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
|
|
19800
|
-
function uvRatio(u,
|
|
19881
|
+
function uvRatio(u, v10) {
|
|
19801
19882
|
const P = ed25519_CURVE_p;
|
|
19802
|
-
const v32 = mod(
|
|
19803
|
-
const v72 = mod(v32 * v32 *
|
|
19883
|
+
const v32 = mod(v10 * v10 * v10, P);
|
|
19884
|
+
const v72 = mod(v32 * v32 * v10, P);
|
|
19804
19885
|
const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
|
|
19805
19886
|
let x = mod(u * v32 * pow, P);
|
|
19806
|
-
const vx2 = mod(
|
|
19887
|
+
const vx2 = mod(v10 * x * x, P);
|
|
19807
19888
|
const root1 = x;
|
|
19808
19889
|
const root2 = mod(x * ED25519_SQRT_M1, P);
|
|
19809
19890
|
const useRoot1 = vx2 === u;
|
|
@@ -20134,7 +20215,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
|
|
|
20134
20215
|
return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
|
|
20135
20216
|
}
|
|
20136
20217
|
function findSeatPriceForProtocolBefore49(validators, numSeats) {
|
|
20137
|
-
const stakes = validators.map((
|
|
20218
|
+
const stakes = validators.map((v10) => BigInt(v10.stake)).sort(sortBigIntAsc);
|
|
20138
20219
|
const num = BigInt(numSeats);
|
|
20139
20220
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
20140
20221
|
if (stakesSum < num) {
|
|
@@ -20163,7 +20244,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
|
|
|
20163
20244
|
if (minimumStakeRatio.length != 2) {
|
|
20164
20245
|
throw Error("minimumStakeRatio should have 2 elements");
|
|
20165
20246
|
}
|
|
20166
|
-
const stakes = validators.map((
|
|
20247
|
+
const stakes = validators.map((v10) => BigInt(v10.stake)).sort(sortBigIntAsc);
|
|
20167
20248
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
20168
20249
|
if (validators.length < maxNumberOfSeats) {
|
|
20169
20250
|
return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
|
|
@@ -20335,10 +20416,10 @@ var DER = {
|
|
|
20335
20416
|
if (length < 128)
|
|
20336
20417
|
throw new E("tlv.decode(long): not minimal encoding");
|
|
20337
20418
|
}
|
|
20338
|
-
const
|
|
20339
|
-
if (
|
|
20419
|
+
const v10 = data.subarray(pos, pos + length);
|
|
20420
|
+
if (v10.length !== length)
|
|
20340
20421
|
throw new E("tlv.decode: wrong value length");
|
|
20341
|
-
return { v:
|
|
20422
|
+
return { v: v10, l: data.subarray(pos + length) };
|
|
20342
20423
|
}
|
|
20343
20424
|
},
|
|
20344
20425
|
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
@@ -20906,9 +20987,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
20906
20987
|
extraEntropy: false
|
|
20907
20988
|
};
|
|
20908
20989
|
const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
|
|
20909
|
-
function isBiggerThanHalfOrder(
|
|
20990
|
+
function isBiggerThanHalfOrder(number4) {
|
|
20910
20991
|
const HALF = CURVE_ORDER >> _1n6;
|
|
20911
|
-
return
|
|
20992
|
+
return number4 > HALF;
|
|
20912
20993
|
}
|
|
20913
20994
|
function validateRS(title, num) {
|
|
20914
20995
|
if (!Fn.isValidNot0(num))
|
|
@@ -21091,8 +21172,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
21091
21172
|
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
21092
21173
|
if (R.is0())
|
|
21093
21174
|
return false;
|
|
21094
|
-
const
|
|
21095
|
-
return
|
|
21175
|
+
const v10 = Fn.create(R.x);
|
|
21176
|
+
return v10 === r;
|
|
21096
21177
|
} catch (e) {
|
|
21097
21178
|
return false;
|
|
21098
21179
|
}
|
|
@@ -24984,6 +25065,7 @@ function isTimeoutError(error) {
|
|
|
24984
25065
|
return error instanceof Error && /timed?\s?out|timeout/i.test(error.message);
|
|
24985
25066
|
}
|
|
24986
25067
|
var DEFAULT_GET_COINS_LIMIT = 10;
|
|
25068
|
+
var LATEST_PACKAGE_ID_TIMEOUT_MS = 1e4;
|
|
24987
25069
|
function toSuiObjectOwner(owner) {
|
|
24988
25070
|
switch (owner?.$kind) {
|
|
24989
25071
|
case "AddressOwner":
|
|
@@ -25052,16 +25134,20 @@ var SuiGrpcTransport = class {
|
|
|
25052
25134
|
return effects.gasUsed;
|
|
25053
25135
|
}
|
|
25054
25136
|
async fetchLatestPackageId(objectId) {
|
|
25055
|
-
let
|
|
25137
|
+
let object4;
|
|
25056
25138
|
try {
|
|
25057
|
-
({ object:
|
|
25139
|
+
({ object: object4 } = await this.client.core.getObject({
|
|
25140
|
+
objectId,
|
|
25141
|
+
include: { json: true },
|
|
25142
|
+
signal: AbortSignal.timeout(LATEST_PACKAGE_ID_TIMEOUT_MS)
|
|
25143
|
+
}));
|
|
25058
25144
|
} catch (error) {
|
|
25059
25145
|
throw new Error("Failed to fetch asset manager id", { cause: error });
|
|
25060
25146
|
}
|
|
25061
|
-
if (!
|
|
25147
|
+
if (!object4) {
|
|
25062
25148
|
throw new Error("Asset manager id not found (no data)");
|
|
25063
25149
|
}
|
|
25064
|
-
const fields =
|
|
25150
|
+
const fields = object4.json;
|
|
25065
25151
|
if (!fields) {
|
|
25066
25152
|
throw new Error("Asset manager id not found (not a move object)");
|
|
25067
25153
|
}
|
|
@@ -25098,7 +25184,11 @@ var SuiSpokeService = class {
|
|
|
25098
25184
|
transport;
|
|
25099
25185
|
/** @deprecated Renamed to `transport`, and no longer a raw `@mysten/sui` client. */
|
|
25100
25186
|
publicClient;
|
|
25101
|
-
|
|
25187
|
+
/**
|
|
25188
|
+
* `latest_package_id` reads still in flight, keyed by chain. An entry is dropped as soon as its
|
|
25189
|
+
* read settles, so concurrent callers share one request while a later build always re-reads.
|
|
25190
|
+
*/
|
|
25191
|
+
assetManagerLookups = /* @__PURE__ */ new Map();
|
|
25102
25192
|
pollingIntervalMs;
|
|
25103
25193
|
maxTimeoutMs;
|
|
25104
25194
|
constructor(config) {
|
|
@@ -25160,10 +25250,19 @@ var SuiSpokeService = class {
|
|
|
25160
25250
|
};
|
|
25161
25251
|
}
|
|
25162
25252
|
async getAssetManagerAddress(chainId) {
|
|
25163
|
-
|
|
25164
|
-
|
|
25165
|
-
|
|
25166
|
-
|
|
25253
|
+
const { packageId, moduleId, stateId } = await this.resolveAssetManager(chainId);
|
|
25254
|
+
return `${packageId}::${moduleId}::${stateId}`;
|
|
25255
|
+
}
|
|
25256
|
+
/**
|
|
25257
|
+
* An upgraded Sui package lives at a new address and the superseded one aborts on
|
|
25258
|
+
* `enforce_version`, so the id is read per call and never held between two builds.
|
|
25259
|
+
*/
|
|
25260
|
+
async resolveAssetManager(chainId) {
|
|
25261
|
+
const inFlight = this.assetManagerLookups.get(chainId);
|
|
25262
|
+
if (inFlight) return inFlight;
|
|
25263
|
+
const lookup = this.fetchAssetManagerAddress(chainId).then((address) => this.splitAddress(address)).finally(() => this.assetManagerLookups.delete(chainId));
|
|
25264
|
+
this.assetManagerLookups.set(chainId, lookup);
|
|
25265
|
+
return lookup;
|
|
25167
25266
|
}
|
|
25168
25267
|
async viewContract(tx, packageId, module, functionName, args, typeArgs = [], sender) {
|
|
25169
25268
|
tx.moveCall({
|
|
@@ -25180,12 +25279,27 @@ var SuiSpokeService = class {
|
|
|
25180
25279
|
* @returns {Promise<TxReturnType<SuiChainKey, R>>} A promise that resolves to the transaction hash or raw transaction base64 string.
|
|
25181
25280
|
*/
|
|
25182
25281
|
async deposit(params) {
|
|
25282
|
+
const { tx, assetManager } = await this.buildDepositTransaction(params);
|
|
25283
|
+
if (params.raw === true) {
|
|
25284
|
+
return {
|
|
25285
|
+
from: params.srcAddress,
|
|
25286
|
+
to: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
|
|
25287
|
+
value: params.amount,
|
|
25288
|
+
data: tx.serialize()
|
|
25289
|
+
};
|
|
25290
|
+
}
|
|
25291
|
+
return params.walletProvider.signAndExecuteTxn(tx);
|
|
25292
|
+
}
|
|
25293
|
+
/** Both deposit paths build here, so the asset manager is resolved the same way for each. */
|
|
25294
|
+
async buildDepositTransaction(params) {
|
|
25183
25295
|
const { srcAddress: from, srcChainKey, token, to, amount, data = "0x" } = params;
|
|
25184
25296
|
const isNative = isNativeToken(srcChainKey, token);
|
|
25185
25297
|
const tx = new transactions.Transaction();
|
|
25186
|
-
const coin = isNative ? await this.getNativeCoin(tx, amount) : await this.getCoin(tx, token, amount, from);
|
|
25187
25298
|
const connection = this.splitAddress(this.config.getChainConfig(srcChainKey).addresses.connection);
|
|
25188
|
-
const assetManager =
|
|
25299
|
+
const [coin, assetManager] = await Promise.all([
|
|
25300
|
+
isNative ? this.getNativeCoin(tx, amount) : this.getCoin(tx, token, amount, from),
|
|
25301
|
+
this.resolveAssetManager(srcChainKey)
|
|
25302
|
+
]);
|
|
25189
25303
|
tx.moveCall({
|
|
25190
25304
|
target: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
|
|
25191
25305
|
typeArguments: [token],
|
|
@@ -25198,15 +25312,7 @@ var SuiSpokeService = class {
|
|
|
25198
25312
|
tx.pure(bcs.bcs.vector(bcs.bcs.u8()).serialize(viem.fromHex(data, "bytes")))
|
|
25199
25313
|
]
|
|
25200
25314
|
});
|
|
25201
|
-
|
|
25202
|
-
return {
|
|
25203
|
-
from,
|
|
25204
|
-
to: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
|
|
25205
|
-
value: amount,
|
|
25206
|
-
data: tx.serialize()
|
|
25207
|
-
};
|
|
25208
|
-
}
|
|
25209
|
-
return params.walletProvider.signAndExecuteTxn(tx);
|
|
25315
|
+
return { tx, assetManager };
|
|
25210
25316
|
}
|
|
25211
25317
|
async sendMessage(params) {
|
|
25212
25318
|
const { srcAddress: from, srcChainKey, dstChainKey, dstAddress, payload } = params;
|
|
@@ -25246,7 +25352,7 @@ var SuiSpokeService = class {
|
|
|
25246
25352
|
* @returns {Promise<bigint>} The balance of the token.
|
|
25247
25353
|
*/
|
|
25248
25354
|
async getDeposit(params) {
|
|
25249
|
-
const assetmanager =
|
|
25355
|
+
const assetmanager = await this.resolveAssetManager(params.srcChainKey);
|
|
25250
25356
|
const tx = new transactions.Transaction();
|
|
25251
25357
|
const result = await this.viewContract(
|
|
25252
25358
|
tx,
|
|
@@ -29575,7 +29681,7 @@ function selectSolvedIntentPacket(packets, intentsContract) {
|
|
|
29575
29681
|
|
|
29576
29682
|
// src/swap/speed-tier.ts
|
|
29577
29683
|
var SPEED_TIER_SECONDS = {
|
|
29578
|
-
/** Either token
|
|
29684
|
+
/** Either token's vault is a money-market-reserve (sodaAsset). */
|
|
29579
29685
|
sodaAsset: 15,
|
|
29580
29686
|
/** Anything else / default. */
|
|
29581
29687
|
default: 35,
|
|
@@ -29593,7 +29699,7 @@ var secondsToTier = (seconds) => {
|
|
|
29593
29699
|
return "slow";
|
|
29594
29700
|
};
|
|
29595
29701
|
function estimateSwapSpeedTier({ srcToken, dstToken }, isSodaAssetRelated) {
|
|
29596
|
-
const eitherSodaAsset = isSodaAssetRelated(srcToken.
|
|
29702
|
+
const eitherSodaAsset = isSodaAssetRelated(srcToken.vault) || isSodaAssetRelated(dstToken.vault);
|
|
29597
29703
|
let estimatedSeconds = eitherSodaAsset ? SPEED_TIER_SECONDS.sodaAsset : SPEED_TIER_SECONDS.default;
|
|
29598
29704
|
if (isEthereumToken(srcToken) || isEthereumToken(dstToken)) {
|
|
29599
29705
|
estimatedSeconds += SPEED_TIER_SECONDS.ethereumPenalty;
|
|
@@ -29803,14 +29909,14 @@ var SwapService = class {
|
|
|
29803
29909
|
*/
|
|
29804
29910
|
async getDetailedStatus(params) {
|
|
29805
29911
|
try {
|
|
29806
|
-
const
|
|
29912
|
+
const record = await this.backendApi.swaps.getSubmitTxStatus({
|
|
29807
29913
|
txHash: params.srcTxHash,
|
|
29808
29914
|
srcChainKey: params.srcChainKey
|
|
29809
29915
|
});
|
|
29810
|
-
if (
|
|
29811
|
-
return { ok: true, value: { source: "backend", data:
|
|
29916
|
+
if (record.ok && record.value.success && !isBackendSubmitTxAbandoned(record.value.data)) {
|
|
29917
|
+
return { ok: true, value: { source: "backend", data: record.value.data } };
|
|
29812
29918
|
}
|
|
29813
|
-
const backendAnswered =
|
|
29919
|
+
const backendAnswered = record.ok || isSodaxError(record.error) && record.error.context?.status === 404;
|
|
29814
29920
|
const dstTxHash = await this.resolveHubTxHash(params, backendAnswered);
|
|
29815
29921
|
if (!dstTxHash.ok) return dstTxHash;
|
|
29816
29922
|
const solver = await this.resolveSolverStatus(
|
|
@@ -30952,7 +31058,7 @@ var SwapService = class {
|
|
|
30952
31058
|
/**
|
|
30953
31059
|
* Offline, rule-based estimate of how fast a `srcToken`→`dstToken` swap will settle.
|
|
30954
31060
|
*
|
|
30955
|
-
* Derived purely from SDK config (no network / on-chain / backend call): tokens
|
|
31061
|
+
* Derived purely from SDK config (no network / on-chain / backend call): tokens whose vault is a
|
|
30956
31062
|
* money-market-reserve sodaAsset settle faster, and an Ethereum leg adds a fixed penalty. See
|
|
30957
31063
|
* {@link estimateSwapSpeedTier} for the rules.
|
|
30958
31064
|
*
|
|
@@ -30960,7 +31066,7 @@ var SwapService = class {
|
|
|
30960
31066
|
* @returns the estimated `tier` bucket and `estimatedSeconds`
|
|
30961
31067
|
*/
|
|
30962
31068
|
getSwapSpeedTier(params) {
|
|
30963
|
-
return estimateSwapSpeedTier(params, (
|
|
31069
|
+
return estimateSwapSpeedTier(params, (vault) => this.config.isMoneyMarketReserveAsset(vault));
|
|
30964
31070
|
}
|
|
30965
31071
|
};
|
|
30966
31072
|
|
|
@@ -33460,173 +33566,6 @@ var SponsoringApiService = class {
|
|
|
33460
33566
|
return this.config.baseURL;
|
|
33461
33567
|
}
|
|
33462
33568
|
};
|
|
33463
|
-
var RelayExtraDataResponseSchema = v__namespace.object({
|
|
33464
|
-
address: v__namespace.string(),
|
|
33465
|
-
payload: v__namespace.string()
|
|
33466
|
-
});
|
|
33467
|
-
var BridgeTokenSchema = v__namespace.object({
|
|
33468
|
-
symbol: v__namespace.string(),
|
|
33469
|
-
name: v__namespace.string(),
|
|
33470
|
-
decimals: v__namespace.number(),
|
|
33471
|
-
address: v__namespace.string(),
|
|
33472
|
-
chainKey: v__namespace.string(),
|
|
33473
|
-
hubAsset: v__namespace.string(),
|
|
33474
|
-
vault: v__namespace.string()
|
|
33475
|
-
});
|
|
33476
|
-
var BridgeTokensResponseSchema = v__namespace.record(v__namespace.string(), v__namespace.array(BridgeTokenSchema));
|
|
33477
|
-
var BridgeTokensByChainResponseSchema = v__namespace.array(BridgeTokenSchema);
|
|
33478
|
-
var BridgeAllowanceCheckResponseSchema = v__namespace.object({
|
|
33479
|
-
valid: v__namespace.boolean()
|
|
33480
|
-
});
|
|
33481
|
-
var makeBridgeApproveResponseSchema = (txSchema) => v__namespace.object({ tx: txSchema, resetTx: v__namespace.optional(txSchema) });
|
|
33482
|
-
var makeCreateBridgeIntentResponseSchema = (txSchema) => v__namespace.object({
|
|
33483
|
-
tx: txSchema,
|
|
33484
|
-
relayData: RelayExtraDataResponseSchema
|
|
33485
|
-
});
|
|
33486
|
-
var BridgeSubmitTxResponseSchema = v__namespace.object({
|
|
33487
|
-
success: v__namespace.boolean(),
|
|
33488
|
-
data: v__namespace.object({
|
|
33489
|
-
status: v__namespace.picklist(["inserted", "duplicate"]),
|
|
33490
|
-
message: v__namespace.string()
|
|
33491
|
-
})
|
|
33492
|
-
});
|
|
33493
|
-
var BridgePacketDataSchema = v__namespace.object({
|
|
33494
|
-
src_chain_id: v__namespace.number(),
|
|
33495
|
-
src_tx_hash: v__namespace.string(),
|
|
33496
|
-
src_address: v__namespace.string(),
|
|
33497
|
-
status: v__namespace.picklist(["pending", "validating", "executing", "executed"]),
|
|
33498
|
-
dst_chain_id: v__namespace.number(),
|
|
33499
|
-
conn_sn: v__namespace.number(),
|
|
33500
|
-
dst_address: v__namespace.string(),
|
|
33501
|
-
dst_tx_hash: v__namespace.string(),
|
|
33502
|
-
signatures: v__namespace.array(v__namespace.string()),
|
|
33503
|
-
payload: v__namespace.string()
|
|
33504
|
-
});
|
|
33505
|
-
var BridgeSubmitTxStatusResultSchema = v__namespace.object({
|
|
33506
|
-
dstIntentTxHash: v__namespace.string(),
|
|
33507
|
-
packetData: v__namespace.optional(BridgePacketDataSchema)
|
|
33508
|
-
});
|
|
33509
|
-
var BridgeSubmitTxStatusDataSchema = v__namespace.object({
|
|
33510
|
-
txHash: v__namespace.string(),
|
|
33511
|
-
srcChainKey: v__namespace.string(),
|
|
33512
|
-
status: v__namespace.string(),
|
|
33513
|
-
failedAtStep: v__namespace.optional(v__namespace.string()),
|
|
33514
|
-
failureReason: v__namespace.optional(v__namespace.string()),
|
|
33515
|
-
processingAttempts: v__namespace.number(),
|
|
33516
|
-
abandonedAt: v__namespace.optional(v__namespace.string()),
|
|
33517
|
-
result: v__namespace.optional(BridgeSubmitTxStatusResultSchema),
|
|
33518
|
-
userMessage: v__namespace.optional(v__namespace.string())
|
|
33519
|
-
});
|
|
33520
|
-
var BridgeSubmitTxStatusResponseSchema = v__namespace.object({
|
|
33521
|
-
success: v__namespace.boolean(),
|
|
33522
|
-
data: BridgeSubmitTxStatusDataSchema
|
|
33523
|
-
});
|
|
33524
|
-
var BridgeFeeResponseSchema = v__namespace.object({ fee: v__namespace.string() });
|
|
33525
|
-
var BridgeLimitSchema = v__namespace.object({
|
|
33526
|
-
amount: v__namespace.string(),
|
|
33527
|
-
decimals: v__namespace.number(),
|
|
33528
|
-
type: v__namespace.picklist(["DEPOSIT_LIMIT", "WITHDRAWAL_LIMIT"])
|
|
33529
|
-
});
|
|
33530
|
-
var BridgeableAmountResponseSchema = v__namespace.object({ limit: BridgeLimitSchema });
|
|
33531
|
-
var BridgeableCheckResponseSchema = v__namespace.object({ bridgeable: v__namespace.boolean() });
|
|
33532
|
-
var AddressSchema2 = v__namespace.custom((input) => typeof input === "string");
|
|
33533
|
-
var HexSchema = v__namespace.custom((input) => typeof input === "string");
|
|
33534
|
-
var BigintFromString = v__namespace.pipe(v__namespace.string(), v__namespace.toBigint());
|
|
33535
|
-
var BytesFromIndexRecord = v__namespace.pipe(
|
|
33536
|
-
v__namespace.record(v__namespace.string(), v__namespace.number()),
|
|
33537
|
-
v__namespace.transform((indexed) => Uint8Array.from(Object.values(indexed)))
|
|
33538
|
-
);
|
|
33539
|
-
var EvmRawTxSchema = v__namespace.object({
|
|
33540
|
-
from: AddressSchema2,
|
|
33541
|
-
to: AddressSchema2,
|
|
33542
|
-
value: BigintFromString,
|
|
33543
|
-
data: HexSchema
|
|
33544
|
-
});
|
|
33545
|
-
var SolanaRawTxSchema = v__namespace.object({
|
|
33546
|
-
from: v__namespace.string(),
|
|
33547
|
-
to: v__namespace.string(),
|
|
33548
|
-
value: BigintFromString,
|
|
33549
|
-
data: v__namespace.string()
|
|
33550
|
-
});
|
|
33551
|
-
var SuiRawTxSchema = v__namespace.object({
|
|
33552
|
-
from: HexSchema,
|
|
33553
|
-
to: v__namespace.string(),
|
|
33554
|
-
value: BigintFromString,
|
|
33555
|
-
data: v__namespace.string()
|
|
33556
|
-
});
|
|
33557
|
-
var StellarRawTxSchema = v__namespace.object({
|
|
33558
|
-
from: v__namespace.string(),
|
|
33559
|
-
to: v__namespace.string(),
|
|
33560
|
-
value: BigintFromString,
|
|
33561
|
-
data: v__namespace.string()
|
|
33562
|
-
});
|
|
33563
|
-
var BitcoinRawTxSchema = v__namespace.object({
|
|
33564
|
-
from: v__namespace.string(),
|
|
33565
|
-
to: v__namespace.string(),
|
|
33566
|
-
value: BigintFromString,
|
|
33567
|
-
data: v__namespace.string()
|
|
33568
|
-
});
|
|
33569
|
-
var InjectiveRawTxSchema = v__namespace.object({
|
|
33570
|
-
from: HexSchema,
|
|
33571
|
-
to: HexSchema,
|
|
33572
|
-
signedDoc: v__namespace.object({
|
|
33573
|
-
bodyBytes: BytesFromIndexRecord,
|
|
33574
|
-
authInfoBytes: BytesFromIndexRecord,
|
|
33575
|
-
chainId: v__namespace.string(),
|
|
33576
|
-
accountNumber: BigintFromString
|
|
33577
|
-
})
|
|
33578
|
-
});
|
|
33579
|
-
var NearRawTxSchema = v__namespace.object({
|
|
33580
|
-
signerId: v__namespace.string(),
|
|
33581
|
-
params: v__namespace.object({
|
|
33582
|
-
contractId: v__namespace.string(),
|
|
33583
|
-
method: v__namespace.string(),
|
|
33584
|
-
args: v__namespace.custom((input) => typeof input === "object" && input !== null),
|
|
33585
|
-
gas: v__namespace.optional(BigintFromString),
|
|
33586
|
-
deposit: v__namespace.optional(BigintFromString)
|
|
33587
|
-
})
|
|
33588
|
-
});
|
|
33589
|
-
var IconRawTxSchema = v__namespace.record(
|
|
33590
|
-
v__namespace.string(),
|
|
33591
|
-
v__namespace.union([v__namespace.string(), v__namespace.custom((input) => typeof input === "object" && input !== null)])
|
|
33592
|
-
);
|
|
33593
|
-
var StacksRawTxSchema = v__namespace.object({
|
|
33594
|
-
payload: v__namespace.string(),
|
|
33595
|
-
estimatedLength: v__namespace.optional(v__namespace.number())
|
|
33596
|
-
});
|
|
33597
|
-
var AnyRawTxSchema = v__namespace.custom((input) => typeof input === "object" && input !== null);
|
|
33598
|
-
function rawTxSchemaForChainKey(chainKey) {
|
|
33599
|
-
let chainType;
|
|
33600
|
-
try {
|
|
33601
|
-
chainType = getChainType(chainKey);
|
|
33602
|
-
} catch {
|
|
33603
|
-
chainType = void 0;
|
|
33604
|
-
}
|
|
33605
|
-
switch (chainType) {
|
|
33606
|
-
case "EVM":
|
|
33607
|
-
return EvmRawTxSchema;
|
|
33608
|
-
case "SOLANA":
|
|
33609
|
-
return SolanaRawTxSchema;
|
|
33610
|
-
case "SUI":
|
|
33611
|
-
return SuiRawTxSchema;
|
|
33612
|
-
case "STELLAR":
|
|
33613
|
-
return StellarRawTxSchema;
|
|
33614
|
-
case "INJECTIVE":
|
|
33615
|
-
return InjectiveRawTxSchema;
|
|
33616
|
-
case "ICON":
|
|
33617
|
-
return IconRawTxSchema;
|
|
33618
|
-
case "STACKS":
|
|
33619
|
-
return StacksRawTxSchema;
|
|
33620
|
-
case "NEAR":
|
|
33621
|
-
return NearRawTxSchema;
|
|
33622
|
-
case "BITCOIN":
|
|
33623
|
-
return BitcoinRawTxSchema;
|
|
33624
|
-
default:
|
|
33625
|
-
return AnyRawTxSchema;
|
|
33626
|
-
}
|
|
33627
|
-
}
|
|
33628
|
-
|
|
33629
|
-
// src/backendApi/BridgeApiService.ts
|
|
33630
33569
|
function toCreateBridgeIntentParamsV2(params, extras) {
|
|
33631
33570
|
return {
|
|
33632
33571
|
srcChainKey: params.srcChainKey,
|
|
@@ -33651,41 +33590,63 @@ var BridgeApiService = class {
|
|
|
33651
33590
|
trimsLegacyOverrides;
|
|
33652
33591
|
constructor(config, logger = consoleLogger, options = {}) {
|
|
33653
33592
|
this.config = config;
|
|
33654
|
-
this.headers =
|
|
33593
|
+
this.headers = mergeHeaders(config.headers);
|
|
33655
33594
|
this.logger = logger;
|
|
33656
33595
|
this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
|
|
33657
33596
|
}
|
|
33658
33597
|
/**
|
|
33659
|
-
*
|
|
33660
|
-
*
|
|
33661
|
-
*
|
|
33662
|
-
*
|
|
33598
|
+
* Build a `@sodax/bridge-api` client for a single call. Maps the SDK's {@link BaseApiConfig}
|
|
33599
|
+
* (`baseURL`/`timeout`/`headers`) to the package's config (`baseUrl`/`timeout`/`headers`), layering
|
|
33600
|
+
* the optional per-call `RequestOverrideConfig` on top (override wins per field; headers merge).
|
|
33601
|
+
* `timeout` falls back to the backend-API default so a config that omits it still gets a ceiling
|
|
33602
|
+
* rather than an unbounded request. Constructed per call so `setHeaders` mutations and per-call
|
|
33603
|
+
* overrides both take effect without caching stale state.
|
|
33663
33604
|
*/
|
|
33664
|
-
|
|
33605
|
+
buildClient(overrideConfig) {
|
|
33606
|
+
const override = overrideConfig?.baseURL;
|
|
33607
|
+
const baseUrl = override ? this.trimsLegacyOverrides ? stripLegacyBackendMount(override) : override : this.config.baseURL;
|
|
33608
|
+
const timeout = overrideConfig?.timeout ?? this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
|
|
33609
|
+
const headers = mergeHeaders(this.headers, apiKeyHeader(overrideConfig?.apiKey), overrideConfig?.headers);
|
|
33610
|
+
return new bridgeApi.BridgeApi({ baseUrl, headers, timeout });
|
|
33611
|
+
}
|
|
33612
|
+
/**
|
|
33613
|
+
* Run one delegated `BridgeApi` call and wrap it in `Result<T>`. A thrown `BridgeApiError`
|
|
33614
|
+
* (network/timeout/HTTP/parse/validation) becomes `{ ok: false }` with a canonical
|
|
33615
|
+
* `SodaxError<'EXTERNAL_API_ERROR'>`; the original error is kept as `cause`, and its
|
|
33616
|
+
* `code`/`status`/`issues` are projected into `context` so consumers can discriminate failure
|
|
33617
|
+
* kinds without unwrapping `cause`. Only a RESPONSE-shape validation failure is tagged
|
|
33618
|
+
* `reason: 'invalid_response_shape'` — a request-side validation error is a caller bug, not a
|
|
33619
|
+
* backend fault.
|
|
33620
|
+
*/
|
|
33621
|
+
async toResult(endpoint, call, overrideConfig) {
|
|
33665
33622
|
try {
|
|
33666
|
-
const
|
|
33667
|
-
|
|
33668
|
-
config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
|
|
33669
|
-
// Normalized like a configured base URL: the override is the gateway root, so a legacy
|
|
33670
|
-
// `/be`-suffixed value must not nest `/bridge/*` under the data API's mount — unless the config
|
|
33671
|
-
// opted out of the legacy trim, in which case the per-call value is left exactly as given.
|
|
33672
|
-
overrideConfig: this.trimsLegacyOverrides ? normalizeOverrideBaseURL(overrideConfig) : overrideConfig,
|
|
33673
|
-
logger: this.logger,
|
|
33674
|
-
serviceLabel: "BridgeApiService"
|
|
33675
|
-
});
|
|
33676
|
-
const parsed = v__namespace.safeParse(schema, raw);
|
|
33677
|
-
if (!parsed.success) {
|
|
33678
|
-
return {
|
|
33679
|
-
ok: false,
|
|
33680
|
-
error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from bridge API for ${endpoint}`, {
|
|
33681
|
-
feature: "backend",
|
|
33682
|
-
context: { api: "bridge", endpoint, reason: "invalid_response_shape", issues: v__namespace.flatten(parsed.issues) }
|
|
33683
|
-
})
|
|
33684
|
-
};
|
|
33685
|
-
}
|
|
33686
|
-
return { ok: true, value: parsed.output };
|
|
33623
|
+
const value = await call(this.buildClient(overrideConfig));
|
|
33624
|
+
return { ok: true, value };
|
|
33687
33625
|
} catch (error) {
|
|
33688
|
-
|
|
33626
|
+
const context = { api: "bridge", endpoint };
|
|
33627
|
+
if (error instanceof bridgeApi.BridgeApiError) {
|
|
33628
|
+
context.code = error.code;
|
|
33629
|
+
if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
|
|
33630
|
+
context.reason = "invalid_response_shape";
|
|
33631
|
+
const issues = error.context.issues;
|
|
33632
|
+
context.issues = issues instanceof v__namespace.ValiError ? v__namespace.flatten(issues.issues) : issues;
|
|
33633
|
+
}
|
|
33634
|
+
if (error.context.status !== void 0) context.status = error.context.status;
|
|
33635
|
+
if (isAuthStatus(error.context.status)) {
|
|
33636
|
+
this.logger.warn(
|
|
33637
|
+
`[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.`
|
|
33638
|
+
);
|
|
33639
|
+
}
|
|
33640
|
+
}
|
|
33641
|
+
this.logger.error(`[BridgeApiService] Request to ${endpoint} failed`, error);
|
|
33642
|
+
return {
|
|
33643
|
+
ok: false,
|
|
33644
|
+
error: new SodaxError(
|
|
33645
|
+
"EXTERNAL_API_ERROR",
|
|
33646
|
+
error instanceof Error ? error.message : `Request to ${endpoint} failed`,
|
|
33647
|
+
{ feature: "backend", cause: error, context }
|
|
33648
|
+
)
|
|
33649
|
+
};
|
|
33689
33650
|
}
|
|
33690
33651
|
}
|
|
33691
33652
|
// ──────────────────────────────────────────────────────────────────────
|
|
@@ -33697,7 +33658,7 @@ var BridgeApiService = class {
|
|
|
33697
33658
|
* @returns `Result<GetBridgeTokensResponseV2>` — map of chain key → token list.
|
|
33698
33659
|
*/
|
|
33699
33660
|
async getTokens(config) {
|
|
33700
|
-
return this.
|
|
33661
|
+
return this.toResult("/bridge/tokens", (c) => c.getTokens(), config);
|
|
33701
33662
|
}
|
|
33702
33663
|
/**
|
|
33703
33664
|
* Fetch supported bridge tokens for a single SpokeChainKey.
|
|
@@ -33706,12 +33667,7 @@ var BridgeApiService = class {
|
|
|
33706
33667
|
* @returns `Result<GetBridgeTokensByChainResponseV2>` — token list for the chain.
|
|
33707
33668
|
*/
|
|
33708
33669
|
async getTokensByChain(chainKey, config) {
|
|
33709
|
-
return this.
|
|
33710
|
-
`/bridge/tokens/${chainKey}`,
|
|
33711
|
-
{ method: "GET" },
|
|
33712
|
-
BridgeTokensByChainResponseSchema,
|
|
33713
|
-
config
|
|
33714
|
-
);
|
|
33670
|
+
return this.toResult(`/bridge/tokens/${chainKey}`, (c) => c.getTokensByChain(chainKey), config);
|
|
33715
33671
|
}
|
|
33716
33672
|
// ──────────────────────────────────────────────────────────────────────
|
|
33717
33673
|
// Allowance · approve · create intent
|
|
@@ -33722,12 +33678,7 @@ var BridgeApiService = class {
|
|
|
33722
33678
|
* @returns `Result<BridgeAllowanceCheckResponseV2>` — `{ valid }`.
|
|
33723
33679
|
*/
|
|
33724
33680
|
async checkAllowance(body, config) {
|
|
33725
|
-
return this.
|
|
33726
|
-
"/bridge/allowance/check",
|
|
33727
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33728
|
-
BridgeAllowanceCheckResponseSchema,
|
|
33729
|
-
config
|
|
33730
|
-
);
|
|
33681
|
+
return this.toResult("/bridge/allowance/check", (c) => c.checkAllowance(body), config);
|
|
33731
33682
|
}
|
|
33732
33683
|
/**
|
|
33733
33684
|
* Build an unsigned token-approval transaction for the source token.
|
|
@@ -33736,13 +33687,7 @@ var BridgeApiService = class {
|
|
|
33736
33687
|
* broadcast and mine `resetTx` first when it is present.
|
|
33737
33688
|
*/
|
|
33738
33689
|
async approve(body, config) {
|
|
33739
|
-
|
|
33740
|
-
return this.request(
|
|
33741
|
-
"/bridge/approve",
|
|
33742
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33743
|
-
makeBridgeApproveResponseSchema(txSchema),
|
|
33744
|
-
config
|
|
33745
|
-
);
|
|
33690
|
+
return this.toResult("/bridge/approve", (c) => c.approve(body), config);
|
|
33746
33691
|
}
|
|
33747
33692
|
/**
|
|
33748
33693
|
* Build an unsigned spoke-deposit (create-bridge-intent) transaction.
|
|
@@ -33750,13 +33695,7 @@ var BridgeApiService = class {
|
|
|
33750
33695
|
* @returns `Result<CreateBridgeIntentResponseV2>` — `{ tx, relayData }` (no intent struct).
|
|
33751
33696
|
*/
|
|
33752
33697
|
async createBridgeIntent(body, config) {
|
|
33753
|
-
|
|
33754
|
-
return this.request(
|
|
33755
|
-
"/bridge/intents",
|
|
33756
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33757
|
-
makeCreateBridgeIntentResponseSchema(txSchema),
|
|
33758
|
-
config
|
|
33759
|
-
);
|
|
33698
|
+
return this.toResult("/bridge/intents", (c) => c.createBridgeIntent(body), config);
|
|
33760
33699
|
}
|
|
33761
33700
|
// ──────────────────────────────────────────────────────────────────────
|
|
33762
33701
|
// Submit-tx state machine
|
|
@@ -33768,12 +33707,7 @@ var BridgeApiService = class {
|
|
|
33768
33707
|
* @returns `Result<BridgeSubmitTxResponseV2>` — `{ success, data: { status, message } }`.
|
|
33769
33708
|
*/
|
|
33770
33709
|
async submitTx(body, config) {
|
|
33771
|
-
return this.
|
|
33772
|
-
"/bridge/submit-tx",
|
|
33773
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33774
|
-
BridgeSubmitTxResponseSchema,
|
|
33775
|
-
config
|
|
33776
|
-
);
|
|
33710
|
+
return this.toResult("/bridge/submit-tx", (c) => c.submitTx(body), config);
|
|
33777
33711
|
}
|
|
33778
33712
|
/**
|
|
33779
33713
|
* Get the processing status of a submitted bridge transaction by `(txHash, srcChainKey)`.
|
|
@@ -33781,13 +33715,7 @@ var BridgeApiService = class {
|
|
|
33781
33715
|
* @returns `Result<BridgeSubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
|
|
33782
33716
|
*/
|
|
33783
33717
|
async getSubmitTxStatus(query, config) {
|
|
33784
|
-
|
|
33785
|
-
return this.request(
|
|
33786
|
-
`/bridge/submit-tx/status?${queryParams.toString()}`,
|
|
33787
|
-
{ method: "GET" },
|
|
33788
|
-
BridgeSubmitTxStatusResponseSchema,
|
|
33789
|
-
config
|
|
33790
|
-
);
|
|
33718
|
+
return this.toResult("/bridge/submit-tx/status", (c) => c.getSubmitTxStatus(query), config);
|
|
33791
33719
|
}
|
|
33792
33720
|
// ──────────────────────────────────────────────────────────────────────
|
|
33793
33721
|
// Fee · bridgeable quote (read-only; mirror the SDK-core client-side methods)
|
|
@@ -33801,12 +33729,7 @@ var BridgeApiService = class {
|
|
|
33801
33729
|
* @returns `Result<BridgeFeeResponseV2>` — `{ fee }` (decimal string).
|
|
33802
33730
|
*/
|
|
33803
33731
|
async getFee(body, config) {
|
|
33804
|
-
return this.
|
|
33805
|
-
"/bridge/fee",
|
|
33806
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33807
|
-
BridgeFeeResponseSchema,
|
|
33808
|
-
config
|
|
33809
|
-
);
|
|
33732
|
+
return this.toResult("/bridge/fee", (c) => c.getFee(body), config);
|
|
33810
33733
|
}
|
|
33811
33734
|
/**
|
|
33812
33735
|
* Deposit capacity / withdrawal liquidity for a (from, to) token pair. Computable client-side in the
|
|
@@ -33815,12 +33738,7 @@ var BridgeApiService = class {
|
|
|
33815
33738
|
* @returns `Result<BridgeableAmountResponseV2>` — `{ limit }`.
|
|
33816
33739
|
*/
|
|
33817
33740
|
async getBridgeableAmount(body, config) {
|
|
33818
|
-
return this.
|
|
33819
|
-
"/bridge/bridgeable-amount",
|
|
33820
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33821
|
-
BridgeableAmountResponseSchema,
|
|
33822
|
-
config
|
|
33823
|
-
);
|
|
33741
|
+
return this.toResult("/bridge/bridgeable-amount", (c) => c.getBridgeableAmount(body), config);
|
|
33824
33742
|
}
|
|
33825
33743
|
/**
|
|
33826
33744
|
* Whether a (from, to) token pair is bridgeable. Computable client-side in the SDK core
|
|
@@ -33829,19 +33747,15 @@ var BridgeApiService = class {
|
|
|
33829
33747
|
* @returns `Result<BridgeableCheckResponseV2>` — `{ bridgeable }`.
|
|
33830
33748
|
*/
|
|
33831
33749
|
async isBridgeable(body, config) {
|
|
33832
|
-
return this.
|
|
33833
|
-
"/bridge/bridgeable/check",
|
|
33834
|
-
{ method: "POST", body: toJsonBody(body) },
|
|
33835
|
-
BridgeableCheckResponseSchema,
|
|
33836
|
-
config
|
|
33837
|
-
);
|
|
33750
|
+
return this.toResult("/bridge/bridgeable/check", (c) => c.isBridgeable(body), config);
|
|
33838
33751
|
}
|
|
33839
33752
|
// ──────────────────────────────────────────────────────────────────────
|
|
33840
33753
|
// Utilities (parity with SwapsApiService)
|
|
33841
33754
|
// ──────────────────────────────────────────────────────────────────────
|
|
33842
33755
|
/**
|
|
33843
33756
|
* Merge additional headers into the service's default header set. Existing
|
|
33844
|
-
* keys are overwritten; keys absent from `headers` are preserved.
|
|
33757
|
+
* keys are overwritten; keys absent from `headers` are preserved. Applied to
|
|
33758
|
+
* every subsequent call (the delegated client is rebuilt per call).
|
|
33845
33759
|
*/
|
|
33846
33760
|
setHeaders(headers) {
|
|
33847
33761
|
assignHeaders(this.headers, headers);
|
|
@@ -43865,6 +43779,24 @@ var isLeverageYieldPostExecutionError = isCodeMember(
|
|
|
43865
43779
|
var isLeverageYieldSwapError = isCodeMember(LEVERAGE_YIELD_SWAP_CODES);
|
|
43866
43780
|
var isLeverageYieldError = isCodeMember(LEVERAGE_YIELD_CODES);
|
|
43867
43781
|
|
|
43782
|
+
// src/leverageYield/positionFunding.ts
|
|
43783
|
+
function resolvePositionFundingAddress(chainKey, hubChainKey, token) {
|
|
43784
|
+
if (chainKey !== hubChainKey) return token?.address ?? "";
|
|
43785
|
+
if (token && isNativeToken(chainKey, token)) return token.address;
|
|
43786
|
+
return token?.hubAsset ?? token?.address ?? "";
|
|
43787
|
+
}
|
|
43788
|
+
|
|
43789
|
+
// src/leverageYield/positionIntent.ts
|
|
43790
|
+
async function reportPositionIntent(notifySolver, txHashes) {
|
|
43791
|
+
const result = await notifySolver({ intent_tx_hash: txHashes.dstChainTxHash }).catch((error2) => ({
|
|
43792
|
+
ok: false,
|
|
43793
|
+
error: error2
|
|
43794
|
+
}));
|
|
43795
|
+
if (result.ok) return { txHashes, notified: true };
|
|
43796
|
+
const { error } = result;
|
|
43797
|
+
return { txHashes, notified: false, notifyError: error instanceof Error ? error.message : String(error) };
|
|
43798
|
+
}
|
|
43799
|
+
|
|
43868
43800
|
// src/leverageYield/LeverageYieldService.ts
|
|
43869
43801
|
var leverageYieldVaultAbi = viem.parseAbi([
|
|
43870
43802
|
"function asset() view returns (address)",
|
|
@@ -43874,7 +43806,31 @@ var leverageYieldVaultAbi = viem.parseAbi([
|
|
|
43874
43806
|
"function borrowToken() view returns (address)",
|
|
43875
43807
|
"function targetLTV() view returns (uint256)"
|
|
43876
43808
|
]);
|
|
43809
|
+
var MAX_POSITION_FEE_BPS = 100;
|
|
43810
|
+
var leveragePositionFactoryAbi = viem.parseAbi([
|
|
43811
|
+
"function positionsOf(address owner) view returns (address[])",
|
|
43812
|
+
"function nextPositionIdFor(address owner) view returns (uint256)",
|
|
43813
|
+
"function predictPosition(address creator, address owner, uint256 positionId) view returns (address)",
|
|
43814
|
+
"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)",
|
|
43815
|
+
"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)"
|
|
43816
|
+
]);
|
|
43817
|
+
var leveragePositionAbi = viem.parseAbi([
|
|
43818
|
+
"function owner() view returns (address)",
|
|
43819
|
+
"function collateral() view returns (address)",
|
|
43820
|
+
"function borrowToken() view returns (address)",
|
|
43821
|
+
"function eModeCategory() view returns (uint8)",
|
|
43822
|
+
"function feeBps() view returns (uint16)",
|
|
43823
|
+
"function feeReceiver() view returns (address)",
|
|
43824
|
+
"function hasPendingOperation() view returns (bool)",
|
|
43825
|
+
"function pendingKind() view returns (uint8)",
|
|
43826
|
+
"function addLeverage(uint256 borrowAmount, uint256 minCollateralOut)",
|
|
43827
|
+
"function decreaseLeverage(uint256 collateralIn, uint256 minDebtOut, address exitAsset)",
|
|
43828
|
+
"function withdraw(uint256 amount, address to)",
|
|
43829
|
+
"function cancel()",
|
|
43830
|
+
"function settle()"
|
|
43831
|
+
]);
|
|
43877
43832
|
var INTENT_DEADLINE_BUFFER_SECONDS = 5 * 60;
|
|
43833
|
+
var BITCOIN_UNSUPPORTED_MESSAGE = "Bitcoin is not a supported source chain for leverage positions; use a supported spoke or the hub";
|
|
43878
43834
|
var ANY_SOLVER_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
43879
43835
|
var MAX_WITHDRAW_DUST_BUFFER = 1000n;
|
|
43880
43836
|
function pctToRay(aprPct) {
|
|
@@ -43931,7 +43887,7 @@ var LeverageYieldService = class {
|
|
|
43931
43887
|
}
|
|
43932
43888
|
/** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
|
|
43933
43889
|
getVault(name) {
|
|
43934
|
-
return this.listVaults().find((
|
|
43890
|
+
return this.listVaults().find((v10) => v10.name === name);
|
|
43935
43891
|
}
|
|
43936
43892
|
/**
|
|
43937
43893
|
* Looks up a registered vault by its on-chain proxy address (case-insensitive).
|
|
@@ -43939,7 +43895,7 @@ var LeverageYieldService = class {
|
|
|
43939
43895
|
*/
|
|
43940
43896
|
getVaultByAddress(address) {
|
|
43941
43897
|
const normalized = address.toLowerCase();
|
|
43942
|
-
return this.listVaults().find((
|
|
43898
|
+
return this.listVaults().find((v10) => v10.vault.toLowerCase() === normalized);
|
|
43943
43899
|
}
|
|
43944
43900
|
/**
|
|
43945
43901
|
* Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
|
|
@@ -44528,7 +44484,12 @@ var LeverageYieldService = class {
|
|
|
44528
44484
|
}
|
|
44529
44485
|
}
|
|
44530
44486
|
/**
|
|
44531
|
-
* Notifies the solver that
|
|
44487
|
+
* Notifies the solver that an intent landed on the hub, triggering it to fill.
|
|
44488
|
+
*
|
|
44489
|
+
* REQUIRED for anything that creates an intent, not an optimisation. An intent created on the hub
|
|
44490
|
+
* is invisible to the solver until this call puts it in the task pool, so an unnotified intent
|
|
44491
|
+
* simply expires. Leverage positions post their intents on-chain from the position contract, so
|
|
44492
|
+
* the caller that sent the transaction is the only one who can report the hash.
|
|
44532
44493
|
* Leverage-yield copy of the swap domain's `postExecution` — emits only
|
|
44533
44494
|
* `EXECUTION_FAILED` / `EXTERNAL_API_ERROR` / `UNKNOWN` (relay/verify codes appear only
|
|
44534
44495
|
* on {@link LeverageYieldService.vaultSwap}, which owns the verify + relay steps).
|
|
@@ -44573,6 +44534,51 @@ var LeverageYieldService = class {
|
|
|
44573
44534
|
return { ok: false, error: executionFailed("leverageYield", error, { phase: "postExecution" }) };
|
|
44574
44535
|
}
|
|
44575
44536
|
}
|
|
44537
|
+
/**
|
|
44538
|
+
* Polls the solver for the execution status of an intent this service created.
|
|
44539
|
+
*
|
|
44540
|
+
* Pair with {@link LeverageYieldService.notifySolver}: `notifySolver` puts the intent in the
|
|
44541
|
+
* solver's task pool, this reports what became of it. `fill_tx_hash` is set only once
|
|
44542
|
+
* `status === SolverIntentStatusCode.SOLVED`.
|
|
44543
|
+
*
|
|
44544
|
+
* A `NOT_FOUND` status usually means the notification never landed rather than that the intent
|
|
44545
|
+
* does not exist — an intent created on the hub is invisible to the solver until it is told.
|
|
44546
|
+
*
|
|
44547
|
+
* @param request - `{ intent_tx_hash }` — the hub-chain (Sonic) tx hash the intent was
|
|
44548
|
+
* registered in. For a position that is the tx that called the factory or the position.
|
|
44549
|
+
*/
|
|
44550
|
+
async getIntentStatus(request) {
|
|
44551
|
+
try {
|
|
44552
|
+
const result = await SolverApiService.getStatus(
|
|
44553
|
+
request,
|
|
44554
|
+
this.config.solver,
|
|
44555
|
+
this.config.logger,
|
|
44556
|
+
void 0,
|
|
44557
|
+
this.config.apiKey
|
|
44558
|
+
);
|
|
44559
|
+
if (result.ok) return result;
|
|
44560
|
+
const detail = result.error?.detail ?? {
|
|
44561
|
+
code: -999,
|
|
44562
|
+
// SolverIntentErrorCode.UNKNOWN
|
|
44563
|
+
message: "Solver returned malformed error response"
|
|
44564
|
+
};
|
|
44565
|
+
return {
|
|
44566
|
+
ok: false,
|
|
44567
|
+
error: new SodaxError("EXTERNAL_API_ERROR", detail.message, {
|
|
44568
|
+
feature: "leverageYield",
|
|
44569
|
+
context: {
|
|
44570
|
+
phase: "lookup",
|
|
44571
|
+
api: "solver",
|
|
44572
|
+
solverCode: detail.code,
|
|
44573
|
+
solverDetail: detail
|
|
44574
|
+
}
|
|
44575
|
+
})
|
|
44576
|
+
};
|
|
44577
|
+
} catch (error) {
|
|
44578
|
+
if (isLeverageYieldPostExecutionError(error)) return { ok: false, error };
|
|
44579
|
+
return { ok: false, error: executionFailed("leverageYield", error, { phase: "lookup" }) };
|
|
44580
|
+
}
|
|
44581
|
+
}
|
|
44576
44582
|
/**
|
|
44577
44583
|
* Approves the vault's underlying asset to the leverage vault on Sonic. For callers
|
|
44578
44584
|
* interacting with the vault directly on the hub — the swap-style {@link
|
|
@@ -44881,6 +44887,1252 @@ var LeverageYieldService = class {
|
|
|
44881
44887
|
return { ok: false, error: lookupFailed("leverageYield", "getShareBalanceForUser", error, { srcChainKey }) };
|
|
44882
44888
|
}
|
|
44883
44889
|
}
|
|
44890
|
+
// ─── Leverage positions ────────────────────────────────────────────────
|
|
44891
|
+
/**
|
|
44892
|
+
* Resolves the `LeveragePositionFactory` address, or a validation error when it is missing.
|
|
44893
|
+
*
|
|
44894
|
+
* The deployed factory ships in `leverageYieldConfig`, so this only fails when an integrator
|
|
44895
|
+
* overrides it with an empty value — which is what a bad env var produces. Failing closed there is
|
|
44896
|
+
* deliberate: a placeholder address would post real intents at nothing.
|
|
44897
|
+
*/
|
|
44898
|
+
requireFactory(action) {
|
|
44899
|
+
const factory = this.config.sodaxConfig.leverageYield.positionFactory;
|
|
44900
|
+
if (!factory) {
|
|
44901
|
+
return {
|
|
44902
|
+
ok: false,
|
|
44903
|
+
error: lookupFailed(
|
|
44904
|
+
"leverageYield",
|
|
44905
|
+
action,
|
|
44906
|
+
new Error("leverageYield.positionFactory is not configured; supply the deployed factory address")
|
|
44907
|
+
)
|
|
44908
|
+
};
|
|
44909
|
+
}
|
|
44910
|
+
return { ok: true, value: factory };
|
|
44911
|
+
}
|
|
44912
|
+
/** Position clones owned by `owner`, in creation order. Empty when the owner has none. */
|
|
44913
|
+
async listPositions(owner) {
|
|
44914
|
+
const factory = this.requireFactory("listPositions");
|
|
44915
|
+
if (!factory.ok) return factory;
|
|
44916
|
+
try {
|
|
44917
|
+
const value = await this.hubProvider.publicClient.readContract({
|
|
44918
|
+
address: factory.value,
|
|
44919
|
+
abi: leveragePositionFactoryAbi,
|
|
44920
|
+
functionName: "positionsOf",
|
|
44921
|
+
args: [owner]
|
|
44922
|
+
});
|
|
44923
|
+
return { ok: true, value };
|
|
44924
|
+
} catch (error) {
|
|
44925
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
44926
|
+
return { ok: false, error: lookupFailed("leverageYield", "listPositions", error) };
|
|
44927
|
+
}
|
|
44928
|
+
}
|
|
44929
|
+
/**
|
|
44930
|
+
* Positions belonging to a user, resolved by their spoke-side address rather than a hub address.
|
|
44931
|
+
*
|
|
44932
|
+
* Positions are owned by the user's hub wallet, so discovery goes through
|
|
44933
|
+
* `getUserHubWalletAddress` — which returns the wallet router for a Sonic user and the
|
|
44934
|
+
* cross-chain wallet for a spoke user, so the same call works on every chain. Prefer this over
|
|
44935
|
+
* `listPositions` in user-facing code; passing a raw EOA finds nothing.
|
|
44936
|
+
*/
|
|
44937
|
+
async listPositionsForUser(srcChainKey, srcAddress) {
|
|
44938
|
+
try {
|
|
44939
|
+
const hubWallet = await this.hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey);
|
|
44940
|
+
return await this.listPositions(hubWallet);
|
|
44941
|
+
} catch (error) {
|
|
44942
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
44943
|
+
return { ok: false, error: lookupFailed("leverageYield", "listPositionsForUser", error, { srcChainKey }) };
|
|
44944
|
+
}
|
|
44945
|
+
}
|
|
44946
|
+
/** Static descriptor of a position — owner, both legs, and the fixed eMode category. */
|
|
44947
|
+
async getPositionInfo(position) {
|
|
44948
|
+
try {
|
|
44949
|
+
const [owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver] = await Promise.all([
|
|
44950
|
+
this.hubProvider.publicClient.readContract({
|
|
44951
|
+
address: position,
|
|
44952
|
+
abi: leveragePositionAbi,
|
|
44953
|
+
functionName: "owner"
|
|
44954
|
+
}),
|
|
44955
|
+
this.hubProvider.publicClient.readContract({
|
|
44956
|
+
address: position,
|
|
44957
|
+
abi: leveragePositionAbi,
|
|
44958
|
+
functionName: "collateral"
|
|
44959
|
+
}),
|
|
44960
|
+
this.hubProvider.publicClient.readContract({
|
|
44961
|
+
address: position,
|
|
44962
|
+
abi: leveragePositionAbi,
|
|
44963
|
+
functionName: "borrowToken"
|
|
44964
|
+
}),
|
|
44965
|
+
this.hubProvider.publicClient.readContract({
|
|
44966
|
+
address: position,
|
|
44967
|
+
abi: leveragePositionAbi,
|
|
44968
|
+
functionName: "eModeCategory"
|
|
44969
|
+
}),
|
|
44970
|
+
this.hubProvider.publicClient.readContract({
|
|
44971
|
+
address: position,
|
|
44972
|
+
abi: leveragePositionAbi,
|
|
44973
|
+
functionName: "feeBps"
|
|
44974
|
+
}),
|
|
44975
|
+
this.hubProvider.publicClient.readContract({
|
|
44976
|
+
address: position,
|
|
44977
|
+
abi: leveragePositionAbi,
|
|
44978
|
+
functionName: "feeReceiver"
|
|
44979
|
+
})
|
|
44980
|
+
]);
|
|
44981
|
+
return {
|
|
44982
|
+
ok: true,
|
|
44983
|
+
value: {
|
|
44984
|
+
address: position,
|
|
44985
|
+
owner,
|
|
44986
|
+
collateral,
|
|
44987
|
+
borrowToken,
|
|
44988
|
+
eModeCategory,
|
|
44989
|
+
// From the position, not from config: config can change and an open can override it, so
|
|
44990
|
+
// what a NEW position would carry is not what THIS one does.
|
|
44991
|
+
feeBps: Number(feeBps),
|
|
44992
|
+
feeReceiver
|
|
44993
|
+
}
|
|
44994
|
+
};
|
|
44995
|
+
} catch (error) {
|
|
44996
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
44997
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionInfo", error) };
|
|
44998
|
+
}
|
|
44999
|
+
}
|
|
45000
|
+
/**
|
|
45001
|
+
* Live AAVE account snapshot for a position. Read from the pool, not the position: the
|
|
45002
|
+
* position contract keeps no accounting of its own, so collateral, debt and health factor
|
|
45003
|
+
* all come from `getUserAccountData`.
|
|
45004
|
+
*
|
|
45005
|
+
* The pool comes from `moneyMarket.lendingPool` config rather than the position's own
|
|
45006
|
+
* `pool()` getter — same address, one fewer round trip, and it keeps the deployment address
|
|
45007
|
+
* sourced from config like the rest of the SDK.
|
|
45008
|
+
*/
|
|
45009
|
+
async getPositionAccount(position) {
|
|
45010
|
+
try {
|
|
45011
|
+
const [totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor] = await this.hubProvider.publicClient.readContract({
|
|
45012
|
+
address: this.config.sodaxConfig.moneyMarket.lendingPool,
|
|
45013
|
+
abi: poolAbi,
|
|
45014
|
+
functionName: "getUserAccountData",
|
|
45015
|
+
args: [position]
|
|
45016
|
+
});
|
|
45017
|
+
return {
|
|
45018
|
+
ok: true,
|
|
45019
|
+
value: {
|
|
45020
|
+
totalCollateralBase,
|
|
45021
|
+
totalDebtBase,
|
|
45022
|
+
availableBorrowsBase,
|
|
45023
|
+
currentLiquidationThreshold,
|
|
45024
|
+
ltv,
|
|
45025
|
+
healthFactor
|
|
45026
|
+
}
|
|
45027
|
+
};
|
|
45028
|
+
} catch (error) {
|
|
45029
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45030
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionAccount", error) };
|
|
45031
|
+
}
|
|
45032
|
+
}
|
|
45033
|
+
/**
|
|
45034
|
+
* The position's collateral holding, as an exact aToken balance.
|
|
45035
|
+
*
|
|
45036
|
+
* Needed to size a full exit. {@link LeverageYieldService.getPositionAccount} reports collateral
|
|
45037
|
+
* in the oracle's base currency at 8 decimals, which is fine to display but cannot name an amount:
|
|
45038
|
+
* dividing it back out by a price lands near the balance, and a `decreaseLeverage` asking for more
|
|
45039
|
+
* collateral than the position holds does not fail on submission — the hook's `transferFrom`
|
|
45040
|
+
* reverts at fill time, so the intent silently expires instead.
|
|
45041
|
+
*
|
|
45042
|
+
* Safe to act on a slightly stale read: aToken balances only grow, since interest accrues into
|
|
45043
|
+
* them, so a value from a few blocks ago is always still spendable. Selling it leaves interest
|
|
45044
|
+
* dust behind rather than coming up short.
|
|
45045
|
+
*
|
|
45046
|
+
* @param collateral The position's collateral reserve. Read from the position when omitted; pass
|
|
45047
|
+
* it if you already hold a {@link LeveragePosition} to save the round trip.
|
|
45048
|
+
*/
|
|
45049
|
+
async getPositionCollateralBalance(position, collateral) {
|
|
45050
|
+
try {
|
|
45051
|
+
const asset = collateral ?? await this.hubProvider.publicClient.readContract({
|
|
45052
|
+
address: position,
|
|
45053
|
+
abi: leveragePositionAbi,
|
|
45054
|
+
functionName: "collateral"
|
|
45055
|
+
});
|
|
45056
|
+
const reserve = await this.hubProvider.publicClient.readContract({
|
|
45057
|
+
address: this.config.sodaxConfig.moneyMarket.lendingPool,
|
|
45058
|
+
abi: poolAbi,
|
|
45059
|
+
functionName: "getReserveData",
|
|
45060
|
+
args: [asset]
|
|
45061
|
+
});
|
|
45062
|
+
const aToken = reserve.aTokenAddress;
|
|
45063
|
+
const balance = await this.hubProvider.publicClient.readContract({
|
|
45064
|
+
address: aToken,
|
|
45065
|
+
abi: viem.erc20Abi,
|
|
45066
|
+
functionName: "balanceOf",
|
|
45067
|
+
args: [position]
|
|
45068
|
+
});
|
|
45069
|
+
return { ok: true, value: { aToken, balance } };
|
|
45070
|
+
} catch (error) {
|
|
45071
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45072
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionCollateralBalance", error) };
|
|
45073
|
+
}
|
|
45074
|
+
}
|
|
45075
|
+
/**
|
|
45076
|
+
* The position's operation slot: which operation it recorded, and whether that intent is still
|
|
45077
|
+
* live on `Intents`.
|
|
45078
|
+
*
|
|
45079
|
+
* Both are needed, because the interesting state is when they disagree. `isLive` false with a
|
|
45080
|
+
* non-zero `kind` means the intent resolved — filled, expired, or cancelled by someone else — but
|
|
45081
|
+
* the position has not been told, so its grant is still open and any debt-side contribution is
|
|
45082
|
+
* still sitting there. That is what `needsSettle` flags, and `buildSettlePosition` clears. A live
|
|
45083
|
+
* intent instead blocks any second operation until it resolves.
|
|
45084
|
+
*/
|
|
45085
|
+
async getPositionPendingState(position) {
|
|
45086
|
+
try {
|
|
45087
|
+
const [isLive, kind] = await Promise.all([
|
|
45088
|
+
this.hubProvider.publicClient.readContract({
|
|
45089
|
+
address: position,
|
|
45090
|
+
abi: leveragePositionAbi,
|
|
45091
|
+
functionName: "hasPendingOperation"
|
|
45092
|
+
}),
|
|
45093
|
+
this.hubProvider.publicClient.readContract({
|
|
45094
|
+
address: position,
|
|
45095
|
+
abi: leveragePositionAbi,
|
|
45096
|
+
functionName: "pendingKind"
|
|
45097
|
+
})
|
|
45098
|
+
]);
|
|
45099
|
+
return { ok: true, value: { kind, isLive, needsSettle: kind !== 0 && !isLive } };
|
|
45100
|
+
} catch (error) {
|
|
45101
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45102
|
+
return { ok: false, error: lookupFailed("leverageYield", "getPositionPendingState", error) };
|
|
45103
|
+
}
|
|
45104
|
+
}
|
|
45105
|
+
/** Deterministic clone address for the next position a given creator opens for `owner`. */
|
|
45106
|
+
async predictPosition(creator, owner, positionId) {
|
|
45107
|
+
const factory = this.requireFactory("predictPosition");
|
|
45108
|
+
if (!factory.ok) return factory;
|
|
45109
|
+
try {
|
|
45110
|
+
const id = positionId ?? await this.hubProvider.publicClient.readContract({
|
|
45111
|
+
address: factory.value,
|
|
45112
|
+
abi: leveragePositionFactoryAbi,
|
|
45113
|
+
functionName: "nextPositionIdFor",
|
|
45114
|
+
args: [owner]
|
|
45115
|
+
});
|
|
45116
|
+
const value = await this.hubProvider.publicClient.readContract({
|
|
45117
|
+
address: factory.value,
|
|
45118
|
+
abi: leveragePositionFactoryAbi,
|
|
45119
|
+
functionName: "predictPosition",
|
|
45120
|
+
args: [creator, owner, id]
|
|
45121
|
+
});
|
|
45122
|
+
return { ok: true, value };
|
|
45123
|
+
} catch (error) {
|
|
45124
|
+
if (isLeverageYieldLookupError(error)) return { ok: false, error };
|
|
45125
|
+
return { ok: false, error: lookupFailed("leverageYield", "predictPosition", error) };
|
|
45126
|
+
}
|
|
45127
|
+
}
|
|
45128
|
+
// ─── Position transaction builders ─────────────────────────────────────
|
|
45129
|
+
//
|
|
45130
|
+
// Positions are driven by direct Sonic calls, not intents, so these return raw transactions
|
|
45131
|
+
// for the caller to sign with a hub wallet provider. The leverage and deleverage calls only
|
|
45132
|
+
// *post* an intent — a solver fills it afterwards, so poll `getPositionPendingState`
|
|
45133
|
+
// rather than treating the receipt as completion.
|
|
45134
|
+
/**
|
|
45135
|
+
* Opens a new position and requests leverage on it in the same transaction — the standard way
|
|
45136
|
+
* to open a leveraged position: one approve, then this.
|
|
45137
|
+
*
|
|
45138
|
+
* `initialAssets` of `collateral` is pulled from the signer, so the factory needs an allowance
|
|
45139
|
+
* first. Control is assigned to `owner`, which may differ from the signer — pass a user's hub
|
|
45140
|
+
* wallet address to have the existing cross-chain path drive the position.
|
|
45141
|
+
*
|
|
45142
|
+
* The leverage is still asynchronous: this posts the intent and a solver fills it afterwards,
|
|
45143
|
+
* so on confirmation the position is funded with the request outstanding, not yet levered. If
|
|
45144
|
+
* no solver fills it, `buildCancelPositionOperation` returns the deposit to the owner.
|
|
45145
|
+
*/
|
|
45146
|
+
/**
|
|
45147
|
+
* Turns a {@link PositionOrigin} into the tuple the factory takes, and refuses the combinations the
|
|
45148
|
+
* contract would refuse anyway — better a rejected build than a transaction that reverts.
|
|
45149
|
+
*/
|
|
45150
|
+
resolveOrigin(origin, method) {
|
|
45151
|
+
const chainId = getIntentRelayChainId(origin.chainKey);
|
|
45152
|
+
if (chainId === void 0) {
|
|
45153
|
+
return {
|
|
45154
|
+
ok: false,
|
|
45155
|
+
error: lookupFailed(
|
|
45156
|
+
"leverageYield",
|
|
45157
|
+
method,
|
|
45158
|
+
new Error(`no relay chain id for origin chain ${origin.chainKey}`)
|
|
45159
|
+
)
|
|
45160
|
+
};
|
|
45161
|
+
}
|
|
45162
|
+
const isHub = origin.chainKey === this.hubProvider.chainConfig.chain.key;
|
|
45163
|
+
if (!isHub && !origin.asset) {
|
|
45164
|
+
return {
|
|
45165
|
+
ok: false,
|
|
45166
|
+
error: lookupFailed(
|
|
45167
|
+
"leverageYield",
|
|
45168
|
+
method,
|
|
45169
|
+
new Error(`origin.asset is required for a refund to ${origin.chainKey}`)
|
|
45170
|
+
)
|
|
45171
|
+
};
|
|
45172
|
+
}
|
|
45173
|
+
return {
|
|
45174
|
+
ok: true,
|
|
45175
|
+
value: {
|
|
45176
|
+
chainId,
|
|
45177
|
+
// The chain's own encoding, not a 0x-prefixed string. `originAddress` is `bytes` on-chain and
|
|
45178
|
+
// is handed to the AssetManager as the refund destination, so a Solana or Stellar address has
|
|
45179
|
+
// to arrive in the form that chain's spoke expects — prefixing `0x` would produce a refund
|
|
45180
|
+
// address that is merely well-formed hex. EVM addresses pass through unchanged.
|
|
45181
|
+
address: encodeAddress(origin.chainKey, origin.address),
|
|
45182
|
+
// Named on the hub as well, not just off it. The asset decides what a cancellation pays back,
|
|
45183
|
+
// and zeroing it here is why someone who funded with USSD was refunded `sodaUSSD`. Callers pass
|
|
45184
|
+
// the asset only when a wrap actually happened — when the reserve IS what was deposited there is
|
|
45185
|
+
// nothing to unwrap and `address(0)` is the correct answer.
|
|
45186
|
+
asset: origin.asset ?? viem.zeroAddress
|
|
45187
|
+
}
|
|
45188
|
+
};
|
|
45189
|
+
}
|
|
45190
|
+
/**
|
|
45191
|
+
* Partner fee for a position, in the shape `PositionConfig` takes.
|
|
45192
|
+
*
|
|
45193
|
+
* Only the PERCENTAGE variant of `PartnerFee` maps: the contract stores basis points and derives
|
|
45194
|
+
* the amount per operation (`_feeFor`), so a fixed-amount fee has nowhere to go and is rejected
|
|
45195
|
+
* rather than silently dropped. Same precedence as the vault flows — per-call, then
|
|
45196
|
+
* `leverageYield.partnerFee`, then none.
|
|
45197
|
+
*
|
|
45198
|
+
* The fee is FIXED AT CREATION on-chain, so this is read when a position is created and never
|
|
45199
|
+
* again; changing the config later does not re-price positions already open.
|
|
45200
|
+
*/
|
|
45201
|
+
/**
|
|
45202
|
+
* The fee a position created NOW would carry, in basis points, plus who receives it.
|
|
45203
|
+
*
|
|
45204
|
+
* Public because a caller cannot project a position correctly without it and cannot derive it:
|
|
45205
|
+
* the fee resolves from `leverageYield.partnerFee`, then the global fee, then none, and it is
|
|
45206
|
+
* FIXED AT CREATION on-chain. Feed `feeBps` to {@link projectLeverageLeg} — the hooks require
|
|
45207
|
+
* `inputAmount + fee`, so a leverage-up borrows the fee ON TOP of what the solver is paid. Leaving
|
|
45208
|
+
* it out understates LTV and overstates the ceiling, which is the Aave `'36'` failure at fill time
|
|
45209
|
+
* this module exists to prevent: 50 bp takes a debt-side ceiling from 9.88x to about 9.44x.
|
|
45210
|
+
*
|
|
45211
|
+
* Pass the same `override` here as to the open call, or omit it on both.
|
|
45212
|
+
*/
|
|
45213
|
+
getEffectivePositionFee(override) {
|
|
45214
|
+
return this.resolvePositionFee(override, "getEffectivePositionFee");
|
|
45215
|
+
}
|
|
45216
|
+
resolvePositionFee(override, method) {
|
|
45217
|
+
const fee = override ?? this.config.leverageYieldPartnerFee;
|
|
45218
|
+
if (!fee) return { ok: true, value: { feeReceiver: viem.zeroAddress, feeBps: 0 } };
|
|
45219
|
+
if (!isPartnerFeePercentage(fee)) {
|
|
45220
|
+
return {
|
|
45221
|
+
ok: false,
|
|
45222
|
+
error: lookupFailed(
|
|
45223
|
+
"leverageYield",
|
|
45224
|
+
method,
|
|
45225
|
+
new Error("a position partner fee must be the percentage variant; PositionConfig stores basis points")
|
|
45226
|
+
)
|
|
45227
|
+
};
|
|
45228
|
+
}
|
|
45229
|
+
if (!Number.isInteger(fee.percentage) || fee.percentage < 0 || fee.percentage > MAX_POSITION_FEE_BPS) {
|
|
45230
|
+
return {
|
|
45231
|
+
ok: false,
|
|
45232
|
+
error: lookupFailed(
|
|
45233
|
+
"leverageYield",
|
|
45234
|
+
method,
|
|
45235
|
+
new Error(
|
|
45236
|
+
`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})`
|
|
45237
|
+
)
|
|
45238
|
+
)
|
|
45239
|
+
};
|
|
45240
|
+
}
|
|
45241
|
+
if (fee.percentage === 0 !== viem.isAddressEqual(fee.address, viem.zeroAddress)) {
|
|
45242
|
+
return {
|
|
45243
|
+
ok: false,
|
|
45244
|
+
error: lookupFailed(
|
|
45245
|
+
"leverageYield",
|
|
45246
|
+
method,
|
|
45247
|
+
new Error(
|
|
45248
|
+
`a position partner fee needs a rate and a receiver together, or neither (got ${fee.percentage} bps for ${fee.address})`
|
|
45249
|
+
)
|
|
45250
|
+
)
|
|
45251
|
+
};
|
|
45252
|
+
}
|
|
45253
|
+
return { ok: true, value: { feeReceiver: fee.address, feeBps: fee.percentage } };
|
|
45254
|
+
}
|
|
45255
|
+
/** A hub transaction. Every builder below produces this shape and none of them sends value. */
|
|
45256
|
+
// Generic so a builder's declared return type applies its own brand. The cast is the single one
|
|
45257
|
+
// the pattern needs — a brand is type-only and erased at runtime — and keeping it here means no
|
|
45258
|
+
// builder carries one of its own.
|
|
45259
|
+
hubTx(from, to, data) {
|
|
45260
|
+
return { from, to, value: 0n, data };
|
|
45261
|
+
}
|
|
45262
|
+
/**
|
|
45263
|
+
* The `PositionConfig` struct both factory entry points take, assembled from a resolved origin.
|
|
45264
|
+
*
|
|
45265
|
+
* Shared so the two create paths cannot drift: which side the funded reserve goes on is their only
|
|
45266
|
+
* real difference, and a field silently spelled differently in one of them would be a
|
|
45267
|
+
* mis-recorded refund destination rather than a compile error.
|
|
45268
|
+
*/
|
|
45269
|
+
positionConfig(args) {
|
|
45270
|
+
return {
|
|
45271
|
+
owner: args.owner,
|
|
45272
|
+
collateral: args.collateral,
|
|
45273
|
+
borrowToken: args.borrowToken,
|
|
45274
|
+
eModeCategory: args.eModeCategory,
|
|
45275
|
+
originChainId: args.origin.chainId,
|
|
45276
|
+
originAddress: args.origin.address,
|
|
45277
|
+
originAsset: args.origin.asset,
|
|
45278
|
+
feeReceiver: args.fee?.feeReceiver ?? viem.zeroAddress,
|
|
45279
|
+
feeBps: args.fee?.feeBps ?? 0
|
|
45280
|
+
};
|
|
45281
|
+
}
|
|
45282
|
+
buildCreatePositionAndLeverage(params) {
|
|
45283
|
+
const method = "buildCreatePositionAndLeverage";
|
|
45284
|
+
const factory = this.requireFactory(method);
|
|
45285
|
+
if (!factory.ok) return factory;
|
|
45286
|
+
const fee = this.resolvePositionFee(params.partnerFee, method);
|
|
45287
|
+
if (!fee.ok) return fee;
|
|
45288
|
+
const origin = this.resolveOrigin(params.origin, method);
|
|
45289
|
+
if (!origin.ok) return origin;
|
|
45290
|
+
return {
|
|
45291
|
+
ok: true,
|
|
45292
|
+
value: this.hubTx(
|
|
45293
|
+
params.from,
|
|
45294
|
+
factory.value,
|
|
45295
|
+
viem.encodeFunctionData({
|
|
45296
|
+
abi: leveragePositionFactoryAbi,
|
|
45297
|
+
functionName: "createPositionAndLeverage",
|
|
45298
|
+
args: [
|
|
45299
|
+
this.positionConfig({ ...params, origin: origin.value, fee: fee.value }),
|
|
45300
|
+
params.initialAssets,
|
|
45301
|
+
params.borrowAmount,
|
|
45302
|
+
params.minCollateralOut
|
|
45303
|
+
]
|
|
45304
|
+
})
|
|
45305
|
+
)
|
|
45306
|
+
};
|
|
45307
|
+
}
|
|
45308
|
+
/**
|
|
45309
|
+
* Opens a levered position starting from the **debt** token, with no collateral of your own.
|
|
45310
|
+
*
|
|
45311
|
+
* Pulls `contribution` of `borrowToken` from the signer — not the collateral. On fill the hook
|
|
45312
|
+
* supplies the solver's collateral, adds the contribution, borrows `totalInput - contribution`,
|
|
45313
|
+
* and pays the solver the total, so a holder of the debt asset lands in a levered collateral
|
|
45314
|
+
* position having never owned collateral. Requires the deployment's implementation to have a
|
|
45315
|
+
* debt-side hook configured; otherwise the position reverts with `DebtSideHookUnavailable`.
|
|
45316
|
+
*/
|
|
45317
|
+
buildCreatePositionFromDebtToken(params) {
|
|
45318
|
+
const method = "buildCreatePositionFromDebtToken";
|
|
45319
|
+
const factory = this.requireFactory(method);
|
|
45320
|
+
if (!factory.ok) return factory;
|
|
45321
|
+
const fee = this.resolvePositionFee(params.partnerFee, method);
|
|
45322
|
+
if (!fee.ok) return fee;
|
|
45323
|
+
const origin = this.resolveOrigin(params.origin, method);
|
|
45324
|
+
if (!origin.ok) return origin;
|
|
45325
|
+
return {
|
|
45326
|
+
ok: true,
|
|
45327
|
+
value: this.hubTx(
|
|
45328
|
+
params.from,
|
|
45329
|
+
factory.value,
|
|
45330
|
+
viem.encodeFunctionData({
|
|
45331
|
+
abi: leveragePositionFactoryAbi,
|
|
45332
|
+
functionName: "createPositionFromDebtToken",
|
|
45333
|
+
args: [
|
|
45334
|
+
this.positionConfig({ ...params, origin: origin.value, fee: fee.value }),
|
|
45335
|
+
params.contribution,
|
|
45336
|
+
params.totalInput,
|
|
45337
|
+
params.minCollateralOut
|
|
45338
|
+
]
|
|
45339
|
+
})
|
|
45340
|
+
)
|
|
45341
|
+
};
|
|
45342
|
+
}
|
|
45343
|
+
/** Borrows `borrowAmount` and swaps it into more collateral. `minCollateralOut` is the slippage floor. */
|
|
45344
|
+
buildAddLeverage(params) {
|
|
45345
|
+
return this.hubTx(
|
|
45346
|
+
params.from,
|
|
45347
|
+
params.position,
|
|
45348
|
+
viem.encodeFunctionData({
|
|
45349
|
+
abi: leveragePositionAbi,
|
|
45350
|
+
functionName: "addLeverage",
|
|
45351
|
+
args: [params.borrowAmount, params.minCollateralOut]
|
|
45352
|
+
})
|
|
45353
|
+
);
|
|
45354
|
+
}
|
|
45355
|
+
/**
|
|
45356
|
+
* Gives up `collateralIn` of collateral to repay debt. `minDebtOut` is the slippage floor.
|
|
45357
|
+
*
|
|
45358
|
+
* CLOSING INTO THE DEBT TOKEN is this call with the position's collateral balance, less the fee a
|
|
45359
|
+
* non-zero `feeBps` gives up on top of the input (`balance x 10_000 / (10_000 + feeBps)`) — there is
|
|
45360
|
+
* no separate close entry point, because selling everything is the same operation as selling part.
|
|
45361
|
+
* Size it with {@link LeverageYieldService.getPositionCollateralBalance}, never off
|
|
45362
|
+
* `totalCollateralBase`, and quote the full amount so `minDebtOut` reflects what the solver will
|
|
45363
|
+
* actually pay for all of it.
|
|
45364
|
+
*
|
|
45365
|
+
* What that leaves behind is worth knowing. The solver delivers more debt token than is owed, so
|
|
45366
|
+
* the hook repays the debt and hands the surplus to the position, which is the owner's equity now
|
|
45367
|
+
* denominated in the debt asset. It sits in the position until someone calls
|
|
45368
|
+
* {@link LeverageYieldService.buildSettlePosition} — that sweep is what actually delivers it, and
|
|
45369
|
+
* it goes to the position's `owner` (the hub wallet), not to whoever signed. Exiting into the
|
|
45370
|
+
* *collateral* instead means repaying only the debt and then calling
|
|
45371
|
+
* {@link LeverageYieldService.buildPositionWithdraw}, which can pay out to any address.
|
|
45372
|
+
*/
|
|
45373
|
+
buildDecreaseLeverage(params) {
|
|
45374
|
+
return this.hubTx(
|
|
45375
|
+
params.from,
|
|
45376
|
+
params.position,
|
|
45377
|
+
viem.encodeFunctionData({
|
|
45378
|
+
abi: leveragePositionAbi,
|
|
45379
|
+
functionName: "decreaseLeverage",
|
|
45380
|
+
args: [params.collateralIn, params.minDebtOut, params.exitAsset ?? viem.zeroAddress]
|
|
45381
|
+
})
|
|
45382
|
+
);
|
|
45383
|
+
}
|
|
45384
|
+
/**
|
|
45385
|
+
* Withdraws collateral out of the position. The pool rejects a withdrawal that would drop
|
|
45386
|
+
* the position below its liquidation threshold, so no client-side health check is applied
|
|
45387
|
+
* here — but note that bound is health factor 1, not a safety buffer above it.
|
|
45388
|
+
*/
|
|
45389
|
+
buildPositionWithdraw(params) {
|
|
45390
|
+
return this.hubTx(
|
|
45391
|
+
params.from,
|
|
45392
|
+
params.position,
|
|
45393
|
+
viem.encodeFunctionData({
|
|
45394
|
+
abi: leveragePositionAbi,
|
|
45395
|
+
functionName: "withdraw",
|
|
45396
|
+
args: [params.amount, params.to]
|
|
45397
|
+
})
|
|
45398
|
+
);
|
|
45399
|
+
}
|
|
45400
|
+
/**
|
|
45401
|
+
* Clears an operation that has already resolved and returns anything the position is holding
|
|
45402
|
+
* loose to its owner.
|
|
45403
|
+
*
|
|
45404
|
+
* PERMISSIONLESS, and deliberately so: it only ever tightens state, so a stranded balance can be
|
|
45405
|
+
* pushed back by anyone rather than waiting on the owner to notice. That matters because an intent
|
|
45406
|
+
* can be cancelled by a third party once past its deadline, which leaves the position resolved but
|
|
45407
|
+
* un-swept if the hook's notification did not land.
|
|
45408
|
+
*
|
|
45409
|
+
* Reverts while the intent is still live — use {@link LeverageYieldService.buildCancelPositionOperation}
|
|
45410
|
+
* to end one that has not resolved yet.
|
|
45411
|
+
*/
|
|
45412
|
+
buildSettlePosition(params) {
|
|
45413
|
+
return this.hubTx(
|
|
45414
|
+
params.from,
|
|
45415
|
+
params.position,
|
|
45416
|
+
viem.encodeFunctionData({ abi: leveragePositionAbi, functionName: "settle" })
|
|
45417
|
+
);
|
|
45418
|
+
}
|
|
45419
|
+
/**
|
|
45420
|
+
* Cancels the in-flight operation and returns the deposit.
|
|
45421
|
+
*
|
|
45422
|
+
* Nothing is escrowed when an intent is posted, so cancelling recovers nothing by itself — but
|
|
45423
|
+
* a position carrying no debt withdraws its whole collateral balance back to the owner, which
|
|
45424
|
+
* is what a leveraged open whose intent never filled needs. With debt outstanding the
|
|
45425
|
+
* collateral stays put: the pool would reject the withdrawal on its health-factor check.
|
|
45426
|
+
*/
|
|
45427
|
+
buildCancelPositionOperation(params) {
|
|
45428
|
+
return this.hubTx(
|
|
45429
|
+
params.from,
|
|
45430
|
+
params.position,
|
|
45431
|
+
viem.encodeFunctionData({ abi: leveragePositionAbi, functionName: "cancel" })
|
|
45432
|
+
);
|
|
45433
|
+
}
|
|
45434
|
+
// ─── Positions from any chain ──────────────────────────────────────────
|
|
45435
|
+
//
|
|
45436
|
+
// The builders above produce a transaction sent straight to the hub. That only works for a user
|
|
45437
|
+
// signing on the hub, and even there it has to be routed so `msg.sender` is their hub wallet —
|
|
45438
|
+
// a position's `onlyOwner` is that wallet, and an EOA cannot send as another address.
|
|
45439
|
+
//
|
|
45440
|
+
// These take over from there: the calls are encoded as a hub-wallet payload and carried by the
|
|
45441
|
+
// spoke transport, which routes them locally on the hub and relays them from anywhere else. So one
|
|
45442
|
+
// code path covers every chain, and the hub is not a special case.
|
|
45443
|
+
/**
|
|
45444
|
+
* Encodes position calls as a hub-wallet payload.
|
|
45445
|
+
*
|
|
45446
|
+
* Takes the raw transactions from the builders above and produces the `(address,uint256,bytes)[]`
|
|
45447
|
+
* payload the hub wallet executes. Public because that payload is the unit the transport takes:
|
|
45448
|
+
* pass it to `spoke.deposit` / `spoke.sendMessage` yourself when you want manual relay control,
|
|
45449
|
+
* or use {@link LeverageYieldService.openPosition} / {@link LeverageYieldService.operatePosition},
|
|
45450
|
+
* which do it for you.
|
|
45451
|
+
*/
|
|
45452
|
+
encodePositionCalls(txs) {
|
|
45453
|
+
return encodeContractCalls(
|
|
45454
|
+
txs.map((tx) => ({ address: tx.to, value: tx.value ?? 0n, data: tx.data }))
|
|
45455
|
+
);
|
|
45456
|
+
}
|
|
45457
|
+
/**
|
|
45458
|
+
* Resolves the hub reserve a spoke token funds, and the hub asset it arrives as.
|
|
45459
|
+
*
|
|
45460
|
+
* Three addresses per token and they are not interchangeable: `hubAsset` is what lands in the hub
|
|
45461
|
+
* wallet, `vault` is the 18-decimal money-market reserve a position actually uses, and the spoke
|
|
45462
|
+
* `address` is neither. Getting this wrong is silent — the wrong one is still a valid ERC-20.
|
|
45463
|
+
*/
|
|
45464
|
+
resolveFunding(srcChainKey, token, method) {
|
|
45465
|
+
const spokeToken = this.config.getSpokeTokenFromOriginalAssetAddress(srcChainKey, token) ?? this.config.getXTokenFromHubAsset(token);
|
|
45466
|
+
if (!spokeToken) {
|
|
45467
|
+
return {
|
|
45468
|
+
ok: false,
|
|
45469
|
+
error: lookupFailed(
|
|
45470
|
+
"leverageYield",
|
|
45471
|
+
method,
|
|
45472
|
+
new Error(`no hub asset registered for ${token} on ${srcChainKey}`),
|
|
45473
|
+
{ srcChainKey }
|
|
45474
|
+
)
|
|
45475
|
+
};
|
|
45476
|
+
}
|
|
45477
|
+
return {
|
|
45478
|
+
ok: true,
|
|
45479
|
+
value: {
|
|
45480
|
+
hubAsset: spokeToken.hubAsset,
|
|
45481
|
+
vault: spokeToken.vault,
|
|
45482
|
+
decimals: spokeToken.decimals
|
|
45483
|
+
}
|
|
45484
|
+
};
|
|
45485
|
+
}
|
|
45486
|
+
/**
|
|
45487
|
+
* What a refund should pay back: the asset the user actually funded with, or `undefined` when that IS
|
|
45488
|
+
* the reserve and there is nothing to unwrap.
|
|
45489
|
+
*
|
|
45490
|
+
* A named asset makes `IntentRefund` unwrap before paying, on the hub as well as off it — so someone
|
|
45491
|
+
* who deposited USSD is refunded USSD rather than `sodaUSSD`.
|
|
45492
|
+
*/
|
|
45493
|
+
refundAsset(funding) {
|
|
45494
|
+
return funding.hubAsset.toLowerCase() === funding.vault.toLowerCase() ? void 0 : funding.hubAsset;
|
|
45495
|
+
}
|
|
45496
|
+
/**
|
|
45497
|
+
* Encodes the wrap of an arriving deposit into its money-market reserve, and returns the reserve
|
|
45498
|
+
* amount that produces.
|
|
45499
|
+
*
|
|
45500
|
+
* A hub asset that is already a soda vault token IS the reserve, so nothing is wrapped. Otherwise
|
|
45501
|
+
* the vault mints 18-decimal shares one-for-one with the asset, which is what
|
|
45502
|
+
* `translateIncomingDecimals` computes — the same conversion the asset manager applies to a spoke
|
|
45503
|
+
* deposit, rather than a second implementation of it. A reserve carrying a non-zero deposit fee
|
|
45504
|
+
* would mint fewer shares than this predicts and the factory's pull would revert; both reserves in
|
|
45505
|
+
* use today are fee-free.
|
|
45506
|
+
*/
|
|
45507
|
+
encodeWrapIntoReserve(funding, amount) {
|
|
45508
|
+
if (this.config.isSodaVaultHubAsset(funding.hubAsset)) {
|
|
45509
|
+
return { calls: [], reserveAmount: amount };
|
|
45510
|
+
}
|
|
45511
|
+
return {
|
|
45512
|
+
calls: [
|
|
45513
|
+
Erc20Service.encodeApprove(funding.hubAsset, funding.vault, amount),
|
|
45514
|
+
EvmVaultTokenService.encodeDeposit(funding.vault, funding.hubAsset, amount)
|
|
45515
|
+
],
|
|
45516
|
+
reserveAmount: EvmVaultTokenService.translateIncomingDecimals(funding.decimals, amount)
|
|
45517
|
+
};
|
|
45518
|
+
}
|
|
45519
|
+
/**
|
|
45520
|
+
* Everything both opens do before they diverge: resolve the factory, the funding token's hub asset
|
|
45521
|
+
* and reserve, and the origin to refund to; predict the address the position will be created at;
|
|
45522
|
+
* and encode the wrap plus the transfer that funds it.
|
|
45523
|
+
*
|
|
45524
|
+
* Only the factory call itself differs between the collateral side and the debt side — which side
|
|
45525
|
+
* the funded reserve lands on, and the two amounts — so everything up to that point lives here
|
|
45526
|
+
* once. `calls` is returned ready to be appended to.
|
|
45527
|
+
*/
|
|
45528
|
+
async prepareOpen(params, method) {
|
|
45529
|
+
const factory = this.requireFactory(method);
|
|
45530
|
+
if (!factory.ok) return factory;
|
|
45531
|
+
const fee = this.resolvePositionFee(params.partnerFee, method);
|
|
45532
|
+
if (!fee.ok) return fee;
|
|
45533
|
+
const funding = this.resolveFunding(params.srcChainKey, params.token, method);
|
|
45534
|
+
if (!funding.ok) return funding;
|
|
45535
|
+
const origin = this.resolveOrigin(
|
|
45536
|
+
{ chainKey: params.srcChainKey, address: params.srcAddress, asset: this.refundAsset(funding.value) },
|
|
45537
|
+
method
|
|
45538
|
+
);
|
|
45539
|
+
if (!origin.ok) return origin;
|
|
45540
|
+
const predicted = await this.predictPosition(params.owner, params.owner);
|
|
45541
|
+
if (!predicted.ok) return predicted;
|
|
45542
|
+
const { calls, reserveAmount } = this.encodeWrapIntoReserve(funding.value, params.amount);
|
|
45543
|
+
calls.push(Erc20Service.encodeTransfer(funding.value.vault, predicted.value, reserveAmount));
|
|
45544
|
+
return {
|
|
45545
|
+
ok: true,
|
|
45546
|
+
value: {
|
|
45547
|
+
factory: factory.value,
|
|
45548
|
+
funding: funding.value,
|
|
45549
|
+
calls,
|
|
45550
|
+
reserveAmount,
|
|
45551
|
+
origin: origin.value,
|
|
45552
|
+
fee: fee.value
|
|
45553
|
+
}
|
|
45554
|
+
};
|
|
45555
|
+
}
|
|
45556
|
+
/**
|
|
45557
|
+
* Hub-side payload for opening a position from the collateral side.
|
|
45558
|
+
*
|
|
45559
|
+
* Wrap the arriving deposit into its reserve, TRANSFER it to the address the position will be
|
|
45560
|
+
* created at, create the position and post its leverage intent — one batch, executed by the user's
|
|
45561
|
+
* hub wallet. The position's collateral is the reserve behind `params.token`; `borrowToken` is
|
|
45562
|
+
* borrowed against it.
|
|
45563
|
+
*
|
|
45564
|
+
* Nothing is ever approved to the factory: it holds no allowance and pulls from nobody, so funding
|
|
45565
|
+
* is a transfer to `predictPosition(creator, owner, nextPositionIdFor(owner))` and the clone supplies
|
|
45566
|
+
* whatever it finds. The id is per-owner, so an unrelated user creating a position cannot move the
|
|
45567
|
+
* address out from under this batch — and because the transfer and the create are in the same batch,
|
|
45568
|
+
* a stale prediction reverts both rather than stranding the tokens.
|
|
45569
|
+
*
|
|
45570
|
+
* The owner's OWN concurrent opens are the one thing that can still advance the id between building
|
|
45571
|
+
* this payload and executing it. On the hub that reverts atomically and nothing is lost; funded from
|
|
45572
|
+
* a spoke the deposit has already landed in the user's hub wallet when the batch reverts, and is
|
|
45573
|
+
* recovered with `sodax.recovery` (see RECOVERY.md). Do not open two positions for one owner at once.
|
|
45574
|
+
*
|
|
45575
|
+
* The origin recorded on the position is `srcChainKey` / `srcAddress` / the deposited hub asset,
|
|
45576
|
+
* so a leverage intent that never fills refunds to the user on the chain they funded from — not to
|
|
45577
|
+
* the position, and not to the hub wallet.
|
|
45578
|
+
*/
|
|
45579
|
+
async buildOpenPositionData(params) {
|
|
45580
|
+
const prep = await this.prepareOpen(params, "buildOpenPositionData");
|
|
45581
|
+
if (!prep.ok) return prep;
|
|
45582
|
+
const { factory, funding, calls, reserveAmount, origin, fee } = prep.value;
|
|
45583
|
+
calls.push({
|
|
45584
|
+
address: factory,
|
|
45585
|
+
value: 0n,
|
|
45586
|
+
data: viem.encodeFunctionData({
|
|
45587
|
+
abi: leveragePositionFactoryAbi,
|
|
45588
|
+
functionName: "createPositionAndLeverage",
|
|
45589
|
+
args: [
|
|
45590
|
+
this.positionConfig({
|
|
45591
|
+
owner: params.owner,
|
|
45592
|
+
collateral: funding.vault,
|
|
45593
|
+
borrowToken: params.borrowToken,
|
|
45594
|
+
eModeCategory: params.eModeCategory ?? 0,
|
|
45595
|
+
origin,
|
|
45596
|
+
fee
|
|
45597
|
+
}),
|
|
45598
|
+
reserveAmount,
|
|
45599
|
+
params.borrowAmount,
|
|
45600
|
+
params.minCollateralOut
|
|
45601
|
+
]
|
|
45602
|
+
})
|
|
45603
|
+
});
|
|
45604
|
+
return { ok: true, value: encodeContractCalls(calls) };
|
|
45605
|
+
}
|
|
45606
|
+
/**
|
|
45607
|
+
* Hub-side payload for opening a position from the debt side.
|
|
45608
|
+
*
|
|
45609
|
+
* The mirror of {@link LeverageYieldService.buildOpenPositionData}: here the deposit is the
|
|
45610
|
+
* position's *debt* token, contributed rather than supplied, and `collateral` is the reserve the
|
|
45611
|
+
* position ends up long. The hook supplies the solver's collateral on fill and borrows only the
|
|
45612
|
+
* shortfall, so the position legitimately starts with no collateral of its own.
|
|
45613
|
+
*/
|
|
45614
|
+
async buildOpenPositionFromDebtTokenData(params) {
|
|
45615
|
+
const prep = await this.prepareOpen(params, "buildOpenPositionFromDebtTokenData");
|
|
45616
|
+
if (!prep.ok) return prep;
|
|
45617
|
+
const { factory, funding, calls, reserveAmount, origin, fee } = prep.value;
|
|
45618
|
+
calls.push({
|
|
45619
|
+
address: factory,
|
|
45620
|
+
value: 0n,
|
|
45621
|
+
data: viem.encodeFunctionData({
|
|
45622
|
+
abi: leveragePositionFactoryAbi,
|
|
45623
|
+
functionName: "createPositionFromDebtToken",
|
|
45624
|
+
args: [
|
|
45625
|
+
this.positionConfig({
|
|
45626
|
+
owner: params.owner,
|
|
45627
|
+
collateral: params.collateral,
|
|
45628
|
+
// The deposited token IS the debt side, so its reserve is the borrow token.
|
|
45629
|
+
borrowToken: funding.vault,
|
|
45630
|
+
eModeCategory: params.eModeCategory ?? 0,
|
|
45631
|
+
origin,
|
|
45632
|
+
fee
|
|
45633
|
+
}),
|
|
45634
|
+
reserveAmount,
|
|
45635
|
+
params.totalInput,
|
|
45636
|
+
params.minCollateralOut
|
|
45637
|
+
]
|
|
45638
|
+
})
|
|
45639
|
+
});
|
|
45640
|
+
return { ok: true, value: encodeContractCalls(calls) };
|
|
45641
|
+
}
|
|
45642
|
+
/**
|
|
45643
|
+
* Whether the funding token is already approved for an open from `srcChainKey`.
|
|
45644
|
+
*
|
|
45645
|
+
* The spender differs by chain and neither choice is guessable: on the hub the deposit is pulled
|
|
45646
|
+
* by the user's own hub wallet, executing inside the routed batch; on an EVM spoke it is pulled by
|
|
45647
|
+
* that spoke's asset manager. Chains with no allowance concept report `true`, and Stellar reports
|
|
45648
|
+
* whether the trustline covers the amount.
|
|
45649
|
+
*/
|
|
45650
|
+
async isPositionFundingAllowanceValid(params) {
|
|
45651
|
+
const baseCtx = { srcChainKey: params.srcChainKey, action: "allowanceCheck" };
|
|
45652
|
+
try {
|
|
45653
|
+
leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
|
|
45654
|
+
const srcChainKey = params.srcChainKey;
|
|
45655
|
+
const inner = isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey) ? await this.spoke.isAllowanceValid({
|
|
45656
|
+
srcChainKey,
|
|
45657
|
+
token: params.token,
|
|
45658
|
+
amount: params.amount,
|
|
45659
|
+
owner: params.srcAddress,
|
|
45660
|
+
spender: await this.resolveFundingSpender(srcChainKey, params.srcAddress)
|
|
45661
|
+
}) : await this.spoke.isAllowanceValid({
|
|
45662
|
+
srcChainKey,
|
|
45663
|
+
token: params.token,
|
|
45664
|
+
amount: params.amount,
|
|
45665
|
+
owner: params.srcAddress
|
|
45666
|
+
});
|
|
45667
|
+
if (inner.ok) return inner;
|
|
45668
|
+
return { ok: false, error: allowanceCheckFailed("leverageYield", inner.error, baseCtx) };
|
|
45669
|
+
} catch (error) {
|
|
45670
|
+
if (isLeverageYieldAllowanceCheckError(error)) return { ok: false, error };
|
|
45671
|
+
return { ok: false, error: allowanceCheckFailed("leverageYield", error, baseCtx) };
|
|
45672
|
+
}
|
|
45673
|
+
}
|
|
45674
|
+
/**
|
|
45675
|
+
* Approves the funding token for an open, against the spender that chain's deposit actually uses —
|
|
45676
|
+
* see {@link LeverageYieldService.isPositionFundingAllowanceValid} for which that is.
|
|
45677
|
+
*
|
|
45678
|
+
* WAITS FOR THE APPROVAL TO LAND before returning. `Erc20Service.approve` resolves with the hash the
|
|
45679
|
+
* moment it is broadcast, so a caller that immediately re-reads the allowance sees the value from
|
|
45680
|
+
* BEFORE the approval — a UI then keeps showing "approve" and the user signs a second, pointless
|
|
45681
|
+
* approval. Returning early from a helper whose whole purpose is "the allowance is now sufficient" is
|
|
45682
|
+
* a footgun, so the wait lives here rather than in each caller.
|
|
45683
|
+
*/
|
|
45684
|
+
async approvePositionFunding(params) {
|
|
45685
|
+
const baseCtx = { srcChainKey: params.srcChainKey, action: "approve" };
|
|
45686
|
+
try {
|
|
45687
|
+
leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
|
|
45688
|
+
const srcChainKey = params.srcChainKey;
|
|
45689
|
+
let inner = {
|
|
45690
|
+
ok: false,
|
|
45691
|
+
error: new Error(`[LeverageYieldService.approvePositionFunding] approve is unsupported on ${srcChainKey}`)
|
|
45692
|
+
};
|
|
45693
|
+
if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
|
|
45694
|
+
leverageYieldInvariant(viem.isAddress(params.token), "Invalid token address", { ...baseCtx, field: "token" });
|
|
45695
|
+
inner = await this.spoke.approve({
|
|
45696
|
+
srcChainKey,
|
|
45697
|
+
token: params.token,
|
|
45698
|
+
amount: params.amount,
|
|
45699
|
+
owner: params.srcAddress,
|
|
45700
|
+
spender: await this.resolveFundingSpender(srcChainKey, params.srcAddress),
|
|
45701
|
+
raw: false,
|
|
45702
|
+
// `K` stays open here, so the provider is only checkable against the chain key inside `spoke.approve`.
|
|
45703
|
+
walletProvider: params.walletProvider
|
|
45704
|
+
});
|
|
45705
|
+
} else if (isStellarChainKeyType(srcChainKey)) {
|
|
45706
|
+
inner = await this.spoke.approve({
|
|
45707
|
+
srcChainKey,
|
|
45708
|
+
token: params.token,
|
|
45709
|
+
amount: params.amount,
|
|
45710
|
+
owner: params.srcAddress,
|
|
45711
|
+
raw: false,
|
|
45712
|
+
walletProvider: params.walletProvider
|
|
45713
|
+
});
|
|
45714
|
+
}
|
|
45715
|
+
if (!inner.ok) return { ok: false, error: approveFailed("leverageYield", inner.error, baseCtx) };
|
|
45716
|
+
if (params.walletProvider && isEvmWalletProviderType(params.walletProvider)) {
|
|
45717
|
+
const receipt = await params.walletProvider.waitForTransactionReceipt(
|
|
45718
|
+
inner.value
|
|
45719
|
+
);
|
|
45720
|
+
if (receipt.status !== "success") {
|
|
45721
|
+
return { ok: false, error: approveFailed("leverageYield", "transaction reverted", baseCtx) };
|
|
45722
|
+
}
|
|
45723
|
+
} else {
|
|
45724
|
+
const landed = await this.spoke.verifyTxHash({ txHash: inner.value, chainKey: params.srcChainKey });
|
|
45725
|
+
if (!landed.ok) return { ok: false, error: approveFailed("leverageYield", landed.error, baseCtx) };
|
|
45726
|
+
}
|
|
45727
|
+
return inner;
|
|
45728
|
+
} catch (error) {
|
|
45729
|
+
if (isLeverageYieldApproveError(error)) return { ok: false, error };
|
|
45730
|
+
return { ok: false, error: approveFailed("leverageYield", error, baseCtx) };
|
|
45731
|
+
}
|
|
45732
|
+
}
|
|
45733
|
+
/**
|
|
45734
|
+
* Who pulls the deposit on an EVM source chain.
|
|
45735
|
+
*
|
|
45736
|
+
* On the hub the pull happens inside the routed batch, so the spender is the user's own hub wallet
|
|
45737
|
+
* rather than any protocol contract; on an EVM spoke it is that spoke's asset manager. Chains with
|
|
45738
|
+
* no ERC-20 allowance never reach here.
|
|
45739
|
+
*/
|
|
45740
|
+
async resolveFundingSpender(srcChainKey, srcAddress) {
|
|
45741
|
+
if (isHubChainKeyType(srcChainKey)) return await this.hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey);
|
|
45742
|
+
return this.config.getChainConfig(srcChainKey).addresses.assetManager;
|
|
45743
|
+
}
|
|
45744
|
+
/**
|
|
45745
|
+
* Opens a leveraged position, funded from any chain, in one signature.
|
|
45746
|
+
*
|
|
45747
|
+
* The deposit is carried to the user's hub wallet and the position is created from inside that
|
|
45748
|
+
* same batch, so there is no window in which the funds sit on the hub unattached to a position.
|
|
45749
|
+
* On the hub this routes locally; from a spoke it relays and this waits for the hub side to land.
|
|
45750
|
+
*
|
|
45751
|
+
* WHAT IS AND IS NOT DONE WHEN THIS RESOLVES: the position exists and its leverage intent is
|
|
45752
|
+
* posted. The leverage itself is not applied — a solver fills that intent afterwards. And an
|
|
45753
|
+
* intent is invisible to the solver until its hub transaction hash is reported, so pass the
|
|
45754
|
+
* returned `dstChainTxHash` to {@link LeverageYieldService.notifySolver}; an unreported intent
|
|
45755
|
+
* simply expires and the deposit comes back.
|
|
45756
|
+
*
|
|
45757
|
+
* Spoke tokens need the spoke asset manager approved first, the same as any other deposit.
|
|
45758
|
+
*
|
|
45759
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
|
|
45760
|
+
* end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
|
|
45761
|
+
* replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
|
|
45762
|
+
* delivering the underlying back to the spoke it came from — has never run on mainnet.
|
|
45763
|
+
* Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
|
|
45764
|
+
* outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
|
|
45765
|
+
*/
|
|
45766
|
+
async openPosition(_params) {
|
|
45767
|
+
return this.runPositionOpen(
|
|
45768
|
+
_params,
|
|
45769
|
+
"openPosition",
|
|
45770
|
+
(owner, params) => this.buildOpenPositionData({ ...params, owner })
|
|
45771
|
+
);
|
|
45772
|
+
}
|
|
45773
|
+
/**
|
|
45774
|
+
* Opens a leveraged position from the **debt** token, funded from any chain.
|
|
45775
|
+
*
|
|
45776
|
+
* Same transport and the same asynchronous settlement as
|
|
45777
|
+
* {@link LeverageYieldService.openPosition} — see there for what is and is not done when this
|
|
45778
|
+
* resolves. The difference is only which side the user funds: here they hand over debt token and
|
|
45779
|
+
* end up long collateral they never held.
|
|
45780
|
+
*
|
|
45781
|
+
* Requires the deployed implementation to have a debt-side hook configured; without one the
|
|
45782
|
+
* position reverts `DebtSideHookUnavailable`.
|
|
45783
|
+
*
|
|
45784
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
|
|
45785
|
+
* end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
|
|
45786
|
+
* replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
|
|
45787
|
+
* delivering the underlying back to the spoke it came from — has never run on mainnet.
|
|
45788
|
+
* Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
|
|
45789
|
+
* outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
|
|
45790
|
+
*/
|
|
45791
|
+
async openPositionFromDebtToken(_params) {
|
|
45792
|
+
return this.runPositionOpen(
|
|
45793
|
+
_params,
|
|
45794
|
+
"openPositionFromDebtToken",
|
|
45795
|
+
(owner, params) => this.buildOpenPositionFromDebtTokenData({ ...params, owner })
|
|
45796
|
+
);
|
|
45797
|
+
}
|
|
45798
|
+
/**
|
|
45799
|
+
* Shared body of the two open paths. They differ only in which factory call the payload ends with,
|
|
45800
|
+
* so everything around it — owner resolution, deposit, verify, relay — lives here rather than
|
|
45801
|
+
* being written twice and drifting.
|
|
45802
|
+
*/
|
|
45803
|
+
/**
|
|
45804
|
+
* Instrumentation for both opens. Wrapping the shared runner rather than each entry point keeps
|
|
45805
|
+
* `openPosition` and `openPositionFromDebtToken` from drifting, and `action` is already threaded
|
|
45806
|
+
* through for the error context, so it doubles as the analytics action.
|
|
45807
|
+
*
|
|
45808
|
+
* `start` carries only the fields common to both param shapes — the funding side's token and
|
|
45809
|
+
* amount. The side-specific ones (`borrowToken`/`borrowAmount` vs `collateral`/`totalInput`) are
|
|
45810
|
+
* not on `PositionFundingParams`, and inventing a cast to reach them would be worse than omitting
|
|
45811
|
+
* them.
|
|
45812
|
+
*/
|
|
45813
|
+
async runPositionOpen(_params, action, build) {
|
|
45814
|
+
return this.config.analytics.trackResult(
|
|
45815
|
+
"leverageYield",
|
|
45816
|
+
action,
|
|
45817
|
+
() => this.executePositionOpen(_params, action, build),
|
|
45818
|
+
{
|
|
45819
|
+
start: () => ({
|
|
45820
|
+
srcChainKey: _params.params.srcChainKey,
|
|
45821
|
+
srcAddress: _params.params.srcAddress,
|
|
45822
|
+
inputToken: _params.params.token,
|
|
45823
|
+
inputAmount: _params.params.amount,
|
|
45824
|
+
eModeCategory: _params.params.eModeCategory
|
|
45825
|
+
}),
|
|
45826
|
+
success: (value) => ({ srcTxHash: value.srcChainTxHash, dstTxHash: value.dstChainTxHash }),
|
|
45827
|
+
failure: (error) => ({ code: error.code })
|
|
45828
|
+
}
|
|
45829
|
+
);
|
|
45830
|
+
}
|
|
45831
|
+
async executePositionOpen(_params, action, buildData) {
|
|
45832
|
+
const { params, timeout = DEFAULT_RELAY_TX_TIMEOUT } = _params;
|
|
45833
|
+
const baseCtx = {
|
|
45834
|
+
srcChainKey: params.srcChainKey,
|
|
45835
|
+
action
|
|
45836
|
+
};
|
|
45837
|
+
try {
|
|
45838
|
+
leverageYieldInvariant(!isBitcoinChainKeyType(params.srcChainKey), BITCOIN_UNSUPPORTED_MESSAGE, {
|
|
45839
|
+
...baseCtx,
|
|
45840
|
+
field: "srcChainKey"
|
|
45841
|
+
});
|
|
45842
|
+
leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
|
|
45843
|
+
leverageYieldInvariant(params.minCollateralOut > 0n, "minCollateralOut must be greater than 0", {
|
|
45844
|
+
...baseCtx,
|
|
45845
|
+
field: "minCollateralOut"
|
|
45846
|
+
});
|
|
45847
|
+
leverageYieldInvariant(
|
|
45848
|
+
isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
|
|
45849
|
+
`Invalid wallet provider for chain key: ${params.srcChainKey}`,
|
|
45850
|
+
{ ...baseCtx, field: "walletProvider" }
|
|
45851
|
+
);
|
|
45852
|
+
const hubWallet = await this.hubProvider.getUserHubWalletAddress(params.srcAddress, params.srcChainKey);
|
|
45853
|
+
const data = await buildData(hubWallet, params);
|
|
45854
|
+
if (!data.ok) return data;
|
|
45855
|
+
const txResult = await this.spoke.deposit({
|
|
45856
|
+
srcChainKey: params.srcChainKey,
|
|
45857
|
+
srcAddress: params.srcAddress,
|
|
45858
|
+
to: hubWallet,
|
|
45859
|
+
token: params.token,
|
|
45860
|
+
amount: params.amount,
|
|
45861
|
+
data: data.value,
|
|
45862
|
+
skipSimulation: _params.skipSimulation ?? false,
|
|
45863
|
+
raw: false,
|
|
45864
|
+
walletProvider: _params.walletProvider
|
|
45865
|
+
});
|
|
45866
|
+
if (!txResult.ok) {
|
|
45867
|
+
if (isLeverageYieldCreateIntentError(txResult.error)) return { ok: false, error: txResult.error };
|
|
45868
|
+
return { ok: false, error: intentCreationFailed("leverageYield", txResult.error, baseCtx) };
|
|
45869
|
+
}
|
|
45870
|
+
return await this.settleHubWalletMessage(txResult.value, { address: hubWallet, payload: data.value }, baseCtx, {
|
|
45871
|
+
timeout
|
|
45872
|
+
});
|
|
45873
|
+
} catch (error) {
|
|
45874
|
+
if (isLeverageYieldSwapError(error)) return { ok: false, error };
|
|
45875
|
+
return { ok: false, error: executionFailed("leverageYield", error, { ...baseCtx, phase: "intentCreation" }) };
|
|
45876
|
+
}
|
|
45877
|
+
}
|
|
45878
|
+
/**
|
|
45879
|
+
* Which address actually funds a position from `chainKey` — what a balance must be read against,
|
|
45880
|
+
* and what the deposit is built from.
|
|
45881
|
+
*
|
|
45882
|
+
* ONE ANSWER FOR BOTH, because two answers cost an open on mainnet: the balance was read from the
|
|
45883
|
+
* registry `address` while the deposit rewrote it to `hubAsset`, so for Sonic's native S the form
|
|
45884
|
+
* showed 42 S and the batch then called `wS.transferFrom(user, hubWallet, 5e18)` against a wS
|
|
45885
|
+
* balance of zero. The approval was correct; the revert surfaced as nothing but "External call
|
|
45886
|
+
* failed". Any integrator reading a balance for a position deposit needs this same answer.
|
|
45887
|
+
*
|
|
45888
|
+
* Three addresses hang off a registry entry and they are not interchangeable:
|
|
45889
|
+
*
|
|
45890
|
+
* `address` the spoke-side original; for a bridged entry it can name another chain entirely
|
|
45891
|
+
* `hubAsset` what the user holds ON THE HUB, and the vault's deposit input
|
|
45892
|
+
* `vault` the hub money-market reserve the position ends up in
|
|
45893
|
+
*
|
|
45894
|
+
* Off the hub the answer is always `address` — that is the chain the user is on. On the hub it is
|
|
45895
|
+
* `hubAsset`, EXCEPT for a native entry: `EvmSpokeService.deposit` keys on the chain's own
|
|
45896
|
+
* `nativeToken` to send `msg.value` rather than an ERC-20 `transferFrom`, and the native entry
|
|
45897
|
+
* carries exactly that sentinel as its `address`. Rewriting that to the wrapper asks for a token
|
|
45898
|
+
* the wallet does not hold.
|
|
45899
|
+
*
|
|
45900
|
+
* @returns The funding address, or `undefined` when the token is not supported on `chainKey`.
|
|
45901
|
+
*/
|
|
45902
|
+
resolvePositionFunding(chainKey, token) {
|
|
45903
|
+
const address = resolvePositionFundingAddress(chainKey, this.hubProvider.chainConfig.chain.key, token);
|
|
45904
|
+
return address === "" ? void 0 : address;
|
|
45905
|
+
}
|
|
45906
|
+
/**
|
|
45907
|
+
* Quotes one leg of a position operation: the borrowed side when levering up, the collateral when
|
|
45908
|
+
* levering down or exiting.
|
|
45909
|
+
*
|
|
45910
|
+
* Use this rather than {@link LeverageYieldService.getQuote} for a position. Both hit the same
|
|
45911
|
+
* endpoint, but this one names the hub reserves as the pair the intent actually swaps and quotes
|
|
45912
|
+
* GROSS — see `positionLegQuote.ts` for why either alone gets the floor wrong. Feed `quotedAmount`
|
|
45913
|
+
* to {@link projectLeverageLeg}.
|
|
45914
|
+
*
|
|
45915
|
+
* A refusal is not always a dead pair: {@link isNoRouteRefusal} is also what the solver answers
|
|
45916
|
+
* for a leg that is only too small, and telling the two apart means quoting again at a healthy
|
|
45917
|
+
* notional. That size is priced, so it is the caller's to choose.
|
|
45918
|
+
*/
|
|
45919
|
+
async getPositionLegQuote(params) {
|
|
45920
|
+
const hubChainKey = this.hubProvider.chainConfig.chain.key;
|
|
45921
|
+
const quote = await this.getQuote({
|
|
45922
|
+
token_src: params.inputHubToken,
|
|
45923
|
+
token_src_blockchain_id: hubChainKey,
|
|
45924
|
+
token_dst: params.outputHubToken,
|
|
45925
|
+
token_dst_blockchain_id: hubChainKey,
|
|
45926
|
+
amount: params.amount,
|
|
45927
|
+
quote_type: "exact_input",
|
|
45928
|
+
// Explicit, not omitted: omitting it applies the configured leverage-yield fee.
|
|
45929
|
+
partnerFee: { address: viem.zeroAddress, percentage: 0 }
|
|
45930
|
+
});
|
|
45931
|
+
if (!quote.ok) return quote;
|
|
45932
|
+
return { ok: true, value: { quotedAmount: quote.value.quoted_amount } };
|
|
45933
|
+
}
|
|
45934
|
+
/**
|
|
45935
|
+
* Opens a leveraged position AND reports the intent it posts. Prefer this to
|
|
45936
|
+
* {@link LeverageYieldService.openPosition} / {@link LeverageYieldService.openPositionFromDebtToken}.
|
|
45937
|
+
*
|
|
45938
|
+
* Those two only post the intent. Reporting it is a separate call that must not be skipped — an
|
|
45939
|
+
* unreported intent expires unfilled, so the owner is left funded with leverage that never arrives
|
|
45940
|
+
* and nothing said so. Pairing them here is the difference between an API that works and one that
|
|
45941
|
+
* works only if you read the docs.
|
|
45942
|
+
*
|
|
45943
|
+
* `side` picks which asset funds the open: `'collateral'` supplies the deposit and borrows against
|
|
45944
|
+
* it, `'debt'` hands the deposit to the solver and ends up long collateral never held.
|
|
45945
|
+
*
|
|
45946
|
+
* RESOLVING MEANS THE INTENT IS LIVE, not that the position is open, and a failed notification is
|
|
45947
|
+
* still `ok: true` — see {@link LeveragePositionIntentResult}.
|
|
45948
|
+
*
|
|
45949
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN — see `operatePosition`.
|
|
45950
|
+
*/
|
|
45951
|
+
async openLeveragePosition(_params) {
|
|
45952
|
+
return this.config.analytics.trackResult(
|
|
45953
|
+
"leverageYield",
|
|
45954
|
+
"openLeveragePosition",
|
|
45955
|
+
async () => {
|
|
45956
|
+
const { side, ...rest } = _params;
|
|
45957
|
+
const opened = side === "debt" ? await this.openPositionFromDebtToken(
|
|
45958
|
+
rest
|
|
45959
|
+
) : await this.openPosition(rest);
|
|
45960
|
+
if (!opened.ok) return opened;
|
|
45961
|
+
return { ok: true, value: await reportPositionIntent(this.notifyIntent, opened.value) };
|
|
45962
|
+
},
|
|
45963
|
+
{
|
|
45964
|
+
start: () => ({ srcChainKey: _params.params.srcChainKey, side: _params.side ?? "collateral" }),
|
|
45965
|
+
success: (result) => ({ ...result.txHashes, notified: result.notified }),
|
|
45966
|
+
failure: (error) => ({ code: error.code })
|
|
45967
|
+
}
|
|
45968
|
+
);
|
|
45969
|
+
}
|
|
45970
|
+
/**
|
|
45971
|
+
* Runs position calls that POST A SOLVER INTENT — `addLeverage` and `decreaseLeverage` — and
|
|
45972
|
+
* reports it. Prefer this to {@link LeverageYieldService.operatePosition} for those two.
|
|
45973
|
+
*
|
|
45974
|
+
* USE {@link LeverageYieldService.runLeveragePositionOperation} FOR `withdraw`, `settle` AND
|
|
45975
|
+
* `cancel`. Those are synchronous on the hub and need no notification, and the split is not
|
|
45976
|
+
* cosmetic: sending a leverage change through the route-only path leaves an intent nothing will
|
|
45977
|
+
* fill, and it expires without a word. The other direction is merely noisy.
|
|
45978
|
+
*
|
|
45979
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN — see `operatePosition`.
|
|
45980
|
+
*/
|
|
45981
|
+
async submitLeveragePositionIntent(_params) {
|
|
45982
|
+
return this.config.analytics.trackResult(
|
|
45983
|
+
"leverageYield",
|
|
45984
|
+
"submitLeveragePositionIntent",
|
|
45985
|
+
async () => {
|
|
45986
|
+
const routed = await this.operatePosition(_params);
|
|
45987
|
+
if (!routed.ok) return routed;
|
|
45988
|
+
return { ok: true, value: await reportPositionIntent(this.notifyIntent, routed.value) };
|
|
45989
|
+
},
|
|
45990
|
+
{
|
|
45991
|
+
start: () => ({ srcChainKey: _params.params.srcChainKey, calls: _params.params.calls.length }),
|
|
45992
|
+
success: (result) => ({ ...result.txHashes, notified: result.notified }),
|
|
45993
|
+
failure: (error) => ({ code: error.code })
|
|
45994
|
+
}
|
|
45995
|
+
);
|
|
45996
|
+
}
|
|
45997
|
+
/**
|
|
45998
|
+
* Runs position calls that do NOT post an intent — `withdraw`, `settle` and `cancel` — as the
|
|
45999
|
+
* owning hub wallet. They are synchronous on the hub, so resolving means the work is done.
|
|
46000
|
+
*
|
|
46001
|
+
* Still routed, never sent directly: the position's `onlyOwner` is the hub wallet, so a builder's
|
|
46002
|
+
* transaction sent from the signer reverts `NotOwner`. Use
|
|
46003
|
+
* {@link LeverageYieldService.submitLeveragePositionIntent} for `addLeverage` and
|
|
46004
|
+
* `decreaseLeverage`, which this deliberately does not report.
|
|
46005
|
+
*
|
|
46006
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN, and this path carries the worst of
|
|
46007
|
+
* it: an exit or cancellation delivering the underlying back to the spoke it came from
|
|
46008
|
+
* has never run on mainnet.
|
|
46009
|
+
*/
|
|
46010
|
+
async runLeveragePositionOperation(_params) {
|
|
46011
|
+
return this.operatePosition(_params);
|
|
46012
|
+
}
|
|
46013
|
+
/** Bound once so the notify half can be handed around without losing `this`. */
|
|
46014
|
+
notifyIntent = (request) => this.notifySolver(request);
|
|
46015
|
+
/**
|
|
46016
|
+
* Runs position calls as the user's hub wallet, from any chain.
|
|
46017
|
+
*
|
|
46018
|
+
* The write counterpart to the read hooks: add or decrease leverage, withdraw, settle, cancel. No
|
|
46019
|
+
* funds move, so this is a bare message rather than a deposit — on the hub it routes locally, from
|
|
46020
|
+
* a spoke it relays and this waits for the hub side to land.
|
|
46021
|
+
*
|
|
46022
|
+
* The leverage calls only *post* an intent, so a resolved promise means the intent is live, not
|
|
46023
|
+
* that leverage moved. Report the returned `dstChainTxHash` to
|
|
46024
|
+
* {@link LeverageYieldService.notifySolver} for those two; `withdraw`, `settle` and `cancel` are
|
|
46025
|
+
* synchronous on the hub and need no notification.
|
|
46026
|
+
*
|
|
46027
|
+
* @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
|
|
46028
|
+
* end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
|
|
46029
|
+
* replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
|
|
46030
|
+
* delivering the underlying back to the spoke it came from — has never run on mainnet.
|
|
46031
|
+
* Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
|
|
46032
|
+
* outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
|
|
46033
|
+
*/
|
|
46034
|
+
async operatePosition(_params) {
|
|
46035
|
+
return this.config.analytics.trackResult(
|
|
46036
|
+
"leverageYield",
|
|
46037
|
+
"operatePosition",
|
|
46038
|
+
() => this.executePositionOperation(_params),
|
|
46039
|
+
{
|
|
46040
|
+
// The calls themselves are not emitted — they are arbitrary hub calldata. The count is
|
|
46041
|
+
// enough to tell a batched adjust from a single write.
|
|
46042
|
+
start: () => ({
|
|
46043
|
+
srcChainKey: _params.params.srcChainKey,
|
|
46044
|
+
srcAddress: _params.params.srcAddress,
|
|
46045
|
+
callCount: _params.params.calls.length
|
|
46046
|
+
}),
|
|
46047
|
+
success: (value) => ({ srcTxHash: value.srcChainTxHash, dstTxHash: value.dstChainTxHash }),
|
|
46048
|
+
failure: (error) => ({ code: error.code })
|
|
46049
|
+
}
|
|
46050
|
+
);
|
|
46051
|
+
}
|
|
46052
|
+
async executePositionOperation(_params) {
|
|
46053
|
+
const { params, timeout = DEFAULT_RELAY_TX_TIMEOUT } = _params;
|
|
46054
|
+
const baseCtx = {
|
|
46055
|
+
srcChainKey: params.srcChainKey,
|
|
46056
|
+
action: "operatePosition"
|
|
46057
|
+
};
|
|
46058
|
+
try {
|
|
46059
|
+
leverageYieldInvariant(!isBitcoinChainKeyType(params.srcChainKey), BITCOIN_UNSUPPORTED_MESSAGE, {
|
|
46060
|
+
...baseCtx,
|
|
46061
|
+
field: "srcChainKey"
|
|
46062
|
+
});
|
|
46063
|
+
leverageYieldInvariant(params.calls.length > 0, "at least one call is required", {
|
|
46064
|
+
...baseCtx,
|
|
46065
|
+
field: "calls"
|
|
46066
|
+
});
|
|
46067
|
+
leverageYieldInvariant(
|
|
46068
|
+
isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
|
|
46069
|
+
`Invalid wallet provider for chain key: ${params.srcChainKey}`,
|
|
46070
|
+
{ ...baseCtx, field: "walletProvider" }
|
|
46071
|
+
);
|
|
46072
|
+
const hubWallet = await this.hubProvider.getUserHubWalletAddress(params.srcAddress, params.srcChainKey);
|
|
46073
|
+
const payload = this.encodePositionCalls(params.calls);
|
|
46074
|
+
const txResult = await this.spoke.sendMessage({
|
|
46075
|
+
srcChainKey: params.srcChainKey,
|
|
46076
|
+
srcAddress: params.srcAddress,
|
|
46077
|
+
dstChainKey: HUB_CHAIN_KEY,
|
|
46078
|
+
dstAddress: hubWallet,
|
|
46079
|
+
payload,
|
|
46080
|
+
skipSimulation: _params.skipSimulation ?? false,
|
|
46081
|
+
raw: false,
|
|
46082
|
+
walletProvider: _params.walletProvider
|
|
46083
|
+
});
|
|
46084
|
+
if (!txResult.ok) {
|
|
46085
|
+
if (isLeverageYieldCreateIntentError(txResult.error)) return { ok: false, error: txResult.error };
|
|
46086
|
+
return { ok: false, error: intentCreationFailed("leverageYield", txResult.error, baseCtx) };
|
|
46087
|
+
}
|
|
46088
|
+
return await this.settleHubWalletMessage(txResult.value, { address: hubWallet, payload }, baseCtx, { timeout });
|
|
46089
|
+
} catch (error) {
|
|
46090
|
+
if (isLeverageYieldSwapError(error)) return { ok: false, error };
|
|
46091
|
+
return { ok: false, error: executionFailed("leverageYield", error, { ...baseCtx, phase: "intentCreation" }) };
|
|
46092
|
+
}
|
|
46093
|
+
}
|
|
46094
|
+
/**
|
|
46095
|
+
* Verifies a submitted source transaction and, off the hub, relays it and waits for the hub side.
|
|
46096
|
+
*
|
|
46097
|
+
* Shared by both write paths because the tail is identical whether funds moved or not. The hub
|
|
46098
|
+
* short-circuit is not an optimisation: a hub transaction has already executed the calls, so there
|
|
46099
|
+
* is nothing to relay, and both hashes are the same transaction.
|
|
46100
|
+
*/
|
|
46101
|
+
async settleHubWalletMessage(srcTxHash, relayData, baseCtx, opts) {
|
|
46102
|
+
const verify = await this.spoke.verifyTxHash({ txHash: srcTxHash, chainKey: baseCtx.srcChainKey });
|
|
46103
|
+
if (!verify.ok) return { ok: false, error: verifyFailed("leverageYield", verify.error, baseCtx) };
|
|
46104
|
+
if (isHubChainKeyType(baseCtx.srcChainKey)) {
|
|
46105
|
+
const receipt = await this.hubProvider.publicClient.waitForTransactionReceipt({
|
|
46106
|
+
hash: srcTxHash,
|
|
46107
|
+
timeout: opts.timeout
|
|
46108
|
+
});
|
|
46109
|
+
if (receipt.status !== "success") {
|
|
46110
|
+
return {
|
|
46111
|
+
ok: false,
|
|
46112
|
+
error: verifyFailed("leverageYield", new Error(`hub transaction ${srcTxHash} reverted`), baseCtx)
|
|
46113
|
+
};
|
|
46114
|
+
}
|
|
46115
|
+
return { ok: true, value: { srcChainTxHash: srcTxHash, dstChainTxHash: srcTxHash } };
|
|
46116
|
+
}
|
|
46117
|
+
const packet = await relayTxAndWaitPacket({
|
|
46118
|
+
srcTxHash,
|
|
46119
|
+
data: relayData,
|
|
46120
|
+
chainKey: baseCtx.srcChainKey,
|
|
46121
|
+
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
46122
|
+
timeout: opts.timeout
|
|
46123
|
+
});
|
|
46124
|
+
if (!packet.ok) {
|
|
46125
|
+
return {
|
|
46126
|
+
ok: false,
|
|
46127
|
+
error: mapRelayFailure(packet.error, {
|
|
46128
|
+
feature: "leverageYield",
|
|
46129
|
+
action: baseCtx.action,
|
|
46130
|
+
srcChainKey: baseCtx.srcChainKey
|
|
46131
|
+
})
|
|
46132
|
+
};
|
|
46133
|
+
}
|
|
46134
|
+
return { ok: true, value: { srcChainTxHash: srcTxHash, dstChainTxHash: packet.value.dst_tx_hash } };
|
|
46135
|
+
}
|
|
44884
46136
|
};
|
|
44885
46137
|
|
|
44886
46138
|
// src/sponsoring/errors.ts
|
|
@@ -44908,12 +46160,12 @@ function toDomainCode(value) {
|
|
|
44908
46160
|
}
|
|
44909
46161
|
function readErrorBody(body) {
|
|
44910
46162
|
if (typeof body !== "object" || body === null) return {};
|
|
44911
|
-
const
|
|
44912
|
-
const retryAfterSeconds = typeof
|
|
44913
|
-
const sponsorSequence = typeof
|
|
46163
|
+
const record = body;
|
|
46164
|
+
const retryAfterSeconds = typeof record.retryAfterSeconds === "number" && Number.isFinite(record.retryAfterSeconds) && record.retryAfterSeconds > 0 ? record.retryAfterSeconds : void 0;
|
|
46165
|
+
const sponsorSequence = typeof record.sponsorSequence === "string" && /^\d+$/.test(record.sponsorSequence) ? record.sponsorSequence : void 0;
|
|
44914
46166
|
return {
|
|
44915
|
-
message: typeof
|
|
44916
|
-
code: toDomainCode(
|
|
46167
|
+
message: typeof record.message === "string" ? record.message : void 0,
|
|
46168
|
+
code: toDomainCode(record.error),
|
|
44917
46169
|
retryAfterSeconds,
|
|
44918
46170
|
sponsorSequence
|
|
44919
46171
|
};
|
|
@@ -45569,6 +46821,81 @@ var PARTNER_CODES = /* @__PURE__ */ new Set([
|
|
|
45569
46821
|
"UNKNOWN"
|
|
45570
46822
|
]);
|
|
45571
46823
|
var isPartnerError = isCodeMember(PARTNER_CODES);
|
|
46824
|
+
function sizeLeverageBorrow(request) {
|
|
46825
|
+
const { side, deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd, borrowDecimals, leverage } = request;
|
|
46826
|
+
const depositTokens = Number(viem.formatUnits(deposit, depositDecimals));
|
|
46827
|
+
const depositUsd = depositTokens * (side === "debt" ? borrowPriceUsd : collateralPriceUsd);
|
|
46828
|
+
const RATIO_SCALE = 1000000000n;
|
|
46829
|
+
const ratio = borrowPriceUsd > 0 && depositTokens > 0 ? depositUsd * Math.max(leverage - 1, 0) / borrowPriceUsd / depositTokens : 0;
|
|
46830
|
+
const borrowAmount = deposit * BigInt(Math.floor(ratio * Number(RATIO_SCALE))) * 10n ** BigInt(borrowDecimals) / (RATIO_SCALE * 10n ** BigInt(depositDecimals));
|
|
46831
|
+
const depositInBorrowUnits = deposit * 10n ** BigInt(borrowDecimals) / 10n ** BigInt(depositDecimals);
|
|
46832
|
+
const intentInput = side === "debt" ? borrowAmount + depositInBorrowUnits : borrowAmount;
|
|
46833
|
+
const feeAmount = request.feeBps ? intentInput * BigInt(Math.round(request.feeBps)) / 10000n : 0n;
|
|
46834
|
+
const borrowUsd = Number(viem.formatUnits(borrowAmount, borrowDecimals)) * borrowPriceUsd;
|
|
46835
|
+
const feeUsd = Number(viem.formatUnits(feeAmount, borrowDecimals)) * borrowPriceUsd;
|
|
46836
|
+
return {
|
|
46837
|
+
borrowAmount,
|
|
46838
|
+
intentInput,
|
|
46839
|
+
depositUsd,
|
|
46840
|
+
// Taken from the amount actually being borrowed, so the projection cannot disagree with the
|
|
46841
|
+
// transaction by the rounding above.
|
|
46842
|
+
borrowUsd,
|
|
46843
|
+
feeAmount,
|
|
46844
|
+
// The fee is borrowed on top on a leverage-up, so it is debt even though the solver never sees it.
|
|
46845
|
+
debtUsd: borrowUsd + feeUsd
|
|
46846
|
+
};
|
|
46847
|
+
}
|
|
46848
|
+
function projectLeverageLeg(request, quote, risk, slippagePct) {
|
|
46849
|
+
const { side, collateralPriceUsd, leverage } = request;
|
|
46850
|
+
const sized = sizeLeverageBorrow(request);
|
|
46851
|
+
const { depositUsd, borrowUsd } = sized;
|
|
46852
|
+
const floor = quote.quotedCollateral * BigInt(Math.round((100 - slippagePct) * 100)) / 10000n;
|
|
46853
|
+
const minCollateralOut = floor > 0n ? floor : 1n;
|
|
46854
|
+
const floorUsd = Number(viem.formatUnits(minCollateralOut, quote.collateralDecimals)) * collateralPriceUsd;
|
|
46855
|
+
const quotedUsd = Number(viem.formatUnits(quote.quotedCollateral, quote.collateralDecimals)) * collateralPriceUsd;
|
|
46856
|
+
const inputUsd = side === "debt" ? depositUsd * leverage : borrowUsd;
|
|
46857
|
+
const f = inputUsd > 0 ? floorUsd / inputUsd : 0;
|
|
46858
|
+
const haircut = inputUsd > 0 ? 1 - quotedUsd / inputUsd : 0;
|
|
46859
|
+
const collateralUsd = (side === "debt" ? 0 : depositUsd) + floorUsd;
|
|
46860
|
+
const debtUsd = sized.debtUsd;
|
|
46861
|
+
const ltv = collateralUsd > 0 ? debtUsd / collateralUsd : 0;
|
|
46862
|
+
const ltvF = risk.ltv * f;
|
|
46863
|
+
const phi = (request.feeBps ?? 0) / 1e4;
|
|
46864
|
+
const denominator = 1 + phi - ltvF;
|
|
46865
|
+
const usableMaxLeverage = risk.ltv <= 0 ? 1 : denominator <= 0 ? Number.POSITIVE_INFINITY : side === "debt" ? 1 / denominator : 1 + risk.ltv / denominator;
|
|
46866
|
+
const equityUsd = collateralUsd - debtUsd;
|
|
46867
|
+
return {
|
|
46868
|
+
minCollateralOut,
|
|
46869
|
+
collateralUsd,
|
|
46870
|
+
debtUsd,
|
|
46871
|
+
exposureLeverage: equityUsd > 0 ? collateralUsd / equityUsd : Number.POSITIVE_INFINITY,
|
|
46872
|
+
ltv,
|
|
46873
|
+
healthFactor: debtUsd > 0 ? collateralUsd * risk.liquidationThreshold / debtUsd : Number.POSITIVE_INFINITY,
|
|
46874
|
+
exceedsMaxLtv: ltv > risk.ltv,
|
|
46875
|
+
haircut,
|
|
46876
|
+
inputUsd,
|
|
46877
|
+
costUsd: inputUsd * haircut + sized.debtUsd - borrowUsd,
|
|
46878
|
+
usableMaxLeverage
|
|
46879
|
+
};
|
|
46880
|
+
}
|
|
46881
|
+
|
|
46882
|
+
// src/leverageYield/positionApyMath.ts
|
|
46883
|
+
function leveragedNetApyPct(supplyApyPct, borrowApyPct, leverage) {
|
|
46884
|
+
return supplyApyPct * leverage - borrowApyPct * (leverage - 1);
|
|
46885
|
+
}
|
|
46886
|
+
function timeToBreakevenYears(supplyApyPct, borrowApyPct, toLeverage, { costUsd, equityUsd, fromLeverage }) {
|
|
46887
|
+
if (!(equityUsd > 0) || !Number.isFinite(costUsd)) return void 0;
|
|
46888
|
+
if (costUsd <= 0) return "immediate";
|
|
46889
|
+
const incrementalPct = leveragedNetApyPct(supplyApyPct, borrowApyPct, toLeverage) - leveragedNetApyPct(supplyApyPct, borrowApyPct, fromLeverage);
|
|
46890
|
+
if (!(incrementalPct > 0)) return "never";
|
|
46891
|
+
return costUsd / (equityUsd * (incrementalPct / 100));
|
|
46892
|
+
}
|
|
46893
|
+
|
|
46894
|
+
// src/leverageYield/positionLegQuote.ts
|
|
46895
|
+
function isNoRouteRefusal(error) {
|
|
46896
|
+
const message = typeof error === "object" && error !== null && "detail" in error ? error.detail?.message : error instanceof Error ? error.message : void 0;
|
|
46897
|
+
return /no path was found/i.test(message ?? "");
|
|
46898
|
+
}
|
|
45572
46899
|
/*! Bundled license information:
|
|
45573
46900
|
|
|
45574
46901
|
@noble/hashes/utils.js:
|
|
@@ -45591,6 +46918,10 @@ Object.defineProperty(exports, "SwapsApiError", {
|
|
|
45591
46918
|
enumerable: true,
|
|
45592
46919
|
get: function () { return swapsApi.SwapsApiError; }
|
|
45593
46920
|
});
|
|
46921
|
+
Object.defineProperty(exports, "BridgeApiError", {
|
|
46922
|
+
enumerable: true,
|
|
46923
|
+
get: function () { return bridgeApi.BridgeApiError; }
|
|
46924
|
+
});
|
|
45594
46925
|
exports.ALLOWANCE_CHECK_CODES = ALLOWANCE_CHECK_CODES;
|
|
45595
46926
|
exports.APPROVE_CODES = APPROVE_CODES;
|
|
45596
46927
|
exports.AssetService = AssetService;
|
|
@@ -45679,6 +47010,7 @@ exports.LockupMultiplier = LockupMultiplier;
|
|
|
45679
47010
|
exports.LockupPeriod = LockupPeriod;
|
|
45680
47011
|
exports.LsodaSymbols = LsodaSymbols;
|
|
45681
47012
|
exports.LsodaTokens = LsodaTokens;
|
|
47013
|
+
exports.MAX_POSITION_FEE_BPS = MAX_POSITION_FEE_BPS;
|
|
45682
47014
|
exports.MAX_UINT256 = MAX_UINT256;
|
|
45683
47015
|
exports.MigrationService = MigrationService;
|
|
45684
47016
|
exports.MintPositionEventAbi = MintPositionEventAbi;
|
|
@@ -45703,6 +47035,7 @@ exports.RadfiApiError = RadfiApiError;
|
|
|
45703
47035
|
exports.RadfiProvider = RadfiProvider;
|
|
45704
47036
|
exports.RecoveryService = RecoveryService;
|
|
45705
47037
|
exports.RelayChainIdMap = RelayChainIdMap;
|
|
47038
|
+
exports.SDK_VERSION = SDK_VERSION;
|
|
45706
47039
|
exports.SECONDS_PER_YEAR = SECONDS_PER_YEAR;
|
|
45707
47040
|
exports.SODAX_ERROR_CODES = SODAX_ERROR_CODES;
|
|
45708
47041
|
exports.SODAX_FEATURES = SODAX_FEATURES;
|
|
@@ -45786,6 +47119,7 @@ exports.clRouterAbi = clRouterAbi;
|
|
|
45786
47119
|
exports.clTickLensAbi = clTickLensAbi;
|
|
45787
47120
|
exports.classifySponsorError = classifySponsorError;
|
|
45788
47121
|
exports.concentratedLiquidityConfig = concentratedLiquidityConfig;
|
|
47122
|
+
exports.configVersionFor = configVersionFor;
|
|
45789
47123
|
exports.connectionAbi = connectionAbi;
|
|
45790
47124
|
exports.consoleLogger = consoleLogger;
|
|
45791
47125
|
exports.convertTransactionInstructionToRaw = convertTransactionInstructionToRaw;
|
|
@@ -45808,6 +47142,7 @@ exports.estimateSwapSpeedTier = estimateSwapSpeedTier;
|
|
|
45808
47142
|
exports.ethereumSupportedTokens = ethereumSupportedTokens;
|
|
45809
47143
|
exports.executionFailed = executionFailed;
|
|
45810
47144
|
exports.formatBasisPoints = formatBasisPoints;
|
|
47145
|
+
exports.formatConfigVersion = formatConfigVersion;
|
|
45811
47146
|
exports.formatEModeCategory = formatEModeCategory;
|
|
45812
47147
|
exports.formatEModes = formatEModes;
|
|
45813
47148
|
exports.formatPercentage = formatPercentage;
|
|
@@ -45921,6 +47256,7 @@ exports.isNearChainKey = isNearChainKey;
|
|
|
45921
47256
|
exports.isNearChainKeyType = isNearChainKeyType;
|
|
45922
47257
|
exports.isNewbnUSDChainId = isNewbnUSDChainId;
|
|
45923
47258
|
exports.isNewbnUSDToken = isNewbnUSDToken;
|
|
47259
|
+
exports.isNoRouteRefusal = isNoRouteRefusal;
|
|
45924
47260
|
exports.isOptionalBitcoinWalletProviderType = isOptionalBitcoinWalletProviderType;
|
|
45925
47261
|
exports.isOptionalEvmWalletProviderType = isOptionalEvmWalletProviderType;
|
|
45926
47262
|
exports.isOptionalStellarWalletProviderType = isOptionalStellarWalletProviderType;
|
|
@@ -45979,6 +47315,7 @@ exports.kaiaSupportedTokens = kaiaSupportedTokens;
|
|
|
45979
47315
|
exports.leverageYieldConfig = leverageYieldConfig;
|
|
45980
47316
|
exports.leverageYieldInvariant = leverageYieldInvariant;
|
|
45981
47317
|
exports.leverageYieldVaults = leverageYieldVaults;
|
|
47318
|
+
exports.leveragedNetApyPct = leveragedNetApyPct;
|
|
45982
47319
|
exports.lightlinkSupportedTokens = lightlinkSupportedTokens;
|
|
45983
47320
|
exports.lookupFailed = lookupFailed;
|
|
45984
47321
|
exports.mapRelayFailure = mapRelayFailure;
|
|
@@ -46004,6 +47341,7 @@ exports.optimismSupportedTokens = optimismSupportedTokens;
|
|
|
46004
47341
|
exports.pancakeSwapInfinityDefaultHookAbi = pancakeSwapInfinityDefaultHookAbi;
|
|
46005
47342
|
exports.pancakeSwapInfinityPoolManagerAbi = pancakeSwapInfinityPoolManagerAbi;
|
|
46006
47343
|
exports.pancakeSwapInfinityPositionManagerAbi = pancakeSwapInfinityPositionManagerAbi;
|
|
47344
|
+
exports.parseConfigVersion = parseConfigVersion;
|
|
46007
47345
|
exports.parseToStroops = parseToStroops;
|
|
46008
47346
|
exports.parseTokenArrayFromJson = parseTokenArrayFromJson;
|
|
46009
47347
|
exports.partnerInvariant = partnerInvariant;
|
|
@@ -46011,6 +47349,7 @@ exports.permit2Abi = permit2Abi;
|
|
|
46011
47349
|
exports.polygonSupportedTokens = polygonSupportedTokens;
|
|
46012
47350
|
exports.poolAbi = poolAbi;
|
|
46013
47351
|
exports.poolKeyAbi = poolKeyAbi;
|
|
47352
|
+
exports.projectLeverageLeg = projectLeverageLeg;
|
|
46014
47353
|
exports.randomUint256 = randomUint256;
|
|
46015
47354
|
exports.rayDiv = rayDiv;
|
|
46016
47355
|
exports.rayMul = rayMul;
|
|
@@ -46020,11 +47359,13 @@ exports.recoveryInvariant = recoveryInvariant;
|
|
|
46020
47359
|
exports.redbellySupportedTokens = redbellySupportedTokens;
|
|
46021
47360
|
exports.relayConfig = relayConfig;
|
|
46022
47361
|
exports.relayTxAndWaitPacket = relayTxAndWaitPacket;
|
|
47362
|
+
exports.reportPositionIntent = reportPositionIntent;
|
|
46023
47363
|
exports.requestAddress = requestAddress;
|
|
46024
47364
|
exports.requestJsonRpc = requestJsonRpc;
|
|
46025
47365
|
exports.requestSigning = requestSigning;
|
|
46026
47366
|
exports.resolveAnalytics = resolveAnalytics;
|
|
46027
47367
|
exports.resolveLogger = resolveLogger;
|
|
47368
|
+
exports.resolvePositionFundingAddress = resolvePositionFundingAddress;
|
|
46028
47369
|
exports.retry = retry;
|
|
46029
47370
|
exports.reverseEncodeAddress = reverseEncodeAddress;
|
|
46030
47371
|
exports.robinhoodChain = robinhoodChain;
|
|
@@ -46032,6 +47373,7 @@ exports.robinhoodSupportedTokens = robinhoodSupportedTokens;
|
|
|
46032
47373
|
exports.serializeAddressData = serializeAddressData;
|
|
46033
47374
|
exports.settleWalletBalances = settleWalletBalances;
|
|
46034
47375
|
exports.silentLogger = silentLogger;
|
|
47376
|
+
exports.sizeLeverageBorrow = sizeLeverageBorrow;
|
|
46035
47377
|
exports.sleep = sleep;
|
|
46036
47378
|
exports.sodaxConfig = sodaxConfig;
|
|
46037
47379
|
exports.sodaxInvariant = sodaxInvariant;
|
|
@@ -46059,6 +47401,7 @@ exports.swapExactInSingleParamsAbi = swapExactInSingleParamsAbi;
|
|
|
46059
47401
|
exports.swapInvariant = swapInvariant;
|
|
46060
47402
|
exports.swapSupportedTokens = swapSupportedTokens;
|
|
46061
47403
|
exports.swapsConfig = swapsConfig;
|
|
47404
|
+
exports.timeToBreakevenYears = timeToBreakevenYears;
|
|
46062
47405
|
exports.toCreateBridgeIntentParamsV2 = toCreateBridgeIntentParamsV2;
|
|
46063
47406
|
exports.toSuiExecutionResult = toSuiExecutionResult;
|
|
46064
47407
|
exports.toSuiExecutionStatus = toSuiExecutionStatus;
|