@sodax/sdk 2.2.0-rc.1 → 2.2.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/index.cjs +1872 -229
- package/dist/index.d.cts +734 -19
- package/dist/index.d.ts +734 -19
- package/dist/index.mjs +1868 -235
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var viem = require('viem');
|
|
4
|
+
var bitcoinjsLib = require('bitcoinjs-lib');
|
|
4
5
|
var bcs = require('@mysten/sui/bcs');
|
|
5
6
|
var web3_js = require('@solana/web3.js');
|
|
6
7
|
var stellarSdk = require('@stellar/stellar-sdk');
|
|
7
8
|
var core = require('@sodax/libs/stacks/core');
|
|
8
9
|
var chains = require('viem/chains');
|
|
9
10
|
var rlp = require('rlp');
|
|
10
|
-
var bitcoinjsLib = require('bitcoinjs-lib');
|
|
11
11
|
var ecc = require('@bitcoinerlab/secp256k1');
|
|
12
12
|
var infinitySdk = require('@pancakeswap/infinity-sdk');
|
|
13
13
|
var transactions = require('@mysten/sui/transactions');
|
|
@@ -122,8 +122,8 @@ function serializeCause(cause, depth) {
|
|
|
122
122
|
}
|
|
123
123
|
function sanitizeContext(value, depth) {
|
|
124
124
|
const out = {};
|
|
125
|
-
for (const [key,
|
|
126
|
-
out[key] = sanitizeValue(
|
|
125
|
+
for (const [key, v12] of Object.entries(value)) {
|
|
126
|
+
out[key] = sanitizeValue(v12, depth + 1);
|
|
127
127
|
}
|
|
128
128
|
return out;
|
|
129
129
|
}
|
|
@@ -134,13 +134,13 @@ function sanitizeValue(value, depth) {
|
|
|
134
134
|
if (t === "bigint") return value.toString();
|
|
135
135
|
if (t === "string" || t === "number" || t === "boolean") return value;
|
|
136
136
|
if (t === "function" || t === "symbol") return safeString(value);
|
|
137
|
-
if (Array.isArray(value)) return value.map((
|
|
137
|
+
if (Array.isArray(value)) return value.map((v12) => sanitizeValue(v12, depth + 1));
|
|
138
138
|
if (value instanceof Date) return value.toISOString();
|
|
139
139
|
if (value instanceof Map) {
|
|
140
|
-
return Array.from(value.entries()).map(([k,
|
|
140
|
+
return Array.from(value.entries()).map(([k, v12]) => [sanitizeValue(k, depth + 1), sanitizeValue(v12, depth + 1)]);
|
|
141
141
|
}
|
|
142
142
|
if (value instanceof Set) {
|
|
143
|
-
return Array.from(value.values()).map((
|
|
143
|
+
return Array.from(value.values()).map((v12) => sanitizeValue(v12, depth + 1));
|
|
144
144
|
}
|
|
145
145
|
if (value instanceof Error) return { name: value.name, message: value.message };
|
|
146
146
|
if (t === "object") {
|
|
@@ -152,9 +152,9 @@ function sanitizeValue(value, depth) {
|
|
|
152
152
|
}
|
|
153
153
|
return safeString(value);
|
|
154
154
|
}
|
|
155
|
-
function safeString(
|
|
155
|
+
function safeString(v12) {
|
|
156
156
|
try {
|
|
157
|
-
return String(
|
|
157
|
+
return String(v12);
|
|
158
158
|
} catch {
|
|
159
159
|
return "[unserializable]";
|
|
160
160
|
}
|
|
@@ -3556,7 +3556,9 @@ var spokeChainConfig = {
|
|
|
3556
3556
|
},
|
|
3557
3557
|
chain: baseChainInfo[ChainKeys.BITCOIN_MAINNET],
|
|
3558
3558
|
bnUSD: "no",
|
|
3559
|
-
|
|
3559
|
+
// Must equal bitcoinSupportedTokens.BTC.address: isNativeToken compares a token's `address`
|
|
3560
|
+
// against this value, so a symbol here classifies native BTC as a contract token.
|
|
3561
|
+
nativeToken: "0:0",
|
|
3560
3562
|
supportedTokens: bitcoinSupportedTokens,
|
|
3561
3563
|
radfi: {
|
|
3562
3564
|
walletMode: "TRADING",
|
|
@@ -4106,8 +4108,12 @@ var moneyMarketSupportedTokens = {
|
|
|
4106
4108
|
spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.USDS,
|
|
4107
4109
|
spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.XLM
|
|
4108
4110
|
],
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
+
[ChainKeys.ROBINHOOD_MAINNET]: [
|
|
4112
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.ETH,
|
|
4113
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.bnUSD,
|
|
4114
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.SODA,
|
|
4115
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.USDG
|
|
4116
|
+
]
|
|
4111
4117
|
};
|
|
4112
4118
|
var moneyMarketReserveAssets = [
|
|
4113
4119
|
...Object.values(SodaTokens).map((vault) => vault.address),
|
|
@@ -4886,7 +4892,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
4886
4892
|
}
|
|
4887
4893
|
|
|
4888
4894
|
// ../types/dist/index.js
|
|
4889
|
-
var CONFIG_VERSION =
|
|
4895
|
+
var CONFIG_VERSION = 233;
|
|
4890
4896
|
|
|
4891
4897
|
// src/shared/utils/resolveTimeoutMs.ts
|
|
4892
4898
|
function resolveTimeoutMs(timeout, fallbackMs) {
|
|
@@ -4899,6 +4905,33 @@ function isEvmSpokeChainConfig(value) {
|
|
|
4899
4905
|
function isIconAddress(value) {
|
|
4900
4906
|
return typeof value === "string" && /^hx[a-f0-9]{40}$|^cx[a-f0-9]{40}$/.test(value);
|
|
4901
4907
|
}
|
|
4908
|
+
var NEAR_ACCOUNT_ID_REGEX = /^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/;
|
|
4909
|
+
function isValidNearAccountId(accountId) {
|
|
4910
|
+
return accountId.length >= 2 && accountId.length <= 64 && NEAR_ACCOUNT_ID_REGEX.test(accountId);
|
|
4911
|
+
}
|
|
4912
|
+
var INJECTIVE_ADDRESS_REGEX = /^inj1(?:[02-9ac-hj-np-z]{38}|[02-9ac-hj-np-z]{58})$/;
|
|
4913
|
+
var BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
4914
|
+
var BECH32_GENERATOR = [996825010, 642813549, 513874426, 1027748829, 705979059];
|
|
4915
|
+
function bech32ChecksumVerifies(hrp, dataChars) {
|
|
4916
|
+
const values = [
|
|
4917
|
+
...[...hrp].map((c) => c.charCodeAt(0) >>> 5),
|
|
4918
|
+
0,
|
|
4919
|
+
...[...hrp].map((c) => c.charCodeAt(0) & 31),
|
|
4920
|
+
...[...dataChars].map((c) => BECH32_CHARSET.indexOf(c))
|
|
4921
|
+
];
|
|
4922
|
+
let chk = 1;
|
|
4923
|
+
for (const value of values) {
|
|
4924
|
+
const top = chk >>> 25;
|
|
4925
|
+
chk = (chk & 33554431) << 5 ^ value;
|
|
4926
|
+
for (let i = 0; i < 5; i++) {
|
|
4927
|
+
if (top >>> i & 1) chk ^= BECH32_GENERATOR[i];
|
|
4928
|
+
}
|
|
4929
|
+
}
|
|
4930
|
+
return chk === 1;
|
|
4931
|
+
}
|
|
4932
|
+
function isValidInjectiveAddress(address) {
|
|
4933
|
+
return INJECTIVE_ADDRESS_REGEX.test(address) && bech32ChecksumVerifies("inj", address.slice(4));
|
|
4934
|
+
}
|
|
4902
4935
|
function isResponseAddressType(value) {
|
|
4903
4936
|
return typeof value === "object" && value !== null && "type" in value && "payload" in value && value.type === "RESPONSE_ADDRESS" && isIconAddress(value.payload);
|
|
4904
4937
|
}
|
|
@@ -5006,6 +5039,81 @@ function isUndefinedOrValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
5006
5039
|
function isOptionalBitcoinWalletProviderType(walletProvider) {
|
|
5007
5040
|
return walletProvider === void 0 || isBitcoinWalletProviderType(walletProvider);
|
|
5008
5041
|
}
|
|
5042
|
+
var BITCOIN_FEE_SAFETY_VBYTES = 20;
|
|
5043
|
+
function calcOpReturnOutputVbytes(payloadByteLength) {
|
|
5044
|
+
let scriptSize;
|
|
5045
|
+
if (payloadByteLength <= 75) {
|
|
5046
|
+
scriptSize = 3 + payloadByteLength;
|
|
5047
|
+
} else if (payloadByteLength <= 255) {
|
|
5048
|
+
scriptSize = 4 + payloadByteLength;
|
|
5049
|
+
} else {
|
|
5050
|
+
scriptSize = 5 + payloadByteLength;
|
|
5051
|
+
}
|
|
5052
|
+
const scriptLenVarint = scriptSize <= 252 ? 1 : 3;
|
|
5053
|
+
return 8 + scriptLenVarint + scriptSize;
|
|
5054
|
+
}
|
|
5055
|
+
function estimateBitcoinTxSize(inputCount, outputCount, addressType, opReturnOutputVbytes = 44) {
|
|
5056
|
+
let inputWeight;
|
|
5057
|
+
switch (addressType) {
|
|
5058
|
+
case "P2PKH":
|
|
5059
|
+
inputWeight = 148;
|
|
5060
|
+
break;
|
|
5061
|
+
case "P2SH":
|
|
5062
|
+
inputWeight = 91;
|
|
5063
|
+
break;
|
|
5064
|
+
case "P2TR":
|
|
5065
|
+
inputWeight = 58;
|
|
5066
|
+
break;
|
|
5067
|
+
default:
|
|
5068
|
+
inputWeight = 68;
|
|
5069
|
+
break;
|
|
5070
|
+
}
|
|
5071
|
+
return Math.ceil(
|
|
5072
|
+
10.5 + opReturnOutputVbytes + BITCOIN_FEE_SAFETY_VBYTES + inputCount * inputWeight + outputCount * 31
|
|
5073
|
+
);
|
|
5074
|
+
}
|
|
5075
|
+
function encodeBtcPayloadToBytes(payload) {
|
|
5076
|
+
const isBase58Check = payload.address_type === "P2PKH" || payload.address_type === "P2SH";
|
|
5077
|
+
return JSON.stringify({
|
|
5078
|
+
src_address: isBase58Check ? payload.src_address : payload.src_address.toLowerCase(),
|
|
5079
|
+
data: payload.data.toLowerCase(),
|
|
5080
|
+
src_chain_id: payload.src_chain_id,
|
|
5081
|
+
dst_chain_id: payload.dst_chain_id,
|
|
5082
|
+
wallet_used: payload.wallet_used,
|
|
5083
|
+
timestamp: payload.timestamp,
|
|
5084
|
+
address_type: payload.address_type
|
|
5085
|
+
});
|
|
5086
|
+
}
|
|
5087
|
+
function isValidBitcoinAddress(address) {
|
|
5088
|
+
try {
|
|
5089
|
+
const { prefix: prefix2, version, data } = bitcoinjsLib.address.fromBech32(address);
|
|
5090
|
+
if (prefix2 !== "bc" && prefix2 !== "tb") return false;
|
|
5091
|
+
return version === 0 && (data.length === 20 || data.length === 32) || version === 1 && data.length === 32;
|
|
5092
|
+
} catch {
|
|
5093
|
+
}
|
|
5094
|
+
try {
|
|
5095
|
+
const { version } = bitcoinjsLib.address.fromBase58Check(address);
|
|
5096
|
+
return version === 0 || version === 5 || version === 111 || version === 196;
|
|
5097
|
+
} catch {
|
|
5098
|
+
return false;
|
|
5099
|
+
}
|
|
5100
|
+
}
|
|
5101
|
+
function canonicalizeBitcoinAddress(address) {
|
|
5102
|
+
try {
|
|
5103
|
+
bitcoinjsLib.address.fromBech32(address);
|
|
5104
|
+
return address.toLowerCase();
|
|
5105
|
+
} catch {
|
|
5106
|
+
return address;
|
|
5107
|
+
}
|
|
5108
|
+
}
|
|
5109
|
+
function normalizePsbtToBase64(signedPsbt) {
|
|
5110
|
+
const isHex2 = /^[0-9a-fA-F]+$/.test(signedPsbt);
|
|
5111
|
+
return isHex2 ? Buffer.from(signedPsbt, "hex").toString("base64") : signedPsbt;
|
|
5112
|
+
}
|
|
5113
|
+
function normalizeSignatureToBase64(signature) {
|
|
5114
|
+
const isHex2 = /^[0-9a-fA-F]+$/.test(signature);
|
|
5115
|
+
return isHex2 ? Buffer.from(signature, "hex").toString("base64") : signature;
|
|
5116
|
+
}
|
|
5009
5117
|
function isNativeBitcoinTransfer(config, chainKey, token) {
|
|
5010
5118
|
return isBitcoinChainKeyType(chainKey) && !!token && isNativeBitcoinToken(config.getChainConfig(chainKey), token.address);
|
|
5011
5119
|
}
|
|
@@ -5025,11 +5133,10 @@ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_R
|
|
|
5025
5133
|
throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
|
|
5026
5134
|
}
|
|
5027
5135
|
function getRandomBytes(length) {
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
array3[i] = Math.floor(Math.random() * 256);
|
|
5136
|
+
if (!globalThis.crypto?.getRandomValues) {
|
|
5137
|
+
throw new Error("Web Crypto (crypto.getRandomValues) is unavailable in this runtime");
|
|
5031
5138
|
}
|
|
5032
|
-
return
|
|
5139
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
5033
5140
|
}
|
|
5034
5141
|
function randomUint256() {
|
|
5035
5142
|
const bytes = getRandomBytes(32);
|
|
@@ -5078,6 +5185,7 @@ function encodeAddress(spokeChainId, address) {
|
|
|
5078
5185
|
const chainType = getChainType(spokeChainId);
|
|
5079
5186
|
switch (chainType) {
|
|
5080
5187
|
case "EVM":
|
|
5188
|
+
invariant(viem.isAddress(address), `Invalid EVM address: ${address}`);
|
|
5081
5189
|
return address;
|
|
5082
5190
|
case "ICON": {
|
|
5083
5191
|
invariant(isIconAddress(address), `Invalid ICON address: ${address}`);
|
|
@@ -5093,8 +5201,13 @@ function encodeAddress(spokeChainId, address) {
|
|
|
5093
5201
|
case "STACKS":
|
|
5094
5202
|
return `0x${core.serializeCV(core.Cl.principal(address))}`;
|
|
5095
5203
|
case "BITCOIN":
|
|
5204
|
+
invariant(isValidBitcoinAddress(address), `Invalid Bitcoin address: ${address}`);
|
|
5205
|
+
return viem.toHex(Buffer.from(canonicalizeBitcoinAddress(address), "utf-8"));
|
|
5096
5206
|
case "NEAR":
|
|
5207
|
+
invariant(isValidNearAccountId(address), `Invalid NEAR account id: ${address}`);
|
|
5208
|
+
return viem.toHex(Buffer.from(address, "utf-8"));
|
|
5097
5209
|
case "INJECTIVE":
|
|
5210
|
+
invariant(isValidInjectiveAddress(address), `Invalid Injective address: ${address}`);
|
|
5098
5211
|
return viem.toHex(Buffer.from(address, "utf-8"));
|
|
5099
5212
|
default: {
|
|
5100
5213
|
const exhaustiveCheck = chainType;
|
|
@@ -5102,6 +5215,16 @@ function encodeAddress(spokeChainId, address) {
|
|
|
5102
5215
|
}
|
|
5103
5216
|
}
|
|
5104
5217
|
}
|
|
5218
|
+
function encodeTokenIdentifier(spokeChainId, token) {
|
|
5219
|
+
switch (getChainType(spokeChainId)) {
|
|
5220
|
+
case "BITCOIN":
|
|
5221
|
+
case "NEAR":
|
|
5222
|
+
case "INJECTIVE":
|
|
5223
|
+
return viem.toHex(Buffer.from(token, "utf-8"));
|
|
5224
|
+
default:
|
|
5225
|
+
return encodeAddress(spokeChainId, token);
|
|
5226
|
+
}
|
|
5227
|
+
}
|
|
5105
5228
|
function reverseEncodeAddress(spokeChainId, encoded) {
|
|
5106
5229
|
const chainType = getChainType(spokeChainId);
|
|
5107
5230
|
switch (chainType) {
|
|
@@ -14801,6 +14924,11 @@ var ConfigService = class {
|
|
|
14801
14924
|
get bridgeUseBackendSubmitTx() {
|
|
14802
14925
|
return this.bridge.useBackendSubmitTx ?? this.sodax.bridgeOptions?.useBackendSubmitTx ?? true;
|
|
14803
14926
|
}
|
|
14927
|
+
// Opt-in (default OFF), unlike the swaps/bridge toggles above: the leverage-yield submit-tx
|
|
14928
|
+
// backend path is newer, so an omitted flag keeps the proven client-side relay.
|
|
14929
|
+
get leverageYieldUseBackendSubmitTx() {
|
|
14930
|
+
return this.leverageYield.useBackendSubmitTx ?? false;
|
|
14931
|
+
}
|
|
14804
14932
|
get dex() {
|
|
14805
14933
|
return this.sodax.dex;
|
|
14806
14934
|
}
|
|
@@ -14852,7 +14980,7 @@ function mergeSodaxConfig(base2, override) {
|
|
|
14852
14980
|
}
|
|
14853
14981
|
function encodeContractCalls(calls) {
|
|
14854
14982
|
return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
|
|
14855
|
-
calls.map((
|
|
14983
|
+
calls.map((v12) => [v12.address, v12.value, v12.data])
|
|
14856
14984
|
]);
|
|
14857
14985
|
}
|
|
14858
14986
|
async function waitForTransactionReceipt(hash, provider) {
|
|
@@ -15055,16 +15183,20 @@ var EvmVaultTokenService = class {
|
|
|
15055
15183
|
*/
|
|
15056
15184
|
static async deposit(vault, token, amount, walletProvider) {
|
|
15057
15185
|
const from = await walletProvider.getWalletAddress();
|
|
15058
|
-
return walletProvider.sendTransaction(
|
|
15059
|
-
|
|
15060
|
-
|
|
15061
|
-
|
|
15062
|
-
|
|
15063
|
-
|
|
15064
|
-
|
|
15065
|
-
|
|
15066
|
-
|
|
15067
|
-
|
|
15186
|
+
return walletProvider.sendTransaction(
|
|
15187
|
+
{
|
|
15188
|
+
from,
|
|
15189
|
+
to: vault,
|
|
15190
|
+
value: 0n,
|
|
15191
|
+
data: viem.encodeFunctionData({
|
|
15192
|
+
abi: vaultTokenAbi,
|
|
15193
|
+
functionName: "deposit",
|
|
15194
|
+
args: [token, amount]
|
|
15195
|
+
})
|
|
15196
|
+
},
|
|
15197
|
+
// Vaults live on the hub; refuse to broadcast from a wallet on another EVM network.
|
|
15198
|
+
{ expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id }
|
|
15199
|
+
);
|
|
15068
15200
|
}
|
|
15069
15201
|
/**
|
|
15070
15202
|
* Withdraws a specified amount of a token from the vault.
|
|
@@ -15076,16 +15208,19 @@ var EvmVaultTokenService = class {
|
|
|
15076
15208
|
*/
|
|
15077
15209
|
static async withdraw(vault, token, amount, provider) {
|
|
15078
15210
|
const from = await provider.getWalletAddress();
|
|
15079
|
-
return provider.sendTransaction(
|
|
15080
|
-
|
|
15081
|
-
|
|
15082
|
-
|
|
15083
|
-
|
|
15084
|
-
|
|
15085
|
-
|
|
15086
|
-
|
|
15087
|
-
|
|
15088
|
-
|
|
15211
|
+
return provider.sendTransaction(
|
|
15212
|
+
{
|
|
15213
|
+
from,
|
|
15214
|
+
to: vault,
|
|
15215
|
+
value: 0n,
|
|
15216
|
+
data: viem.encodeFunctionData({
|
|
15217
|
+
abi: vaultTokenAbi,
|
|
15218
|
+
functionName: "withdraw",
|
|
15219
|
+
args: [token, amount]
|
|
15220
|
+
})
|
|
15221
|
+
},
|
|
15222
|
+
{ expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id }
|
|
15223
|
+
);
|
|
15089
15224
|
}
|
|
15090
15225
|
/**
|
|
15091
15226
|
* Encodes the deposit transaction data for the vault.
|
|
@@ -15286,7 +15421,9 @@ var Erc20Service = class _Erc20Service {
|
|
|
15286
15421
|
if (params.raw) {
|
|
15287
15422
|
return rawTx;
|
|
15288
15423
|
}
|
|
15289
|
-
return await params.walletProvider.sendTransaction(rawTx
|
|
15424
|
+
return await params.walletProvider.sendTransaction(rawTx, {
|
|
15425
|
+
expectedChainId: params.expectedChainId
|
|
15426
|
+
});
|
|
15290
15427
|
}
|
|
15291
15428
|
/**
|
|
15292
15429
|
* Encodes a transfer transaction for a token.
|
|
@@ -15450,10 +15587,54 @@ var EvmAssetManagerService = class _EvmAssetManagerService {
|
|
|
15450
15587
|
});
|
|
15451
15588
|
}
|
|
15452
15589
|
};
|
|
15590
|
+
|
|
15591
|
+
// src/shared/services/spoke/balance-utils.ts
|
|
15592
|
+
function createBalanceCollector({ logger, chainKey }) {
|
|
15593
|
+
const balances = {};
|
|
15594
|
+
let attempted = 0;
|
|
15595
|
+
let failed = 0;
|
|
15596
|
+
return {
|
|
15597
|
+
ok(tokenAddress, value) {
|
|
15598
|
+
attempted++;
|
|
15599
|
+
balances[tokenAddress] = value;
|
|
15600
|
+
},
|
|
15601
|
+
fail(tokenAddress, reason) {
|
|
15602
|
+
attempted++;
|
|
15603
|
+
failed++;
|
|
15604
|
+
logger.warn("[getWalletBalances] balance read failed, reporting 0n", {
|
|
15605
|
+
chainKey,
|
|
15606
|
+
token: tokenAddress,
|
|
15607
|
+
error: reason instanceof Error ? reason.message : String(reason)
|
|
15608
|
+
});
|
|
15609
|
+
balances[tokenAddress] = 0n;
|
|
15610
|
+
},
|
|
15611
|
+
finish() {
|
|
15612
|
+
if (attempted > 0 && failed === attempted) {
|
|
15613
|
+
throw new Error(`[getWalletBalances] every balance read failed on ${chainKey} (${failed}/${attempted})`);
|
|
15614
|
+
}
|
|
15615
|
+
return balances;
|
|
15616
|
+
}
|
|
15617
|
+
};
|
|
15618
|
+
}
|
|
15619
|
+
async function settleWalletBalances(collector, tokens, read) {
|
|
15620
|
+
const settled = await Promise.allSettled(tokens.map((token) => read(token)));
|
|
15621
|
+
tokens.forEach((token, index) => {
|
|
15622
|
+
const outcome = settled[index];
|
|
15623
|
+
if (!outcome) return;
|
|
15624
|
+
if (outcome.status === "fulfilled") {
|
|
15625
|
+
collector.ok(token.address, outcome.value);
|
|
15626
|
+
} else {
|
|
15627
|
+
collector.fail(token.address, outcome.reason);
|
|
15628
|
+
}
|
|
15629
|
+
});
|
|
15630
|
+
}
|
|
15453
15631
|
var HEDERA_NATIVE_VALUE_SCALE = 10n ** 10n;
|
|
15454
15632
|
function scaleNativeMsgValue(chainKey, amount) {
|
|
15455
15633
|
return chainKey === ChainKeys.HEDERA_MAINNET ? amount * HEDERA_NATIVE_VALUE_SCALE : amount;
|
|
15456
15634
|
}
|
|
15635
|
+
function scaleNativeBalance(chainKey, amount) {
|
|
15636
|
+
return chainKey === ChainKeys.HEDERA_MAINNET ? amount / HEDERA_NATIVE_VALUE_SCALE : amount;
|
|
15637
|
+
}
|
|
15457
15638
|
var EvmSpokeService = class {
|
|
15458
15639
|
config;
|
|
15459
15640
|
// map containing the public clients for each evm spoke chain, lazy loaded on demand
|
|
@@ -15555,7 +15736,9 @@ var EvmSpokeService = class {
|
|
|
15555
15736
|
if (params.raw === true) {
|
|
15556
15737
|
return rawTx;
|
|
15557
15738
|
}
|
|
15558
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
15739
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
15740
|
+
expectedChainId: getEvmViemChain(srcChainKey).id
|
|
15741
|
+
});
|
|
15559
15742
|
}
|
|
15560
15743
|
/**
|
|
15561
15744
|
* Get the balance of the token deposited in the spoke chain asset manager.
|
|
@@ -15570,6 +15753,79 @@ var EvmSpokeService = class {
|
|
|
15570
15753
|
args: [this.config.getChainConfig(params.srcChainKey).addresses.assetManager]
|
|
15571
15754
|
});
|
|
15572
15755
|
}
|
|
15756
|
+
/**
|
|
15757
|
+
* Get the user's own wallet balance of a token on an EVM spoke chain, in smallest units.
|
|
15758
|
+
* Native coin via `eth_getBalance` (Hedera scaled to canonical decimals); erc20 via `balanceOf`.
|
|
15759
|
+
* @param {GetBalanceParams<EvmSpokeOnlyChainKey>} params - The chain key, user address, and token.
|
|
15760
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
15761
|
+
*/
|
|
15762
|
+
async getWalletBalance(params) {
|
|
15763
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
15764
|
+
const publicClient = this.getPublicClient(srcChainKey);
|
|
15765
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
15766
|
+
const balance2 = await publicClient.getBalance({ address: srcAddress });
|
|
15767
|
+
return scaleNativeBalance(srcChainKey, balance2);
|
|
15768
|
+
}
|
|
15769
|
+
const balance = await publicClient.readContract({
|
|
15770
|
+
address: token.address,
|
|
15771
|
+
abi: erc20Abi,
|
|
15772
|
+
functionName: "balanceOf",
|
|
15773
|
+
args: [srcAddress]
|
|
15774
|
+
});
|
|
15775
|
+
return balance ?? 0n;
|
|
15776
|
+
}
|
|
15777
|
+
/**
|
|
15778
|
+
* Get the user's own wallet balances of multiple tokens on an EVM spoke chain, in smallest
|
|
15779
|
+
* units. Non-native tokens are batched via multicall3 when the chain supports it, otherwise
|
|
15780
|
+
* read in parallel.
|
|
15781
|
+
* @param {GetBalancesParams<EvmSpokeOnlyChainKey>} params - The chain key, user address, and tokens.
|
|
15782
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
15783
|
+
*/
|
|
15784
|
+
async getWalletBalances(params) {
|
|
15785
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
15786
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
15787
|
+
const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
15788
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
15789
|
+
await settleWalletBalances(
|
|
15790
|
+
collector,
|
|
15791
|
+
nativeTokens,
|
|
15792
|
+
(token) => this.getWalletBalance({ srcChainKey, srcAddress, token })
|
|
15793
|
+
);
|
|
15794
|
+
if (nonNativeTokens.length === 0) {
|
|
15795
|
+
return collector.finish();
|
|
15796
|
+
}
|
|
15797
|
+
const publicClient = this.getPublicClient(srcChainKey);
|
|
15798
|
+
if (getEvmViemChain(srcChainKey).contracts?.multicall3) {
|
|
15799
|
+
const results = await publicClient.multicall({
|
|
15800
|
+
contracts: nonNativeTokens.map((token) => ({
|
|
15801
|
+
abi: erc20Abi,
|
|
15802
|
+
address: token.address,
|
|
15803
|
+
functionName: "balanceOf",
|
|
15804
|
+
args: [srcAddress]
|
|
15805
|
+
}))
|
|
15806
|
+
});
|
|
15807
|
+
nonNativeTokens.forEach((token, index) => {
|
|
15808
|
+
const result = results[index];
|
|
15809
|
+
if (result?.status === "success") {
|
|
15810
|
+
collector.ok(token.address, BigInt(result.result));
|
|
15811
|
+
} else {
|
|
15812
|
+
collector.fail(token.address, result?.error ?? new Error(`missing multicall result for ${token.address}`));
|
|
15813
|
+
}
|
|
15814
|
+
});
|
|
15815
|
+
return collector.finish();
|
|
15816
|
+
}
|
|
15817
|
+
await settleWalletBalances(
|
|
15818
|
+
collector,
|
|
15819
|
+
nonNativeTokens,
|
|
15820
|
+
(token) => publicClient.readContract({
|
|
15821
|
+
address: token.address,
|
|
15822
|
+
abi: erc20Abi,
|
|
15823
|
+
functionName: "balanceOf",
|
|
15824
|
+
args: [srcAddress]
|
|
15825
|
+
})
|
|
15826
|
+
);
|
|
15827
|
+
return collector.finish();
|
|
15828
|
+
}
|
|
15573
15829
|
/**
|
|
15574
15830
|
* Sends a message to the hub chain.
|
|
15575
15831
|
* @param {SendMessageParams} params - Includes dstChainKey, the chain key of the hub chain.
|
|
@@ -15595,7 +15851,9 @@ var EvmSpokeService = class {
|
|
|
15595
15851
|
if (params.raw) {
|
|
15596
15852
|
return rawTx;
|
|
15597
15853
|
}
|
|
15598
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
15854
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
15855
|
+
expectedChainId: getEvmViemChain(srcChainKey).id
|
|
15856
|
+
});
|
|
15599
15857
|
}
|
|
15600
15858
|
async waitForTransactionReceipt(params) {
|
|
15601
15859
|
try {
|
|
@@ -15687,6 +15945,24 @@ var StacksSpokeService = class {
|
|
|
15687
15945
|
});
|
|
15688
15946
|
return result.value.value;
|
|
15689
15947
|
}
|
|
15948
|
+
ftAssetNames = /* @__PURE__ */ new Map();
|
|
15949
|
+
/** Post-conditions need the on-chain `define-fungible-token` names; SIP-10 exposes no read for them. */
|
|
15950
|
+
async getFtAssetNames(tokenContractId) {
|
|
15951
|
+
const cached = this.ftAssetNames.get(tokenContractId);
|
|
15952
|
+
if (cached) return cached;
|
|
15953
|
+
const [address, name] = core.parseContractId(tokenContractId);
|
|
15954
|
+
const response = await fetch(`${this.network.client.baseUrl}/v2/contracts/interface/${address}/${name}`);
|
|
15955
|
+
if (!response.ok) {
|
|
15956
|
+
throw new Error(`Failed to fetch the contract interface for ${tokenContractId}: ${response.statusText}`);
|
|
15957
|
+
}
|
|
15958
|
+
const abi = await response.json();
|
|
15959
|
+
const assetNames = (abi.fungible_tokens ?? []).map((token) => token.name);
|
|
15960
|
+
if (assetNames.length === 0) {
|
|
15961
|
+
throw new Error(`${tokenContractId} defines no fungible token \u2014 not a SIP-10 contract`);
|
|
15962
|
+
}
|
|
15963
|
+
this.ftAssetNames.set(tokenContractId, assetNames);
|
|
15964
|
+
return assetNames;
|
|
15965
|
+
}
|
|
15690
15966
|
async getImplContractAddress(stateContract) {
|
|
15691
15967
|
const [contractAddress, contractName] = core.parseContractId(stateContract);
|
|
15692
15968
|
const txParams = {
|
|
@@ -15709,18 +15985,18 @@ var StacksSpokeService = class {
|
|
|
15709
15985
|
const assetManagerImpl = await this.getImplContractAddress(chainConfig.addresses.assetManager);
|
|
15710
15986
|
const [implAddress, implName] = core.parseContractId(assetManagerImpl);
|
|
15711
15987
|
const [connectionAddress, connectionName] = core.parseContractId(chainConfig.addresses.connection);
|
|
15988
|
+
const isNative = isNativeToken(params.srcChainKey, params.token);
|
|
15712
15989
|
const reqData = {
|
|
15713
15990
|
contractAddress: implAddress,
|
|
15714
15991
|
contractName: implName,
|
|
15715
15992
|
functionName: "transfer",
|
|
15716
15993
|
functionArgs: [
|
|
15717
|
-
|
|
15994
|
+
isNative ? core.noneCV() : core.someCV(core.Cl.principal(params.token)),
|
|
15718
15995
|
core.Cl.bufferFromHex(params.to),
|
|
15719
15996
|
core.uintCV(params.amount),
|
|
15720
15997
|
core.Cl.bufferFromHex(params.data),
|
|
15721
15998
|
core.Cl.contractPrincipal(connectionAddress, connectionName)
|
|
15722
|
-
]
|
|
15723
|
-
postConditionMode: core.PostConditionMode.Allow
|
|
15999
|
+
]
|
|
15724
16000
|
};
|
|
15725
16001
|
if (params.raw === true) {
|
|
15726
16002
|
if (!params.srcPublicKey) {
|
|
@@ -15749,9 +16025,25 @@ var StacksSpokeService = class {
|
|
|
15749
16025
|
payload: viem.bytesToHex(core.serializePayloadBytes(tx.payload))
|
|
15750
16026
|
};
|
|
15751
16027
|
}
|
|
15752
|
-
const txId = await params.walletProvider.sendTransaction(
|
|
16028
|
+
const txId = await params.walletProvider.sendTransaction({
|
|
16029
|
+
...reqData,
|
|
16030
|
+
postConditionMode: core.PostConditionMode.Deny,
|
|
16031
|
+
postConditions: await this.depositPostConditions(params.srcAddress, params.token, params.amount, isNative)
|
|
16032
|
+
});
|
|
15753
16033
|
return txId;
|
|
15754
16034
|
}
|
|
16035
|
+
/**
|
|
16036
|
+
* Caps for a Deny-mode deposit: asset-manager-state.deposit moves exactly `amount` from the
|
|
16037
|
+
* caller, so cap the sender at `amount` — one cap per FT the token contract defines (sBTC has
|
|
16038
|
+
* two; the unmoved ones pass at 0 trivially), or uSTX for native.
|
|
16039
|
+
*/
|
|
16040
|
+
async depositPostConditions(srcAddress, token, amount, isNative) {
|
|
16041
|
+
if (isNative) return [core.Pc.principal(srcAddress).willSendLte(amount).ustx()];
|
|
16042
|
+
const assetNames = await this.getFtAssetNames(token);
|
|
16043
|
+
return assetNames.map(
|
|
16044
|
+
(assetName) => core.Pc.principal(srcAddress).willSendLte(amount).ft(token, assetName)
|
|
16045
|
+
);
|
|
16046
|
+
}
|
|
15755
16047
|
/**
|
|
15756
16048
|
* Get the balance of the token deposited in the spoke chain asset manager.
|
|
15757
16049
|
* @param {GetDepositParams<StacksChainKey>} params - The parameters for the deposit, including the user's address, token address, and chain id.
|
|
@@ -15764,6 +16056,31 @@ var StacksSpokeService = class {
|
|
|
15764
16056
|
}
|
|
15765
16057
|
return this.readTokenBalance(params.token, assetManager);
|
|
15766
16058
|
}
|
|
16059
|
+
/**
|
|
16060
|
+
* Get the user's own wallet balance of a token on Stacks, in smallest units. Native STX via the
|
|
16061
|
+
* Hiro REST `/extended/v1/address/{addr}/balances` endpoint; SIP-010 fungible tokens via the
|
|
16062
|
+
* read-only `get-balance` contract call. Unlike {@link getDeposit}, this reads the holding of
|
|
16063
|
+
* `srcAddress` (the user), not the protocol asset manager.
|
|
16064
|
+
* @param {GetBalanceParams<StacksChainKey>} params - The chain key, user address, and token.
|
|
16065
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
16066
|
+
*/
|
|
16067
|
+
async getWalletBalance(params) {
|
|
16068
|
+
if (isNativeToken(params.srcChainKey, params.token)) {
|
|
16069
|
+
return this.getSTXBalance(params.srcAddress);
|
|
16070
|
+
}
|
|
16071
|
+
return this.readTokenBalance(params.token.address, params.srcAddress);
|
|
16072
|
+
}
|
|
16073
|
+
/**
|
|
16074
|
+
* Get the user's own wallet balances of multiple tokens on Stacks, in smallest units.
|
|
16075
|
+
* @param {GetBalancesParams<StacksChainKey>} params - The chain key, user address, and tokens.
|
|
16076
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
16077
|
+
*/
|
|
16078
|
+
async getWalletBalances(params) {
|
|
16079
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
16080
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
16081
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
16082
|
+
return collector.finish();
|
|
16083
|
+
}
|
|
15767
16084
|
/**
|
|
15768
16085
|
* Sends a message to the hub chain.
|
|
15769
16086
|
*/
|
|
@@ -15776,8 +16093,7 @@ var StacksSpokeService = class {
|
|
|
15776
16093
|
contractAddress: connectionAddress,
|
|
15777
16094
|
contractName: connectionName,
|
|
15778
16095
|
functionName: "send-message",
|
|
15779
|
-
functionArgs: [core.uintCV(dstRelayChainId), core.Cl.bufferFromHex(params.dstAddress), core.Cl.bufferFromHex(params.payload)]
|
|
15780
|
-
postConditionMode: core.PostConditionMode.Allow
|
|
16096
|
+
functionArgs: [core.uintCV(dstRelayChainId), core.Cl.bufferFromHex(params.dstAddress), core.Cl.bufferFromHex(params.payload)]
|
|
15781
16097
|
};
|
|
15782
16098
|
if (params.raw === true) {
|
|
15783
16099
|
const tx = await core.makeUnsignedContractCall({
|
|
@@ -15792,7 +16108,12 @@ var StacksSpokeService = class {
|
|
|
15792
16108
|
payload: viem.bytesToHex(core.serializePayloadBytes(tx.payload))
|
|
15793
16109
|
};
|
|
15794
16110
|
}
|
|
15795
|
-
const txId = await params.walletProvider.sendTransaction(
|
|
16111
|
+
const txId = await params.walletProvider.sendTransaction({
|
|
16112
|
+
...reqData,
|
|
16113
|
+
// send-message moves no assets — deny with no conditions aborts if it ever tries.
|
|
16114
|
+
postConditionMode: core.PostConditionMode.Deny,
|
|
16115
|
+
postConditions: []
|
|
16116
|
+
});
|
|
15796
16117
|
return txId;
|
|
15797
16118
|
}
|
|
15798
16119
|
async waitForTransactionReceipt(params) {
|
|
@@ -16239,60 +16560,6 @@ var RadfiProvider = class {
|
|
|
16239
16560
|
}
|
|
16240
16561
|
};
|
|
16241
16562
|
|
|
16242
|
-
// src/shared/entities/btc/btc-utils.ts
|
|
16243
|
-
var BITCOIN_FEE_SAFETY_VBYTES = 20;
|
|
16244
|
-
function calcOpReturnOutputVbytes(payloadByteLength) {
|
|
16245
|
-
let scriptSize;
|
|
16246
|
-
if (payloadByteLength <= 75) {
|
|
16247
|
-
scriptSize = 3 + payloadByteLength;
|
|
16248
|
-
} else if (payloadByteLength <= 255) {
|
|
16249
|
-
scriptSize = 4 + payloadByteLength;
|
|
16250
|
-
} else {
|
|
16251
|
-
scriptSize = 5 + payloadByteLength;
|
|
16252
|
-
}
|
|
16253
|
-
const scriptLenVarint = scriptSize <= 252 ? 1 : 3;
|
|
16254
|
-
return 8 + scriptLenVarint + scriptSize;
|
|
16255
|
-
}
|
|
16256
|
-
function estimateBitcoinTxSize(inputCount, outputCount, addressType, opReturnOutputVbytes = 44) {
|
|
16257
|
-
let inputWeight;
|
|
16258
|
-
switch (addressType) {
|
|
16259
|
-
case "P2PKH":
|
|
16260
|
-
inputWeight = 148;
|
|
16261
|
-
break;
|
|
16262
|
-
case "P2SH":
|
|
16263
|
-
inputWeight = 91;
|
|
16264
|
-
break;
|
|
16265
|
-
case "P2TR":
|
|
16266
|
-
inputWeight = 58;
|
|
16267
|
-
break;
|
|
16268
|
-
default:
|
|
16269
|
-
inputWeight = 68;
|
|
16270
|
-
break;
|
|
16271
|
-
}
|
|
16272
|
-
return Math.ceil(
|
|
16273
|
-
10.5 + opReturnOutputVbytes + BITCOIN_FEE_SAFETY_VBYTES + inputCount * inputWeight + outputCount * 31
|
|
16274
|
-
);
|
|
16275
|
-
}
|
|
16276
|
-
function encodeBtcPayloadToBytes(payload) {
|
|
16277
|
-
return JSON.stringify({
|
|
16278
|
-
src_address: payload.src_address.toLowerCase(),
|
|
16279
|
-
data: payload.data.toLowerCase(),
|
|
16280
|
-
src_chain_id: payload.src_chain_id,
|
|
16281
|
-
dst_chain_id: payload.dst_chain_id,
|
|
16282
|
-
wallet_used: payload.wallet_used,
|
|
16283
|
-
timestamp: payload.timestamp,
|
|
16284
|
-
address_type: payload.address_type
|
|
16285
|
-
});
|
|
16286
|
-
}
|
|
16287
|
-
function normalizePsbtToBase64(signedPsbt) {
|
|
16288
|
-
const isHex2 = /^[0-9a-fA-F]+$/.test(signedPsbt);
|
|
16289
|
-
return isHex2 ? Buffer.from(signedPsbt, "hex").toString("base64") : signedPsbt;
|
|
16290
|
-
}
|
|
16291
|
-
function normalizeSignatureToBase64(signature) {
|
|
16292
|
-
const isHex2 = /^[0-9a-fA-F]+$/.test(signature);
|
|
16293
|
-
return isHex2 ? Buffer.from(signature, "hex").toString("base64") : signature;
|
|
16294
|
-
}
|
|
16295
|
-
|
|
16296
16563
|
// src/shared/services/spoke/BitcoinSpokeService.ts
|
|
16297
16564
|
bitcoinjsLib.initEccLib(ecc__namespace);
|
|
16298
16565
|
var BITCOIN_DEFAULT_FEE_RATE = 3;
|
|
@@ -16324,6 +16591,32 @@ var BitcoinSpokeService = class {
|
|
|
16324
16591
|
}
|
|
16325
16592
|
throw new Error("Token balance queries not yet implemented for non-BTC assets");
|
|
16326
16593
|
}
|
|
16594
|
+
/**
|
|
16595
|
+
* Get the user's own wallet balance of a token on Bitcoin, in satoshis. Only native BTC is
|
|
16596
|
+
* readable (summed from confirmed/unconfirmed UTXOs). Non-native spoke tokens are Rune ids
|
|
16597
|
+
* (`block:tx`), whose amounts the Esplora UTXO endpoint does not carry, so they resolve to 0n.
|
|
16598
|
+
* @param {GetBalanceParams<BitcoinChainKey>} params - The chain key, user address, and token.
|
|
16599
|
+
* @returns {Promise<bigint>} The balance in satoshis.
|
|
16600
|
+
*/
|
|
16601
|
+
async getWalletBalance(params) {
|
|
16602
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
16603
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
16604
|
+
const utxos = await this.fetchUTXOs(srcAddress);
|
|
16605
|
+
return BigInt(utxos.reduce((sum, utxo) => sum + utxo.value, 0));
|
|
16606
|
+
}
|
|
16607
|
+
return 0n;
|
|
16608
|
+
}
|
|
16609
|
+
/**
|
|
16610
|
+
* Get the user's own wallet balances of multiple tokens on Bitcoin, in satoshis.
|
|
16611
|
+
* @param {GetBalancesParams<BitcoinChainKey>} params - The chain key, user address, and tokens.
|
|
16612
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
16613
|
+
*/
|
|
16614
|
+
async getWalletBalances(params) {
|
|
16615
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
16616
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
16617
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
16618
|
+
return collector.finish();
|
|
16619
|
+
}
|
|
16327
16620
|
async fetchScriptPubKey(utxo) {
|
|
16328
16621
|
const txHex = await this.fetchRawTransaction(utxo.txid);
|
|
16329
16622
|
const tx = bitcoinjsLib.Transaction.fromHex(txHex);
|
|
@@ -16924,7 +17217,7 @@ function hexToBytes2(hex) {
|
|
|
16924
17217
|
const al = hl / 2;
|
|
16925
17218
|
if (hl % 2)
|
|
16926
17219
|
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
16927
|
-
const
|
|
17220
|
+
const array4 = new Uint8Array(al);
|
|
16928
17221
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
16929
17222
|
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
16930
17223
|
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
@@ -16932,9 +17225,9 @@ function hexToBytes2(hex) {
|
|
|
16932
17225
|
const char = hex[hi] + hex[hi + 1];
|
|
16933
17226
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
16934
17227
|
}
|
|
16935
|
-
|
|
17228
|
+
array4[ai] = n1 * 16 + n2;
|
|
16936
17229
|
}
|
|
16937
|
-
return
|
|
17230
|
+
return array4;
|
|
16938
17231
|
}
|
|
16939
17232
|
function concatBytes(...arrays) {
|
|
16940
17233
|
let sum = 0;
|
|
@@ -17564,22 +17857,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
17564
17857
|
const byte0 = Uint8Array.of(0);
|
|
17565
17858
|
const byte1 = Uint8Array.of(1);
|
|
17566
17859
|
const _maxDrbgIters = 1e3;
|
|
17567
|
-
let
|
|
17860
|
+
let v12 = u8n(hashLen);
|
|
17568
17861
|
let k = u8n(hashLen);
|
|
17569
17862
|
let i = 0;
|
|
17570
17863
|
const reset = () => {
|
|
17571
|
-
|
|
17864
|
+
v12.fill(1);
|
|
17572
17865
|
k.fill(0);
|
|
17573
17866
|
i = 0;
|
|
17574
17867
|
};
|
|
17575
|
-
const h = (...msgs) => hmacFn(k, concatBytes(
|
|
17868
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v12, ...msgs));
|
|
17576
17869
|
const reseed = (seed = NULL) => {
|
|
17577
17870
|
k = h(byte0, seed);
|
|
17578
|
-
|
|
17871
|
+
v12 = h();
|
|
17579
17872
|
if (seed.length === 0)
|
|
17580
17873
|
return;
|
|
17581
17874
|
k = h(byte1, seed);
|
|
17582
|
-
|
|
17875
|
+
v12 = h();
|
|
17583
17876
|
};
|
|
17584
17877
|
const gen = () => {
|
|
17585
17878
|
if (i++ >= _maxDrbgIters)
|
|
@@ -17587,10 +17880,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
17587
17880
|
let len = 0;
|
|
17588
17881
|
const out = [];
|
|
17589
17882
|
while (len < qByteLen) {
|
|
17590
|
-
|
|
17591
|
-
const sl =
|
|
17883
|
+
v12 = h();
|
|
17884
|
+
const sl = v12.slice();
|
|
17592
17885
|
out.push(sl);
|
|
17593
|
-
len +=
|
|
17886
|
+
len += v12.length;
|
|
17594
17887
|
}
|
|
17595
17888
|
return concatBytes(...out);
|
|
17596
17889
|
};
|
|
@@ -17605,18 +17898,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
17605
17898
|
};
|
|
17606
17899
|
return genUntil;
|
|
17607
17900
|
}
|
|
17608
|
-
function validateObject(
|
|
17609
|
-
if (!
|
|
17901
|
+
function validateObject(object6, fields = {}, optFields = {}) {
|
|
17902
|
+
if (!object6 || typeof object6 !== "object")
|
|
17610
17903
|
throw new Error("expected valid options object");
|
|
17611
17904
|
function checkField(fieldName, expectedType, isOpt) {
|
|
17612
|
-
const val =
|
|
17905
|
+
const val = object6[fieldName];
|
|
17613
17906
|
if (isOpt && val === void 0)
|
|
17614
17907
|
return;
|
|
17615
17908
|
const current = typeof val;
|
|
17616
17909
|
if (current !== expectedType || val === null)
|
|
17617
17910
|
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
17618
17911
|
}
|
|
17619
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k,
|
|
17912
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v12]) => checkField(k, v12, isOpt));
|
|
17620
17913
|
iter(fields, false);
|
|
17621
17914
|
iter(optFields, true);
|
|
17622
17915
|
}
|
|
@@ -17655,12 +17948,12 @@ function pow2(x, power, modulo) {
|
|
|
17655
17948
|
}
|
|
17656
17949
|
return res;
|
|
17657
17950
|
}
|
|
17658
|
-
function invert(
|
|
17659
|
-
if (
|
|
17951
|
+
function invert(number6, modulo) {
|
|
17952
|
+
if (number6 === _0n2)
|
|
17660
17953
|
throw new Error("invert: expected non-zero number");
|
|
17661
17954
|
if (modulo <= _0n2)
|
|
17662
17955
|
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
17663
|
-
let a = mod(
|
|
17956
|
+
let a = mod(number6, modulo);
|
|
17664
17957
|
let b = modulo;
|
|
17665
17958
|
let x = _0n2, u = _1n2;
|
|
17666
17959
|
while (a !== _0n2) {
|
|
@@ -17687,9 +17980,9 @@ function sqrt3mod4(Fp, n) {
|
|
|
17687
17980
|
function sqrt5mod8(Fp, n) {
|
|
17688
17981
|
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
17689
17982
|
const n2 = Fp.mul(n, _2n);
|
|
17690
|
-
const
|
|
17691
|
-
const nv = Fp.mul(n,
|
|
17692
|
-
const i = Fp.mul(Fp.mul(nv, _2n),
|
|
17983
|
+
const v12 = Fp.pow(n2, p5div8);
|
|
17984
|
+
const nv = Fp.mul(n, v12);
|
|
17985
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v12);
|
|
17693
17986
|
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
17694
17987
|
assertIsSquare(Fp, root, n);
|
|
17695
17988
|
return root;
|
|
@@ -18271,9 +18564,9 @@ function edwards(params, extraOpts = {}) {
|
|
|
18271
18564
|
validateObject(extraOpts, {}, { uvRatio: "function" });
|
|
18272
18565
|
const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
|
|
18273
18566
|
const modP = (n) => Fp.create(n);
|
|
18274
|
-
const uvRatio2 = extraOpts.uvRatio || ((u,
|
|
18567
|
+
const uvRatio2 = extraOpts.uvRatio || ((u, v12) => {
|
|
18275
18568
|
try {
|
|
18276
|
-
return { isValid: true, value: Fp.sqrt(Fp.div(u,
|
|
18569
|
+
return { isValid: true, value: Fp.sqrt(Fp.div(u, v12)) };
|
|
18277
18570
|
} catch (e) {
|
|
18278
18571
|
return { isValid: false, value: _0n4 };
|
|
18279
18572
|
}
|
|
@@ -18369,8 +18662,8 @@ function edwards(params, extraOpts = {}) {
|
|
|
18369
18662
|
aInRange("point.y", y, _0n4, max);
|
|
18370
18663
|
const y2 = modP(y * y);
|
|
18371
18664
|
const u = modP(y2 - _1n4);
|
|
18372
|
-
const
|
|
18373
|
-
let { isValid, value: x } = uvRatio2(u,
|
|
18665
|
+
const v12 = modP(d * y2 - a);
|
|
18666
|
+
let { isValid, value: x } = uvRatio2(u, v12);
|
|
18374
18667
|
if (!isValid)
|
|
18375
18668
|
throw new Error("bad point: invalid y coordinate");
|
|
18376
18669
|
const isXOdd = (x & _1n4) === _1n4;
|
|
@@ -18710,13 +19003,13 @@ function adjustScalarBytes(bytes) {
|
|
|
18710
19003
|
return bytes;
|
|
18711
19004
|
}
|
|
18712
19005
|
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
|
|
18713
|
-
function uvRatio(u,
|
|
19006
|
+
function uvRatio(u, v12) {
|
|
18714
19007
|
const P = ed25519_CURVE_p;
|
|
18715
|
-
const v32 = mod(
|
|
18716
|
-
const v72 = mod(v32 * v32 *
|
|
19008
|
+
const v32 = mod(v12 * v12 * v12, P);
|
|
19009
|
+
const v72 = mod(v32 * v32 * v12, P);
|
|
18717
19010
|
const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
|
|
18718
19011
|
let x = mod(u * v32 * pow, P);
|
|
18719
|
-
const vx2 = mod(
|
|
19012
|
+
const vx2 = mod(v12 * x * x, P);
|
|
18720
19013
|
const root1 = x;
|
|
18721
19014
|
const root2 = mod(x * ED25519_SQRT_M1, P);
|
|
18722
19015
|
const useRoot1 = vx2 === u;
|
|
@@ -19047,7 +19340,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
|
|
|
19047
19340
|
return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
|
|
19048
19341
|
}
|
|
19049
19342
|
function findSeatPriceForProtocolBefore49(validators, numSeats) {
|
|
19050
|
-
const stakes = validators.map((
|
|
19343
|
+
const stakes = validators.map((v12) => BigInt(v12.stake)).sort(sortBigIntAsc);
|
|
19051
19344
|
const num = BigInt(numSeats);
|
|
19052
19345
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
19053
19346
|
if (stakesSum < num) {
|
|
@@ -19076,7 +19369,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
|
|
|
19076
19369
|
if (minimumStakeRatio.length != 2) {
|
|
19077
19370
|
throw Error("minimumStakeRatio should have 2 elements");
|
|
19078
19371
|
}
|
|
19079
|
-
const stakes = validators.map((
|
|
19372
|
+
const stakes = validators.map((v12) => BigInt(v12.stake)).sort(sortBigIntAsc);
|
|
19080
19373
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
19081
19374
|
if (validators.length < maxNumberOfSeats) {
|
|
19082
19375
|
return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
|
|
@@ -19248,10 +19541,10 @@ var DER = {
|
|
|
19248
19541
|
if (length < 128)
|
|
19249
19542
|
throw new E("tlv.decode(long): not minimal encoding");
|
|
19250
19543
|
}
|
|
19251
|
-
const
|
|
19252
|
-
if (
|
|
19544
|
+
const v12 = data.subarray(pos, pos + length);
|
|
19545
|
+
if (v12.length !== length)
|
|
19253
19546
|
throw new E("tlv.decode: wrong value length");
|
|
19254
|
-
return { v:
|
|
19547
|
+
return { v: v12, l: data.subarray(pos + length) };
|
|
19255
19548
|
}
|
|
19256
19549
|
},
|
|
19257
19550
|
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
@@ -19819,9 +20112,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
19819
20112
|
extraEntropy: false
|
|
19820
20113
|
};
|
|
19821
20114
|
const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
|
|
19822
|
-
function isBiggerThanHalfOrder(
|
|
20115
|
+
function isBiggerThanHalfOrder(number6) {
|
|
19823
20116
|
const HALF = CURVE_ORDER >> _1n6;
|
|
19824
|
-
return
|
|
20117
|
+
return number6 > HALF;
|
|
19825
20118
|
}
|
|
19826
20119
|
function validateRS(title, num) {
|
|
19827
20120
|
if (!Fn.isValidNot0(num))
|
|
@@ -20004,8 +20297,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
20004
20297
|
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
20005
20298
|
if (R.is0())
|
|
20006
20299
|
return false;
|
|
20007
|
-
const
|
|
20008
|
-
return
|
|
20300
|
+
const v12 = Fn.create(R.x);
|
|
20301
|
+
return v12 === r;
|
|
20009
20302
|
} catch (e) {
|
|
20010
20303
|
return false;
|
|
20011
20304
|
}
|
|
@@ -22870,6 +23163,39 @@ var NearSpokeService = class {
|
|
|
22870
23163
|
}
|
|
22871
23164
|
return BigInt(bal);
|
|
22872
23165
|
}
|
|
23166
|
+
/**
|
|
23167
|
+
* Get the user's own wallet balance of a token on NEAR, in smallest units (yoctoNEAR for the
|
|
23168
|
+
* native coin). Native NEAR via the account's `viewAccount().amount`; NEP-141 tokens via the
|
|
23169
|
+
* token contract's `ft_balance_of` view. Reads the balance held by `srcAddress` (the user
|
|
23170
|
+
* wallet), not the protocol asset manager. Uses this service's own configured RPC provider.
|
|
23171
|
+
* @param {GetBalanceParams<NearChainKey>} params - The chain key, user address, and token.
|
|
23172
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
23173
|
+
*/
|
|
23174
|
+
async getWalletBalance(params) {
|
|
23175
|
+
if (isNativeToken(params.srcChainKey, params.token)) {
|
|
23176
|
+
const account = await this.rpcProvider.viewAccount({ accountId: params.srcAddress });
|
|
23177
|
+
return BigInt(account.amount);
|
|
23178
|
+
}
|
|
23179
|
+
const bal = await this.queryContract(params.token.address, "ft_balance_of", {
|
|
23180
|
+
account_id: params.srcAddress
|
|
23181
|
+
});
|
|
23182
|
+
if (typeof bal !== "string") {
|
|
23183
|
+
throw new Error("[NearSpokeService.getWalletBalance] Failed to get balance. Unexpected response type.");
|
|
23184
|
+
}
|
|
23185
|
+
return BigInt(bal);
|
|
23186
|
+
}
|
|
23187
|
+
/**
|
|
23188
|
+
* Get the user's own wallet balances of multiple tokens on NEAR, in smallest units. Fans out
|
|
23189
|
+
* over {@link getWalletBalance}, keyed by `token.address`.
|
|
23190
|
+
* @param {GetBalancesParams<NearChainKey>} params - The chain key, user address, and tokens.
|
|
23191
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
23192
|
+
*/
|
|
23193
|
+
async getWalletBalances(params) {
|
|
23194
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
23195
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
23196
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
23197
|
+
return collector.finish();
|
|
23198
|
+
}
|
|
22873
23199
|
/**
|
|
22874
23200
|
* Whether `accountId` is storage-registered on a NEP-141 `token` contract. NEP-141 requires an
|
|
22875
23201
|
* account to pay a one-time storage bond before it can receive (hold a balance of) the token, so
|
|
@@ -23660,7 +23986,9 @@ var SonicSpokeService = class {
|
|
|
23660
23986
|
if (params.raw === true) {
|
|
23661
23987
|
return rawTx;
|
|
23662
23988
|
}
|
|
23663
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
23989
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
23990
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
23991
|
+
});
|
|
23664
23992
|
}
|
|
23665
23993
|
static async createSwapIntent(params) {
|
|
23666
23994
|
const { createIntentParams, creatorHubWalletAddress, solverConfig: solverConfig2, fee, hubProvider } = params;
|
|
@@ -23710,7 +24038,9 @@ var SonicSpokeService = class {
|
|
|
23710
24038
|
return [rawTx, intent, feeAmount, txData.data];
|
|
23711
24039
|
}
|
|
23712
24040
|
return [
|
|
23713
|
-
await params.walletProvider.sendTransaction(rawTx
|
|
24041
|
+
await params.walletProvider.sendTransaction(rawTx, {
|
|
24042
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
24043
|
+
}),
|
|
23714
24044
|
intent,
|
|
23715
24045
|
feeAmount,
|
|
23716
24046
|
txData.data
|
|
@@ -23729,6 +24059,76 @@ var SonicSpokeService = class {
|
|
|
23729
24059
|
args: [params.token]
|
|
23730
24060
|
});
|
|
23731
24061
|
}
|
|
24062
|
+
/**
|
|
24063
|
+
* Get the user's own wallet balance of a token on the hub (Sonic) chain, in smallest units.
|
|
24064
|
+
* Native coin via `eth_getBalance`; erc20 via `balanceOf`.
|
|
24065
|
+
* @param {GetBalanceParams<SonicChainKey>} params - The chain key, user address, and token.
|
|
24066
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
24067
|
+
*/
|
|
24068
|
+
async getWalletBalance(params) {
|
|
24069
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
24070
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
24071
|
+
return this.publicClient.getBalance({ address: srcAddress });
|
|
24072
|
+
}
|
|
24073
|
+
const balance = await this.publicClient.readContract({
|
|
24074
|
+
address: token.address,
|
|
24075
|
+
abi: viem.erc20Abi,
|
|
24076
|
+
functionName: "balanceOf",
|
|
24077
|
+
args: [srcAddress]
|
|
24078
|
+
});
|
|
24079
|
+
return balance ?? 0n;
|
|
24080
|
+
}
|
|
24081
|
+
/**
|
|
24082
|
+
* Get the user's own wallet balances of multiple tokens on the hub (Sonic) chain, in smallest
|
|
24083
|
+
* units. Non-native tokens are batched via multicall3 when the chain supports it, otherwise
|
|
24084
|
+
* read in parallel.
|
|
24085
|
+
* @param {GetBalancesParams<SonicChainKey>} params - The chain key, user address, and tokens.
|
|
24086
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
24087
|
+
*/
|
|
24088
|
+
async getWalletBalances(params) {
|
|
24089
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
24090
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
24091
|
+
const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
24092
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
24093
|
+
await settleWalletBalances(
|
|
24094
|
+
collector,
|
|
24095
|
+
nativeTokens,
|
|
24096
|
+
(token) => this.getWalletBalance({ srcChainKey, srcAddress, token })
|
|
24097
|
+
);
|
|
24098
|
+
if (nonNativeTokens.length === 0) {
|
|
24099
|
+
return collector.finish();
|
|
24100
|
+
}
|
|
24101
|
+
if (getEvmViemChain(srcChainKey).contracts?.multicall3) {
|
|
24102
|
+
const results = await this.publicClient.multicall({
|
|
24103
|
+
contracts: nonNativeTokens.map((token) => ({
|
|
24104
|
+
abi: viem.erc20Abi,
|
|
24105
|
+
address: token.address,
|
|
24106
|
+
functionName: "balanceOf",
|
|
24107
|
+
args: [srcAddress]
|
|
24108
|
+
}))
|
|
24109
|
+
});
|
|
24110
|
+
nonNativeTokens.forEach((token, index) => {
|
|
24111
|
+
const result = results[index];
|
|
24112
|
+
if (result?.status === "success") {
|
|
24113
|
+
collector.ok(token.address, BigInt(result.result));
|
|
24114
|
+
} else {
|
|
24115
|
+
collector.fail(token.address, result?.error ?? new Error(`missing multicall result for ${token.address}`));
|
|
24116
|
+
}
|
|
24117
|
+
});
|
|
24118
|
+
return collector.finish();
|
|
24119
|
+
}
|
|
24120
|
+
await settleWalletBalances(
|
|
24121
|
+
collector,
|
|
24122
|
+
nonNativeTokens,
|
|
24123
|
+
(token) => this.publicClient.readContract({
|
|
24124
|
+
address: token.address,
|
|
24125
|
+
abi: viem.erc20Abi,
|
|
24126
|
+
functionName: "balanceOf",
|
|
24127
|
+
args: [srcAddress]
|
|
24128
|
+
})
|
|
24129
|
+
);
|
|
24130
|
+
return collector.finish();
|
|
24131
|
+
}
|
|
23732
24132
|
/**
|
|
23733
24133
|
* Execute a batch of contract calls through the Sonic wallet contract.
|
|
23734
24134
|
* @param {Hex} payload - The encoded payload containing the calls array
|
|
@@ -23771,7 +24171,9 @@ var SonicSpokeService = class {
|
|
|
23771
24171
|
if (params.raw === true) {
|
|
23772
24172
|
return rawTx;
|
|
23773
24173
|
}
|
|
23774
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
24174
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
24175
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
24176
|
+
});
|
|
23775
24177
|
}
|
|
23776
24178
|
};
|
|
23777
24179
|
async function toMystenTransaction(txn) {
|
|
@@ -23827,8 +24229,8 @@ var SuiGrpcTransport = class {
|
|
|
23827
24229
|
this.endpoint = endpoint;
|
|
23828
24230
|
this.client = new grpc.SuiGrpcClient({ network: "mainnet", baseUrl: endpoint });
|
|
23829
24231
|
}
|
|
23830
|
-
async getCoins(owner, coinType, limit = DEFAULT_GET_COINS_LIMIT) {
|
|
23831
|
-
const response = await this.client.core.listCoins({ owner, coinType, limit });
|
|
24232
|
+
async getCoins(owner, coinType, limit = DEFAULT_GET_COINS_LIMIT, cursor) {
|
|
24233
|
+
const response = await this.client.core.listCoins({ owner, coinType, limit, cursor: cursor ?? void 0 });
|
|
23832
24234
|
return toSuiPaginatedCoins(response, coinType);
|
|
23833
24235
|
}
|
|
23834
24236
|
async simulate(tx, sender) {
|
|
@@ -23856,16 +24258,16 @@ var SuiGrpcTransport = class {
|
|
|
23856
24258
|
return effects.gasUsed;
|
|
23857
24259
|
}
|
|
23858
24260
|
async fetchLatestPackageId(objectId) {
|
|
23859
|
-
let
|
|
24261
|
+
let object6;
|
|
23860
24262
|
try {
|
|
23861
|
-
({ object:
|
|
24263
|
+
({ object: object6 } = await this.client.core.getObject({ objectId, include: { json: true } }));
|
|
23862
24264
|
} catch (error) {
|
|
23863
24265
|
throw new Error("Failed to fetch asset manager id", { cause: error });
|
|
23864
24266
|
}
|
|
23865
|
-
if (!
|
|
24267
|
+
if (!object6) {
|
|
23866
24268
|
throw new Error("Asset manager id not found (no data)");
|
|
23867
24269
|
}
|
|
23868
|
-
const fields =
|
|
24270
|
+
const fields = object6.json;
|
|
23869
24271
|
if (!fields) {
|
|
23870
24272
|
throw new Error("Asset manager id not found (not a move object)");
|
|
23871
24273
|
}
|
|
@@ -24068,6 +24470,42 @@ var SuiSpokeService = class {
|
|
|
24068
24470
|
const str_u64 = bcs.bcs.U64.parse(Uint8Array.from(val));
|
|
24069
24471
|
return BigInt(str_u64);
|
|
24070
24472
|
}
|
|
24473
|
+
/**
|
|
24474
|
+
* Get the user's own wallet balance of a token on Sui, in smallest units. Unlike {@link getDeposit}
|
|
24475
|
+
* (which reads the protocol asset manager holding), this reads the balance held by `params.srcAddress`
|
|
24476
|
+
* itself. Native SUI is read via its canonical `0x2::sui::SUI` coin type; other coins use the token's
|
|
24477
|
+
* Sui coinType (`token.address`).
|
|
24478
|
+
* @param {GetBalanceParams<SuiChainKey>} params - The chain key, user address, and token.
|
|
24479
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
24480
|
+
*/
|
|
24481
|
+
async getWalletBalance(params) {
|
|
24482
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
24483
|
+
let coinType = isNativeToken(srcChainKey, token) ? "0x2::sui::SUI" : token.address;
|
|
24484
|
+
if (coinType === "0x03917a812fe4a6d6bc779c5ab53f8a80ba741f8af04121193fc44e0f662e2ceb::balanced_dollar::BALANCED_DOLLAR") {
|
|
24485
|
+
coinType = "0x3917a812fe4a6d6bc779c5ab53f8a80ba741f8af04121193fc44e0f662e2ceb::balanced_dollar::BALANCED_DOLLAR";
|
|
24486
|
+
}
|
|
24487
|
+
let total = 0n;
|
|
24488
|
+
let cursor;
|
|
24489
|
+
do {
|
|
24490
|
+
const page = await this.transport.getCoins(srcAddress, coinType, void 0, cursor);
|
|
24491
|
+
for (const coin of page.data) {
|
|
24492
|
+
total += BigInt(coin.balance);
|
|
24493
|
+
}
|
|
24494
|
+
cursor = page.hasNextPage ? page.nextCursor : void 0;
|
|
24495
|
+
} while (cursor);
|
|
24496
|
+
return total;
|
|
24497
|
+
}
|
|
24498
|
+
/**
|
|
24499
|
+
* Get the user's own wallet balances of multiple tokens on Sui, in smallest units.
|
|
24500
|
+
* @param {GetBalancesParams<SuiChainKey>} params - The chain key, user address, and tokens.
|
|
24501
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
24502
|
+
*/
|
|
24503
|
+
async getWalletBalances(params) {
|
|
24504
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
24505
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
24506
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
24507
|
+
return collector.finish();
|
|
24508
|
+
}
|
|
24071
24509
|
/**
|
|
24072
24510
|
* Fetch the asset manager config from the spoke chain.
|
|
24073
24511
|
* @param {SuiChainKey} chainId - The Sui chain key.
|
|
@@ -24214,6 +24652,11 @@ var CustomSorobanServer = class extends stellarSdk.rpc.Server {
|
|
|
24214
24652
|
return response.json().then((json) => json.result);
|
|
24215
24653
|
}
|
|
24216
24654
|
};
|
|
24655
|
+
var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
|
|
24656
|
+
function parseXlmBalanceToStroops(balanceStr) {
|
|
24657
|
+
const [whole = "0", frac = ""] = balanceStr.split(".");
|
|
24658
|
+
return BigInt(whole + frac.padEnd(7, "0").slice(0, 7));
|
|
24659
|
+
}
|
|
24217
24660
|
var CustomStellarAccount = class {
|
|
24218
24661
|
accountId;
|
|
24219
24662
|
sequenceNumber;
|
|
@@ -24252,7 +24695,7 @@ var CustomStellarAccount = class {
|
|
|
24252
24695
|
}
|
|
24253
24696
|
};
|
|
24254
24697
|
var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
|
|
24255
|
-
var StellarSpokeService = class {
|
|
24698
|
+
var StellarSpokeService = class _StellarSpokeService {
|
|
24256
24699
|
config;
|
|
24257
24700
|
chainConfig;
|
|
24258
24701
|
server;
|
|
@@ -24293,6 +24736,109 @@ var StellarSpokeService = class {
|
|
|
24293
24736
|
}
|
|
24294
24737
|
throw new Error("result undefined");
|
|
24295
24738
|
}
|
|
24739
|
+
/**
|
|
24740
|
+
* Get the user's own wallet balance of a token on Stellar, in smallest units. Native XLM returns
|
|
24741
|
+
* the spendable amount (total minus the minimum reserve and selling liabilities) via Horizon;
|
|
24742
|
+
* other assets return the Soroban token contract's `balance` for the user.
|
|
24743
|
+
* @param {GetBalanceParams<StellarChainKey>} params - The chain key, user address, and token.
|
|
24744
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
24745
|
+
*/
|
|
24746
|
+
async getWalletBalance(params) {
|
|
24747
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
24748
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
24749
|
+
return _StellarSpokeService.spendableXlmStroops(await this.server.loadAccount(srcAddress));
|
|
24750
|
+
}
|
|
24751
|
+
const [network, sourceAccount] = await Promise.all([
|
|
24752
|
+
this.sorobanServer.getNetwork(),
|
|
24753
|
+
this.sorobanServer.getAccount(srcAddress)
|
|
24754
|
+
]);
|
|
24755
|
+
return this.simulateTokenBalance(
|
|
24756
|
+
token.address,
|
|
24757
|
+
srcAddress,
|
|
24758
|
+
new CustomStellarAccount({ account_id: sourceAccount.accountId(), sequence: sourceAccount.sequenceNumber() }),
|
|
24759
|
+
network.passphrase
|
|
24760
|
+
);
|
|
24761
|
+
}
|
|
24762
|
+
/**
|
|
24763
|
+
* Spendable XLM in stroops: the account's native balance minus its minimum reserve and selling
|
|
24764
|
+
* liabilities. Reporting the raw balance would let a user try to spend reserves the network
|
|
24765
|
+
* refuses to release.
|
|
24766
|
+
*/
|
|
24767
|
+
static spendableXlmStroops(account) {
|
|
24768
|
+
const nativeBalance = account.balances.find(
|
|
24769
|
+
(balance) => balance.asset_type === "native"
|
|
24770
|
+
);
|
|
24771
|
+
if (!nativeBalance) {
|
|
24772
|
+
return 0n;
|
|
24773
|
+
}
|
|
24774
|
+
const rawStroops = parseXlmBalanceToStroops(nativeBalance.balance);
|
|
24775
|
+
const sellingLiabilitiesStroops = nativeBalance.selling_liabilities ? parseXlmBalanceToStroops(nativeBalance.selling_liabilities) : 0n;
|
|
24776
|
+
const reserveCount = Math.max(0, 2 + account.subentry_count + account.num_sponsoring - account.num_sponsored);
|
|
24777
|
+
const minStroops = BigInt(reserveCount) * STELLAR_BASE_RESERVE_STROOPS + sellingLiabilitiesStroops;
|
|
24778
|
+
return rawStroops > minStroops ? rawStroops - minStroops : 0n;
|
|
24779
|
+
}
|
|
24780
|
+
/**
|
|
24781
|
+
* Simulate a Soroban token `balance` call. Takes the network passphrase and source account so a
|
|
24782
|
+
* batch can fetch them once; `getAccountClone()` hands each builder its own `Account`, because
|
|
24783
|
+
* `TransactionBuilder.build()` increments the source's sequence number and concurrent builders
|
|
24784
|
+
* would otherwise interleave on a shared one.
|
|
24785
|
+
*/
|
|
24786
|
+
async simulateTokenBalance(tokenAddress, srcAddress, account, networkPassphrase) {
|
|
24787
|
+
const contract = new stellarSdk.Contract(tokenAddress);
|
|
24788
|
+
const tx = new stellarSdk.TransactionBuilder(account.getAccountClone(), { fee: this.baseFee, networkPassphrase }).addOperation(contract.call("balance", stellarSdk.nativeToScVal(srcAddress, { type: "address" }))).setTimeout(stellarSdk.TimeoutInfinite).build();
|
|
24789
|
+
const result = await this.sorobanServer.simulateTransaction(tx);
|
|
24790
|
+
if (!stellarSdk.rpc.Api.isSimulationSuccess(result)) {
|
|
24791
|
+
throw new Error("Failed to simulate transaction");
|
|
24792
|
+
}
|
|
24793
|
+
if (!result.result) {
|
|
24794
|
+
throw new Error("Failed to read token balance: simulation returned no result");
|
|
24795
|
+
}
|
|
24796
|
+
return stellarSdk.scValToBigInt(result.result.retval);
|
|
24797
|
+
}
|
|
24798
|
+
/**
|
|
24799
|
+
* Get the user's own wallet balances of multiple tokens on Stellar, in smallest units.
|
|
24800
|
+
*
|
|
24801
|
+
* The network passphrase and the source account are the same for every token, so they are
|
|
24802
|
+
* fetched once per batch instead of once per token — and only when a partition actually needs
|
|
24803
|
+
* them, so an all-native request issues no Soroban calls at all.
|
|
24804
|
+
* @param {GetBalancesParams<StellarChainKey>} params - The chain key, user address, and tokens.
|
|
24805
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
24806
|
+
*/
|
|
24807
|
+
async getWalletBalances(params) {
|
|
24808
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
24809
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
24810
|
+
const sorobanTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
24811
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
24812
|
+
if (nativeTokens.length > 0) {
|
|
24813
|
+
try {
|
|
24814
|
+
const spendable = _StellarSpokeService.spendableXlmStroops(await this.server.loadAccount(srcAddress));
|
|
24815
|
+
for (const token of nativeTokens) {
|
|
24816
|
+
collector.ok(token.address, spendable);
|
|
24817
|
+
}
|
|
24818
|
+
} catch (error) {
|
|
24819
|
+
for (const token of nativeTokens) {
|
|
24820
|
+
collector.fail(token.address, error);
|
|
24821
|
+
}
|
|
24822
|
+
}
|
|
24823
|
+
}
|
|
24824
|
+
if (sorobanTokens.length === 0) {
|
|
24825
|
+
return collector.finish();
|
|
24826
|
+
}
|
|
24827
|
+
const [network, sourceAccount] = await Promise.all([
|
|
24828
|
+
this.sorobanServer.getNetwork(),
|
|
24829
|
+
this.sorobanServer.getAccount(srcAddress)
|
|
24830
|
+
]);
|
|
24831
|
+
const account = new CustomStellarAccount({
|
|
24832
|
+
account_id: sourceAccount.accountId(),
|
|
24833
|
+
sequence: sourceAccount.sequenceNumber()
|
|
24834
|
+
});
|
|
24835
|
+
await settleWalletBalances(
|
|
24836
|
+
collector,
|
|
24837
|
+
sorobanTokens,
|
|
24838
|
+
(token) => this.simulateTokenBalance(token.address, srcAddress, account, network.passphrase)
|
|
24839
|
+
);
|
|
24840
|
+
return collector.finish();
|
|
24841
|
+
}
|
|
24296
24842
|
async buildPriorityStellarTransaction(account, network, operation) {
|
|
24297
24843
|
const simulationForFee = await this.sorobanServer.simulateTransaction(
|
|
24298
24844
|
new stellarSdk.TransactionBuilder(account.getAccountClone(), {
|
|
@@ -24866,6 +25412,48 @@ var SolanaSpokeService = class _SolanaSpokeService {
|
|
|
24866
25412
|
const tokenAccount = await _SolanaSpokeService.getTokenAccountBalance(this.connection, vaultToken.pda.toBase58());
|
|
24867
25413
|
return BigInt(tokenAccount.value.amount);
|
|
24868
25414
|
}
|
|
25415
|
+
/**
|
|
25416
|
+
* Get the user's own wallet balance of a token on Solana, in smallest units. Native SOL via
|
|
25417
|
+
* `getBalance`; SPL via the associated token account. The mint may belong to the legacy SPL
|
|
25418
|
+
* Token program or Token-2022 (e.g. xStock tokens), which derive different ATAs, so both
|
|
25419
|
+
* candidate ATAs are read in one call and the existing one is used.
|
|
25420
|
+
* @param {GetBalanceParams<SolanaChainKey>} params - The chain key, user address, and token.
|
|
25421
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
25422
|
+
*/
|
|
25423
|
+
async getWalletBalance(params) {
|
|
25424
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
25425
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
25426
|
+
return BigInt(await _SolanaSpokeService.getBalance(this.connection, srcAddress));
|
|
25427
|
+
}
|
|
25428
|
+
const owner = new web3_js.PublicKey(srcAddress);
|
|
25429
|
+
const mint = new web3_js.PublicKey(token.address);
|
|
25430
|
+
const candidates = [splToken.TOKEN_PROGRAM_ID, splToken.TOKEN_2022_PROGRAM_ID].map((programId) => ({
|
|
25431
|
+
programId,
|
|
25432
|
+
ata: splToken.getAssociatedTokenAddressSync(mint, owner, true, programId)
|
|
25433
|
+
}));
|
|
25434
|
+
const accounts = await this.connection.getMultipleAccountsInfo(candidates.map((c) => c.ata));
|
|
25435
|
+
let balance = 0n;
|
|
25436
|
+
for (const [i, candidate] of candidates.entries()) {
|
|
25437
|
+
const info = accounts[i];
|
|
25438
|
+
if (!info) continue;
|
|
25439
|
+
try {
|
|
25440
|
+
balance += splToken.unpackAccount(candidate.ata, info, candidate.programId).amount;
|
|
25441
|
+
} catch {
|
|
25442
|
+
}
|
|
25443
|
+
}
|
|
25444
|
+
return balance;
|
|
25445
|
+
}
|
|
25446
|
+
/**
|
|
25447
|
+
* Get the user's own wallet balances of multiple tokens on Solana, in smallest units.
|
|
25448
|
+
* @param {GetBalancesParams<SolanaChainKey>} params - The chain key, user address, and tokens.
|
|
25449
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
25450
|
+
*/
|
|
25451
|
+
async getWalletBalances(params) {
|
|
25452
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
25453
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
25454
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
25455
|
+
return collector.finish();
|
|
25456
|
+
}
|
|
24869
25457
|
/**
|
|
24870
25458
|
* Sends a message to the hub chain.
|
|
24871
25459
|
* @param dstChainKey - The chain key of the hub chain.
|
|
@@ -25087,8 +25675,84 @@ var IconSpokeService = class {
|
|
|
25087
25675
|
async getDeposit(params) {
|
|
25088
25676
|
const { token, srcChainKey } = params;
|
|
25089
25677
|
const transaction = new CallBuilder().to(token).method("balanceOf").params({ _owner: this.config.getChainConfig(srcChainKey).addresses.assetManager }).build();
|
|
25678
|
+
return this.readIrc2Balance(transaction);
|
|
25679
|
+
}
|
|
25680
|
+
/**
|
|
25681
|
+
* Read an int-returning SCORE call. `iconService.call(...)` registers no result converter, so
|
|
25682
|
+
* `execute()` resolves the raw JSON-RPC `result` — a bare hex string for an int, not `{ value }`.
|
|
25683
|
+
*/
|
|
25684
|
+
async readIrc2Balance(transaction) {
|
|
25090
25685
|
const result = await this.iconService.call(transaction).execute();
|
|
25091
|
-
|
|
25686
|
+
if (typeof result !== "string") {
|
|
25687
|
+
throw new Error(`[IconSpokeService] Unexpected balanceOf response: ${JSON.stringify(result)}`);
|
|
25688
|
+
}
|
|
25689
|
+
return hexToBigInt(result);
|
|
25690
|
+
}
|
|
25691
|
+
/**
|
|
25692
|
+
* Get the user's own wallet balance of a token on ICON, in smallest units. Native ICX is read
|
|
25693
|
+
* via `iconService.getBalance`; IRC-2 tokens via a `balanceOf(_owner)` call on the token contract.
|
|
25694
|
+
* @param {GetBalanceParams<IconChainKey>} params - The chain key, user address, and token.
|
|
25695
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
25696
|
+
*/
|
|
25697
|
+
async getWalletBalance(params) {
|
|
25698
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
25699
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
25700
|
+
const balance = await this.iconService.getBalance(srcAddress).execute();
|
|
25701
|
+
return BigInt(balance.toFixed());
|
|
25702
|
+
}
|
|
25703
|
+
const transaction = new CallBuilder().to(token.address).method("balanceOf").params({ _owner: srcAddress }).build();
|
|
25704
|
+
return this.readIrc2Balance(transaction);
|
|
25705
|
+
}
|
|
25706
|
+
/**
|
|
25707
|
+
* Get the user's own wallet balances of multiple tokens on ICON, in smallest units. Native ICX
|
|
25708
|
+
* is read via `iconService.getBalance`; IRC-2 balances are batched into a single `tryAggregate`
|
|
25709
|
+
* multicall so every `balanceOf(_owner)` read shares one round-trip.
|
|
25710
|
+
* @param {GetBalancesParams<IconChainKey>} params - The chain key, user address, and tokens.
|
|
25711
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
25712
|
+
*/
|
|
25713
|
+
async getWalletBalances(params) {
|
|
25714
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
25715
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
25716
|
+
const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
25717
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
25718
|
+
if (nativeTokens.length > 0) {
|
|
25719
|
+
try {
|
|
25720
|
+
const balance = await this.iconService.getBalance(srcAddress).execute();
|
|
25721
|
+
for (const token of nativeTokens) {
|
|
25722
|
+
collector.ok(token.address, BigInt(balance.toFixed()));
|
|
25723
|
+
}
|
|
25724
|
+
} catch (error) {
|
|
25725
|
+
for (const token of nativeTokens) {
|
|
25726
|
+
collector.fail(token.address, error);
|
|
25727
|
+
}
|
|
25728
|
+
}
|
|
25729
|
+
}
|
|
25730
|
+
if (nonNativeTokens.length === 0) {
|
|
25731
|
+
return collector.finish();
|
|
25732
|
+
}
|
|
25733
|
+
const multicallAddress = "cxa4aa9185e23558cff990f494c1fd2845f6cbf741";
|
|
25734
|
+
const calls = nonNativeTokens.map((token) => ({
|
|
25735
|
+
target: token.address,
|
|
25736
|
+
method: "balanceOf",
|
|
25737
|
+
params: [srcAddress]
|
|
25738
|
+
}));
|
|
25739
|
+
const transaction = new CallBuilder().to(multicallAddress).method("tryAggregate").params({ requireSuccess: Converter.toHex(0), calls }).build();
|
|
25740
|
+
const result = await this.iconService.call(transaction).execute();
|
|
25741
|
+
const aggregated = result.returnData;
|
|
25742
|
+
if (!Array.isArray(aggregated) || aggregated.length !== nonNativeTokens.length) {
|
|
25743
|
+
throw new Error(
|
|
25744
|
+
`[IconSpokeService] tryAggregate returned ${Array.isArray(aggregated) ? aggregated.length : "no"} entries for ${nonNativeTokens.length} tokens`
|
|
25745
|
+
);
|
|
25746
|
+
}
|
|
25747
|
+
nonNativeTokens.forEach((token, index) => {
|
|
25748
|
+
const agg = aggregated[index];
|
|
25749
|
+
if (agg && agg.success !== "0x0" && typeof agg.returnData === "string") {
|
|
25750
|
+
collector.ok(token.address, hexToBigInt(agg.returnData));
|
|
25751
|
+
} else {
|
|
25752
|
+
collector.fail(token.address, new Error(`balanceOf failed for ${token.address}: ${agg?.returnData}`));
|
|
25753
|
+
}
|
|
25754
|
+
});
|
|
25755
|
+
return collector.finish();
|
|
25092
25756
|
}
|
|
25093
25757
|
/**
|
|
25094
25758
|
* Sends a message to the hub chain.
|
|
@@ -25154,6 +25818,7 @@ var GAS_PRICE_REGEX = /^(\d+)(.*)$/;
|
|
|
25154
25818
|
var InjectiveSpokeService = class {
|
|
25155
25819
|
config;
|
|
25156
25820
|
chainGrpcWasmApi;
|
|
25821
|
+
indexerGrpcAccountPortfolioApi;
|
|
25157
25822
|
txClient;
|
|
25158
25823
|
endpoints;
|
|
25159
25824
|
pollingIntervalMs;
|
|
@@ -25163,6 +25828,7 @@ var InjectiveSpokeService = class {
|
|
|
25163
25828
|
this.config = config;
|
|
25164
25829
|
this.endpoints = networks.getNetworkEndpoints(networks.Network.Mainnet);
|
|
25165
25830
|
this.chainGrpcWasmApi = new sdkTs.ChainGrpcWasmApi(this.endpoints.grpc);
|
|
25831
|
+
this.indexerGrpcAccountPortfolioApi = new sdkTs.IndexerGrpcAccountPortfolioApi(this.endpoints.indexer);
|
|
25166
25832
|
this.txClient = new sdkTs.TxGrpcApi(this.endpoints.grpc);
|
|
25167
25833
|
this.pollingIntervalMs = this.config.sodaxConfig.chains[ChainKeys.INJECTIVE_MAINNET].pollingConfig.pollingIntervalMs;
|
|
25168
25834
|
this.maxTimeoutMs = this.config.sodaxConfig.chains[ChainKeys.INJECTIVE_MAINNET].pollingConfig.maxTimeoutMs;
|
|
@@ -25246,6 +25912,37 @@ var InjectiveSpokeService = class {
|
|
|
25246
25912
|
);
|
|
25247
25913
|
return BigInt(sdkTs.fromBase64(response.data));
|
|
25248
25914
|
}
|
|
25915
|
+
/**
|
|
25916
|
+
* Get the user's own wallet balance of a token on Injective, in smallest units. On Injective every
|
|
25917
|
+
* asset is a bank coin, so the native coin (`inj`) and factory/peggy/IBC tokens are all read from the
|
|
25918
|
+
* account's portfolio bank balances and matched by denom. The denom is the chain's native denom for
|
|
25919
|
+
* the native coin and `params.token.address` for standard tokens.
|
|
25920
|
+
* @param {GetBalanceParams<InjectiveChainKey>} params - The chain key, user address, and token.
|
|
25921
|
+
* @returns {Promise<bigint>} The token balance in smallest units, or 0n when the account holds none.
|
|
25922
|
+
*/
|
|
25923
|
+
async getWalletBalance(params) {
|
|
25924
|
+
const denom = isNativeToken(params.srcChainKey, params.token) ? this.config.getChainConfig(params.srcChainKey).nativeToken : params.token.address;
|
|
25925
|
+
const portfolio = await this.indexerGrpcAccountPortfolioApi.fetchAccountPortfolioBalances(params.srcAddress);
|
|
25926
|
+
const balance = portfolio.bankBalancesList.find((_balance) => _balance.denom === denom);
|
|
25927
|
+
return balance ? BigInt(balance.amount) : 0n;
|
|
25928
|
+
}
|
|
25929
|
+
/**
|
|
25930
|
+
* Get the user's own wallet balances of multiple tokens on Injective, in smallest units.
|
|
25931
|
+
* @param {GetBalancesParams<InjectiveChainKey>} params - The chain key, user address, and tokens.
|
|
25932
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
25933
|
+
*/
|
|
25934
|
+
async getWalletBalances(params) {
|
|
25935
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
25936
|
+
const portfolio = await this.indexerGrpcAccountPortfolioApi.fetchAccountPortfolioBalances(srcAddress);
|
|
25937
|
+
const amountByDenom = new Map(portfolio.bankBalancesList.map((balance) => [balance.denom, BigInt(balance.amount)]));
|
|
25938
|
+
const nativeDenom = this.config.getChainConfig(srcChainKey).nativeToken;
|
|
25939
|
+
const balances = {};
|
|
25940
|
+
for (const token of tokens) {
|
|
25941
|
+
const denom = isNativeToken(srcChainKey, token) ? nativeDenom : token.address;
|
|
25942
|
+
balances[token.address] = amountByDenom.get(denom) ?? 0n;
|
|
25943
|
+
}
|
|
25944
|
+
return balances;
|
|
25945
|
+
}
|
|
25249
25946
|
async getRawTransaction(chainId, senderAddress, contractAddress, msg, memo, funds = []) {
|
|
25250
25947
|
const msgExec = sdkTs.MsgExecuteContract.fromJSON({
|
|
25251
25948
|
contractAddress,
|
|
@@ -25627,7 +26324,9 @@ var SpokeService = class _SpokeService {
|
|
|
25627
26324
|
from: params.owner,
|
|
25628
26325
|
spender: params.spender,
|
|
25629
26326
|
raw: false,
|
|
25630
|
-
walletProvider
|
|
26327
|
+
walletProvider,
|
|
26328
|
+
// Covers the reset leg too — an approval must not broadcast on the wrong EVM network.
|
|
26329
|
+
expectedChainId: getEvmViemChain(params.srcChainKey).id
|
|
25631
26330
|
});
|
|
25632
26331
|
if (plan.resetAmount !== void 0) {
|
|
25633
26332
|
const resetHash = await sendApprove(plan.resetAmount);
|
|
@@ -25834,7 +26533,8 @@ var SpokeService = class _SpokeService {
|
|
|
25834
26533
|
return this.sui.encodeSimulationParams(token, assetManager);
|
|
25835
26534
|
default:
|
|
25836
26535
|
return {
|
|
25837
|
-
|
|
26536
|
+
// Token identifiers on BITCOIN/NEAR/INJECTIVE are not addresses — recipient validation stays on the address leg only.
|
|
26537
|
+
encodedToken: encodeTokenIdentifier(srcChainKey, token),
|
|
25838
26538
|
encodedSrcAddress: encodeAddress(srcChainKey, assetManager)
|
|
25839
26539
|
};
|
|
25840
26540
|
}
|
|
@@ -26053,6 +26753,138 @@ var SpokeService = class _SpokeService {
|
|
|
26053
26753
|
return { ok: false, error };
|
|
26054
26754
|
}
|
|
26055
26755
|
}
|
|
26756
|
+
/**
|
|
26757
|
+
* Get a user's own wallet balance of a single token on a spoke chain, in smallest units.
|
|
26758
|
+
* Chain-agnostic: dispatches to the per-chain service, which reads the native coin or the
|
|
26759
|
+
* chain's token standard (EVM erc20, Solana SPL, …). Unlike {@link getDeposit}, this reads
|
|
26760
|
+
* `srcAddress` itself, not the protocol asset manager.
|
|
26761
|
+
* @param {GetBalanceParams<C>} params - The chain key, user address, and token.
|
|
26762
|
+
* @returns {Promise<Result<bigint>>} The token balance in smallest units.
|
|
26763
|
+
*/
|
|
26764
|
+
async getWalletBalance(params) {
|
|
26765
|
+
try {
|
|
26766
|
+
if (isHubChainKeyType(params.srcChainKey)) {
|
|
26767
|
+
const value = await this.sonic.getWalletBalance(params);
|
|
26768
|
+
return { ok: true, value };
|
|
26769
|
+
}
|
|
26770
|
+
const chainType = getChainType(params.srcChainKey);
|
|
26771
|
+
switch (chainType) {
|
|
26772
|
+
case "EVM": {
|
|
26773
|
+
const value = await this.evm.getWalletBalance(params);
|
|
26774
|
+
return { ok: true, value };
|
|
26775
|
+
}
|
|
26776
|
+
case "INJECTIVE": {
|
|
26777
|
+
const value = await this.injective.getWalletBalance(params);
|
|
26778
|
+
return { ok: true, value };
|
|
26779
|
+
}
|
|
26780
|
+
case "STELLAR": {
|
|
26781
|
+
const value = await this.stellar.getWalletBalance(params);
|
|
26782
|
+
return { ok: true, value };
|
|
26783
|
+
}
|
|
26784
|
+
case "SUI": {
|
|
26785
|
+
const value = await this.sui.getWalletBalance(params);
|
|
26786
|
+
return { ok: true, value };
|
|
26787
|
+
}
|
|
26788
|
+
case "ICON": {
|
|
26789
|
+
const value = await this.icon.getWalletBalance(params);
|
|
26790
|
+
return { ok: true, value };
|
|
26791
|
+
}
|
|
26792
|
+
case "SOLANA": {
|
|
26793
|
+
const value = await this.solana.getWalletBalance(params);
|
|
26794
|
+
return { ok: true, value };
|
|
26795
|
+
}
|
|
26796
|
+
case "STACKS": {
|
|
26797
|
+
const value = await this.stacks.getWalletBalance(params);
|
|
26798
|
+
return { ok: true, value };
|
|
26799
|
+
}
|
|
26800
|
+
case "BITCOIN": {
|
|
26801
|
+
const value = await this.bitcoin.getWalletBalance(params);
|
|
26802
|
+
return { ok: true, value };
|
|
26803
|
+
}
|
|
26804
|
+
case "NEAR": {
|
|
26805
|
+
const value = await this.near.getWalletBalance(params);
|
|
26806
|
+
return { ok: true, value };
|
|
26807
|
+
}
|
|
26808
|
+
default: {
|
|
26809
|
+
const exhaustiveCheck = chainType;
|
|
26810
|
+
this.config.logger.debug("Unhandled exhaustive case", { value: exhaustiveCheck });
|
|
26811
|
+
return {
|
|
26812
|
+
ok: false,
|
|
26813
|
+
error: new Error(`[getWalletBalance] Invalid chain type. Valid chain types: ${ChainTypeArr.join(", ")}`)
|
|
26814
|
+
};
|
|
26815
|
+
}
|
|
26816
|
+
}
|
|
26817
|
+
} catch (error) {
|
|
26818
|
+
return { ok: false, error };
|
|
26819
|
+
}
|
|
26820
|
+
}
|
|
26821
|
+
/**
|
|
26822
|
+
* Get a user's own wallet balances of multiple tokens on a spoke chain, in smallest units.
|
|
26823
|
+
* Chain-agnostic sibling of {@link getWalletBalance}; per-chain services batch the reads where the
|
|
26824
|
+
* chain supports it (e.g. EVM multicall3, ICON aggregated call data).
|
|
26825
|
+
* @param {GetBalancesParams<C>} params - The chain key, user address, and tokens.
|
|
26826
|
+
* @returns {Promise<Result<WalletBalanceMap>>} A map of token address to balance in smallest
|
|
26827
|
+
* units. A token that could not be read is logged and reported as `0n`; the `Result` fails when
|
|
26828
|
+
* the whole batch is unusable — invalid chain, a shared round-trip every token depends on, or a
|
|
26829
|
+
* batch in which no token could be read at all.
|
|
26830
|
+
*/
|
|
26831
|
+
async getWalletBalances(params) {
|
|
26832
|
+
try {
|
|
26833
|
+
if (isHubChainKeyType(params.srcChainKey)) {
|
|
26834
|
+
const value = await this.sonic.getWalletBalances(params);
|
|
26835
|
+
return { ok: true, value };
|
|
26836
|
+
}
|
|
26837
|
+
const chainType = getChainType(params.srcChainKey);
|
|
26838
|
+
switch (chainType) {
|
|
26839
|
+
case "EVM": {
|
|
26840
|
+
const value = await this.evm.getWalletBalances(params);
|
|
26841
|
+
return { ok: true, value };
|
|
26842
|
+
}
|
|
26843
|
+
case "INJECTIVE": {
|
|
26844
|
+
const value = await this.injective.getWalletBalances(params);
|
|
26845
|
+
return { ok: true, value };
|
|
26846
|
+
}
|
|
26847
|
+
case "STELLAR": {
|
|
26848
|
+
const value = await this.stellar.getWalletBalances(params);
|
|
26849
|
+
return { ok: true, value };
|
|
26850
|
+
}
|
|
26851
|
+
case "SUI": {
|
|
26852
|
+
const value = await this.sui.getWalletBalances(params);
|
|
26853
|
+
return { ok: true, value };
|
|
26854
|
+
}
|
|
26855
|
+
case "ICON": {
|
|
26856
|
+
const value = await this.icon.getWalletBalances(params);
|
|
26857
|
+
return { ok: true, value };
|
|
26858
|
+
}
|
|
26859
|
+
case "SOLANA": {
|
|
26860
|
+
const value = await this.solana.getWalletBalances(params);
|
|
26861
|
+
return { ok: true, value };
|
|
26862
|
+
}
|
|
26863
|
+
case "STACKS": {
|
|
26864
|
+
const value = await this.stacks.getWalletBalances(params);
|
|
26865
|
+
return { ok: true, value };
|
|
26866
|
+
}
|
|
26867
|
+
case "BITCOIN": {
|
|
26868
|
+
const value = await this.bitcoin.getWalletBalances(params);
|
|
26869
|
+
return { ok: true, value };
|
|
26870
|
+
}
|
|
26871
|
+
case "NEAR": {
|
|
26872
|
+
const value = await this.near.getWalletBalances(params);
|
|
26873
|
+
return { ok: true, value };
|
|
26874
|
+
}
|
|
26875
|
+
default: {
|
|
26876
|
+
const exhaustiveCheck = chainType;
|
|
26877
|
+
this.config.logger.debug("Unhandled exhaustive case", { value: exhaustiveCheck });
|
|
26878
|
+
return {
|
|
26879
|
+
ok: false,
|
|
26880
|
+
error: new Error(`[getWalletBalances] Invalid chain type. Valid chain types: ${ChainTypeArr.join(", ")}`)
|
|
26881
|
+
};
|
|
26882
|
+
}
|
|
26883
|
+
}
|
|
26884
|
+
} catch (error) {
|
|
26885
|
+
return { ok: false, error };
|
|
26886
|
+
}
|
|
26887
|
+
}
|
|
26056
26888
|
/**
|
|
26057
26889
|
* Calls the connection contract on the spoke chain to send a message to the hub wallet, which then executes the message's payload.
|
|
26058
26890
|
* @param {HubAddress} from - The address of the user on the hub chain.
|
|
@@ -26329,6 +27161,7 @@ var SpokeService = class _SpokeService {
|
|
|
26329
27161
|
}
|
|
26330
27162
|
}
|
|
26331
27163
|
};
|
|
27164
|
+
var HUB_CHAIN_ID = getEvmViemChain(ChainKeys.SONIC_MAINNET).id;
|
|
26332
27165
|
var Erc4626Service = class {
|
|
26333
27166
|
constructor() {
|
|
26334
27167
|
}
|
|
@@ -26507,7 +27340,7 @@ var Erc4626Service = class {
|
|
|
26507
27340
|
if (raw) {
|
|
26508
27341
|
return rawTx;
|
|
26509
27342
|
}
|
|
26510
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27343
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26511
27344
|
}
|
|
26512
27345
|
/**
|
|
26513
27346
|
* Get the maximum amount of shares that can be minted
|
|
@@ -26584,7 +27417,7 @@ var Erc4626Service = class {
|
|
|
26584
27417
|
if (raw) {
|
|
26585
27418
|
return rawTx;
|
|
26586
27419
|
}
|
|
26587
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27420
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26588
27421
|
}
|
|
26589
27422
|
/**
|
|
26590
27423
|
* Get the maximum amount of assets that can be withdrawn
|
|
@@ -26662,7 +27495,7 @@ var Erc4626Service = class {
|
|
|
26662
27495
|
if (raw) {
|
|
26663
27496
|
return rawTx;
|
|
26664
27497
|
}
|
|
26665
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27498
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26666
27499
|
}
|
|
26667
27500
|
/**
|
|
26668
27501
|
* Get the maximum amount of shares that can be redeemed
|
|
@@ -26740,7 +27573,7 @@ var Erc4626Service = class {
|
|
|
26740
27573
|
if (raw) {
|
|
26741
27574
|
return rawTx;
|
|
26742
27575
|
}
|
|
26743
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27576
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26744
27577
|
}
|
|
26745
27578
|
/**
|
|
26746
27579
|
* Encodes a deposit transaction for a vault.
|
|
@@ -26817,6 +27650,7 @@ var Erc4626Service = class {
|
|
|
26817
27650
|
};
|
|
26818
27651
|
}
|
|
26819
27652
|
};
|
|
27653
|
+
var HUB_CHAIN_ID2 = getEvmViemChain(ChainKeys.SONIC_MAINNET).id;
|
|
26820
27654
|
var Permit2Service = class _Permit2Service {
|
|
26821
27655
|
constructor() {
|
|
26822
27656
|
}
|
|
@@ -26905,7 +27739,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26905
27739
|
if (raw) {
|
|
26906
27740
|
return rawTx;
|
|
26907
27741
|
}
|
|
26908
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27742
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26909
27743
|
}
|
|
26910
27744
|
/**
|
|
26911
27745
|
* Execute a permit for a single token
|
|
@@ -26930,7 +27764,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26930
27764
|
if (raw) {
|
|
26931
27765
|
return rawTx;
|
|
26932
27766
|
}
|
|
26933
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27767
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26934
27768
|
}
|
|
26935
27769
|
/**
|
|
26936
27770
|
* Execute a permit for multiple tokens
|
|
@@ -26955,7 +27789,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26955
27789
|
if (raw) {
|
|
26956
27790
|
return rawTx;
|
|
26957
27791
|
}
|
|
26958
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27792
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26959
27793
|
}
|
|
26960
27794
|
/**
|
|
26961
27795
|
* Transfer tokens from one address to another using Permit2
|
|
@@ -26981,7 +27815,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26981
27815
|
if (raw) {
|
|
26982
27816
|
return rawTx;
|
|
26983
27817
|
}
|
|
26984
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27818
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26985
27819
|
}
|
|
26986
27820
|
/**
|
|
26987
27821
|
* Transfer multiple tokens in a batch using Permit2
|
|
@@ -27004,7 +27838,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
27004
27838
|
if (raw) {
|
|
27005
27839
|
return rawTx;
|
|
27006
27840
|
}
|
|
27007
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27841
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
27008
27842
|
}
|
|
27009
27843
|
/**
|
|
27010
27844
|
* Lockdown approvals to prevent malicious usage
|
|
@@ -27027,7 +27861,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
27027
27861
|
if (raw) {
|
|
27028
27862
|
return rawTx;
|
|
27029
27863
|
}
|
|
27030
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27864
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
27031
27865
|
}
|
|
27032
27866
|
/**
|
|
27033
27867
|
* Invalidate nonces to prevent replay attacks
|
|
@@ -27052,7 +27886,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
27052
27886
|
if (raw) {
|
|
27053
27887
|
return rawTx;
|
|
27054
27888
|
}
|
|
27055
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27889
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
27056
27890
|
}
|
|
27057
27891
|
/**
|
|
27058
27892
|
* Encodes an approve transaction for Permit2.
|
|
@@ -27894,9 +28728,38 @@ var TokensByChainMapSchema = v__namespace.custom(
|
|
|
27894
28728
|
);
|
|
27895
28729
|
var TokensListSchema = v__namespace.array(XTokenSchema);
|
|
27896
28730
|
var ReserveAssetsSchema = v__namespace.array(AddressSchema);
|
|
28731
|
+
var ORACLE_CANDLE_INTERVALS = ["1m", "5m", "1h", "1d"];
|
|
28732
|
+
var OracleCandleIntervalSchema = v__namespace.picklist(ORACLE_CANDLE_INTERVALS);
|
|
28733
|
+
var OracleMarketsResponseSchema = v__namespace.object({
|
|
28734
|
+
quote: v__namespace.string(),
|
|
28735
|
+
intervals: v__namespace.array(
|
|
28736
|
+
v__namespace.object({
|
|
28737
|
+
key: v__namespace.string(),
|
|
28738
|
+
label: v__namespace.string(),
|
|
28739
|
+
seconds: v__namespace.number()
|
|
28740
|
+
})
|
|
28741
|
+
),
|
|
28742
|
+
symbols: v__namespace.array(v__namespace.string())
|
|
28743
|
+
});
|
|
28744
|
+
var OracleCandlesResponseSchema = v__namespace.object({
|
|
28745
|
+
symbol: v__namespace.string(),
|
|
28746
|
+
quote: v__namespace.string(),
|
|
28747
|
+
interval: OracleCandleIntervalSchema,
|
|
28748
|
+
candles: v__namespace.array(
|
|
28749
|
+
v__namespace.object({
|
|
28750
|
+
timestamp: v__namespace.number(),
|
|
28751
|
+
open: v__namespace.string(),
|
|
28752
|
+
high: v__namespace.string(),
|
|
28753
|
+
low: v__namespace.string(),
|
|
28754
|
+
close: v__namespace.string(),
|
|
28755
|
+
final: v__namespace.optional(v__namespace.boolean())
|
|
28756
|
+
})
|
|
28757
|
+
)
|
|
28758
|
+
});
|
|
27897
28759
|
|
|
27898
28760
|
// src/backendApi/guards.ts
|
|
27899
28761
|
var isFillEvent = (value) => v__namespace.is(FillEventSchema, value);
|
|
28762
|
+
var isOracleCandleInterval = (value) => v__namespace.is(OracleCandleIntervalSchema, value);
|
|
27900
28763
|
function decodePacketIntentTarget(payload) {
|
|
27901
28764
|
try {
|
|
27902
28765
|
const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
|
|
@@ -30281,7 +31144,9 @@ var BalnSwapService = class {
|
|
|
30281
31144
|
if (walletProviderSlot.raw) {
|
|
30282
31145
|
return tx;
|
|
30283
31146
|
}
|
|
30284
|
-
return walletProviderSlot.walletProvider.sendTransaction(tx
|
|
31147
|
+
return walletProviderSlot.walletProvider.sendTransaction(tx, {
|
|
31148
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
31149
|
+
});
|
|
30285
31150
|
}
|
|
30286
31151
|
};
|
|
30287
31152
|
|
|
@@ -31420,6 +32285,9 @@ function resolveSponsoringApiConfig(layers) {
|
|
|
31420
32285
|
function resolveBridgeApiConfig(layers) {
|
|
31421
32286
|
return resolveSharedApiConfig(layers);
|
|
31422
32287
|
}
|
|
32288
|
+
function resolveLeverageYieldApiConfig(layers) {
|
|
32289
|
+
return resolveSharedApiConfig(layers);
|
|
32290
|
+
}
|
|
31423
32291
|
var SwapsApiService = class _SwapsApiService {
|
|
31424
32292
|
// Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
|
|
31425
32293
|
// `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
|
|
@@ -32145,6 +33013,623 @@ var BridgeApiService = class {
|
|
|
32145
33013
|
return this.config.timeout;
|
|
32146
33014
|
}
|
|
32147
33015
|
};
|
|
33016
|
+
var LsdSourceSchema = v__namespace.object({
|
|
33017
|
+
poolId: v__namespace.string(),
|
|
33018
|
+
fallbackAprPct: v__namespace.number(),
|
|
33019
|
+
label: v__namespace.string()
|
|
33020
|
+
});
|
|
33021
|
+
var LeverageVaultSchema = v__namespace.object({
|
|
33022
|
+
name: v__namespace.string(),
|
|
33023
|
+
vault: v__namespace.string(),
|
|
33024
|
+
asset: v__namespace.string(),
|
|
33025
|
+
borrowToken: v__namespace.string(),
|
|
33026
|
+
lsdSource: v__namespace.optional(LsdSourceSchema)
|
|
33027
|
+
});
|
|
33028
|
+
var GetLeverageVaultsResponseSchema = v__namespace.array(LeverageVaultSchema);
|
|
33029
|
+
var GetLeverageVaultResponseSchema = LeverageVaultSchema;
|
|
33030
|
+
var VaultAssetResponseSchema = v__namespace.object({
|
|
33031
|
+
asset: v__namespace.string()
|
|
33032
|
+
});
|
|
33033
|
+
var LeverageYieldPositionSchema = v__namespace.object({
|
|
33034
|
+
collateral: v__namespace.string(),
|
|
33035
|
+
debt: v__namespace.string(),
|
|
33036
|
+
ltv: v__namespace.string(),
|
|
33037
|
+
healthFactor: v__namespace.string(),
|
|
33038
|
+
idleAsset: v__namespace.string()
|
|
33039
|
+
});
|
|
33040
|
+
var LeverageYieldAprSchema = v__namespace.object({
|
|
33041
|
+
supplyAprRay: v__namespace.string(),
|
|
33042
|
+
borrowAprRay: v__namespace.string(),
|
|
33043
|
+
targetLtvBps: v__namespace.string(),
|
|
33044
|
+
leverageMultiplierWad: v__namespace.string(),
|
|
33045
|
+
netAprRay: v__namespace.string()
|
|
33046
|
+
});
|
|
33047
|
+
var LeverageYieldLsdAprSchema = v__namespace.object({
|
|
33048
|
+
aprRay: v__namespace.string(),
|
|
33049
|
+
label: v__namespace.string(),
|
|
33050
|
+
stale: v__namespace.boolean()
|
|
33051
|
+
});
|
|
33052
|
+
var LeverageYieldEffectiveAprSchema = v__namespace.object({
|
|
33053
|
+
supplyAprRay: v__namespace.string(),
|
|
33054
|
+
borrowAprRay: v__namespace.string(),
|
|
33055
|
+
targetLtvBps: v__namespace.string(),
|
|
33056
|
+
leverageMultiplierWad: v__namespace.string(),
|
|
33057
|
+
netAprRay: v__namespace.string(),
|
|
33058
|
+
lsdApr: LeverageYieldLsdAprSchema,
|
|
33059
|
+
effectiveSupplyAprRay: v__namespace.string(),
|
|
33060
|
+
effectiveNetAprRay: v__namespace.string()
|
|
33061
|
+
});
|
|
33062
|
+
var VaultTotalAssetsResponseSchema = v__namespace.object({
|
|
33063
|
+
totalAssets: v__namespace.string()
|
|
33064
|
+
});
|
|
33065
|
+
var PreviewDepositResponseSchema = v__namespace.object({
|
|
33066
|
+
shares: v__namespace.string()
|
|
33067
|
+
});
|
|
33068
|
+
var PreviewWithdrawResponseSchema = v__namespace.object({
|
|
33069
|
+
shares: v__namespace.string()
|
|
33070
|
+
});
|
|
33071
|
+
var PreviewRedeemResponseSchema = v__namespace.object({
|
|
33072
|
+
assets: v__namespace.string()
|
|
33073
|
+
});
|
|
33074
|
+
var ShareBalanceResponseSchema = v__namespace.object({
|
|
33075
|
+
balance: v__namespace.string()
|
|
33076
|
+
});
|
|
33077
|
+
var MaxWithdrawResponseSchema = v__namespace.object({
|
|
33078
|
+
maxWithdraw: v__namespace.string()
|
|
33079
|
+
});
|
|
33080
|
+
|
|
33081
|
+
// src/backendApi/LeverageYieldApiService.ts
|
|
33082
|
+
var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
33083
|
+
// Fully-resolved API config supplied by the caller (BackendApiService resolves the ApiConfig
|
|
33084
|
+
// union via `resolveBaseApiConfig`); leverage-yield endpoints are sub-paths under the base URL.
|
|
33085
|
+
config;
|
|
33086
|
+
headers;
|
|
33087
|
+
logger;
|
|
33088
|
+
/** See {@link LeverageYieldApiServiceOptions.trimLegacyOverrides}. */
|
|
33089
|
+
trimsLegacyOverrides;
|
|
33090
|
+
constructor(config, logger = consoleLogger, options = {}) {
|
|
33091
|
+
this.config = config;
|
|
33092
|
+
this.headers = { ...config.headers };
|
|
33093
|
+
this.logger = logger;
|
|
33094
|
+
this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
|
|
33095
|
+
}
|
|
33096
|
+
/**
|
|
33097
|
+
* Issues a single HTTP request, validates the JSON body against `schema`, and wraps the
|
|
33098
|
+
* result in `Result<T>`. Mirrors `SwapsApiService.request`; every public method delegates here.
|
|
33099
|
+
*/
|
|
33100
|
+
async request(endpoint, config, schema, overrideConfig) {
|
|
33101
|
+
try {
|
|
33102
|
+
const raw = await makeRequest({
|
|
33103
|
+
endpoint,
|
|
33104
|
+
config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
|
|
33105
|
+
// Normalized like a configured base URL: the override is the gateway root, so a legacy
|
|
33106
|
+
// `/be`-suffixed value must not nest `/leverage-yield/*` under the data API's mount — unless the
|
|
33107
|
+
// config opted out of the legacy trim, in which case the per-call value is left as given.
|
|
33108
|
+
overrideConfig: this.trimsLegacyOverrides ? normalizeOverrideBaseURL(overrideConfig) : overrideConfig,
|
|
33109
|
+
logger: this.logger,
|
|
33110
|
+
serviceLabel: "LeverageYieldApiService"
|
|
33111
|
+
});
|
|
33112
|
+
const parsed = v__namespace.safeParse(schema, raw);
|
|
33113
|
+
if (!parsed.success) {
|
|
33114
|
+
return {
|
|
33115
|
+
ok: false,
|
|
33116
|
+
error: toInvalidResponseShapeError({
|
|
33117
|
+
api: "leverageYield",
|
|
33118
|
+
feature: "backend",
|
|
33119
|
+
endpoint,
|
|
33120
|
+
issues: v__namespace.flatten(parsed.issues)
|
|
33121
|
+
})
|
|
33122
|
+
};
|
|
33123
|
+
}
|
|
33124
|
+
return { ok: true, value: parsed.output };
|
|
33125
|
+
} catch (error) {
|
|
33126
|
+
return { ok: false, error: toExternalApiError({ api: "leverageYield", feature: "backend", endpoint, error }) };
|
|
33127
|
+
}
|
|
33128
|
+
}
|
|
33129
|
+
/**
|
|
33130
|
+
* Drop the SDK-only display field `feeAmount` before an intent reaches the strict wire serializer.
|
|
33131
|
+
* `sodax.leverageYield.createVaultIntent` returns `Intent & FeeAmount`, which is structurally
|
|
33132
|
+
* assignable to the wire `IntentRequestV2` and so gets passed straight into the intent-carrying
|
|
33133
|
+
* endpoints; the lenient JSON serializer would send the extra bigint wholesale. Mirrors
|
|
33134
|
+
* `SwapsApiService.toWireIntent`; a no-op for an already-clean `IntentRequestV2`.
|
|
33135
|
+
*/
|
|
33136
|
+
static toWireIntent(intent) {
|
|
33137
|
+
const { feeAmount: _feeAmount, ...rest } = intent;
|
|
33138
|
+
return rest;
|
|
33139
|
+
}
|
|
33140
|
+
/** Append `params` to `base` as a query string, returning `base` unchanged when `params` is empty. */
|
|
33141
|
+
withQuery(base2, params) {
|
|
33142
|
+
const queryString = new URLSearchParams(params).toString();
|
|
33143
|
+
return queryString.length > 0 ? `${base2}?${queryString}` : base2;
|
|
33144
|
+
}
|
|
33145
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33146
|
+
// Vault registry
|
|
33147
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33148
|
+
/**
|
|
33149
|
+
* Fetch the registry of deployed leverage-yield vaults.
|
|
33150
|
+
*
|
|
33151
|
+
* @returns `Result<GetLeverageVaultsResponseV2>` — array of vault descriptors.
|
|
33152
|
+
*/
|
|
33153
|
+
async getVaults(config) {
|
|
33154
|
+
return this.request("/leverage-yield/vaults", { method: "GET" }, GetLeverageVaultsResponseSchema, config);
|
|
33155
|
+
}
|
|
33156
|
+
/**
|
|
33157
|
+
* Fetch a single vault descriptor by its lsoda* share-token name (e.g. `lsodaWEETH`).
|
|
33158
|
+
*
|
|
33159
|
+
* @returns `Result<GetLeverageVaultResponseV2>` — the vault descriptor.
|
|
33160
|
+
*/
|
|
33161
|
+
async getVault(name, config) {
|
|
33162
|
+
return this.request(
|
|
33163
|
+
`/leverage-yield/vaults/${name}`,
|
|
33164
|
+
{ method: "GET" },
|
|
33165
|
+
GetLeverageVaultResponseSchema,
|
|
33166
|
+
config
|
|
33167
|
+
);
|
|
33168
|
+
}
|
|
33169
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33170
|
+
// Vault reads
|
|
33171
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33172
|
+
/**
|
|
33173
|
+
* Get the vault's underlying hub asset (Sodax vault-token wrapper).
|
|
33174
|
+
*
|
|
33175
|
+
* @returns `Result<VaultAssetResponseV2>` — `{ asset }`.
|
|
33176
|
+
*/
|
|
33177
|
+
async getAsset(query, config) {
|
|
33178
|
+
return this.request(
|
|
33179
|
+
this.withQuery("/leverage-yield/asset", { vault: query.vault }),
|
|
33180
|
+
{ method: "GET" },
|
|
33181
|
+
VaultAssetResponseSchema,
|
|
33182
|
+
config
|
|
33183
|
+
);
|
|
33184
|
+
}
|
|
33185
|
+
/**
|
|
33186
|
+
* Get a leveraged-position snapshot for the vault.
|
|
33187
|
+
*
|
|
33188
|
+
* @returns `Result<LeverageYieldPositionV2>` — `{ collateral, debt, ltv, healthFactor, idleAsset }` (decimal strings).
|
|
33189
|
+
*/
|
|
33190
|
+
async getPosition(query, config) {
|
|
33191
|
+
return this.request(
|
|
33192
|
+
this.withQuery("/leverage-yield/position", { vault: query.vault }),
|
|
33193
|
+
{ method: "GET" },
|
|
33194
|
+
LeverageYieldPositionSchema,
|
|
33195
|
+
config
|
|
33196
|
+
);
|
|
33197
|
+
}
|
|
33198
|
+
/**
|
|
33199
|
+
* Get the AAVE-only steady-state APR for the vault (goes negative when the LSD yield is the alpha).
|
|
33200
|
+
*
|
|
33201
|
+
* @returns `Result<LeverageYieldAprV2>` — RAY-denominated rates as decimal strings.
|
|
33202
|
+
*/
|
|
33203
|
+
async getApr(query, config) {
|
|
33204
|
+
return this.request(
|
|
33205
|
+
this.withQuery("/leverage-yield/apr", { vault: query.vault }),
|
|
33206
|
+
{ method: "GET" },
|
|
33207
|
+
LeverageYieldAprSchema,
|
|
33208
|
+
config
|
|
33209
|
+
);
|
|
33210
|
+
}
|
|
33211
|
+
/**
|
|
33212
|
+
* Get the honest combined AAVE + LSD effective APR for the vault.
|
|
33213
|
+
*
|
|
33214
|
+
* @returns `Result<LeverageYieldEffectiveAprV2>` — includes `effectiveNetAprRay` (the headline number).
|
|
33215
|
+
*/
|
|
33216
|
+
async getEffectiveApr(query, config) {
|
|
33217
|
+
return this.request(
|
|
33218
|
+
this.withQuery("/leverage-yield/apr/effective", { vault: query.vault }),
|
|
33219
|
+
{ method: "GET" },
|
|
33220
|
+
LeverageYieldEffectiveAprSchema,
|
|
33221
|
+
config
|
|
33222
|
+
);
|
|
33223
|
+
}
|
|
33224
|
+
/**
|
|
33225
|
+
* Get the off-chain LSD staking-APR snapshot for the vault's underlying asset.
|
|
33226
|
+
*
|
|
33227
|
+
* @returns `Result<LeverageYieldLsdAprV2>` — `{ aprRay, label, stale }`.
|
|
33228
|
+
*/
|
|
33229
|
+
async getLsdApr(query, config) {
|
|
33230
|
+
return this.request(
|
|
33231
|
+
this.withQuery("/leverage-yield/apr/lsd", { vault: query.vault }),
|
|
33232
|
+
{ method: "GET" },
|
|
33233
|
+
LeverageYieldLsdAprSchema,
|
|
33234
|
+
config
|
|
33235
|
+
);
|
|
33236
|
+
}
|
|
33237
|
+
/**
|
|
33238
|
+
* Get the total assets managed by the vault.
|
|
33239
|
+
*
|
|
33240
|
+
* @returns `Result<VaultTotalAssetsResponseV2>` — `{ totalAssets }` (decimal string).
|
|
33241
|
+
*/
|
|
33242
|
+
async getTotalAssets(query, config) {
|
|
33243
|
+
return this.request(
|
|
33244
|
+
this.withQuery("/leverage-yield/total-assets", { vault: query.vault }),
|
|
33245
|
+
{ method: "GET" },
|
|
33246
|
+
VaultTotalAssetsResponseSchema,
|
|
33247
|
+
config
|
|
33248
|
+
);
|
|
33249
|
+
}
|
|
33250
|
+
/**
|
|
33251
|
+
* Preview the shares minted for depositing `assets` into the vault (ERC-4626 `previewDeposit`).
|
|
33252
|
+
*
|
|
33253
|
+
* @returns `Result<PreviewDepositResponseV2>` — `{ shares }` (decimal string).
|
|
33254
|
+
*/
|
|
33255
|
+
async previewDeposit(query, config) {
|
|
33256
|
+
return this.request(
|
|
33257
|
+
this.withQuery("/leverage-yield/preview/deposit", { vault: query.vault, assets: query.assets }),
|
|
33258
|
+
{ method: "GET" },
|
|
33259
|
+
PreviewDepositResponseSchema,
|
|
33260
|
+
config
|
|
33261
|
+
);
|
|
33262
|
+
}
|
|
33263
|
+
/**
|
|
33264
|
+
* Preview the shares burned to withdraw `assets` from the vault (ERC-4626 `previewWithdraw`).
|
|
33265
|
+
*
|
|
33266
|
+
* @returns `Result<PreviewWithdrawResponseV2>` — `{ shares }` (decimal string).
|
|
33267
|
+
*/
|
|
33268
|
+
async previewWithdraw(query, config) {
|
|
33269
|
+
return this.request(
|
|
33270
|
+
this.withQuery("/leverage-yield/preview/withdraw", { vault: query.vault, assets: query.assets }),
|
|
33271
|
+
{ method: "GET" },
|
|
33272
|
+
PreviewWithdrawResponseSchema,
|
|
33273
|
+
config
|
|
33274
|
+
);
|
|
33275
|
+
}
|
|
33276
|
+
/**
|
|
33277
|
+
* Preview the assets returned for redeeming `shares` from the vault (ERC-4626 `previewRedeem`).
|
|
33278
|
+
*
|
|
33279
|
+
* @returns `Result<PreviewRedeemResponseV2>` — `{ assets }` (decimal string).
|
|
33280
|
+
*/
|
|
33281
|
+
async previewRedeem(query, config) {
|
|
33282
|
+
return this.request(
|
|
33283
|
+
this.withQuery("/leverage-yield/preview/redeem", { vault: query.vault, shares: query.shares }),
|
|
33284
|
+
{ method: "GET" },
|
|
33285
|
+
PreviewRedeemResponseSchema,
|
|
33286
|
+
config
|
|
33287
|
+
);
|
|
33288
|
+
}
|
|
33289
|
+
/**
|
|
33290
|
+
* Get an owner's vault share (lsoda*) balance.
|
|
33291
|
+
*
|
|
33292
|
+
* @returns `Result<ShareBalanceResponseV2>` — `{ balance }` (decimal string).
|
|
33293
|
+
*/
|
|
33294
|
+
async getShareBalance(query, config) {
|
|
33295
|
+
return this.request(
|
|
33296
|
+
this.withQuery("/leverage-yield/share-balance", { vault: query.vault, owner: query.owner }),
|
|
33297
|
+
{ method: "GET" },
|
|
33298
|
+
ShareBalanceResponseSchema,
|
|
33299
|
+
config
|
|
33300
|
+
);
|
|
33301
|
+
}
|
|
33302
|
+
/**
|
|
33303
|
+
* Get an owner's RAW ERC-4626 `maxWithdraw` — NOT dust-trimmed, unlike the SDK-local
|
|
33304
|
+
* `sodax.leverageYield.getMaxWithdrawForUser`. Apply a margin before using it as a withdraw amount.
|
|
33305
|
+
*
|
|
33306
|
+
* @returns `Result<MaxWithdrawResponseV2>` — `{ maxWithdraw }` (decimal string).
|
|
33307
|
+
*/
|
|
33308
|
+
async getMaxWithdraw(query, config) {
|
|
33309
|
+
return this.request(
|
|
33310
|
+
this.withQuery("/leverage-yield/max-withdraw", { vault: query.vault, owner: query.owner }),
|
|
33311
|
+
{ method: "GET" },
|
|
33312
|
+
MaxWithdrawResponseSchema,
|
|
33313
|
+
config
|
|
33314
|
+
);
|
|
33315
|
+
}
|
|
33316
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33317
|
+
// Quote · deadline
|
|
33318
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33319
|
+
/**
|
|
33320
|
+
* Quote a swap-style deposit: any solver-supported `tokenSrc` → the vault's lsoda* shares.
|
|
33321
|
+
* Pass `query.includeTxData = true` to also build the unsigned create-intent tx (`srcAddress`
|
|
33322
|
+
* required in the body then).
|
|
33323
|
+
*
|
|
33324
|
+
* @returns `Result<QuoteResponseV2>` — `quotedAmount` (shares) and optional `txData`.
|
|
33325
|
+
*/
|
|
33326
|
+
async getDepositQuote(body, query, config) {
|
|
33327
|
+
const endpoint = query?.includeTxData ? "/leverage-yield/quote/deposit?includeTxData=true" : "/leverage-yield/quote/deposit";
|
|
33328
|
+
const txSchema = swapsApi.rawTxSchemaForChainKey(body.tokenSrcChainKey);
|
|
33329
|
+
return this.request(
|
|
33330
|
+
endpoint,
|
|
33331
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33332
|
+
swapsApi.makeQuoteResponseSchema(txSchema),
|
|
33333
|
+
config
|
|
33334
|
+
);
|
|
33335
|
+
}
|
|
33336
|
+
/**
|
|
33337
|
+
* Quote a swap-style withdraw: the vault's lsoda* shares → any solver-supported `tokenDst`.
|
|
33338
|
+
* Pass `query.includeTxData = true` to also build the unsigned tx (signed on `srcChainKey`;
|
|
33339
|
+
* `srcAddress`/`dstAddress` required in the body then).
|
|
33340
|
+
*
|
|
33341
|
+
* @returns `Result<QuoteResponseV2>` — `quotedAmount` (output token) and optional `txData`.
|
|
33342
|
+
*/
|
|
33343
|
+
async getWithdrawQuote(body, query, config) {
|
|
33344
|
+
const endpoint = query?.includeTxData ? "/leverage-yield/quote/withdraw?includeTxData=true" : "/leverage-yield/quote/withdraw";
|
|
33345
|
+
const txSchema = swapsApi.rawTxSchemaForChainKey(body.srcChainKey);
|
|
33346
|
+
return this.request(
|
|
33347
|
+
endpoint,
|
|
33348
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33349
|
+
swapsApi.makeQuoteResponseSchema(txSchema),
|
|
33350
|
+
config
|
|
33351
|
+
);
|
|
33352
|
+
}
|
|
33353
|
+
/**
|
|
33354
|
+
* Compute a deposit/withdraw deadline (hub timestamp + `offsetSeconds`, default 300s).
|
|
33355
|
+
*
|
|
33356
|
+
* @returns `Result<DeadlineResponseV2>` — unix-seconds deadline (decimal string).
|
|
33357
|
+
*/
|
|
33358
|
+
async getDeadline(query, config) {
|
|
33359
|
+
const params = {};
|
|
33360
|
+
if (query?.offsetSeconds !== void 0) params.offsetSeconds = String(query.offsetSeconds);
|
|
33361
|
+
return this.request(
|
|
33362
|
+
this.withQuery("/leverage-yield/deadline", params),
|
|
33363
|
+
{ method: "GET" },
|
|
33364
|
+
swapsApi.DeadlineResponseSchema,
|
|
33365
|
+
config
|
|
33366
|
+
);
|
|
33367
|
+
}
|
|
33368
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33369
|
+
// Deposit allowance · approve · create intent (deposit / withdraw)
|
|
33370
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33371
|
+
/**
|
|
33372
|
+
* Check whether the deposit input-token allowance is already sufficient for the intent.
|
|
33373
|
+
* (Withdraw needs no spoke allowance — it spends lsoda* from the hub wallet.)
|
|
33374
|
+
*
|
|
33375
|
+
* @returns `Result<AllowanceCheckResponseV2>` — `{ valid }`.
|
|
33376
|
+
*/
|
|
33377
|
+
async checkAllowance(body, config) {
|
|
33378
|
+
return this.request(
|
|
33379
|
+
"/leverage-yield/allowance/check",
|
|
33380
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33381
|
+
swapsApi.AllowanceCheckResponseSchema,
|
|
33382
|
+
config
|
|
33383
|
+
);
|
|
33384
|
+
}
|
|
33385
|
+
/**
|
|
33386
|
+
* Build an unsigned token-approval transaction for the deposit input token.
|
|
33387
|
+
*
|
|
33388
|
+
* @returns `Result<ApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
|
|
33389
|
+
*/
|
|
33390
|
+
async approve(body, config) {
|
|
33391
|
+
const txSchema = swapsApi.rawTxSchemaForChainKey(body.srcChainKey);
|
|
33392
|
+
return this.request(
|
|
33393
|
+
"/leverage-yield/approve",
|
|
33394
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33395
|
+
swapsApi.makeApproveResponseSchema(txSchema),
|
|
33396
|
+
config
|
|
33397
|
+
);
|
|
33398
|
+
}
|
|
33399
|
+
/**
|
|
33400
|
+
* Build an unsigned deposit create-intent transaction (any token → lsoda* shares).
|
|
33401
|
+
*
|
|
33402
|
+
* @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
|
|
33403
|
+
*/
|
|
33404
|
+
async createDepositIntent(body, config) {
|
|
33405
|
+
const txSchema = swapsApi.rawTxSchemaForChainKey(body.srcChainKey);
|
|
33406
|
+
return this.request(
|
|
33407
|
+
"/leverage-yield/intents/deposit",
|
|
33408
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33409
|
+
swapsApi.makeCreateIntentResponseSchema(txSchema),
|
|
33410
|
+
config
|
|
33411
|
+
);
|
|
33412
|
+
}
|
|
33413
|
+
/**
|
|
33414
|
+
* Build an unsigned withdraw create-intent transaction (lsoda* shares → any token). The backend
|
|
33415
|
+
* sets `hubWalletSwap` internally so the swap spends the lsoda* held in the user's hub wallet.
|
|
33416
|
+
*
|
|
33417
|
+
* @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
|
|
33418
|
+
*/
|
|
33419
|
+
async createWithdrawIntent(body, config) {
|
|
33420
|
+
const txSchema = swapsApi.rawTxSchemaForChainKey(body.srcChainKey);
|
|
33421
|
+
return this.request(
|
|
33422
|
+
"/leverage-yield/intents/withdraw",
|
|
33423
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33424
|
+
swapsApi.makeCreateIntentResponseSchema(txSchema),
|
|
33425
|
+
config
|
|
33426
|
+
);
|
|
33427
|
+
}
|
|
33428
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33429
|
+
// Intent lifecycle: submit · status · cancel · hash · packet · extra-data
|
|
33430
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33431
|
+
/**
|
|
33432
|
+
* Submit the broadcast intent tx to the relay.
|
|
33433
|
+
*
|
|
33434
|
+
* @returns `Result<SubmitIntentResponseV2>` — `{ result }` (opaque relay response).
|
|
33435
|
+
*/
|
|
33436
|
+
async submitIntent(body, config) {
|
|
33437
|
+
return this.request(
|
|
33438
|
+
"/leverage-yield/intents/submit",
|
|
33439
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33440
|
+
swapsApi.SubmitIntentResponseSchema,
|
|
33441
|
+
config
|
|
33442
|
+
);
|
|
33443
|
+
}
|
|
33444
|
+
/**
|
|
33445
|
+
* Poll the solver for intent execution status.
|
|
33446
|
+
*
|
|
33447
|
+
* @returns `Result<StatusResponseV2>` — `{ status, fillTxHash? }`.
|
|
33448
|
+
*/
|
|
33449
|
+
async getStatus(body, config) {
|
|
33450
|
+
return this.request(
|
|
33451
|
+
"/leverage-yield/intents/status",
|
|
33452
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33453
|
+
swapsApi.StatusResponseSchema,
|
|
33454
|
+
config
|
|
33455
|
+
);
|
|
33456
|
+
}
|
|
33457
|
+
/**
|
|
33458
|
+
* Build an unsigned cancel-intent transaction. The `intent` field carries `bigint` numerics —
|
|
33459
|
+
* {@link toJsonBody} serializes them to decimal strings.
|
|
33460
|
+
*
|
|
33461
|
+
* @returns `Result<CancelIntentResponseV2>` — `{ tx }`.
|
|
33462
|
+
*/
|
|
33463
|
+
async cancelIntent(body, config) {
|
|
33464
|
+
const txSchema = swapsApi.rawTxSchemaForChainKey(body.srcChainKey);
|
|
33465
|
+
return this.request(
|
|
33466
|
+
"/leverage-yield/intents/cancel",
|
|
33467
|
+
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
33468
|
+
swapsApi.makeCancelIntentResponseSchema(txSchema),
|
|
33469
|
+
config
|
|
33470
|
+
);
|
|
33471
|
+
}
|
|
33472
|
+
/**
|
|
33473
|
+
* Compute the keccak256 hash of an Intent struct. The `intent` field carries `bigint` numerics.
|
|
33474
|
+
*
|
|
33475
|
+
* @returns `Result<IntentHashResponseV2>` — `{ hash }`.
|
|
33476
|
+
*/
|
|
33477
|
+
async getIntentHash(body, config) {
|
|
33478
|
+
return this.request(
|
|
33479
|
+
"/leverage-yield/intents/hash",
|
|
33480
|
+
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
33481
|
+
swapsApi.IntentHashResponseSchema,
|
|
33482
|
+
config
|
|
33483
|
+
);
|
|
33484
|
+
}
|
|
33485
|
+
/**
|
|
33486
|
+
* Long-poll the relayer until the fill packet lands on the destination chain.
|
|
33487
|
+
*
|
|
33488
|
+
* @returns `Result<IntentPacketResponseV2>` — delivered packet data.
|
|
33489
|
+
*/
|
|
33490
|
+
async getSolvedIntentPacket(body, config) {
|
|
33491
|
+
return this.request(
|
|
33492
|
+
"/leverage-yield/intents/packet",
|
|
33493
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33494
|
+
swapsApi.IntentPacketResponseSchema,
|
|
33495
|
+
config
|
|
33496
|
+
);
|
|
33497
|
+
}
|
|
33498
|
+
/**
|
|
33499
|
+
* Recover the relay extra data needed by `/leverage-yield/intents/submit`. Provide EITHER
|
|
33500
|
+
* `txHash` OR `intent` (whose `bigint` numerics {@link toJsonBody} serializes).
|
|
33501
|
+
*
|
|
33502
|
+
* @returns `Result<IntentExtraDataResponseV2>` — `{ address, payload }`.
|
|
33503
|
+
*/
|
|
33504
|
+
async getIntentSubmitTxExtraData(body, config) {
|
|
33505
|
+
const normalized = body.intent ? { ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) } : body;
|
|
33506
|
+
return this.request(
|
|
33507
|
+
"/leverage-yield/intents/extra-data",
|
|
33508
|
+
{ method: "POST", body: toJsonBody(normalized) },
|
|
33509
|
+
swapsApi.RelayExtraDataResponseSchema,
|
|
33510
|
+
config
|
|
33511
|
+
);
|
|
33512
|
+
}
|
|
33513
|
+
/**
|
|
33514
|
+
* Get the on-chain fill state for an intent by its hub-chain tx hash.
|
|
33515
|
+
*
|
|
33516
|
+
* @returns `Result<IntentStateV2>` — `{ exists, remainingInput, receivedOutput, pendingPayment }`.
|
|
33517
|
+
*/
|
|
33518
|
+
async getFilledIntent(txHash, config) {
|
|
33519
|
+
return this.request(
|
|
33520
|
+
`/leverage-yield/intents/${txHash}/fill`,
|
|
33521
|
+
{ method: "GET" },
|
|
33522
|
+
swapsApi.IntentStateSchema,
|
|
33523
|
+
config
|
|
33524
|
+
);
|
|
33525
|
+
}
|
|
33526
|
+
/**
|
|
33527
|
+
* Look up an Intent struct by its hub-chain creation tx hash.
|
|
33528
|
+
*
|
|
33529
|
+
* @returns `Result<GetIntentResponseV2>` — the decoded intent (bigint fields as decimal strings).
|
|
33530
|
+
*/
|
|
33531
|
+
async getIntent(txHash, config) {
|
|
33532
|
+
return this.request(`/leverage-yield/intents/${txHash}`, { method: "GET" }, swapsApi.IntentResponseSchema, config);
|
|
33533
|
+
}
|
|
33534
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33535
|
+
// Gas · fees
|
|
33536
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33537
|
+
/**
|
|
33538
|
+
* Estimate gas for a raw transaction on a spoke chain.
|
|
33539
|
+
*
|
|
33540
|
+
* @returns `Result<GasEstimateResponseV2>` — `{ gas }` (chain-specific shape).
|
|
33541
|
+
*/
|
|
33542
|
+
async estimateGas(body, config) {
|
|
33543
|
+
return this.request(
|
|
33544
|
+
"/leverage-yield/gas/estimate",
|
|
33545
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33546
|
+
swapsApi.GasEstimateResponseSchema,
|
|
33547
|
+
config
|
|
33548
|
+
);
|
|
33549
|
+
}
|
|
33550
|
+
/**
|
|
33551
|
+
* Compute the partner fee for a given input amount.
|
|
33552
|
+
*
|
|
33553
|
+
* @returns `Result<FeeResponseV2>` — `{ fee }` (decimal string).
|
|
33554
|
+
*/
|
|
33555
|
+
async getPartnerFee(query, config) {
|
|
33556
|
+
return this.request(
|
|
33557
|
+
this.withQuery("/leverage-yield/fees/partner", { amount: query.amount }),
|
|
33558
|
+
{ method: "GET" },
|
|
33559
|
+
swapsApi.FeeResponseSchema,
|
|
33560
|
+
config
|
|
33561
|
+
);
|
|
33562
|
+
}
|
|
33563
|
+
/**
|
|
33564
|
+
* Compute the protocol (solver) fee for a given input amount.
|
|
33565
|
+
*
|
|
33566
|
+
* @returns `Result<FeeResponseV2>` — `{ fee }` (decimal string).
|
|
33567
|
+
*/
|
|
33568
|
+
async getSolverFee(query, config) {
|
|
33569
|
+
return this.request(
|
|
33570
|
+
this.withQuery("/leverage-yield/fees/solver", { amount: query.amount }),
|
|
33571
|
+
{ method: "GET" },
|
|
33572
|
+
swapsApi.FeeResponseSchema,
|
|
33573
|
+
config
|
|
33574
|
+
);
|
|
33575
|
+
}
|
|
33576
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33577
|
+
// Submit-tx state machine
|
|
33578
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33579
|
+
/**
|
|
33580
|
+
* Submit a vault-swap transaction to be processed (relay, post-execution, etc.). The `intent`
|
|
33581
|
+
* field carries `bigint` numerics — {@link toJsonBody} serializes them. Idempotent on
|
|
33582
|
+
* `(txHash, srcChainKey)`.
|
|
33583
|
+
*
|
|
33584
|
+
* @returns `Result<SubmitTxResponseV2>` — `{ success, data: { status, message } }`.
|
|
33585
|
+
*/
|
|
33586
|
+
async submitTx(body, config) {
|
|
33587
|
+
return this.request(
|
|
33588
|
+
"/leverage-yield/submit-tx",
|
|
33589
|
+
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
33590
|
+
swapsApi.SubmitTxResponseSchema,
|
|
33591
|
+
config
|
|
33592
|
+
);
|
|
33593
|
+
}
|
|
33594
|
+
/**
|
|
33595
|
+
* Get the processing status of a submitted vault-swap transaction by `(txHash, srcChainKey)`.
|
|
33596
|
+
*
|
|
33597
|
+
* @returns `Result<SubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
|
|
33598
|
+
*/
|
|
33599
|
+
async getSubmitTxStatus(query, config) {
|
|
33600
|
+
return this.request(
|
|
33601
|
+
this.withQuery("/leverage-yield/submit-tx/status", { txHash: query.txHash, srcChainKey: query.srcChainKey }),
|
|
33602
|
+
{ method: "GET" },
|
|
33603
|
+
swapsApi.SubmitTxStatusResponseSchema,
|
|
33604
|
+
config
|
|
33605
|
+
);
|
|
33606
|
+
}
|
|
33607
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33608
|
+
// Utilities (parity with SwapsApiService)
|
|
33609
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33610
|
+
/**
|
|
33611
|
+
* Merge additional headers into the service's default header set. Existing keys are
|
|
33612
|
+
* overwritten; keys absent from `headers` are preserved.
|
|
33613
|
+
*/
|
|
33614
|
+
setHeaders(headers) {
|
|
33615
|
+
assignHeaders(this.headers, headers);
|
|
33616
|
+
}
|
|
33617
|
+
/** Return the base URL the service is currently pointing at. */
|
|
33618
|
+
getBaseURL() {
|
|
33619
|
+
return this.config.baseURL;
|
|
33620
|
+
}
|
|
33621
|
+
/**
|
|
33622
|
+
* Return the effective per-request timeout (ms).
|
|
33623
|
+
*
|
|
33624
|
+
* Callers bounding a request tighter than this need it as the CEILING, because a
|
|
33625
|
+
* `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it: an override
|
|
33626
|
+
* derived from a caller budget alone would raise the bound whenever that budget is the larger of the
|
|
33627
|
+
* two. `SubmitTxAttempt.requestTimeout` clamps against both (`min(budget left in the attempt, this)`).
|
|
33628
|
+
*/
|
|
33629
|
+
getTimeout() {
|
|
33630
|
+
return this.config.timeout;
|
|
33631
|
+
}
|
|
33632
|
+
};
|
|
32148
33633
|
|
|
32149
33634
|
// src/backendApi/BackendApiService.ts
|
|
32150
33635
|
var BackendApiService = class {
|
|
@@ -32152,6 +33637,7 @@ var BackendApiService = class {
|
|
|
32152
33637
|
swaps;
|
|
32153
33638
|
sponsoring;
|
|
32154
33639
|
bridge;
|
|
33640
|
+
leverageYield;
|
|
32155
33641
|
// resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on
|
|
32156
33642
|
// top. `baseURL` is the gateway root; `basePath` is this service's own mount below it.
|
|
32157
33643
|
config;
|
|
@@ -32180,6 +33666,7 @@ var BackendApiService = class {
|
|
|
32180
33666
|
const swapsConfig2 = resolveSwapsApiConfig(config);
|
|
32181
33667
|
const sponsoringConfig = resolveSponsoringApiConfig(config);
|
|
32182
33668
|
const bridgeConfig2 = resolveBridgeApiConfig(config);
|
|
33669
|
+
const leverageYieldConfig2 = resolveLeverageYieldApiConfig(config);
|
|
32183
33670
|
const shortRoots = [
|
|
32184
33671
|
["backendApi", this.config.baseURL],
|
|
32185
33672
|
["api.swaps", swapsConfig2.baseURL],
|
|
@@ -32204,6 +33691,11 @@ var BackendApiService = class {
|
|
|
32204
33691
|
inheritedApiKeyBaseURLs: [DEFAULT_SPONSORING_API_ENDPOINT, this.config.baseURL]
|
|
32205
33692
|
});
|
|
32206
33693
|
this.bridge = new BridgeApiService(withApiKey(bridgeConfig2, options.apiKey), this.logger, overrideOptions);
|
|
33694
|
+
this.leverageYield = new LeverageYieldApiService(
|
|
33695
|
+
withApiKey(leverageYieldConfig2, options.apiKey),
|
|
33696
|
+
this.logger,
|
|
33697
|
+
overrideOptions
|
|
33698
|
+
);
|
|
32207
33699
|
}
|
|
32208
33700
|
/**
|
|
32209
33701
|
* Issue the HTTP call for a route.
|
|
@@ -32429,6 +33921,46 @@ var BackendApiService = class {
|
|
|
32429
33921
|
const endpoint = `/moneymarket/borrowers?${queryString}`;
|
|
32430
33922
|
return this.request(endpoint, { ...config, method: "GET" }, MoneyMarketBorrowersSchema);
|
|
32431
33923
|
}
|
|
33924
|
+
// Oracle endpoints
|
|
33925
|
+
/**
|
|
33926
|
+
* Fetch the oracle candle store's discovery payload: the quote currency (currently always
|
|
33927
|
+
* `"USD"`), the selectable candle intervals, and the canonical symbols that have candle data.
|
|
33928
|
+
*
|
|
33929
|
+
* Use this to populate a symbol picker and interval switcher before calling
|
|
33930
|
+
* {@link getOracleCandles}.
|
|
33931
|
+
*
|
|
33932
|
+
* @returns `Result<OracleMarketsResponse>` — on success, `{ quote, intervals, symbols }`.
|
|
33933
|
+
*/
|
|
33934
|
+
async getOracleMarkets(config) {
|
|
33935
|
+
return this.request("/oracle/markets", { ...config, method: "GET" }, OracleMarketsResponseSchema);
|
|
33936
|
+
}
|
|
33937
|
+
/**
|
|
33938
|
+
* Fetch USD OHLC candles for a symbol over the half-open time range `[from, to)`.
|
|
33939
|
+
*
|
|
33940
|
+
* `from` and `to` are UNIX **seconds** (integers); `to` is exclusive and must exceed `from`,
|
|
33941
|
+
* and the range may cover at most 5000 buckets of the requested interval (invalid or wider
|
|
33942
|
+
* ranges fail with HTTP 400). A valid range with no stored candles resolves `ok` with
|
|
33943
|
+
* `candles: []`; an unknown symbol currently does the same rather than returning 404. The last
|
|
33944
|
+
* candle may still be forming; re-poll while its `final === false`.
|
|
33945
|
+
* Responses are cached server-side for roughly 10 seconds per distinct URL.
|
|
33946
|
+
*
|
|
33947
|
+
* @param params.symbol - Canonical symbol, exact case, from {@link getOracleMarkets} (e.g. `"ETH"`).
|
|
33948
|
+
* @param params.interval - Candle bucket size: `'1m' | '5m' | '1h' | '1d'`.
|
|
33949
|
+
* @param params.from - Range start, UNIX seconds, inclusive.
|
|
33950
|
+
* @param params.to - Range end, UNIX seconds, exclusive.
|
|
33951
|
+
* @returns `Result<OracleCandlesResponse>` — on success, the echoed query dimensions and
|
|
33952
|
+
* oldest-first candles with USD decimal-string prices (no volume field).
|
|
33953
|
+
*/
|
|
33954
|
+
async getOracleCandles(params, config) {
|
|
33955
|
+
const queryParams = new URLSearchParams();
|
|
33956
|
+
queryParams.append("symbol", params.symbol);
|
|
33957
|
+
queryParams.append("interval", params.interval);
|
|
33958
|
+
queryParams.append("from", String(params.from));
|
|
33959
|
+
queryParams.append("to", String(params.to));
|
|
33960
|
+
const queryString = queryParams.toString();
|
|
33961
|
+
const endpoint = `/oracle/candles?${queryString}`;
|
|
33962
|
+
return this.request(endpoint, { ...config, method: "GET" }, OracleCandlesResponseSchema);
|
|
33963
|
+
}
|
|
32432
33964
|
/**
|
|
32433
33965
|
* Fetch the complete SODAX runtime configuration in a single request.
|
|
32434
33966
|
*
|
|
@@ -32567,15 +34099,17 @@ var BackendApiService = class {
|
|
|
32567
34099
|
* without constructing a new service instance. Existing header keys are
|
|
32568
34100
|
* overwritten; keys absent from `headers` are preserved.
|
|
32569
34101
|
*
|
|
32570
|
-
* Headers also reach `swaps` and `
|
|
32571
|
-
* base-API credentials must not be forwarded to whatever origin it points at. Note
|
|
32572
|
-
* retargeted to another origin via `swapsApiConfig`, in which case a header set
|
|
34102
|
+
* Headers also reach `swaps`, `bridge` and `leverageYield`, but never `sponsoring`: it is configured
|
|
34103
|
+
* independently, so base-API credentials must not be forwarded to whatever origin it points at. Note
|
|
34104
|
+
* `swaps` can also be retargeted to another origin via `swapsApiConfig`, in which case a header set
|
|
34105
|
+
* here follows it.
|
|
32573
34106
|
*
|
|
32574
34107
|
* @param headers - Key-value pairs to add or overwrite in the default headers.
|
|
32575
34108
|
*/
|
|
32576
34109
|
setHeaders(headers) {
|
|
32577
34110
|
assignHeaders(this.headers, headers);
|
|
32578
34111
|
this.swaps.setHeaders(headers);
|
|
34112
|
+
this.leverageYield.setHeaders(headers);
|
|
32579
34113
|
this.bridge.setHeaders(headers);
|
|
32580
34114
|
}
|
|
32581
34115
|
/**
|
|
@@ -35517,7 +37051,7 @@ var AssetService = class {
|
|
|
35517
37051
|
ok: true,
|
|
35518
37052
|
value: {
|
|
35519
37053
|
tx: txResult.value,
|
|
35520
|
-
relayData: { address:
|
|
37054
|
+
relayData: { address: fromHubWallet, payload: data }
|
|
35521
37055
|
}
|
|
35522
37056
|
};
|
|
35523
37057
|
} catch (error) {
|
|
@@ -40801,7 +42335,9 @@ var PartnerFeeClaimService = class {
|
|
|
40801
42335
|
isEvmWalletProviderType(walletProvider),
|
|
40802
42336
|
"PartnerFeeClaimService only supports Evm (sonic) wallet provider"
|
|
40803
42337
|
);
|
|
40804
|
-
const txHash = await walletProvider.sendTransaction(rawTx
|
|
42338
|
+
const txHash = await walletProvider.sendTransaction(rawTx, {
|
|
42339
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
42340
|
+
});
|
|
40805
42341
|
return {
|
|
40806
42342
|
ok: true,
|
|
40807
42343
|
value: txHash
|
|
@@ -40996,7 +42532,9 @@ var PartnerFeeClaimService = class {
|
|
|
40996
42532
|
value: rawTx
|
|
40997
42533
|
};
|
|
40998
42534
|
}
|
|
40999
|
-
const txHash = await _params.walletProvider.sendTransaction(rawTx
|
|
42535
|
+
const txHash = await _params.walletProvider.sendTransaction(rawTx, {
|
|
42536
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
42537
|
+
});
|
|
41000
42538
|
return {
|
|
41001
42539
|
ok: true,
|
|
41002
42540
|
value: txHash
|
|
@@ -41143,7 +42681,9 @@ var PartnerFeeClaimService = class {
|
|
|
41143
42681
|
value: rawTx
|
|
41144
42682
|
};
|
|
41145
42683
|
}
|
|
41146
|
-
const txHash = await _params.walletProvider.sendTransaction(rawTx
|
|
42684
|
+
const txHash = await _params.walletProvider.sendTransaction(rawTx, {
|
|
42685
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
42686
|
+
});
|
|
41147
42687
|
return {
|
|
41148
42688
|
ok: true,
|
|
41149
42689
|
value: txHash
|
|
@@ -41520,10 +43060,20 @@ var LeverageYieldService = class {
|
|
|
41520
43060
|
hubProvider;
|
|
41521
43061
|
config;
|
|
41522
43062
|
spoke;
|
|
41523
|
-
|
|
43063
|
+
backendApi;
|
|
43064
|
+
/**
|
|
43065
|
+
* Effective backend submit-tx flow (`leverageYield.useBackendSubmitTx`, default off). Read live off
|
|
43066
|
+
* `ConfigService`, like `config.leverageYieldPartnerFee`, so the config object and the behavior can
|
|
43067
|
+
* never disagree.
|
|
43068
|
+
*/
|
|
43069
|
+
get useBackendSubmitTx() {
|
|
43070
|
+
return this.config.leverageYieldUseBackendSubmitTx;
|
|
43071
|
+
}
|
|
43072
|
+
constructor({ hubProvider, config, spoke, backendApi }) {
|
|
41524
43073
|
this.hubProvider = hubProvider;
|
|
41525
43074
|
this.config = config;
|
|
41526
43075
|
this.spoke = spoke;
|
|
43076
|
+
this.backendApi = backendApi;
|
|
41527
43077
|
}
|
|
41528
43078
|
// ─── Registry ──────────────────────────────────────────────────────────
|
|
41529
43079
|
/** Returns the static registry of known leverage-yield vaults. */
|
|
@@ -41532,7 +43082,7 @@ var LeverageYieldService = class {
|
|
|
41532
43082
|
}
|
|
41533
43083
|
/** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
|
|
41534
43084
|
getVault(name) {
|
|
41535
|
-
return this.listVaults().find((
|
|
43085
|
+
return this.listVaults().find((v12) => v12.name === name);
|
|
41536
43086
|
}
|
|
41537
43087
|
/**
|
|
41538
43088
|
* Looks up a registered vault by its on-chain proxy address (case-insensitive).
|
|
@@ -41540,7 +43090,7 @@ var LeverageYieldService = class {
|
|
|
41540
43090
|
*/
|
|
41541
43091
|
getVaultByAddress(address) {
|
|
41542
43092
|
const normalized = address.toLowerCase();
|
|
41543
|
-
return this.listVaults().find((
|
|
43093
|
+
return this.listVaults().find((v12) => v12.vault.toLowerCase() === normalized);
|
|
41544
43094
|
}
|
|
41545
43095
|
/**
|
|
41546
43096
|
* Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
|
|
@@ -41963,62 +43513,21 @@ var LeverageYieldService = class {
|
|
|
41963
43513
|
"vaultSwap",
|
|
41964
43514
|
async () => {
|
|
41965
43515
|
try {
|
|
41966
|
-
const timeout = _params.timeout;
|
|
41967
43516
|
const createIntentResult = await this.createVaultIntent(_params);
|
|
41968
43517
|
if (!createIntentResult.ok) {
|
|
41969
43518
|
return { ok: false, error: createIntentResult.error };
|
|
41970
43519
|
}
|
|
41971
|
-
const
|
|
41972
|
-
const
|
|
41973
|
-
|
|
41974
|
-
|
|
41975
|
-
|
|
41976
|
-
|
|
41977
|
-
|
|
41978
|
-
|
|
41979
|
-
|
|
41980
|
-
};
|
|
41981
|
-
}
|
|
41982
|
-
let dstIntentTxHash;
|
|
41983
|
-
if (isHubChainKeyType(srcChainKey)) {
|
|
41984
|
-
dstIntentTxHash = spokeTxHash;
|
|
41985
|
-
} else {
|
|
41986
|
-
const packet = await relayTxAndWaitPacket({
|
|
41987
|
-
srcTxHash: spokeTxHash,
|
|
41988
|
-
data: relayData,
|
|
41989
|
-
chainKey: srcChainKey,
|
|
41990
|
-
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
41991
|
-
timeout
|
|
41992
|
-
});
|
|
41993
|
-
if (!packet.ok) {
|
|
41994
|
-
return {
|
|
41995
|
-
ok: false,
|
|
41996
|
-
error: mapRelayFailure(packet.error, { feature: "leverageYield", ...baseCtx })
|
|
41997
|
-
};
|
|
41998
|
-
}
|
|
41999
|
-
dstIntentTxHash = packet.value.dst_tx_hash;
|
|
42000
|
-
}
|
|
42001
|
-
const postExecResult = await this.notifySolver({
|
|
42002
|
-
intent_tx_hash: dstIntentTxHash
|
|
42003
|
-
});
|
|
42004
|
-
if (!postExecResult.ok) {
|
|
42005
|
-
return { ok: false, error: postExecResult.error };
|
|
43520
|
+
const created = createIntentResult.value;
|
|
43521
|
+
const timeoutMs = resolveTimeoutMs(_params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
43522
|
+
if (this.useBackendSubmitTx) {
|
|
43523
|
+
const submitted = await this.submitTx(_params, created, createSubmitTxAttempt(timeoutMs));
|
|
43524
|
+
if (submitted.ok) return submitted;
|
|
43525
|
+
this.config.logger.warn(
|
|
43526
|
+
"[leverageYield] backend submit-tx did not complete; falling back to the client-side relay",
|
|
43527
|
+
{ error: submitted.error }
|
|
43528
|
+
);
|
|
42006
43529
|
}
|
|
42007
|
-
return
|
|
42008
|
-
ok: true,
|
|
42009
|
-
value: {
|
|
42010
|
-
solverExecutionResponse: postExecResult.value,
|
|
42011
|
-
intent,
|
|
42012
|
-
intentDeliveryInfo: {
|
|
42013
|
-
srcChainKey,
|
|
42014
|
-
srcTxHash: spokeTxHash,
|
|
42015
|
-
srcAddress: params.srcAddress,
|
|
42016
|
-
dstChainKey: params.dstChainKey,
|
|
42017
|
-
dstTxHash: dstIntentTxHash,
|
|
42018
|
-
dstAddress: params.dstAddress
|
|
42019
|
-
}
|
|
42020
|
-
}
|
|
42021
|
-
};
|
|
43530
|
+
return this.fallbackVaultSwapSteps(_params, created, timeoutMs);
|
|
42022
43531
|
} catch (error) {
|
|
42023
43532
|
if (isLeverageYieldSwapError(error)) return { ok: false, error };
|
|
42024
43533
|
return {
|
|
@@ -42046,6 +43555,129 @@ var LeverageYieldService = class {
|
|
|
42046
43555
|
}
|
|
42047
43556
|
);
|
|
42048
43557
|
}
|
|
43558
|
+
/**
|
|
43559
|
+
* Client-side vault-swap completion (the default path): verify the broadcast intent tx landed,
|
|
43560
|
+
* relay it to the hub (Sonic) — or use it directly when the source IS the hub — then notify the
|
|
43561
|
+
* solver via {@link LeverageYieldService.notifySolver} and build the {@link VaultSwapResponse}.
|
|
43562
|
+
* Extracted from `vaultSwap()` so the opt-in backend 2-step path ({@link LeverageYieldService.submitTx})
|
|
43563
|
+
* can fall back to it on any non-success. Leverage-yield copy of `SwapService.fallbackSwapSteps`.
|
|
43564
|
+
*/
|
|
43565
|
+
async fallbackVaultSwapSteps(_params, created, timeoutMs) {
|
|
43566
|
+
const { params } = _params;
|
|
43567
|
+
const srcChainKey = params.srcChainKey;
|
|
43568
|
+
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey, action: "vaultSwap" };
|
|
43569
|
+
const { tx: spokeTxHash, intent, relayData } = created;
|
|
43570
|
+
const verifyTxHashResult = await this.spoke.verifyTxHash({
|
|
43571
|
+
txHash: spokeTxHash,
|
|
43572
|
+
chainKey: srcChainKey
|
|
43573
|
+
});
|
|
43574
|
+
if (!verifyTxHashResult.ok) {
|
|
43575
|
+
return { ok: false, error: verifyFailed("leverageYield", verifyTxHashResult.error, baseCtx) };
|
|
43576
|
+
}
|
|
43577
|
+
let dstIntentTxHash;
|
|
43578
|
+
if (isHubChainKeyType(srcChainKey)) {
|
|
43579
|
+
dstIntentTxHash = spokeTxHash;
|
|
43580
|
+
} else {
|
|
43581
|
+
const packet = await relayTxAndWaitPacket({
|
|
43582
|
+
srcTxHash: spokeTxHash,
|
|
43583
|
+
data: relayData,
|
|
43584
|
+
chainKey: srcChainKey,
|
|
43585
|
+
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
43586
|
+
// The caller's full `timeout`, starting HERE — whether this runs as the only path or as the
|
|
43587
|
+
// backend's fallback, so a stalled backend attempt cannot shorten the relay wait. The floor
|
|
43588
|
+
// covers a sub-floor caller `timeout`: `relayTxAndWaitPacket` SUBMITS before `timeout` bounds
|
|
43589
|
+
// anything, so a zero budget would strand an already-landed tx unrelayed.
|
|
43590
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS)
|
|
43591
|
+
});
|
|
43592
|
+
if (!packet.ok) {
|
|
43593
|
+
return { ok: false, error: mapRelayFailure(packet.error, { feature: "leverageYield", ...baseCtx }) };
|
|
43594
|
+
}
|
|
43595
|
+
dstIntentTxHash = packet.value.dst_tx_hash;
|
|
43596
|
+
}
|
|
43597
|
+
const postExecResult = await this.notifySolver({
|
|
43598
|
+
intent_tx_hash: dstIntentTxHash
|
|
43599
|
+
});
|
|
43600
|
+
if (!postExecResult.ok) {
|
|
43601
|
+
return { ok: false, error: postExecResult.error };
|
|
43602
|
+
}
|
|
43603
|
+
return {
|
|
43604
|
+
ok: true,
|
|
43605
|
+
value: {
|
|
43606
|
+
solverExecutionResponse: postExecResult.value,
|
|
43607
|
+
intent,
|
|
43608
|
+
intentDeliveryInfo: {
|
|
43609
|
+
srcChainKey,
|
|
43610
|
+
srcTxHash: spokeTxHash,
|
|
43611
|
+
srcAddress: params.srcAddress,
|
|
43612
|
+
dstChainKey: params.dstChainKey,
|
|
43613
|
+
dstTxHash: dstIntentTxHash,
|
|
43614
|
+
dstAddress: params.dstAddress
|
|
43615
|
+
}
|
|
43616
|
+
}
|
|
43617
|
+
};
|
|
43618
|
+
}
|
|
43619
|
+
/**
|
|
43620
|
+
* Backend 2-step vault-swap path (opt-in via `leverageYield.useBackendSubmitTx`): hand the
|
|
43621
|
+
* broadcast intent tx to the leverage-yield API (`POST /leverage-yield/submit-tx`); the backend
|
|
43622
|
+
* relays + post-executes server-side. Polls `getSubmitTxStatus` until `solved`, then reconstructs
|
|
43623
|
+
* the same {@link VaultSwapResponse} the client-side path returns.
|
|
43624
|
+
*
|
|
43625
|
+
* Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, a 200 the backend did not
|
|
43626
|
+
* accept, terminal `failed` / abandoned, or poll timeout) so `vaultSwap()` falls back to
|
|
43627
|
+
* {@link LeverageYieldService.fallbackVaultSwapSteps}. Falling back is safe: re-relaying / re-posting
|
|
43628
|
+
* an already-processed vault swap is idempotent (the relay dedups the `executed` packet and the solver
|
|
43629
|
+
* re-affirms the intent — no double-fill), and load-bearing rather than belt-and-braces: the backend
|
|
43630
|
+
* keeps processing after this attempt gives up, so the fallback's relay can race the backend's own.
|
|
43631
|
+
*
|
|
43632
|
+
* The attempt itself — POST, budget clamps, status poll — is {@link runBackendSubmitTx}, shared with
|
|
43633
|
+
* swaps and bridge. What is leverage-yield-specific and lives here: the request body (including the
|
|
43634
|
+
* `operation` discriminator), the `solved` terminal status, the mapping to a
|
|
43635
|
+
* {@link VaultSwapResponse}, and the leverage-yield error taxonomy.
|
|
43636
|
+
*
|
|
43637
|
+
* `attempt` bounds this attempt alone — the POST and every status request draw on it, and the
|
|
43638
|
+
* client-side fallback holds a separate fresh `timeout`.
|
|
43639
|
+
*/
|
|
43640
|
+
async submitTx(_params, created, attempt) {
|
|
43641
|
+
const { params } = _params;
|
|
43642
|
+
const srcChainKey = params.srcChainKey;
|
|
43643
|
+
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey, action: "vaultSwap" };
|
|
43644
|
+
const { tx: spokeTxHash, intent, relayData } = created;
|
|
43645
|
+
try {
|
|
43646
|
+
const outcome = await runBackendSubmitTx({
|
|
43647
|
+
attempt,
|
|
43648
|
+
api: this.backendApi.leverageYield,
|
|
43649
|
+
body: {
|
|
43650
|
+
txHash: spokeTxHash,
|
|
43651
|
+
srcChainKey,
|
|
43652
|
+
walletAddress: params.srcAddress,
|
|
43653
|
+
intent,
|
|
43654
|
+
relayData: relayData.payload,
|
|
43655
|
+
// `withdraw` sets `hubWalletSwap: true` (spends the hub-wallet lsoda*); a plain deposit doesn't.
|
|
43656
|
+
operation: _params.hubWalletSwap ? "withdraw" : "deposit"
|
|
43657
|
+
},
|
|
43658
|
+
statusQuery: { txHash: spokeTxHash, srcChainKey },
|
|
43659
|
+
// A vault deposit/withdraw IS a solver swap, so terminal success is `solved` — not bridge's
|
|
43660
|
+
// `executed`.
|
|
43661
|
+
terminalStatus: "solved",
|
|
43662
|
+
onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
|
|
43663
|
+
// Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
|
|
43664
|
+
solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
|
|
43665
|
+
intent,
|
|
43666
|
+
intentDeliveryInfo: {
|
|
43667
|
+
srcChainKey,
|
|
43668
|
+
srcTxHash: spokeTxHash,
|
|
43669
|
+
srcAddress: params.srcAddress,
|
|
43670
|
+
dstChainKey: params.dstChainKey,
|
|
43671
|
+
dstTxHash: result.dstIntentTxHash,
|
|
43672
|
+
dstAddress: params.dstAddress
|
|
43673
|
+
}
|
|
43674
|
+
} : void 0
|
|
43675
|
+
});
|
|
43676
|
+
return outcome.ok ? { ok: true, value: outcome.value } : { ok: false, error: executionFailed("leverageYield", outcome.cause, baseCtx) };
|
|
43677
|
+
} catch (error) {
|
|
43678
|
+
return { ok: false, error: unknownFailed("leverageYield", error, baseCtx) };
|
|
43679
|
+
}
|
|
43680
|
+
}
|
|
42049
43681
|
/**
|
|
42050
43682
|
* Notifies the solver that the vault intent landed on the hub, triggering it to fill.
|
|
42051
43683
|
* Leverage-yield copy of the swap domain's `postExecution` — emits only
|
|
@@ -42619,7 +44251,7 @@ function xlmDecimalToStroops(amount) {
|
|
|
42619
44251
|
const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
|
|
42620
44252
|
return BigInt(scaled);
|
|
42621
44253
|
}
|
|
42622
|
-
var
|
|
44254
|
+
var STELLAR_BASE_RESERVE_STROOPS2 = 5000000n;
|
|
42623
44255
|
var BASE_RESERVE_UNITS = 2;
|
|
42624
44256
|
function parseBaseReserveStroops(ledger) {
|
|
42625
44257
|
const value = ledger?.base_reserve_in_stroops;
|
|
@@ -42646,7 +44278,7 @@ var SPONSOR_CONFIG_TTL_MS = 6e4;
|
|
|
42646
44278
|
var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
|
|
42647
44279
|
var DEFAULT_MAX_HORIZON_RETRIES = 2;
|
|
42648
44280
|
var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
|
|
42649
|
-
var STELLAR_TRUSTLINE_MIN_XLM_STROOPS =
|
|
44281
|
+
var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS2 + STELLAR_FEE_HEADROOM_STROOPS;
|
|
42650
44282
|
var SponsoringService = class {
|
|
42651
44283
|
config;
|
|
42652
44284
|
spoke;
|
|
@@ -42749,7 +44381,7 @@ var SponsoringService = class {
|
|
|
42749
44381
|
reason: messageOf(error, String(error))
|
|
42750
44382
|
});
|
|
42751
44383
|
}
|
|
42752
|
-
return
|
|
44384
|
+
return STELLAR_BASE_RESERVE_STROOPS2;
|
|
42753
44385
|
};
|
|
42754
44386
|
const request = read().then((value) => {
|
|
42755
44387
|
this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
|
|
@@ -43057,7 +44689,8 @@ var Sodax = class {
|
|
|
43057
44689
|
this.leverageYield = new LeverageYieldService({
|
|
43058
44690
|
hubProvider: this.hubProvider,
|
|
43059
44691
|
config: this.config,
|
|
43060
|
-
spoke: this.spoke
|
|
44692
|
+
spoke: this.spoke,
|
|
44693
|
+
backendApi: this.backendApi
|
|
43061
44694
|
});
|
|
43062
44695
|
this.sponsoring = new SponsoringService({
|
|
43063
44696
|
config: this.config,
|
|
@@ -43188,6 +44821,7 @@ exports.IntentsAbi = IntentsAbi;
|
|
|
43188
44821
|
exports.LOOKUP_CODES = LOOKUP_CODES;
|
|
43189
44822
|
exports.LTV_PRECISION = LTV_PRECISION;
|
|
43190
44823
|
exports.LendingPoolService = LendingPoolService;
|
|
44824
|
+
exports.LeverageYieldApiService = LeverageYieldApiService;
|
|
43191
44825
|
exports.LeverageYieldService = LeverageYieldService;
|
|
43192
44826
|
exports.LockupMultiplier = LockupMultiplier;
|
|
43193
44827
|
exports.LockupPeriod = LockupPeriod;
|
|
@@ -43203,6 +44837,7 @@ exports.NEAR_CHAIN_KEYS_SET = NEAR_CHAIN_KEYS_SET;
|
|
|
43203
44837
|
exports.NEAR_DEFAULT_GAS = NEAR_DEFAULT_GAS;
|
|
43204
44838
|
exports.NEAR_STORAGE_DEPOSIT = NEAR_STORAGE_DEPOSIT;
|
|
43205
44839
|
exports.NearSpokeService = NearSpokeService;
|
|
44840
|
+
exports.ORACLE_CANDLE_INTERVALS = ORACLE_CANDLE_INTERVALS;
|
|
43206
44841
|
exports.PartnerFeeClaimService = PartnerFeeClaimService;
|
|
43207
44842
|
exports.PartnerService = PartnerService;
|
|
43208
44843
|
exports.Permit2Service = Permit2Service;
|
|
@@ -43290,6 +44925,7 @@ exports.calculateHealthFactorFromBalances = calculateHealthFactorFromBalances;
|
|
|
43290
44925
|
exports.calculateHealthFactorFromBalancesBigUnits = calculateHealthFactorFromBalancesBigUnits;
|
|
43291
44926
|
exports.calculateLinearInterest = calculateLinearInterest;
|
|
43292
44927
|
exports.calculatePercentageFeeAmount = calculatePercentageFeeAmount;
|
|
44928
|
+
exports.canonicalizeBitcoinAddress = canonicalizeBitcoinAddress;
|
|
43293
44929
|
exports.clPoolAbi = clPoolAbi;
|
|
43294
44930
|
exports.clPoolManagerAbi = clPoolManagerAbi;
|
|
43295
44931
|
exports.clPositionManagerAbi = clPositionManagerAbi;
|
|
@@ -43301,6 +44937,7 @@ exports.concentratedLiquidityConfig = concentratedLiquidityConfig;
|
|
|
43301
44937
|
exports.connectionAbi = connectionAbi;
|
|
43302
44938
|
exports.consoleLogger = consoleLogger;
|
|
43303
44939
|
exports.convertTransactionInstructionToRaw = convertTransactionInstructionToRaw;
|
|
44940
|
+
exports.createBalanceCollector = createBalanceCollector;
|
|
43304
44941
|
exports.createInvariant = createInvariant;
|
|
43305
44942
|
exports.deepMerge = deepMerge;
|
|
43306
44943
|
exports.defaultHookAbi = defaultHookAbi;
|
|
@@ -43311,6 +44948,7 @@ exports.dexPools = dexPools;
|
|
|
43311
44948
|
exports.encodeAddress = encodeAddress;
|
|
43312
44949
|
exports.encodeBtcPayloadToBytes = encodeBtcPayloadToBytes;
|
|
43313
44950
|
exports.encodeContractCalls = encodeContractCalls;
|
|
44951
|
+
exports.encodeTokenIdentifier = encodeTokenIdentifier;
|
|
43314
44952
|
exports.erc20Abi = erc20Abi;
|
|
43315
44953
|
exports.erc4626Abi = erc4626Abi;
|
|
43316
44954
|
exports.estimateBitcoinTxSize = estimateBitcoinTxSize;
|
|
@@ -43434,6 +45072,7 @@ exports.isNewbnUSDToken = isNewbnUSDToken;
|
|
|
43434
45072
|
exports.isOptionalBitcoinWalletProviderType = isOptionalBitcoinWalletProviderType;
|
|
43435
45073
|
exports.isOptionalEvmWalletProviderType = isOptionalEvmWalletProviderType;
|
|
43436
45074
|
exports.isOptionalStellarWalletProviderType = isOptionalStellarWalletProviderType;
|
|
45075
|
+
exports.isOracleCandleInterval = isOracleCandleInterval;
|
|
43437
45076
|
exports.isPartnerError = isPartnerError;
|
|
43438
45077
|
exports.isPartnerFeeAmount = isPartnerFeeAmount;
|
|
43439
45078
|
exports.isPartnerFeePercentage = isPartnerFeePercentage;
|
|
@@ -43479,6 +45118,9 @@ exports.isSwapError = isSwapError;
|
|
|
43479
45118
|
exports.isSwapSupportedToken = isSwapSupportedToken;
|
|
43480
45119
|
exports.isUndefinedOrValidWalletProviderForChainKey = isUndefinedOrValidWalletProviderForChainKey;
|
|
43481
45120
|
exports.isUnifiedBnUSDMigrateParams = isUnifiedBnUSDMigrateParams;
|
|
45121
|
+
exports.isValidBitcoinAddress = isValidBitcoinAddress;
|
|
45122
|
+
exports.isValidInjectiveAddress = isValidInjectiveAddress;
|
|
45123
|
+
exports.isValidNearAccountId = isValidNearAccountId;
|
|
43482
45124
|
exports.isValidWalletProviderForChainKey = isValidWalletProviderForChainKey;
|
|
43483
45125
|
exports.kaiaSupportedTokens = kaiaSupportedTokens;
|
|
43484
45126
|
exports.leverageYieldConfig = leverageYieldConfig;
|
|
@@ -43535,6 +45177,7 @@ exports.reverseEncodeAddress = reverseEncodeAddress;
|
|
|
43535
45177
|
exports.robinhoodChain = robinhoodChain;
|
|
43536
45178
|
exports.robinhoodSupportedTokens = robinhoodSupportedTokens;
|
|
43537
45179
|
exports.serializeAddressData = serializeAddressData;
|
|
45180
|
+
exports.settleWalletBalances = settleWalletBalances;
|
|
43538
45181
|
exports.silentLogger = silentLogger;
|
|
43539
45182
|
exports.sleep = sleep;
|
|
43540
45183
|
exports.sodaxConfig = sodaxConfig;
|