@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.mjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import { getAbiItem, parseAbi, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters,
|
|
1
|
+
import { getAbiItem, parseAbi, defineChain, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, stringToBytes, fromHex, encodePacked, decodeAbiParameters, parseEventLogs, isHex, maxUint160, maxUint48, fallback } from 'viem';
|
|
2
|
+
import { initEccLib, address, networks, Transaction, Psbt, payments, opcodes, script } from 'bitcoinjs-lib';
|
|
2
3
|
import { bcs } from '@mysten/sui/bcs';
|
|
3
4
|
import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram, TransactionMessage, TransactionInstruction } from '@solana/web3.js';
|
|
4
5
|
import { rpc, Address, xdr, Account, Horizon, Contract, TransactionBuilder, nativeToScVal, TimeoutInfinite, scValToBigInt, Operation, Asset, FeeBumpTransaction, NotFoundError, Networks, Keypair } from '@stellar/stellar-sdk';
|
|
5
|
-
import { serializeCV, Cl, deserializeCV, cvToString, createNetwork, fetchFeeEstimateTransaction, fetchCallReadOnlyFunction, parseContractId,
|
|
6
|
+
import { serializeCV, Cl, deserializeCV, cvToString, createNetwork, fetchFeeEstimateTransaction, fetchCallReadOnlyFunction, parseContractId, noneCV, someCV, uintCV, getAddressFromPublicKey, makeUnsignedContractCall, serializePayloadBytes, PostConditionMode, Pc } from '@sodax/libs/stacks/core';
|
|
6
7
|
import { hedera, kaia, redbellyMainnet, mainnet, lightlinkPhoenix, polygon, bsc, optimism, base, arbitrum, avalanche, sonic } from 'viem/chains';
|
|
7
8
|
import * as rlp from 'rlp';
|
|
8
|
-
import { initEccLib, networks, Transaction, Psbt, payments, opcodes, script } from 'bitcoinjs-lib';
|
|
9
9
|
import * as ecc from '@bitcoinerlab/secp256k1';
|
|
10
10
|
import { CLPositionManagerAbi, encodeCLPositionManagerMintCalldata, encodeCLPositionManagerIncreaseLiquidityCalldata, encodeCLPositionManagerDecreaseLiquidityCalldata, getPoolId, CLPoolManagerAbi, decodePoolKey } from '@pancakeswap/infinity-sdk';
|
|
11
11
|
import { Transaction as Transaction$1 } from '@mysten/sui/transactions';
|
|
12
12
|
import { SuiGrpcClient } from '@mysten/sui/grpc';
|
|
13
|
-
import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddress } from '@solana/spl-token';
|
|
13
|
+
import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddressSync, unpackAccount, getAssociatedTokenAddress } from '@solana/spl-token';
|
|
14
14
|
import { AnchorProvider, Program } from '@coral-xyz/anchor';
|
|
15
15
|
import BN from 'bn.js';
|
|
16
16
|
import * as IconSdkRaw from 'icon-sdk-js';
|
|
17
|
-
import { ChainGrpcWasmApi, TxGrpcApi, toBase64, fromBase64, MsgExecuteContract, ChainRestAuthApi, BaseAccount, createTransaction } from '@injectivelabs/sdk-ts';
|
|
17
|
+
import { ChainGrpcWasmApi, IndexerGrpcAccountPortfolioApi, TxGrpcApi, toBase64, fromBase64, MsgExecuteContract, ChainRestAuthApi, BaseAccount, createTransaction } from '@injectivelabs/sdk-ts';
|
|
18
18
|
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
|
|
19
19
|
import { getNetworkEndpoints, Network } from '@injectivelabs/networks';
|
|
20
20
|
import * as v from 'valibot';
|
|
21
|
-
import { SwapsApi, SwapsApiError } from '@sodax/swaps-api';
|
|
21
|
+
import { SwapsApi, SwapsApiError, rawTxSchemaForChainKey as rawTxSchemaForChainKey$1, makeQuoteResponseSchema, DeadlineResponseSchema, AllowanceCheckResponseSchema, makeApproveResponseSchema, makeCreateIntentResponseSchema, SubmitIntentResponseSchema, StatusResponseSchema, makeCancelIntentResponseSchema, IntentHashResponseSchema, IntentPacketResponseSchema, RelayExtraDataResponseSchema as RelayExtraDataResponseSchema$1, IntentStateSchema, IntentResponseSchema as IntentResponseSchema$1, GasEstimateResponseSchema, FeeResponseSchema, SubmitTxResponseSchema, SubmitTxStatusResponseSchema } from '@sodax/swaps-api';
|
|
22
22
|
export { SwapsApiError } from '@sodax/swaps-api';
|
|
23
23
|
import BigNumber5, { BigNumber } from 'bignumber.js';
|
|
24
24
|
import { Token, Price } from '@pancakeswap/swap-sdk-core';
|
|
@@ -94,8 +94,8 @@ function serializeCause(cause, depth) {
|
|
|
94
94
|
}
|
|
95
95
|
function sanitizeContext(value, depth) {
|
|
96
96
|
const out = {};
|
|
97
|
-
for (const [key,
|
|
98
|
-
out[key] = sanitizeValue(
|
|
97
|
+
for (const [key, v12] of Object.entries(value)) {
|
|
98
|
+
out[key] = sanitizeValue(v12, depth + 1);
|
|
99
99
|
}
|
|
100
100
|
return out;
|
|
101
101
|
}
|
|
@@ -106,13 +106,13 @@ function sanitizeValue(value, depth) {
|
|
|
106
106
|
if (t === "bigint") return value.toString();
|
|
107
107
|
if (t === "string" || t === "number" || t === "boolean") return value;
|
|
108
108
|
if (t === "function" || t === "symbol") return safeString(value);
|
|
109
|
-
if (Array.isArray(value)) return value.map((
|
|
109
|
+
if (Array.isArray(value)) return value.map((v12) => sanitizeValue(v12, depth + 1));
|
|
110
110
|
if (value instanceof Date) return value.toISOString();
|
|
111
111
|
if (value instanceof Map) {
|
|
112
|
-
return Array.from(value.entries()).map(([k,
|
|
112
|
+
return Array.from(value.entries()).map(([k, v12]) => [sanitizeValue(k, depth + 1), sanitizeValue(v12, depth + 1)]);
|
|
113
113
|
}
|
|
114
114
|
if (value instanceof Set) {
|
|
115
|
-
return Array.from(value.values()).map((
|
|
115
|
+
return Array.from(value.values()).map((v12) => sanitizeValue(v12, depth + 1));
|
|
116
116
|
}
|
|
117
117
|
if (value instanceof Error) return { name: value.name, message: value.message };
|
|
118
118
|
if (t === "object") {
|
|
@@ -124,9 +124,9 @@ function sanitizeValue(value, depth) {
|
|
|
124
124
|
}
|
|
125
125
|
return safeString(value);
|
|
126
126
|
}
|
|
127
|
-
function safeString(
|
|
127
|
+
function safeString(v12) {
|
|
128
128
|
try {
|
|
129
|
-
return String(
|
|
129
|
+
return String(v12);
|
|
130
130
|
} catch {
|
|
131
131
|
return "[unserializable]";
|
|
132
132
|
}
|
|
@@ -3528,7 +3528,9 @@ var spokeChainConfig = {
|
|
|
3528
3528
|
},
|
|
3529
3529
|
chain: baseChainInfo[ChainKeys.BITCOIN_MAINNET],
|
|
3530
3530
|
bnUSD: "no",
|
|
3531
|
-
|
|
3531
|
+
// Must equal bitcoinSupportedTokens.BTC.address: isNativeToken compares a token's `address`
|
|
3532
|
+
// against this value, so a symbol here classifies native BTC as a contract token.
|
|
3533
|
+
nativeToken: "0:0",
|
|
3532
3534
|
supportedTokens: bitcoinSupportedTokens,
|
|
3533
3535
|
radfi: {
|
|
3534
3536
|
walletMode: "TRADING",
|
|
@@ -4078,8 +4080,12 @@ var moneyMarketSupportedTokens = {
|
|
|
4078
4080
|
spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.USDS,
|
|
4079
4081
|
spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.XLM
|
|
4080
4082
|
],
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
+
[ChainKeys.ROBINHOOD_MAINNET]: [
|
|
4084
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.ETH,
|
|
4085
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.bnUSD,
|
|
4086
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.SODA,
|
|
4087
|
+
spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.USDG
|
|
4088
|
+
]
|
|
4083
4089
|
};
|
|
4084
4090
|
var moneyMarketReserveAssets = [
|
|
4085
4091
|
...Object.values(SodaTokens).map((vault) => vault.address),
|
|
@@ -4858,7 +4864,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
4858
4864
|
}
|
|
4859
4865
|
|
|
4860
4866
|
// ../types/dist/index.js
|
|
4861
|
-
var CONFIG_VERSION =
|
|
4867
|
+
var CONFIG_VERSION = 233;
|
|
4862
4868
|
|
|
4863
4869
|
// src/shared/utils/resolveTimeoutMs.ts
|
|
4864
4870
|
function resolveTimeoutMs(timeout, fallbackMs) {
|
|
@@ -4871,6 +4877,33 @@ function isEvmSpokeChainConfig(value) {
|
|
|
4871
4877
|
function isIconAddress(value) {
|
|
4872
4878
|
return typeof value === "string" && /^hx[a-f0-9]{40}$|^cx[a-f0-9]{40}$/.test(value);
|
|
4873
4879
|
}
|
|
4880
|
+
var NEAR_ACCOUNT_ID_REGEX = /^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/;
|
|
4881
|
+
function isValidNearAccountId(accountId) {
|
|
4882
|
+
return accountId.length >= 2 && accountId.length <= 64 && NEAR_ACCOUNT_ID_REGEX.test(accountId);
|
|
4883
|
+
}
|
|
4884
|
+
var INJECTIVE_ADDRESS_REGEX = /^inj1(?:[02-9ac-hj-np-z]{38}|[02-9ac-hj-np-z]{58})$/;
|
|
4885
|
+
var BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
4886
|
+
var BECH32_GENERATOR = [996825010, 642813549, 513874426, 1027748829, 705979059];
|
|
4887
|
+
function bech32ChecksumVerifies(hrp, dataChars) {
|
|
4888
|
+
const values = [
|
|
4889
|
+
...[...hrp].map((c) => c.charCodeAt(0) >>> 5),
|
|
4890
|
+
0,
|
|
4891
|
+
...[...hrp].map((c) => c.charCodeAt(0) & 31),
|
|
4892
|
+
...[...dataChars].map((c) => BECH32_CHARSET.indexOf(c))
|
|
4893
|
+
];
|
|
4894
|
+
let chk = 1;
|
|
4895
|
+
for (const value of values) {
|
|
4896
|
+
const top = chk >>> 25;
|
|
4897
|
+
chk = (chk & 33554431) << 5 ^ value;
|
|
4898
|
+
for (let i = 0; i < 5; i++) {
|
|
4899
|
+
if (top >>> i & 1) chk ^= BECH32_GENERATOR[i];
|
|
4900
|
+
}
|
|
4901
|
+
}
|
|
4902
|
+
return chk === 1;
|
|
4903
|
+
}
|
|
4904
|
+
function isValidInjectiveAddress(address) {
|
|
4905
|
+
return INJECTIVE_ADDRESS_REGEX.test(address) && bech32ChecksumVerifies("inj", address.slice(4));
|
|
4906
|
+
}
|
|
4874
4907
|
function isResponseAddressType(value) {
|
|
4875
4908
|
return typeof value === "object" && value !== null && "type" in value && "payload" in value && value.type === "RESPONSE_ADDRESS" && isIconAddress(value.payload);
|
|
4876
4909
|
}
|
|
@@ -4978,6 +5011,81 @@ function isUndefinedOrValidWalletProviderForChainKey(chainKey, walletProvider) {
|
|
|
4978
5011
|
function isOptionalBitcoinWalletProviderType(walletProvider) {
|
|
4979
5012
|
return walletProvider === void 0 || isBitcoinWalletProviderType(walletProvider);
|
|
4980
5013
|
}
|
|
5014
|
+
var BITCOIN_FEE_SAFETY_VBYTES = 20;
|
|
5015
|
+
function calcOpReturnOutputVbytes(payloadByteLength) {
|
|
5016
|
+
let scriptSize;
|
|
5017
|
+
if (payloadByteLength <= 75) {
|
|
5018
|
+
scriptSize = 3 + payloadByteLength;
|
|
5019
|
+
} else if (payloadByteLength <= 255) {
|
|
5020
|
+
scriptSize = 4 + payloadByteLength;
|
|
5021
|
+
} else {
|
|
5022
|
+
scriptSize = 5 + payloadByteLength;
|
|
5023
|
+
}
|
|
5024
|
+
const scriptLenVarint = scriptSize <= 252 ? 1 : 3;
|
|
5025
|
+
return 8 + scriptLenVarint + scriptSize;
|
|
5026
|
+
}
|
|
5027
|
+
function estimateBitcoinTxSize(inputCount, outputCount, addressType, opReturnOutputVbytes = 44) {
|
|
5028
|
+
let inputWeight;
|
|
5029
|
+
switch (addressType) {
|
|
5030
|
+
case "P2PKH":
|
|
5031
|
+
inputWeight = 148;
|
|
5032
|
+
break;
|
|
5033
|
+
case "P2SH":
|
|
5034
|
+
inputWeight = 91;
|
|
5035
|
+
break;
|
|
5036
|
+
case "P2TR":
|
|
5037
|
+
inputWeight = 58;
|
|
5038
|
+
break;
|
|
5039
|
+
default:
|
|
5040
|
+
inputWeight = 68;
|
|
5041
|
+
break;
|
|
5042
|
+
}
|
|
5043
|
+
return Math.ceil(
|
|
5044
|
+
10.5 + opReturnOutputVbytes + BITCOIN_FEE_SAFETY_VBYTES + inputCount * inputWeight + outputCount * 31
|
|
5045
|
+
);
|
|
5046
|
+
}
|
|
5047
|
+
function encodeBtcPayloadToBytes(payload) {
|
|
5048
|
+
const isBase58Check = payload.address_type === "P2PKH" || payload.address_type === "P2SH";
|
|
5049
|
+
return JSON.stringify({
|
|
5050
|
+
src_address: isBase58Check ? payload.src_address : payload.src_address.toLowerCase(),
|
|
5051
|
+
data: payload.data.toLowerCase(),
|
|
5052
|
+
src_chain_id: payload.src_chain_id,
|
|
5053
|
+
dst_chain_id: payload.dst_chain_id,
|
|
5054
|
+
wallet_used: payload.wallet_used,
|
|
5055
|
+
timestamp: payload.timestamp,
|
|
5056
|
+
address_type: payload.address_type
|
|
5057
|
+
});
|
|
5058
|
+
}
|
|
5059
|
+
function isValidBitcoinAddress(address$1) {
|
|
5060
|
+
try {
|
|
5061
|
+
const { prefix: prefix2, version, data } = address.fromBech32(address$1);
|
|
5062
|
+
if (prefix2 !== "bc" && prefix2 !== "tb") return false;
|
|
5063
|
+
return version === 0 && (data.length === 20 || data.length === 32) || version === 1 && data.length === 32;
|
|
5064
|
+
} catch {
|
|
5065
|
+
}
|
|
5066
|
+
try {
|
|
5067
|
+
const { version } = address.fromBase58Check(address$1);
|
|
5068
|
+
return version === 0 || version === 5 || version === 111 || version === 196;
|
|
5069
|
+
} catch {
|
|
5070
|
+
return false;
|
|
5071
|
+
}
|
|
5072
|
+
}
|
|
5073
|
+
function canonicalizeBitcoinAddress(address$1) {
|
|
5074
|
+
try {
|
|
5075
|
+
address.fromBech32(address$1);
|
|
5076
|
+
return address$1.toLowerCase();
|
|
5077
|
+
} catch {
|
|
5078
|
+
return address$1;
|
|
5079
|
+
}
|
|
5080
|
+
}
|
|
5081
|
+
function normalizePsbtToBase64(signedPsbt) {
|
|
5082
|
+
const isHex2 = /^[0-9a-fA-F]+$/.test(signedPsbt);
|
|
5083
|
+
return isHex2 ? Buffer.from(signedPsbt, "hex").toString("base64") : signedPsbt;
|
|
5084
|
+
}
|
|
5085
|
+
function normalizeSignatureToBase64(signature) {
|
|
5086
|
+
const isHex2 = /^[0-9a-fA-F]+$/.test(signature);
|
|
5087
|
+
return isHex2 ? Buffer.from(signature, "hex").toString("base64") : signature;
|
|
5088
|
+
}
|
|
4981
5089
|
function isNativeBitcoinTransfer(config, chainKey, token) {
|
|
4982
5090
|
return isBitcoinChainKeyType(chainKey) && !!token && isNativeBitcoinToken(config.getChainConfig(chainKey), token.address);
|
|
4983
5091
|
}
|
|
@@ -4997,11 +5105,10 @@ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_R
|
|
|
4997
5105
|
throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
|
|
4998
5106
|
}
|
|
4999
5107
|
function getRandomBytes(length) {
|
|
5000
|
-
|
|
5001
|
-
|
|
5002
|
-
array3[i] = Math.floor(Math.random() * 256);
|
|
5108
|
+
if (!globalThis.crypto?.getRandomValues) {
|
|
5109
|
+
throw new Error("Web Crypto (crypto.getRandomValues) is unavailable in this runtime");
|
|
5003
5110
|
}
|
|
5004
|
-
return
|
|
5111
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
5005
5112
|
}
|
|
5006
5113
|
function randomUint256() {
|
|
5007
5114
|
const bytes = getRandomBytes(32);
|
|
@@ -5050,6 +5157,7 @@ function encodeAddress(spokeChainId, address) {
|
|
|
5050
5157
|
const chainType = getChainType(spokeChainId);
|
|
5051
5158
|
switch (chainType) {
|
|
5052
5159
|
case "EVM":
|
|
5160
|
+
invariant(isAddress(address), `Invalid EVM address: ${address}`);
|
|
5053
5161
|
return address;
|
|
5054
5162
|
case "ICON": {
|
|
5055
5163
|
invariant(isIconAddress(address), `Invalid ICON address: ${address}`);
|
|
@@ -5065,8 +5173,13 @@ function encodeAddress(spokeChainId, address) {
|
|
|
5065
5173
|
case "STACKS":
|
|
5066
5174
|
return `0x${serializeCV(Cl.principal(address))}`;
|
|
5067
5175
|
case "BITCOIN":
|
|
5176
|
+
invariant(isValidBitcoinAddress(address), `Invalid Bitcoin address: ${address}`);
|
|
5177
|
+
return toHex(Buffer.from(canonicalizeBitcoinAddress(address), "utf-8"));
|
|
5068
5178
|
case "NEAR":
|
|
5179
|
+
invariant(isValidNearAccountId(address), `Invalid NEAR account id: ${address}`);
|
|
5180
|
+
return toHex(Buffer.from(address, "utf-8"));
|
|
5069
5181
|
case "INJECTIVE":
|
|
5182
|
+
invariant(isValidInjectiveAddress(address), `Invalid Injective address: ${address}`);
|
|
5070
5183
|
return toHex(Buffer.from(address, "utf-8"));
|
|
5071
5184
|
default: {
|
|
5072
5185
|
const exhaustiveCheck = chainType;
|
|
@@ -5074,6 +5187,16 @@ function encodeAddress(spokeChainId, address) {
|
|
|
5074
5187
|
}
|
|
5075
5188
|
}
|
|
5076
5189
|
}
|
|
5190
|
+
function encodeTokenIdentifier(spokeChainId, token) {
|
|
5191
|
+
switch (getChainType(spokeChainId)) {
|
|
5192
|
+
case "BITCOIN":
|
|
5193
|
+
case "NEAR":
|
|
5194
|
+
case "INJECTIVE":
|
|
5195
|
+
return toHex(Buffer.from(token, "utf-8"));
|
|
5196
|
+
default:
|
|
5197
|
+
return encodeAddress(spokeChainId, token);
|
|
5198
|
+
}
|
|
5199
|
+
}
|
|
5077
5200
|
function reverseEncodeAddress(spokeChainId, encoded) {
|
|
5078
5201
|
const chainType = getChainType(spokeChainId);
|
|
5079
5202
|
switch (chainType) {
|
|
@@ -14773,6 +14896,11 @@ var ConfigService = class {
|
|
|
14773
14896
|
get bridgeUseBackendSubmitTx() {
|
|
14774
14897
|
return this.bridge.useBackendSubmitTx ?? this.sodax.bridgeOptions?.useBackendSubmitTx ?? true;
|
|
14775
14898
|
}
|
|
14899
|
+
// Opt-in (default OFF), unlike the swaps/bridge toggles above: the leverage-yield submit-tx
|
|
14900
|
+
// backend path is newer, so an omitted flag keeps the proven client-side relay.
|
|
14901
|
+
get leverageYieldUseBackendSubmitTx() {
|
|
14902
|
+
return this.leverageYield.useBackendSubmitTx ?? false;
|
|
14903
|
+
}
|
|
14776
14904
|
get dex() {
|
|
14777
14905
|
return this.sodax.dex;
|
|
14778
14906
|
}
|
|
@@ -14824,7 +14952,7 @@ function mergeSodaxConfig(base2, override) {
|
|
|
14824
14952
|
}
|
|
14825
14953
|
function encodeContractCalls(calls) {
|
|
14826
14954
|
return encodeAbiParameters(parseAbiParameters("(address,uint256,bytes)[]"), [
|
|
14827
|
-
calls.map((
|
|
14955
|
+
calls.map((v12) => [v12.address, v12.value, v12.data])
|
|
14828
14956
|
]);
|
|
14829
14957
|
}
|
|
14830
14958
|
async function waitForTransactionReceipt(hash, provider) {
|
|
@@ -15027,16 +15155,20 @@ var EvmVaultTokenService = class {
|
|
|
15027
15155
|
*/
|
|
15028
15156
|
static async deposit(vault, token, amount, walletProvider) {
|
|
15029
15157
|
const from = await walletProvider.getWalletAddress();
|
|
15030
|
-
return walletProvider.sendTransaction(
|
|
15031
|
-
|
|
15032
|
-
|
|
15033
|
-
|
|
15034
|
-
|
|
15035
|
-
|
|
15036
|
-
|
|
15037
|
-
|
|
15038
|
-
|
|
15039
|
-
|
|
15158
|
+
return walletProvider.sendTransaction(
|
|
15159
|
+
{
|
|
15160
|
+
from,
|
|
15161
|
+
to: vault,
|
|
15162
|
+
value: 0n,
|
|
15163
|
+
data: encodeFunctionData({
|
|
15164
|
+
abi: vaultTokenAbi,
|
|
15165
|
+
functionName: "deposit",
|
|
15166
|
+
args: [token, amount]
|
|
15167
|
+
})
|
|
15168
|
+
},
|
|
15169
|
+
// Vaults live on the hub; refuse to broadcast from a wallet on another EVM network.
|
|
15170
|
+
{ expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id }
|
|
15171
|
+
);
|
|
15040
15172
|
}
|
|
15041
15173
|
/**
|
|
15042
15174
|
* Withdraws a specified amount of a token from the vault.
|
|
@@ -15048,16 +15180,19 @@ var EvmVaultTokenService = class {
|
|
|
15048
15180
|
*/
|
|
15049
15181
|
static async withdraw(vault, token, amount, provider) {
|
|
15050
15182
|
const from = await provider.getWalletAddress();
|
|
15051
|
-
return provider.sendTransaction(
|
|
15052
|
-
|
|
15053
|
-
|
|
15054
|
-
|
|
15055
|
-
|
|
15056
|
-
|
|
15057
|
-
|
|
15058
|
-
|
|
15059
|
-
|
|
15060
|
-
|
|
15183
|
+
return provider.sendTransaction(
|
|
15184
|
+
{
|
|
15185
|
+
from,
|
|
15186
|
+
to: vault,
|
|
15187
|
+
value: 0n,
|
|
15188
|
+
data: encodeFunctionData({
|
|
15189
|
+
abi: vaultTokenAbi,
|
|
15190
|
+
functionName: "withdraw",
|
|
15191
|
+
args: [token, amount]
|
|
15192
|
+
})
|
|
15193
|
+
},
|
|
15194
|
+
{ expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id }
|
|
15195
|
+
);
|
|
15061
15196
|
}
|
|
15062
15197
|
/**
|
|
15063
15198
|
* Encodes the deposit transaction data for the vault.
|
|
@@ -15258,7 +15393,9 @@ var Erc20Service = class _Erc20Service {
|
|
|
15258
15393
|
if (params.raw) {
|
|
15259
15394
|
return rawTx;
|
|
15260
15395
|
}
|
|
15261
|
-
return await params.walletProvider.sendTransaction(rawTx
|
|
15396
|
+
return await params.walletProvider.sendTransaction(rawTx, {
|
|
15397
|
+
expectedChainId: params.expectedChainId
|
|
15398
|
+
});
|
|
15262
15399
|
}
|
|
15263
15400
|
/**
|
|
15264
15401
|
* Encodes a transfer transaction for a token.
|
|
@@ -15422,10 +15559,54 @@ var EvmAssetManagerService = class _EvmAssetManagerService {
|
|
|
15422
15559
|
});
|
|
15423
15560
|
}
|
|
15424
15561
|
};
|
|
15562
|
+
|
|
15563
|
+
// src/shared/services/spoke/balance-utils.ts
|
|
15564
|
+
function createBalanceCollector({ logger, chainKey }) {
|
|
15565
|
+
const balances = {};
|
|
15566
|
+
let attempted = 0;
|
|
15567
|
+
let failed = 0;
|
|
15568
|
+
return {
|
|
15569
|
+
ok(tokenAddress, value) {
|
|
15570
|
+
attempted++;
|
|
15571
|
+
balances[tokenAddress] = value;
|
|
15572
|
+
},
|
|
15573
|
+
fail(tokenAddress, reason) {
|
|
15574
|
+
attempted++;
|
|
15575
|
+
failed++;
|
|
15576
|
+
logger.warn("[getWalletBalances] balance read failed, reporting 0n", {
|
|
15577
|
+
chainKey,
|
|
15578
|
+
token: tokenAddress,
|
|
15579
|
+
error: reason instanceof Error ? reason.message : String(reason)
|
|
15580
|
+
});
|
|
15581
|
+
balances[tokenAddress] = 0n;
|
|
15582
|
+
},
|
|
15583
|
+
finish() {
|
|
15584
|
+
if (attempted > 0 && failed === attempted) {
|
|
15585
|
+
throw new Error(`[getWalletBalances] every balance read failed on ${chainKey} (${failed}/${attempted})`);
|
|
15586
|
+
}
|
|
15587
|
+
return balances;
|
|
15588
|
+
}
|
|
15589
|
+
};
|
|
15590
|
+
}
|
|
15591
|
+
async function settleWalletBalances(collector, tokens, read) {
|
|
15592
|
+
const settled = await Promise.allSettled(tokens.map((token) => read(token)));
|
|
15593
|
+
tokens.forEach((token, index) => {
|
|
15594
|
+
const outcome = settled[index];
|
|
15595
|
+
if (!outcome) return;
|
|
15596
|
+
if (outcome.status === "fulfilled") {
|
|
15597
|
+
collector.ok(token.address, outcome.value);
|
|
15598
|
+
} else {
|
|
15599
|
+
collector.fail(token.address, outcome.reason);
|
|
15600
|
+
}
|
|
15601
|
+
});
|
|
15602
|
+
}
|
|
15425
15603
|
var HEDERA_NATIVE_VALUE_SCALE = 10n ** 10n;
|
|
15426
15604
|
function scaleNativeMsgValue(chainKey, amount) {
|
|
15427
15605
|
return chainKey === ChainKeys.HEDERA_MAINNET ? amount * HEDERA_NATIVE_VALUE_SCALE : amount;
|
|
15428
15606
|
}
|
|
15607
|
+
function scaleNativeBalance(chainKey, amount) {
|
|
15608
|
+
return chainKey === ChainKeys.HEDERA_MAINNET ? amount / HEDERA_NATIVE_VALUE_SCALE : amount;
|
|
15609
|
+
}
|
|
15429
15610
|
var EvmSpokeService = class {
|
|
15430
15611
|
config;
|
|
15431
15612
|
// map containing the public clients for each evm spoke chain, lazy loaded on demand
|
|
@@ -15527,7 +15708,9 @@ var EvmSpokeService = class {
|
|
|
15527
15708
|
if (params.raw === true) {
|
|
15528
15709
|
return rawTx;
|
|
15529
15710
|
}
|
|
15530
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
15711
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
15712
|
+
expectedChainId: getEvmViemChain(srcChainKey).id
|
|
15713
|
+
});
|
|
15531
15714
|
}
|
|
15532
15715
|
/**
|
|
15533
15716
|
* Get the balance of the token deposited in the spoke chain asset manager.
|
|
@@ -15542,6 +15725,79 @@ var EvmSpokeService = class {
|
|
|
15542
15725
|
args: [this.config.getChainConfig(params.srcChainKey).addresses.assetManager]
|
|
15543
15726
|
});
|
|
15544
15727
|
}
|
|
15728
|
+
/**
|
|
15729
|
+
* Get the user's own wallet balance of a token on an EVM spoke chain, in smallest units.
|
|
15730
|
+
* Native coin via `eth_getBalance` (Hedera scaled to canonical decimals); erc20 via `balanceOf`.
|
|
15731
|
+
* @param {GetBalanceParams<EvmSpokeOnlyChainKey>} params - The chain key, user address, and token.
|
|
15732
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
15733
|
+
*/
|
|
15734
|
+
async getWalletBalance(params) {
|
|
15735
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
15736
|
+
const publicClient = this.getPublicClient(srcChainKey);
|
|
15737
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
15738
|
+
const balance2 = await publicClient.getBalance({ address: srcAddress });
|
|
15739
|
+
return scaleNativeBalance(srcChainKey, balance2);
|
|
15740
|
+
}
|
|
15741
|
+
const balance = await publicClient.readContract({
|
|
15742
|
+
address: token.address,
|
|
15743
|
+
abi: erc20Abi,
|
|
15744
|
+
functionName: "balanceOf",
|
|
15745
|
+
args: [srcAddress]
|
|
15746
|
+
});
|
|
15747
|
+
return balance ?? 0n;
|
|
15748
|
+
}
|
|
15749
|
+
/**
|
|
15750
|
+
* Get the user's own wallet balances of multiple tokens on an EVM spoke chain, in smallest
|
|
15751
|
+
* units. Non-native tokens are batched via multicall3 when the chain supports it, otherwise
|
|
15752
|
+
* read in parallel.
|
|
15753
|
+
* @param {GetBalancesParams<EvmSpokeOnlyChainKey>} params - The chain key, user address, and tokens.
|
|
15754
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
15755
|
+
*/
|
|
15756
|
+
async getWalletBalances(params) {
|
|
15757
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
15758
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
15759
|
+
const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
15760
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
15761
|
+
await settleWalletBalances(
|
|
15762
|
+
collector,
|
|
15763
|
+
nativeTokens,
|
|
15764
|
+
(token) => this.getWalletBalance({ srcChainKey, srcAddress, token })
|
|
15765
|
+
);
|
|
15766
|
+
if (nonNativeTokens.length === 0) {
|
|
15767
|
+
return collector.finish();
|
|
15768
|
+
}
|
|
15769
|
+
const publicClient = this.getPublicClient(srcChainKey);
|
|
15770
|
+
if (getEvmViemChain(srcChainKey).contracts?.multicall3) {
|
|
15771
|
+
const results = await publicClient.multicall({
|
|
15772
|
+
contracts: nonNativeTokens.map((token) => ({
|
|
15773
|
+
abi: erc20Abi,
|
|
15774
|
+
address: token.address,
|
|
15775
|
+
functionName: "balanceOf",
|
|
15776
|
+
args: [srcAddress]
|
|
15777
|
+
}))
|
|
15778
|
+
});
|
|
15779
|
+
nonNativeTokens.forEach((token, index) => {
|
|
15780
|
+
const result = results[index];
|
|
15781
|
+
if (result?.status === "success") {
|
|
15782
|
+
collector.ok(token.address, BigInt(result.result));
|
|
15783
|
+
} else {
|
|
15784
|
+
collector.fail(token.address, result?.error ?? new Error(`missing multicall result for ${token.address}`));
|
|
15785
|
+
}
|
|
15786
|
+
});
|
|
15787
|
+
return collector.finish();
|
|
15788
|
+
}
|
|
15789
|
+
await settleWalletBalances(
|
|
15790
|
+
collector,
|
|
15791
|
+
nonNativeTokens,
|
|
15792
|
+
(token) => publicClient.readContract({
|
|
15793
|
+
address: token.address,
|
|
15794
|
+
abi: erc20Abi,
|
|
15795
|
+
functionName: "balanceOf",
|
|
15796
|
+
args: [srcAddress]
|
|
15797
|
+
})
|
|
15798
|
+
);
|
|
15799
|
+
return collector.finish();
|
|
15800
|
+
}
|
|
15545
15801
|
/**
|
|
15546
15802
|
* Sends a message to the hub chain.
|
|
15547
15803
|
* @param {SendMessageParams} params - Includes dstChainKey, the chain key of the hub chain.
|
|
@@ -15567,7 +15823,9 @@ var EvmSpokeService = class {
|
|
|
15567
15823
|
if (params.raw) {
|
|
15568
15824
|
return rawTx;
|
|
15569
15825
|
}
|
|
15570
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
15826
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
15827
|
+
expectedChainId: getEvmViemChain(srcChainKey).id
|
|
15828
|
+
});
|
|
15571
15829
|
}
|
|
15572
15830
|
async waitForTransactionReceipt(params) {
|
|
15573
15831
|
try {
|
|
@@ -15659,6 +15917,24 @@ var StacksSpokeService = class {
|
|
|
15659
15917
|
});
|
|
15660
15918
|
return result.value.value;
|
|
15661
15919
|
}
|
|
15920
|
+
ftAssetNames = /* @__PURE__ */ new Map();
|
|
15921
|
+
/** Post-conditions need the on-chain `define-fungible-token` names; SIP-10 exposes no read for them. */
|
|
15922
|
+
async getFtAssetNames(tokenContractId) {
|
|
15923
|
+
const cached = this.ftAssetNames.get(tokenContractId);
|
|
15924
|
+
if (cached) return cached;
|
|
15925
|
+
const [address, name] = parseContractId(tokenContractId);
|
|
15926
|
+
const response = await fetch(`${this.network.client.baseUrl}/v2/contracts/interface/${address}/${name}`);
|
|
15927
|
+
if (!response.ok) {
|
|
15928
|
+
throw new Error(`Failed to fetch the contract interface for ${tokenContractId}: ${response.statusText}`);
|
|
15929
|
+
}
|
|
15930
|
+
const abi = await response.json();
|
|
15931
|
+
const assetNames = (abi.fungible_tokens ?? []).map((token) => token.name);
|
|
15932
|
+
if (assetNames.length === 0) {
|
|
15933
|
+
throw new Error(`${tokenContractId} defines no fungible token \u2014 not a SIP-10 contract`);
|
|
15934
|
+
}
|
|
15935
|
+
this.ftAssetNames.set(tokenContractId, assetNames);
|
|
15936
|
+
return assetNames;
|
|
15937
|
+
}
|
|
15662
15938
|
async getImplContractAddress(stateContract) {
|
|
15663
15939
|
const [contractAddress, contractName] = parseContractId(stateContract);
|
|
15664
15940
|
const txParams = {
|
|
@@ -15681,18 +15957,18 @@ var StacksSpokeService = class {
|
|
|
15681
15957
|
const assetManagerImpl = await this.getImplContractAddress(chainConfig.addresses.assetManager);
|
|
15682
15958
|
const [implAddress, implName] = parseContractId(assetManagerImpl);
|
|
15683
15959
|
const [connectionAddress, connectionName] = parseContractId(chainConfig.addresses.connection);
|
|
15960
|
+
const isNative = isNativeToken(params.srcChainKey, params.token);
|
|
15684
15961
|
const reqData = {
|
|
15685
15962
|
contractAddress: implAddress,
|
|
15686
15963
|
contractName: implName,
|
|
15687
15964
|
functionName: "transfer",
|
|
15688
15965
|
functionArgs: [
|
|
15689
|
-
|
|
15966
|
+
isNative ? noneCV() : someCV(Cl.principal(params.token)),
|
|
15690
15967
|
Cl.bufferFromHex(params.to),
|
|
15691
15968
|
uintCV(params.amount),
|
|
15692
15969
|
Cl.bufferFromHex(params.data),
|
|
15693
15970
|
Cl.contractPrincipal(connectionAddress, connectionName)
|
|
15694
|
-
]
|
|
15695
|
-
postConditionMode: PostConditionMode.Allow
|
|
15971
|
+
]
|
|
15696
15972
|
};
|
|
15697
15973
|
if (params.raw === true) {
|
|
15698
15974
|
if (!params.srcPublicKey) {
|
|
@@ -15721,9 +15997,25 @@ var StacksSpokeService = class {
|
|
|
15721
15997
|
payload: bytesToHex(serializePayloadBytes(tx.payload))
|
|
15722
15998
|
};
|
|
15723
15999
|
}
|
|
15724
|
-
const txId = await params.walletProvider.sendTransaction(
|
|
16000
|
+
const txId = await params.walletProvider.sendTransaction({
|
|
16001
|
+
...reqData,
|
|
16002
|
+
postConditionMode: PostConditionMode.Deny,
|
|
16003
|
+
postConditions: await this.depositPostConditions(params.srcAddress, params.token, params.amount, isNative)
|
|
16004
|
+
});
|
|
15725
16005
|
return txId;
|
|
15726
16006
|
}
|
|
16007
|
+
/**
|
|
16008
|
+
* Caps for a Deny-mode deposit: asset-manager-state.deposit moves exactly `amount` from the
|
|
16009
|
+
* caller, so cap the sender at `amount` — one cap per FT the token contract defines (sBTC has
|
|
16010
|
+
* two; the unmoved ones pass at 0 trivially), or uSTX for native.
|
|
16011
|
+
*/
|
|
16012
|
+
async depositPostConditions(srcAddress, token, amount, isNative) {
|
|
16013
|
+
if (isNative) return [Pc.principal(srcAddress).willSendLte(amount).ustx()];
|
|
16014
|
+
const assetNames = await this.getFtAssetNames(token);
|
|
16015
|
+
return assetNames.map(
|
|
16016
|
+
(assetName) => Pc.principal(srcAddress).willSendLte(amount).ft(token, assetName)
|
|
16017
|
+
);
|
|
16018
|
+
}
|
|
15727
16019
|
/**
|
|
15728
16020
|
* Get the balance of the token deposited in the spoke chain asset manager.
|
|
15729
16021
|
* @param {GetDepositParams<StacksChainKey>} params - The parameters for the deposit, including the user's address, token address, and chain id.
|
|
@@ -15736,6 +16028,31 @@ var StacksSpokeService = class {
|
|
|
15736
16028
|
}
|
|
15737
16029
|
return this.readTokenBalance(params.token, assetManager);
|
|
15738
16030
|
}
|
|
16031
|
+
/**
|
|
16032
|
+
* Get the user's own wallet balance of a token on Stacks, in smallest units. Native STX via the
|
|
16033
|
+
* Hiro REST `/extended/v1/address/{addr}/balances` endpoint; SIP-010 fungible tokens via the
|
|
16034
|
+
* read-only `get-balance` contract call. Unlike {@link getDeposit}, this reads the holding of
|
|
16035
|
+
* `srcAddress` (the user), not the protocol asset manager.
|
|
16036
|
+
* @param {GetBalanceParams<StacksChainKey>} params - The chain key, user address, and token.
|
|
16037
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
16038
|
+
*/
|
|
16039
|
+
async getWalletBalance(params) {
|
|
16040
|
+
if (isNativeToken(params.srcChainKey, params.token)) {
|
|
16041
|
+
return this.getSTXBalance(params.srcAddress);
|
|
16042
|
+
}
|
|
16043
|
+
return this.readTokenBalance(params.token.address, params.srcAddress);
|
|
16044
|
+
}
|
|
16045
|
+
/**
|
|
16046
|
+
* Get the user's own wallet balances of multiple tokens on Stacks, in smallest units.
|
|
16047
|
+
* @param {GetBalancesParams<StacksChainKey>} params - The chain key, user address, and tokens.
|
|
16048
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
16049
|
+
*/
|
|
16050
|
+
async getWalletBalances(params) {
|
|
16051
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
16052
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
16053
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
16054
|
+
return collector.finish();
|
|
16055
|
+
}
|
|
15739
16056
|
/**
|
|
15740
16057
|
* Sends a message to the hub chain.
|
|
15741
16058
|
*/
|
|
@@ -15748,8 +16065,7 @@ var StacksSpokeService = class {
|
|
|
15748
16065
|
contractAddress: connectionAddress,
|
|
15749
16066
|
contractName: connectionName,
|
|
15750
16067
|
functionName: "send-message",
|
|
15751
|
-
functionArgs: [uintCV(dstRelayChainId), Cl.bufferFromHex(params.dstAddress), Cl.bufferFromHex(params.payload)]
|
|
15752
|
-
postConditionMode: PostConditionMode.Allow
|
|
16068
|
+
functionArgs: [uintCV(dstRelayChainId), Cl.bufferFromHex(params.dstAddress), Cl.bufferFromHex(params.payload)]
|
|
15753
16069
|
};
|
|
15754
16070
|
if (params.raw === true) {
|
|
15755
16071
|
const tx = await makeUnsignedContractCall({
|
|
@@ -15764,7 +16080,12 @@ var StacksSpokeService = class {
|
|
|
15764
16080
|
payload: bytesToHex(serializePayloadBytes(tx.payload))
|
|
15765
16081
|
};
|
|
15766
16082
|
}
|
|
15767
|
-
const txId = await params.walletProvider.sendTransaction(
|
|
16083
|
+
const txId = await params.walletProvider.sendTransaction({
|
|
16084
|
+
...reqData,
|
|
16085
|
+
// send-message moves no assets — deny with no conditions aborts if it ever tries.
|
|
16086
|
+
postConditionMode: PostConditionMode.Deny,
|
|
16087
|
+
postConditions: []
|
|
16088
|
+
});
|
|
15768
16089
|
return txId;
|
|
15769
16090
|
}
|
|
15770
16091
|
async waitForTransactionReceipt(params) {
|
|
@@ -16211,60 +16532,6 @@ var RadfiProvider = class {
|
|
|
16211
16532
|
}
|
|
16212
16533
|
};
|
|
16213
16534
|
|
|
16214
|
-
// src/shared/entities/btc/btc-utils.ts
|
|
16215
|
-
var BITCOIN_FEE_SAFETY_VBYTES = 20;
|
|
16216
|
-
function calcOpReturnOutputVbytes(payloadByteLength) {
|
|
16217
|
-
let scriptSize;
|
|
16218
|
-
if (payloadByteLength <= 75) {
|
|
16219
|
-
scriptSize = 3 + payloadByteLength;
|
|
16220
|
-
} else if (payloadByteLength <= 255) {
|
|
16221
|
-
scriptSize = 4 + payloadByteLength;
|
|
16222
|
-
} else {
|
|
16223
|
-
scriptSize = 5 + payloadByteLength;
|
|
16224
|
-
}
|
|
16225
|
-
const scriptLenVarint = scriptSize <= 252 ? 1 : 3;
|
|
16226
|
-
return 8 + scriptLenVarint + scriptSize;
|
|
16227
|
-
}
|
|
16228
|
-
function estimateBitcoinTxSize(inputCount, outputCount, addressType, opReturnOutputVbytes = 44) {
|
|
16229
|
-
let inputWeight;
|
|
16230
|
-
switch (addressType) {
|
|
16231
|
-
case "P2PKH":
|
|
16232
|
-
inputWeight = 148;
|
|
16233
|
-
break;
|
|
16234
|
-
case "P2SH":
|
|
16235
|
-
inputWeight = 91;
|
|
16236
|
-
break;
|
|
16237
|
-
case "P2TR":
|
|
16238
|
-
inputWeight = 58;
|
|
16239
|
-
break;
|
|
16240
|
-
default:
|
|
16241
|
-
inputWeight = 68;
|
|
16242
|
-
break;
|
|
16243
|
-
}
|
|
16244
|
-
return Math.ceil(
|
|
16245
|
-
10.5 + opReturnOutputVbytes + BITCOIN_FEE_SAFETY_VBYTES + inputCount * inputWeight + outputCount * 31
|
|
16246
|
-
);
|
|
16247
|
-
}
|
|
16248
|
-
function encodeBtcPayloadToBytes(payload) {
|
|
16249
|
-
return JSON.stringify({
|
|
16250
|
-
src_address: payload.src_address.toLowerCase(),
|
|
16251
|
-
data: payload.data.toLowerCase(),
|
|
16252
|
-
src_chain_id: payload.src_chain_id,
|
|
16253
|
-
dst_chain_id: payload.dst_chain_id,
|
|
16254
|
-
wallet_used: payload.wallet_used,
|
|
16255
|
-
timestamp: payload.timestamp,
|
|
16256
|
-
address_type: payload.address_type
|
|
16257
|
-
});
|
|
16258
|
-
}
|
|
16259
|
-
function normalizePsbtToBase64(signedPsbt) {
|
|
16260
|
-
const isHex2 = /^[0-9a-fA-F]+$/.test(signedPsbt);
|
|
16261
|
-
return isHex2 ? Buffer.from(signedPsbt, "hex").toString("base64") : signedPsbt;
|
|
16262
|
-
}
|
|
16263
|
-
function normalizeSignatureToBase64(signature) {
|
|
16264
|
-
const isHex2 = /^[0-9a-fA-F]+$/.test(signature);
|
|
16265
|
-
return isHex2 ? Buffer.from(signature, "hex").toString("base64") : signature;
|
|
16266
|
-
}
|
|
16267
|
-
|
|
16268
16535
|
// src/shared/services/spoke/BitcoinSpokeService.ts
|
|
16269
16536
|
initEccLib(ecc);
|
|
16270
16537
|
var BITCOIN_DEFAULT_FEE_RATE = 3;
|
|
@@ -16296,6 +16563,32 @@ var BitcoinSpokeService = class {
|
|
|
16296
16563
|
}
|
|
16297
16564
|
throw new Error("Token balance queries not yet implemented for non-BTC assets");
|
|
16298
16565
|
}
|
|
16566
|
+
/**
|
|
16567
|
+
* Get the user's own wallet balance of a token on Bitcoin, in satoshis. Only native BTC is
|
|
16568
|
+
* readable (summed from confirmed/unconfirmed UTXOs). Non-native spoke tokens are Rune ids
|
|
16569
|
+
* (`block:tx`), whose amounts the Esplora UTXO endpoint does not carry, so they resolve to 0n.
|
|
16570
|
+
* @param {GetBalanceParams<BitcoinChainKey>} params - The chain key, user address, and token.
|
|
16571
|
+
* @returns {Promise<bigint>} The balance in satoshis.
|
|
16572
|
+
*/
|
|
16573
|
+
async getWalletBalance(params) {
|
|
16574
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
16575
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
16576
|
+
const utxos = await this.fetchUTXOs(srcAddress);
|
|
16577
|
+
return BigInt(utxos.reduce((sum, utxo) => sum + utxo.value, 0));
|
|
16578
|
+
}
|
|
16579
|
+
return 0n;
|
|
16580
|
+
}
|
|
16581
|
+
/**
|
|
16582
|
+
* Get the user's own wallet balances of multiple tokens on Bitcoin, in satoshis.
|
|
16583
|
+
* @param {GetBalancesParams<BitcoinChainKey>} params - The chain key, user address, and tokens.
|
|
16584
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
16585
|
+
*/
|
|
16586
|
+
async getWalletBalances(params) {
|
|
16587
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
16588
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
16589
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
16590
|
+
return collector.finish();
|
|
16591
|
+
}
|
|
16299
16592
|
async fetchScriptPubKey(utxo) {
|
|
16300
16593
|
const txHex = await this.fetchRawTransaction(utxo.txid);
|
|
16301
16594
|
const tx = Transaction.fromHex(txHex);
|
|
@@ -16896,7 +17189,7 @@ function hexToBytes2(hex) {
|
|
|
16896
17189
|
const al = hl / 2;
|
|
16897
17190
|
if (hl % 2)
|
|
16898
17191
|
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
16899
|
-
const
|
|
17192
|
+
const array4 = new Uint8Array(al);
|
|
16900
17193
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
16901
17194
|
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
16902
17195
|
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
@@ -16904,9 +17197,9 @@ function hexToBytes2(hex) {
|
|
|
16904
17197
|
const char = hex[hi] + hex[hi + 1];
|
|
16905
17198
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
16906
17199
|
}
|
|
16907
|
-
|
|
17200
|
+
array4[ai] = n1 * 16 + n2;
|
|
16908
17201
|
}
|
|
16909
|
-
return
|
|
17202
|
+
return array4;
|
|
16910
17203
|
}
|
|
16911
17204
|
function concatBytes(...arrays) {
|
|
16912
17205
|
let sum = 0;
|
|
@@ -17536,22 +17829,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
17536
17829
|
const byte0 = Uint8Array.of(0);
|
|
17537
17830
|
const byte1 = Uint8Array.of(1);
|
|
17538
17831
|
const _maxDrbgIters = 1e3;
|
|
17539
|
-
let
|
|
17832
|
+
let v12 = u8n(hashLen);
|
|
17540
17833
|
let k = u8n(hashLen);
|
|
17541
17834
|
let i = 0;
|
|
17542
17835
|
const reset = () => {
|
|
17543
|
-
|
|
17836
|
+
v12.fill(1);
|
|
17544
17837
|
k.fill(0);
|
|
17545
17838
|
i = 0;
|
|
17546
17839
|
};
|
|
17547
|
-
const h = (...msgs) => hmacFn(k, concatBytes(
|
|
17840
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v12, ...msgs));
|
|
17548
17841
|
const reseed = (seed = NULL) => {
|
|
17549
17842
|
k = h(byte0, seed);
|
|
17550
|
-
|
|
17843
|
+
v12 = h();
|
|
17551
17844
|
if (seed.length === 0)
|
|
17552
17845
|
return;
|
|
17553
17846
|
k = h(byte1, seed);
|
|
17554
|
-
|
|
17847
|
+
v12 = h();
|
|
17555
17848
|
};
|
|
17556
17849
|
const gen = () => {
|
|
17557
17850
|
if (i++ >= _maxDrbgIters)
|
|
@@ -17559,10 +17852,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
17559
17852
|
let len = 0;
|
|
17560
17853
|
const out = [];
|
|
17561
17854
|
while (len < qByteLen) {
|
|
17562
|
-
|
|
17563
|
-
const sl =
|
|
17855
|
+
v12 = h();
|
|
17856
|
+
const sl = v12.slice();
|
|
17564
17857
|
out.push(sl);
|
|
17565
|
-
len +=
|
|
17858
|
+
len += v12.length;
|
|
17566
17859
|
}
|
|
17567
17860
|
return concatBytes(...out);
|
|
17568
17861
|
};
|
|
@@ -17577,18 +17870,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
|
17577
17870
|
};
|
|
17578
17871
|
return genUntil;
|
|
17579
17872
|
}
|
|
17580
|
-
function validateObject(
|
|
17581
|
-
if (!
|
|
17873
|
+
function validateObject(object6, fields = {}, optFields = {}) {
|
|
17874
|
+
if (!object6 || typeof object6 !== "object")
|
|
17582
17875
|
throw new Error("expected valid options object");
|
|
17583
17876
|
function checkField(fieldName, expectedType, isOpt) {
|
|
17584
|
-
const val =
|
|
17877
|
+
const val = object6[fieldName];
|
|
17585
17878
|
if (isOpt && val === void 0)
|
|
17586
17879
|
return;
|
|
17587
17880
|
const current = typeof val;
|
|
17588
17881
|
if (current !== expectedType || val === null)
|
|
17589
17882
|
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
17590
17883
|
}
|
|
17591
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k,
|
|
17884
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v12]) => checkField(k, v12, isOpt));
|
|
17592
17885
|
iter(fields, false);
|
|
17593
17886
|
iter(optFields, true);
|
|
17594
17887
|
}
|
|
@@ -17627,12 +17920,12 @@ function pow2(x, power, modulo) {
|
|
|
17627
17920
|
}
|
|
17628
17921
|
return res;
|
|
17629
17922
|
}
|
|
17630
|
-
function invert(
|
|
17631
|
-
if (
|
|
17923
|
+
function invert(number6, modulo) {
|
|
17924
|
+
if (number6 === _0n2)
|
|
17632
17925
|
throw new Error("invert: expected non-zero number");
|
|
17633
17926
|
if (modulo <= _0n2)
|
|
17634
17927
|
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
17635
|
-
let a = mod(
|
|
17928
|
+
let a = mod(number6, modulo);
|
|
17636
17929
|
let b = modulo;
|
|
17637
17930
|
let x = _0n2, u = _1n2;
|
|
17638
17931
|
while (a !== _0n2) {
|
|
@@ -17659,9 +17952,9 @@ function sqrt3mod4(Fp, n) {
|
|
|
17659
17952
|
function sqrt5mod8(Fp, n) {
|
|
17660
17953
|
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
17661
17954
|
const n2 = Fp.mul(n, _2n);
|
|
17662
|
-
const
|
|
17663
|
-
const nv = Fp.mul(n,
|
|
17664
|
-
const i = Fp.mul(Fp.mul(nv, _2n),
|
|
17955
|
+
const v12 = Fp.pow(n2, p5div8);
|
|
17956
|
+
const nv = Fp.mul(n, v12);
|
|
17957
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v12);
|
|
17665
17958
|
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
17666
17959
|
assertIsSquare(Fp, root, n);
|
|
17667
17960
|
return root;
|
|
@@ -18243,9 +18536,9 @@ function edwards(params, extraOpts = {}) {
|
|
|
18243
18536
|
validateObject(extraOpts, {}, { uvRatio: "function" });
|
|
18244
18537
|
const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
|
|
18245
18538
|
const modP = (n) => Fp.create(n);
|
|
18246
|
-
const uvRatio2 = extraOpts.uvRatio || ((u,
|
|
18539
|
+
const uvRatio2 = extraOpts.uvRatio || ((u, v12) => {
|
|
18247
18540
|
try {
|
|
18248
|
-
return { isValid: true, value: Fp.sqrt(Fp.div(u,
|
|
18541
|
+
return { isValid: true, value: Fp.sqrt(Fp.div(u, v12)) };
|
|
18249
18542
|
} catch (e) {
|
|
18250
18543
|
return { isValid: false, value: _0n4 };
|
|
18251
18544
|
}
|
|
@@ -18341,8 +18634,8 @@ function edwards(params, extraOpts = {}) {
|
|
|
18341
18634
|
aInRange("point.y", y, _0n4, max);
|
|
18342
18635
|
const y2 = modP(y * y);
|
|
18343
18636
|
const u = modP(y2 - _1n4);
|
|
18344
|
-
const
|
|
18345
|
-
let { isValid, value: x } = uvRatio2(u,
|
|
18637
|
+
const v12 = modP(d * y2 - a);
|
|
18638
|
+
let { isValid, value: x } = uvRatio2(u, v12);
|
|
18346
18639
|
if (!isValid)
|
|
18347
18640
|
throw new Error("bad point: invalid y coordinate");
|
|
18348
18641
|
const isXOdd = (x & _1n4) === _1n4;
|
|
@@ -18682,13 +18975,13 @@ function adjustScalarBytes(bytes) {
|
|
|
18682
18975
|
return bytes;
|
|
18683
18976
|
}
|
|
18684
18977
|
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
|
|
18685
|
-
function uvRatio(u,
|
|
18978
|
+
function uvRatio(u, v12) {
|
|
18686
18979
|
const P = ed25519_CURVE_p;
|
|
18687
|
-
const v32 = mod(
|
|
18688
|
-
const v72 = mod(v32 * v32 *
|
|
18980
|
+
const v32 = mod(v12 * v12 * v12, P);
|
|
18981
|
+
const v72 = mod(v32 * v32 * v12, P);
|
|
18689
18982
|
const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
|
|
18690
18983
|
let x = mod(u * v32 * pow, P);
|
|
18691
|
-
const vx2 = mod(
|
|
18984
|
+
const vx2 = mod(v12 * x * x, P);
|
|
18692
18985
|
const root1 = x;
|
|
18693
18986
|
const root2 = mod(x * ED25519_SQRT_M1, P);
|
|
18694
18987
|
const useRoot1 = vx2 === u;
|
|
@@ -19019,7 +19312,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
|
|
|
19019
19312
|
return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
|
|
19020
19313
|
}
|
|
19021
19314
|
function findSeatPriceForProtocolBefore49(validators, numSeats) {
|
|
19022
|
-
const stakes = validators.map((
|
|
19315
|
+
const stakes = validators.map((v12) => BigInt(v12.stake)).sort(sortBigIntAsc);
|
|
19023
19316
|
const num = BigInt(numSeats);
|
|
19024
19317
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
19025
19318
|
if (stakesSum < num) {
|
|
@@ -19048,7 +19341,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
|
|
|
19048
19341
|
if (minimumStakeRatio.length != 2) {
|
|
19049
19342
|
throw Error("minimumStakeRatio should have 2 elements");
|
|
19050
19343
|
}
|
|
19051
|
-
const stakes = validators.map((
|
|
19344
|
+
const stakes = validators.map((v12) => BigInt(v12.stake)).sort(sortBigIntAsc);
|
|
19052
19345
|
const stakesSum = stakes.reduce((a, b) => a + b);
|
|
19053
19346
|
if (validators.length < maxNumberOfSeats) {
|
|
19054
19347
|
return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
|
|
@@ -19220,10 +19513,10 @@ var DER = {
|
|
|
19220
19513
|
if (length < 128)
|
|
19221
19514
|
throw new E("tlv.decode(long): not minimal encoding");
|
|
19222
19515
|
}
|
|
19223
|
-
const
|
|
19224
|
-
if (
|
|
19516
|
+
const v12 = data.subarray(pos, pos + length);
|
|
19517
|
+
if (v12.length !== length)
|
|
19225
19518
|
throw new E("tlv.decode: wrong value length");
|
|
19226
|
-
return { v:
|
|
19519
|
+
return { v: v12, l: data.subarray(pos + length) };
|
|
19227
19520
|
}
|
|
19228
19521
|
},
|
|
19229
19522
|
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
@@ -19791,9 +20084,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
19791
20084
|
extraEntropy: false
|
|
19792
20085
|
};
|
|
19793
20086
|
const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
|
|
19794
|
-
function isBiggerThanHalfOrder(
|
|
20087
|
+
function isBiggerThanHalfOrder(number6) {
|
|
19795
20088
|
const HALF = CURVE_ORDER >> _1n6;
|
|
19796
|
-
return
|
|
20089
|
+
return number6 > HALF;
|
|
19797
20090
|
}
|
|
19798
20091
|
function validateRS(title, num) {
|
|
19799
20092
|
if (!Fn.isValidNot0(num))
|
|
@@ -19976,8 +20269,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
|
19976
20269
|
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
19977
20270
|
if (R.is0())
|
|
19978
20271
|
return false;
|
|
19979
|
-
const
|
|
19980
|
-
return
|
|
20272
|
+
const v12 = Fn.create(R.x);
|
|
20273
|
+
return v12 === r;
|
|
19981
20274
|
} catch (e) {
|
|
19982
20275
|
return false;
|
|
19983
20276
|
}
|
|
@@ -22842,6 +23135,39 @@ var NearSpokeService = class {
|
|
|
22842
23135
|
}
|
|
22843
23136
|
return BigInt(bal);
|
|
22844
23137
|
}
|
|
23138
|
+
/**
|
|
23139
|
+
* Get the user's own wallet balance of a token on NEAR, in smallest units (yoctoNEAR for the
|
|
23140
|
+
* native coin). Native NEAR via the account's `viewAccount().amount`; NEP-141 tokens via the
|
|
23141
|
+
* token contract's `ft_balance_of` view. Reads the balance held by `srcAddress` (the user
|
|
23142
|
+
* wallet), not the protocol asset manager. Uses this service's own configured RPC provider.
|
|
23143
|
+
* @param {GetBalanceParams<NearChainKey>} params - The chain key, user address, and token.
|
|
23144
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
23145
|
+
*/
|
|
23146
|
+
async getWalletBalance(params) {
|
|
23147
|
+
if (isNativeToken(params.srcChainKey, params.token)) {
|
|
23148
|
+
const account = await this.rpcProvider.viewAccount({ accountId: params.srcAddress });
|
|
23149
|
+
return BigInt(account.amount);
|
|
23150
|
+
}
|
|
23151
|
+
const bal = await this.queryContract(params.token.address, "ft_balance_of", {
|
|
23152
|
+
account_id: params.srcAddress
|
|
23153
|
+
});
|
|
23154
|
+
if (typeof bal !== "string") {
|
|
23155
|
+
throw new Error("[NearSpokeService.getWalletBalance] Failed to get balance. Unexpected response type.");
|
|
23156
|
+
}
|
|
23157
|
+
return BigInt(bal);
|
|
23158
|
+
}
|
|
23159
|
+
/**
|
|
23160
|
+
* Get the user's own wallet balances of multiple tokens on NEAR, in smallest units. Fans out
|
|
23161
|
+
* over {@link getWalletBalance}, keyed by `token.address`.
|
|
23162
|
+
* @param {GetBalancesParams<NearChainKey>} params - The chain key, user address, and tokens.
|
|
23163
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
23164
|
+
*/
|
|
23165
|
+
async getWalletBalances(params) {
|
|
23166
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
23167
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
23168
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
23169
|
+
return collector.finish();
|
|
23170
|
+
}
|
|
22845
23171
|
/**
|
|
22846
23172
|
* Whether `accountId` is storage-registered on a NEP-141 `token` contract. NEP-141 requires an
|
|
22847
23173
|
* account to pay a one-time storage bond before it can receive (hold a balance of) the token, so
|
|
@@ -23632,7 +23958,9 @@ var SonicSpokeService = class {
|
|
|
23632
23958
|
if (params.raw === true) {
|
|
23633
23959
|
return rawTx;
|
|
23634
23960
|
}
|
|
23635
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
23961
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
23962
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
23963
|
+
});
|
|
23636
23964
|
}
|
|
23637
23965
|
static async createSwapIntent(params) {
|
|
23638
23966
|
const { createIntentParams, creatorHubWalletAddress, solverConfig: solverConfig2, fee, hubProvider } = params;
|
|
@@ -23682,7 +24010,9 @@ var SonicSpokeService = class {
|
|
|
23682
24010
|
return [rawTx, intent, feeAmount, txData.data];
|
|
23683
24011
|
}
|
|
23684
24012
|
return [
|
|
23685
|
-
await params.walletProvider.sendTransaction(rawTx
|
|
24013
|
+
await params.walletProvider.sendTransaction(rawTx, {
|
|
24014
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
24015
|
+
}),
|
|
23686
24016
|
intent,
|
|
23687
24017
|
feeAmount,
|
|
23688
24018
|
txData.data
|
|
@@ -23701,6 +24031,76 @@ var SonicSpokeService = class {
|
|
|
23701
24031
|
args: [params.token]
|
|
23702
24032
|
});
|
|
23703
24033
|
}
|
|
24034
|
+
/**
|
|
24035
|
+
* Get the user's own wallet balance of a token on the hub (Sonic) chain, in smallest units.
|
|
24036
|
+
* Native coin via `eth_getBalance`; erc20 via `balanceOf`.
|
|
24037
|
+
* @param {GetBalanceParams<SonicChainKey>} params - The chain key, user address, and token.
|
|
24038
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
24039
|
+
*/
|
|
24040
|
+
async getWalletBalance(params) {
|
|
24041
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
24042
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
24043
|
+
return this.publicClient.getBalance({ address: srcAddress });
|
|
24044
|
+
}
|
|
24045
|
+
const balance = await this.publicClient.readContract({
|
|
24046
|
+
address: token.address,
|
|
24047
|
+
abi: erc20Abi$1,
|
|
24048
|
+
functionName: "balanceOf",
|
|
24049
|
+
args: [srcAddress]
|
|
24050
|
+
});
|
|
24051
|
+
return balance ?? 0n;
|
|
24052
|
+
}
|
|
24053
|
+
/**
|
|
24054
|
+
* Get the user's own wallet balances of multiple tokens on the hub (Sonic) chain, in smallest
|
|
24055
|
+
* units. Non-native tokens are batched via multicall3 when the chain supports it, otherwise
|
|
24056
|
+
* read in parallel.
|
|
24057
|
+
* @param {GetBalancesParams<SonicChainKey>} params - The chain key, user address, and tokens.
|
|
24058
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
24059
|
+
*/
|
|
24060
|
+
async getWalletBalances(params) {
|
|
24061
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
24062
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
24063
|
+
const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
24064
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
24065
|
+
await settleWalletBalances(
|
|
24066
|
+
collector,
|
|
24067
|
+
nativeTokens,
|
|
24068
|
+
(token) => this.getWalletBalance({ srcChainKey, srcAddress, token })
|
|
24069
|
+
);
|
|
24070
|
+
if (nonNativeTokens.length === 0) {
|
|
24071
|
+
return collector.finish();
|
|
24072
|
+
}
|
|
24073
|
+
if (getEvmViemChain(srcChainKey).contracts?.multicall3) {
|
|
24074
|
+
const results = await this.publicClient.multicall({
|
|
24075
|
+
contracts: nonNativeTokens.map((token) => ({
|
|
24076
|
+
abi: erc20Abi$1,
|
|
24077
|
+
address: token.address,
|
|
24078
|
+
functionName: "balanceOf",
|
|
24079
|
+
args: [srcAddress]
|
|
24080
|
+
}))
|
|
24081
|
+
});
|
|
24082
|
+
nonNativeTokens.forEach((token, index) => {
|
|
24083
|
+
const result = results[index];
|
|
24084
|
+
if (result?.status === "success") {
|
|
24085
|
+
collector.ok(token.address, BigInt(result.result));
|
|
24086
|
+
} else {
|
|
24087
|
+
collector.fail(token.address, result?.error ?? new Error(`missing multicall result for ${token.address}`));
|
|
24088
|
+
}
|
|
24089
|
+
});
|
|
24090
|
+
return collector.finish();
|
|
24091
|
+
}
|
|
24092
|
+
await settleWalletBalances(
|
|
24093
|
+
collector,
|
|
24094
|
+
nonNativeTokens,
|
|
24095
|
+
(token) => this.publicClient.readContract({
|
|
24096
|
+
address: token.address,
|
|
24097
|
+
abi: erc20Abi$1,
|
|
24098
|
+
functionName: "balanceOf",
|
|
24099
|
+
args: [srcAddress]
|
|
24100
|
+
})
|
|
24101
|
+
);
|
|
24102
|
+
return collector.finish();
|
|
24103
|
+
}
|
|
23704
24104
|
/**
|
|
23705
24105
|
* Execute a batch of contract calls through the Sonic wallet contract.
|
|
23706
24106
|
* @param {Hex} payload - The encoded payload containing the calls array
|
|
@@ -23743,7 +24143,9 @@ var SonicSpokeService = class {
|
|
|
23743
24143
|
if (params.raw === true) {
|
|
23744
24144
|
return rawTx;
|
|
23745
24145
|
}
|
|
23746
|
-
return params.walletProvider.sendTransaction(rawTx
|
|
24146
|
+
return params.walletProvider.sendTransaction(rawTx, {
|
|
24147
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
24148
|
+
});
|
|
23747
24149
|
}
|
|
23748
24150
|
};
|
|
23749
24151
|
async function toMystenTransaction(txn) {
|
|
@@ -23799,8 +24201,8 @@ var SuiGrpcTransport = class {
|
|
|
23799
24201
|
this.endpoint = endpoint;
|
|
23800
24202
|
this.client = new SuiGrpcClient({ network: "mainnet", baseUrl: endpoint });
|
|
23801
24203
|
}
|
|
23802
|
-
async getCoins(owner, coinType, limit = DEFAULT_GET_COINS_LIMIT) {
|
|
23803
|
-
const response = await this.client.core.listCoins({ owner, coinType, limit });
|
|
24204
|
+
async getCoins(owner, coinType, limit = DEFAULT_GET_COINS_LIMIT, cursor) {
|
|
24205
|
+
const response = await this.client.core.listCoins({ owner, coinType, limit, cursor: cursor ?? void 0 });
|
|
23804
24206
|
return toSuiPaginatedCoins(response, coinType);
|
|
23805
24207
|
}
|
|
23806
24208
|
async simulate(tx, sender) {
|
|
@@ -23828,16 +24230,16 @@ var SuiGrpcTransport = class {
|
|
|
23828
24230
|
return effects.gasUsed;
|
|
23829
24231
|
}
|
|
23830
24232
|
async fetchLatestPackageId(objectId) {
|
|
23831
|
-
let
|
|
24233
|
+
let object6;
|
|
23832
24234
|
try {
|
|
23833
|
-
({ object:
|
|
24235
|
+
({ object: object6 } = await this.client.core.getObject({ objectId, include: { json: true } }));
|
|
23834
24236
|
} catch (error) {
|
|
23835
24237
|
throw new Error("Failed to fetch asset manager id", { cause: error });
|
|
23836
24238
|
}
|
|
23837
|
-
if (!
|
|
24239
|
+
if (!object6) {
|
|
23838
24240
|
throw new Error("Asset manager id not found (no data)");
|
|
23839
24241
|
}
|
|
23840
|
-
const fields =
|
|
24242
|
+
const fields = object6.json;
|
|
23841
24243
|
if (!fields) {
|
|
23842
24244
|
throw new Error("Asset manager id not found (not a move object)");
|
|
23843
24245
|
}
|
|
@@ -24040,6 +24442,42 @@ var SuiSpokeService = class {
|
|
|
24040
24442
|
const str_u64 = bcs.U64.parse(Uint8Array.from(val));
|
|
24041
24443
|
return BigInt(str_u64);
|
|
24042
24444
|
}
|
|
24445
|
+
/**
|
|
24446
|
+
* Get the user's own wallet balance of a token on Sui, in smallest units. Unlike {@link getDeposit}
|
|
24447
|
+
* (which reads the protocol asset manager holding), this reads the balance held by `params.srcAddress`
|
|
24448
|
+
* itself. Native SUI is read via its canonical `0x2::sui::SUI` coin type; other coins use the token's
|
|
24449
|
+
* Sui coinType (`token.address`).
|
|
24450
|
+
* @param {GetBalanceParams<SuiChainKey>} params - The chain key, user address, and token.
|
|
24451
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
24452
|
+
*/
|
|
24453
|
+
async getWalletBalance(params) {
|
|
24454
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
24455
|
+
let coinType = isNativeToken(srcChainKey, token) ? "0x2::sui::SUI" : token.address;
|
|
24456
|
+
if (coinType === "0x03917a812fe4a6d6bc779c5ab53f8a80ba741f8af04121193fc44e0f662e2ceb::balanced_dollar::BALANCED_DOLLAR") {
|
|
24457
|
+
coinType = "0x3917a812fe4a6d6bc779c5ab53f8a80ba741f8af04121193fc44e0f662e2ceb::balanced_dollar::BALANCED_DOLLAR";
|
|
24458
|
+
}
|
|
24459
|
+
let total = 0n;
|
|
24460
|
+
let cursor;
|
|
24461
|
+
do {
|
|
24462
|
+
const page = await this.transport.getCoins(srcAddress, coinType, void 0, cursor);
|
|
24463
|
+
for (const coin of page.data) {
|
|
24464
|
+
total += BigInt(coin.balance);
|
|
24465
|
+
}
|
|
24466
|
+
cursor = page.hasNextPage ? page.nextCursor : void 0;
|
|
24467
|
+
} while (cursor);
|
|
24468
|
+
return total;
|
|
24469
|
+
}
|
|
24470
|
+
/**
|
|
24471
|
+
* Get the user's own wallet balances of multiple tokens on Sui, in smallest units.
|
|
24472
|
+
* @param {GetBalancesParams<SuiChainKey>} params - The chain key, user address, and tokens.
|
|
24473
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
24474
|
+
*/
|
|
24475
|
+
async getWalletBalances(params) {
|
|
24476
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
24477
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
24478
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
24479
|
+
return collector.finish();
|
|
24480
|
+
}
|
|
24043
24481
|
/**
|
|
24044
24482
|
* Fetch the asset manager config from the spoke chain.
|
|
24045
24483
|
* @param {SuiChainKey} chainId - The Sui chain key.
|
|
@@ -24186,6 +24624,11 @@ var CustomSorobanServer = class extends rpc.Server {
|
|
|
24186
24624
|
return response.json().then((json) => json.result);
|
|
24187
24625
|
}
|
|
24188
24626
|
};
|
|
24627
|
+
var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
|
|
24628
|
+
function parseXlmBalanceToStroops(balanceStr) {
|
|
24629
|
+
const [whole = "0", frac = ""] = balanceStr.split(".");
|
|
24630
|
+
return BigInt(whole + frac.padEnd(7, "0").slice(0, 7));
|
|
24631
|
+
}
|
|
24189
24632
|
var CustomStellarAccount = class {
|
|
24190
24633
|
accountId;
|
|
24191
24634
|
sequenceNumber;
|
|
@@ -24224,7 +24667,7 @@ var CustomStellarAccount = class {
|
|
|
24224
24667
|
}
|
|
24225
24668
|
};
|
|
24226
24669
|
var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
|
|
24227
|
-
var StellarSpokeService = class {
|
|
24670
|
+
var StellarSpokeService = class _StellarSpokeService {
|
|
24228
24671
|
config;
|
|
24229
24672
|
chainConfig;
|
|
24230
24673
|
server;
|
|
@@ -24265,6 +24708,109 @@ var StellarSpokeService = class {
|
|
|
24265
24708
|
}
|
|
24266
24709
|
throw new Error("result undefined");
|
|
24267
24710
|
}
|
|
24711
|
+
/**
|
|
24712
|
+
* Get the user's own wallet balance of a token on Stellar, in smallest units. Native XLM returns
|
|
24713
|
+
* the spendable amount (total minus the minimum reserve and selling liabilities) via Horizon;
|
|
24714
|
+
* other assets return the Soroban token contract's `balance` for the user.
|
|
24715
|
+
* @param {GetBalanceParams<StellarChainKey>} params - The chain key, user address, and token.
|
|
24716
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
24717
|
+
*/
|
|
24718
|
+
async getWalletBalance(params) {
|
|
24719
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
24720
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
24721
|
+
return _StellarSpokeService.spendableXlmStroops(await this.server.loadAccount(srcAddress));
|
|
24722
|
+
}
|
|
24723
|
+
const [network, sourceAccount] = await Promise.all([
|
|
24724
|
+
this.sorobanServer.getNetwork(),
|
|
24725
|
+
this.sorobanServer.getAccount(srcAddress)
|
|
24726
|
+
]);
|
|
24727
|
+
return this.simulateTokenBalance(
|
|
24728
|
+
token.address,
|
|
24729
|
+
srcAddress,
|
|
24730
|
+
new CustomStellarAccount({ account_id: sourceAccount.accountId(), sequence: sourceAccount.sequenceNumber() }),
|
|
24731
|
+
network.passphrase
|
|
24732
|
+
);
|
|
24733
|
+
}
|
|
24734
|
+
/**
|
|
24735
|
+
* Spendable XLM in stroops: the account's native balance minus its minimum reserve and selling
|
|
24736
|
+
* liabilities. Reporting the raw balance would let a user try to spend reserves the network
|
|
24737
|
+
* refuses to release.
|
|
24738
|
+
*/
|
|
24739
|
+
static spendableXlmStroops(account) {
|
|
24740
|
+
const nativeBalance = account.balances.find(
|
|
24741
|
+
(balance) => balance.asset_type === "native"
|
|
24742
|
+
);
|
|
24743
|
+
if (!nativeBalance) {
|
|
24744
|
+
return 0n;
|
|
24745
|
+
}
|
|
24746
|
+
const rawStroops = parseXlmBalanceToStroops(nativeBalance.balance);
|
|
24747
|
+
const sellingLiabilitiesStroops = nativeBalance.selling_liabilities ? parseXlmBalanceToStroops(nativeBalance.selling_liabilities) : 0n;
|
|
24748
|
+
const reserveCount = Math.max(0, 2 + account.subentry_count + account.num_sponsoring - account.num_sponsored);
|
|
24749
|
+
const minStroops = BigInt(reserveCount) * STELLAR_BASE_RESERVE_STROOPS + sellingLiabilitiesStroops;
|
|
24750
|
+
return rawStroops > minStroops ? rawStroops - minStroops : 0n;
|
|
24751
|
+
}
|
|
24752
|
+
/**
|
|
24753
|
+
* Simulate a Soroban token `balance` call. Takes the network passphrase and source account so a
|
|
24754
|
+
* batch can fetch them once; `getAccountClone()` hands each builder its own `Account`, because
|
|
24755
|
+
* `TransactionBuilder.build()` increments the source's sequence number and concurrent builders
|
|
24756
|
+
* would otherwise interleave on a shared one.
|
|
24757
|
+
*/
|
|
24758
|
+
async simulateTokenBalance(tokenAddress, srcAddress, account, networkPassphrase) {
|
|
24759
|
+
const contract = new Contract(tokenAddress);
|
|
24760
|
+
const tx = new TransactionBuilder(account.getAccountClone(), { fee: this.baseFee, networkPassphrase }).addOperation(contract.call("balance", nativeToScVal(srcAddress, { type: "address" }))).setTimeout(TimeoutInfinite).build();
|
|
24761
|
+
const result = await this.sorobanServer.simulateTransaction(tx);
|
|
24762
|
+
if (!rpc.Api.isSimulationSuccess(result)) {
|
|
24763
|
+
throw new Error("Failed to simulate transaction");
|
|
24764
|
+
}
|
|
24765
|
+
if (!result.result) {
|
|
24766
|
+
throw new Error("Failed to read token balance: simulation returned no result");
|
|
24767
|
+
}
|
|
24768
|
+
return scValToBigInt(result.result.retval);
|
|
24769
|
+
}
|
|
24770
|
+
/**
|
|
24771
|
+
* Get the user's own wallet balances of multiple tokens on Stellar, in smallest units.
|
|
24772
|
+
*
|
|
24773
|
+
* The network passphrase and the source account are the same for every token, so they are
|
|
24774
|
+
* fetched once per batch instead of once per token — and only when a partition actually needs
|
|
24775
|
+
* them, so an all-native request issues no Soroban calls at all.
|
|
24776
|
+
* @param {GetBalancesParams<StellarChainKey>} params - The chain key, user address, and tokens.
|
|
24777
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
24778
|
+
*/
|
|
24779
|
+
async getWalletBalances(params) {
|
|
24780
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
24781
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
24782
|
+
const sorobanTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
24783
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
24784
|
+
if (nativeTokens.length > 0) {
|
|
24785
|
+
try {
|
|
24786
|
+
const spendable = _StellarSpokeService.spendableXlmStroops(await this.server.loadAccount(srcAddress));
|
|
24787
|
+
for (const token of nativeTokens) {
|
|
24788
|
+
collector.ok(token.address, spendable);
|
|
24789
|
+
}
|
|
24790
|
+
} catch (error) {
|
|
24791
|
+
for (const token of nativeTokens) {
|
|
24792
|
+
collector.fail(token.address, error);
|
|
24793
|
+
}
|
|
24794
|
+
}
|
|
24795
|
+
}
|
|
24796
|
+
if (sorobanTokens.length === 0) {
|
|
24797
|
+
return collector.finish();
|
|
24798
|
+
}
|
|
24799
|
+
const [network, sourceAccount] = await Promise.all([
|
|
24800
|
+
this.sorobanServer.getNetwork(),
|
|
24801
|
+
this.sorobanServer.getAccount(srcAddress)
|
|
24802
|
+
]);
|
|
24803
|
+
const account = new CustomStellarAccount({
|
|
24804
|
+
account_id: sourceAccount.accountId(),
|
|
24805
|
+
sequence: sourceAccount.sequenceNumber()
|
|
24806
|
+
});
|
|
24807
|
+
await settleWalletBalances(
|
|
24808
|
+
collector,
|
|
24809
|
+
sorobanTokens,
|
|
24810
|
+
(token) => this.simulateTokenBalance(token.address, srcAddress, account, network.passphrase)
|
|
24811
|
+
);
|
|
24812
|
+
return collector.finish();
|
|
24813
|
+
}
|
|
24268
24814
|
async buildPriorityStellarTransaction(account, network, operation) {
|
|
24269
24815
|
const simulationForFee = await this.sorobanServer.simulateTransaction(
|
|
24270
24816
|
new TransactionBuilder(account.getAccountClone(), {
|
|
@@ -24838,6 +25384,48 @@ var SolanaSpokeService = class _SolanaSpokeService {
|
|
|
24838
25384
|
const tokenAccount = await _SolanaSpokeService.getTokenAccountBalance(this.connection, vaultToken.pda.toBase58());
|
|
24839
25385
|
return BigInt(tokenAccount.value.amount);
|
|
24840
25386
|
}
|
|
25387
|
+
/**
|
|
25388
|
+
* Get the user's own wallet balance of a token on Solana, in smallest units. Native SOL via
|
|
25389
|
+
* `getBalance`; SPL via the associated token account. The mint may belong to the legacy SPL
|
|
25390
|
+
* Token program or Token-2022 (e.g. xStock tokens), which derive different ATAs, so both
|
|
25391
|
+
* candidate ATAs are read in one call and the existing one is used.
|
|
25392
|
+
* @param {GetBalanceParams<SolanaChainKey>} params - The chain key, user address, and token.
|
|
25393
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
25394
|
+
*/
|
|
25395
|
+
async getWalletBalance(params) {
|
|
25396
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
25397
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
25398
|
+
return BigInt(await _SolanaSpokeService.getBalance(this.connection, srcAddress));
|
|
25399
|
+
}
|
|
25400
|
+
const owner = new PublicKey(srcAddress);
|
|
25401
|
+
const mint = new PublicKey(token.address);
|
|
25402
|
+
const candidates = [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID].map((programId) => ({
|
|
25403
|
+
programId,
|
|
25404
|
+
ata: getAssociatedTokenAddressSync(mint, owner, true, programId)
|
|
25405
|
+
}));
|
|
25406
|
+
const accounts = await this.connection.getMultipleAccountsInfo(candidates.map((c) => c.ata));
|
|
25407
|
+
let balance = 0n;
|
|
25408
|
+
for (const [i, candidate] of candidates.entries()) {
|
|
25409
|
+
const info = accounts[i];
|
|
25410
|
+
if (!info) continue;
|
|
25411
|
+
try {
|
|
25412
|
+
balance += unpackAccount(candidate.ata, info, candidate.programId).amount;
|
|
25413
|
+
} catch {
|
|
25414
|
+
}
|
|
25415
|
+
}
|
|
25416
|
+
return balance;
|
|
25417
|
+
}
|
|
25418
|
+
/**
|
|
25419
|
+
* Get the user's own wallet balances of multiple tokens on Solana, in smallest units.
|
|
25420
|
+
* @param {GetBalancesParams<SolanaChainKey>} params - The chain key, user address, and tokens.
|
|
25421
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
25422
|
+
*/
|
|
25423
|
+
async getWalletBalances(params) {
|
|
25424
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
25425
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
25426
|
+
await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
|
|
25427
|
+
return collector.finish();
|
|
25428
|
+
}
|
|
24841
25429
|
/**
|
|
24842
25430
|
* Sends a message to the hub chain.
|
|
24843
25431
|
* @param dstChainKey - The chain key of the hub chain.
|
|
@@ -25059,8 +25647,84 @@ var IconSpokeService = class {
|
|
|
25059
25647
|
async getDeposit(params) {
|
|
25060
25648
|
const { token, srcChainKey } = params;
|
|
25061
25649
|
const transaction = new CallBuilder().to(token).method("balanceOf").params({ _owner: this.config.getChainConfig(srcChainKey).addresses.assetManager }).build();
|
|
25650
|
+
return this.readIrc2Balance(transaction);
|
|
25651
|
+
}
|
|
25652
|
+
/**
|
|
25653
|
+
* Read an int-returning SCORE call. `iconService.call(...)` registers no result converter, so
|
|
25654
|
+
* `execute()` resolves the raw JSON-RPC `result` — a bare hex string for an int, not `{ value }`.
|
|
25655
|
+
*/
|
|
25656
|
+
async readIrc2Balance(transaction) {
|
|
25062
25657
|
const result = await this.iconService.call(transaction).execute();
|
|
25063
|
-
|
|
25658
|
+
if (typeof result !== "string") {
|
|
25659
|
+
throw new Error(`[IconSpokeService] Unexpected balanceOf response: ${JSON.stringify(result)}`);
|
|
25660
|
+
}
|
|
25661
|
+
return hexToBigInt(result);
|
|
25662
|
+
}
|
|
25663
|
+
/**
|
|
25664
|
+
* Get the user's own wallet balance of a token on ICON, in smallest units. Native ICX is read
|
|
25665
|
+
* via `iconService.getBalance`; IRC-2 tokens via a `balanceOf(_owner)` call on the token contract.
|
|
25666
|
+
* @param {GetBalanceParams<IconChainKey>} params - The chain key, user address, and token.
|
|
25667
|
+
* @returns {Promise<bigint>} The token balance in smallest units.
|
|
25668
|
+
*/
|
|
25669
|
+
async getWalletBalance(params) {
|
|
25670
|
+
const { srcChainKey, srcAddress, token } = params;
|
|
25671
|
+
if (isNativeToken(srcChainKey, token)) {
|
|
25672
|
+
const balance = await this.iconService.getBalance(srcAddress).execute();
|
|
25673
|
+
return BigInt(balance.toFixed());
|
|
25674
|
+
}
|
|
25675
|
+
const transaction = new CallBuilder().to(token.address).method("balanceOf").params({ _owner: srcAddress }).build();
|
|
25676
|
+
return this.readIrc2Balance(transaction);
|
|
25677
|
+
}
|
|
25678
|
+
/**
|
|
25679
|
+
* Get the user's own wallet balances of multiple tokens on ICON, in smallest units. Native ICX
|
|
25680
|
+
* is read via `iconService.getBalance`; IRC-2 balances are batched into a single `tryAggregate`
|
|
25681
|
+
* multicall so every `balanceOf(_owner)` read shares one round-trip.
|
|
25682
|
+
* @param {GetBalancesParams<IconChainKey>} params - The chain key, user address, and tokens.
|
|
25683
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
25684
|
+
*/
|
|
25685
|
+
async getWalletBalances(params) {
|
|
25686
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
25687
|
+
const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
|
|
25688
|
+
const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
|
|
25689
|
+
const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
|
|
25690
|
+
if (nativeTokens.length > 0) {
|
|
25691
|
+
try {
|
|
25692
|
+
const balance = await this.iconService.getBalance(srcAddress).execute();
|
|
25693
|
+
for (const token of nativeTokens) {
|
|
25694
|
+
collector.ok(token.address, BigInt(balance.toFixed()));
|
|
25695
|
+
}
|
|
25696
|
+
} catch (error) {
|
|
25697
|
+
for (const token of nativeTokens) {
|
|
25698
|
+
collector.fail(token.address, error);
|
|
25699
|
+
}
|
|
25700
|
+
}
|
|
25701
|
+
}
|
|
25702
|
+
if (nonNativeTokens.length === 0) {
|
|
25703
|
+
return collector.finish();
|
|
25704
|
+
}
|
|
25705
|
+
const multicallAddress = "cxa4aa9185e23558cff990f494c1fd2845f6cbf741";
|
|
25706
|
+
const calls = nonNativeTokens.map((token) => ({
|
|
25707
|
+
target: token.address,
|
|
25708
|
+
method: "balanceOf",
|
|
25709
|
+
params: [srcAddress]
|
|
25710
|
+
}));
|
|
25711
|
+
const transaction = new CallBuilder().to(multicallAddress).method("tryAggregate").params({ requireSuccess: Converter.toHex(0), calls }).build();
|
|
25712
|
+
const result = await this.iconService.call(transaction).execute();
|
|
25713
|
+
const aggregated = result.returnData;
|
|
25714
|
+
if (!Array.isArray(aggregated) || aggregated.length !== nonNativeTokens.length) {
|
|
25715
|
+
throw new Error(
|
|
25716
|
+
`[IconSpokeService] tryAggregate returned ${Array.isArray(aggregated) ? aggregated.length : "no"} entries for ${nonNativeTokens.length} tokens`
|
|
25717
|
+
);
|
|
25718
|
+
}
|
|
25719
|
+
nonNativeTokens.forEach((token, index) => {
|
|
25720
|
+
const agg = aggregated[index];
|
|
25721
|
+
if (agg && agg.success !== "0x0" && typeof agg.returnData === "string") {
|
|
25722
|
+
collector.ok(token.address, hexToBigInt(agg.returnData));
|
|
25723
|
+
} else {
|
|
25724
|
+
collector.fail(token.address, new Error(`balanceOf failed for ${token.address}: ${agg?.returnData}`));
|
|
25725
|
+
}
|
|
25726
|
+
});
|
|
25727
|
+
return collector.finish();
|
|
25064
25728
|
}
|
|
25065
25729
|
/**
|
|
25066
25730
|
* Sends a message to the hub chain.
|
|
@@ -25126,6 +25790,7 @@ var GAS_PRICE_REGEX = /^(\d+)(.*)$/;
|
|
|
25126
25790
|
var InjectiveSpokeService = class {
|
|
25127
25791
|
config;
|
|
25128
25792
|
chainGrpcWasmApi;
|
|
25793
|
+
indexerGrpcAccountPortfolioApi;
|
|
25129
25794
|
txClient;
|
|
25130
25795
|
endpoints;
|
|
25131
25796
|
pollingIntervalMs;
|
|
@@ -25135,6 +25800,7 @@ var InjectiveSpokeService = class {
|
|
|
25135
25800
|
this.config = config;
|
|
25136
25801
|
this.endpoints = getNetworkEndpoints(Network.Mainnet);
|
|
25137
25802
|
this.chainGrpcWasmApi = new ChainGrpcWasmApi(this.endpoints.grpc);
|
|
25803
|
+
this.indexerGrpcAccountPortfolioApi = new IndexerGrpcAccountPortfolioApi(this.endpoints.indexer);
|
|
25138
25804
|
this.txClient = new TxGrpcApi(this.endpoints.grpc);
|
|
25139
25805
|
this.pollingIntervalMs = this.config.sodaxConfig.chains[ChainKeys.INJECTIVE_MAINNET].pollingConfig.pollingIntervalMs;
|
|
25140
25806
|
this.maxTimeoutMs = this.config.sodaxConfig.chains[ChainKeys.INJECTIVE_MAINNET].pollingConfig.maxTimeoutMs;
|
|
@@ -25218,6 +25884,37 @@ var InjectiveSpokeService = class {
|
|
|
25218
25884
|
);
|
|
25219
25885
|
return BigInt(fromBase64(response.data));
|
|
25220
25886
|
}
|
|
25887
|
+
/**
|
|
25888
|
+
* Get the user's own wallet balance of a token on Injective, in smallest units. On Injective every
|
|
25889
|
+
* asset is a bank coin, so the native coin (`inj`) and factory/peggy/IBC tokens are all read from the
|
|
25890
|
+
* account's portfolio bank balances and matched by denom. The denom is the chain's native denom for
|
|
25891
|
+
* the native coin and `params.token.address` for standard tokens.
|
|
25892
|
+
* @param {GetBalanceParams<InjectiveChainKey>} params - The chain key, user address, and token.
|
|
25893
|
+
* @returns {Promise<bigint>} The token balance in smallest units, or 0n when the account holds none.
|
|
25894
|
+
*/
|
|
25895
|
+
async getWalletBalance(params) {
|
|
25896
|
+
const denom = isNativeToken(params.srcChainKey, params.token) ? this.config.getChainConfig(params.srcChainKey).nativeToken : params.token.address;
|
|
25897
|
+
const portfolio = await this.indexerGrpcAccountPortfolioApi.fetchAccountPortfolioBalances(params.srcAddress);
|
|
25898
|
+
const balance = portfolio.bankBalancesList.find((_balance) => _balance.denom === denom);
|
|
25899
|
+
return balance ? BigInt(balance.amount) : 0n;
|
|
25900
|
+
}
|
|
25901
|
+
/**
|
|
25902
|
+
* Get the user's own wallet balances of multiple tokens on Injective, in smallest units.
|
|
25903
|
+
* @param {GetBalancesParams<InjectiveChainKey>} params - The chain key, user address, and tokens.
|
|
25904
|
+
* @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
|
|
25905
|
+
*/
|
|
25906
|
+
async getWalletBalances(params) {
|
|
25907
|
+
const { srcChainKey, srcAddress, tokens } = params;
|
|
25908
|
+
const portfolio = await this.indexerGrpcAccountPortfolioApi.fetchAccountPortfolioBalances(srcAddress);
|
|
25909
|
+
const amountByDenom = new Map(portfolio.bankBalancesList.map((balance) => [balance.denom, BigInt(balance.amount)]));
|
|
25910
|
+
const nativeDenom = this.config.getChainConfig(srcChainKey).nativeToken;
|
|
25911
|
+
const balances = {};
|
|
25912
|
+
for (const token of tokens) {
|
|
25913
|
+
const denom = isNativeToken(srcChainKey, token) ? nativeDenom : token.address;
|
|
25914
|
+
balances[token.address] = amountByDenom.get(denom) ?? 0n;
|
|
25915
|
+
}
|
|
25916
|
+
return balances;
|
|
25917
|
+
}
|
|
25221
25918
|
async getRawTransaction(chainId, senderAddress, contractAddress, msg, memo, funds = []) {
|
|
25222
25919
|
const msgExec = MsgExecuteContract.fromJSON({
|
|
25223
25920
|
contractAddress,
|
|
@@ -25599,7 +26296,9 @@ var SpokeService = class _SpokeService {
|
|
|
25599
26296
|
from: params.owner,
|
|
25600
26297
|
spender: params.spender,
|
|
25601
26298
|
raw: false,
|
|
25602
|
-
walletProvider
|
|
26299
|
+
walletProvider,
|
|
26300
|
+
// Covers the reset leg too — an approval must not broadcast on the wrong EVM network.
|
|
26301
|
+
expectedChainId: getEvmViemChain(params.srcChainKey).id
|
|
25603
26302
|
});
|
|
25604
26303
|
if (plan.resetAmount !== void 0) {
|
|
25605
26304
|
const resetHash = await sendApprove(plan.resetAmount);
|
|
@@ -25806,7 +26505,8 @@ var SpokeService = class _SpokeService {
|
|
|
25806
26505
|
return this.sui.encodeSimulationParams(token, assetManager);
|
|
25807
26506
|
default:
|
|
25808
26507
|
return {
|
|
25809
|
-
|
|
26508
|
+
// Token identifiers on BITCOIN/NEAR/INJECTIVE are not addresses — recipient validation stays on the address leg only.
|
|
26509
|
+
encodedToken: encodeTokenIdentifier(srcChainKey, token),
|
|
25810
26510
|
encodedSrcAddress: encodeAddress(srcChainKey, assetManager)
|
|
25811
26511
|
};
|
|
25812
26512
|
}
|
|
@@ -26025,6 +26725,138 @@ var SpokeService = class _SpokeService {
|
|
|
26025
26725
|
return { ok: false, error };
|
|
26026
26726
|
}
|
|
26027
26727
|
}
|
|
26728
|
+
/**
|
|
26729
|
+
* Get a user's own wallet balance of a single token on a spoke chain, in smallest units.
|
|
26730
|
+
* Chain-agnostic: dispatches to the per-chain service, which reads the native coin or the
|
|
26731
|
+
* chain's token standard (EVM erc20, Solana SPL, …). Unlike {@link getDeposit}, this reads
|
|
26732
|
+
* `srcAddress` itself, not the protocol asset manager.
|
|
26733
|
+
* @param {GetBalanceParams<C>} params - The chain key, user address, and token.
|
|
26734
|
+
* @returns {Promise<Result<bigint>>} The token balance in smallest units.
|
|
26735
|
+
*/
|
|
26736
|
+
async getWalletBalance(params) {
|
|
26737
|
+
try {
|
|
26738
|
+
if (isHubChainKeyType(params.srcChainKey)) {
|
|
26739
|
+
const value = await this.sonic.getWalletBalance(params);
|
|
26740
|
+
return { ok: true, value };
|
|
26741
|
+
}
|
|
26742
|
+
const chainType = getChainType(params.srcChainKey);
|
|
26743
|
+
switch (chainType) {
|
|
26744
|
+
case "EVM": {
|
|
26745
|
+
const value = await this.evm.getWalletBalance(params);
|
|
26746
|
+
return { ok: true, value };
|
|
26747
|
+
}
|
|
26748
|
+
case "INJECTIVE": {
|
|
26749
|
+
const value = await this.injective.getWalletBalance(params);
|
|
26750
|
+
return { ok: true, value };
|
|
26751
|
+
}
|
|
26752
|
+
case "STELLAR": {
|
|
26753
|
+
const value = await this.stellar.getWalletBalance(params);
|
|
26754
|
+
return { ok: true, value };
|
|
26755
|
+
}
|
|
26756
|
+
case "SUI": {
|
|
26757
|
+
const value = await this.sui.getWalletBalance(params);
|
|
26758
|
+
return { ok: true, value };
|
|
26759
|
+
}
|
|
26760
|
+
case "ICON": {
|
|
26761
|
+
const value = await this.icon.getWalletBalance(params);
|
|
26762
|
+
return { ok: true, value };
|
|
26763
|
+
}
|
|
26764
|
+
case "SOLANA": {
|
|
26765
|
+
const value = await this.solana.getWalletBalance(params);
|
|
26766
|
+
return { ok: true, value };
|
|
26767
|
+
}
|
|
26768
|
+
case "STACKS": {
|
|
26769
|
+
const value = await this.stacks.getWalletBalance(params);
|
|
26770
|
+
return { ok: true, value };
|
|
26771
|
+
}
|
|
26772
|
+
case "BITCOIN": {
|
|
26773
|
+
const value = await this.bitcoin.getWalletBalance(params);
|
|
26774
|
+
return { ok: true, value };
|
|
26775
|
+
}
|
|
26776
|
+
case "NEAR": {
|
|
26777
|
+
const value = await this.near.getWalletBalance(params);
|
|
26778
|
+
return { ok: true, value };
|
|
26779
|
+
}
|
|
26780
|
+
default: {
|
|
26781
|
+
const exhaustiveCheck = chainType;
|
|
26782
|
+
this.config.logger.debug("Unhandled exhaustive case", { value: exhaustiveCheck });
|
|
26783
|
+
return {
|
|
26784
|
+
ok: false,
|
|
26785
|
+
error: new Error(`[getWalletBalance] Invalid chain type. Valid chain types: ${ChainTypeArr.join(", ")}`)
|
|
26786
|
+
};
|
|
26787
|
+
}
|
|
26788
|
+
}
|
|
26789
|
+
} catch (error) {
|
|
26790
|
+
return { ok: false, error };
|
|
26791
|
+
}
|
|
26792
|
+
}
|
|
26793
|
+
/**
|
|
26794
|
+
* Get a user's own wallet balances of multiple tokens on a spoke chain, in smallest units.
|
|
26795
|
+
* Chain-agnostic sibling of {@link getWalletBalance}; per-chain services batch the reads where the
|
|
26796
|
+
* chain supports it (e.g. EVM multicall3, ICON aggregated call data).
|
|
26797
|
+
* @param {GetBalancesParams<C>} params - The chain key, user address, and tokens.
|
|
26798
|
+
* @returns {Promise<Result<WalletBalanceMap>>} A map of token address to balance in smallest
|
|
26799
|
+
* units. A token that could not be read is logged and reported as `0n`; the `Result` fails when
|
|
26800
|
+
* the whole batch is unusable — invalid chain, a shared round-trip every token depends on, or a
|
|
26801
|
+
* batch in which no token could be read at all.
|
|
26802
|
+
*/
|
|
26803
|
+
async getWalletBalances(params) {
|
|
26804
|
+
try {
|
|
26805
|
+
if (isHubChainKeyType(params.srcChainKey)) {
|
|
26806
|
+
const value = await this.sonic.getWalletBalances(params);
|
|
26807
|
+
return { ok: true, value };
|
|
26808
|
+
}
|
|
26809
|
+
const chainType = getChainType(params.srcChainKey);
|
|
26810
|
+
switch (chainType) {
|
|
26811
|
+
case "EVM": {
|
|
26812
|
+
const value = await this.evm.getWalletBalances(params);
|
|
26813
|
+
return { ok: true, value };
|
|
26814
|
+
}
|
|
26815
|
+
case "INJECTIVE": {
|
|
26816
|
+
const value = await this.injective.getWalletBalances(params);
|
|
26817
|
+
return { ok: true, value };
|
|
26818
|
+
}
|
|
26819
|
+
case "STELLAR": {
|
|
26820
|
+
const value = await this.stellar.getWalletBalances(params);
|
|
26821
|
+
return { ok: true, value };
|
|
26822
|
+
}
|
|
26823
|
+
case "SUI": {
|
|
26824
|
+
const value = await this.sui.getWalletBalances(params);
|
|
26825
|
+
return { ok: true, value };
|
|
26826
|
+
}
|
|
26827
|
+
case "ICON": {
|
|
26828
|
+
const value = await this.icon.getWalletBalances(params);
|
|
26829
|
+
return { ok: true, value };
|
|
26830
|
+
}
|
|
26831
|
+
case "SOLANA": {
|
|
26832
|
+
const value = await this.solana.getWalletBalances(params);
|
|
26833
|
+
return { ok: true, value };
|
|
26834
|
+
}
|
|
26835
|
+
case "STACKS": {
|
|
26836
|
+
const value = await this.stacks.getWalletBalances(params);
|
|
26837
|
+
return { ok: true, value };
|
|
26838
|
+
}
|
|
26839
|
+
case "BITCOIN": {
|
|
26840
|
+
const value = await this.bitcoin.getWalletBalances(params);
|
|
26841
|
+
return { ok: true, value };
|
|
26842
|
+
}
|
|
26843
|
+
case "NEAR": {
|
|
26844
|
+
const value = await this.near.getWalletBalances(params);
|
|
26845
|
+
return { ok: true, value };
|
|
26846
|
+
}
|
|
26847
|
+
default: {
|
|
26848
|
+
const exhaustiveCheck = chainType;
|
|
26849
|
+
this.config.logger.debug("Unhandled exhaustive case", { value: exhaustiveCheck });
|
|
26850
|
+
return {
|
|
26851
|
+
ok: false,
|
|
26852
|
+
error: new Error(`[getWalletBalances] Invalid chain type. Valid chain types: ${ChainTypeArr.join(", ")}`)
|
|
26853
|
+
};
|
|
26854
|
+
}
|
|
26855
|
+
}
|
|
26856
|
+
} catch (error) {
|
|
26857
|
+
return { ok: false, error };
|
|
26858
|
+
}
|
|
26859
|
+
}
|
|
26028
26860
|
/**
|
|
26029
26861
|
* Calls the connection contract on the spoke chain to send a message to the hub wallet, which then executes the message's payload.
|
|
26030
26862
|
* @param {HubAddress} from - The address of the user on the hub chain.
|
|
@@ -26301,6 +27133,7 @@ var SpokeService = class _SpokeService {
|
|
|
26301
27133
|
}
|
|
26302
27134
|
}
|
|
26303
27135
|
};
|
|
27136
|
+
var HUB_CHAIN_ID = getEvmViemChain(ChainKeys.SONIC_MAINNET).id;
|
|
26304
27137
|
var Erc4626Service = class {
|
|
26305
27138
|
constructor() {
|
|
26306
27139
|
}
|
|
@@ -26479,7 +27312,7 @@ var Erc4626Service = class {
|
|
|
26479
27312
|
if (raw) {
|
|
26480
27313
|
return rawTx;
|
|
26481
27314
|
}
|
|
26482
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27315
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26483
27316
|
}
|
|
26484
27317
|
/**
|
|
26485
27318
|
* Get the maximum amount of shares that can be minted
|
|
@@ -26556,7 +27389,7 @@ var Erc4626Service = class {
|
|
|
26556
27389
|
if (raw) {
|
|
26557
27390
|
return rawTx;
|
|
26558
27391
|
}
|
|
26559
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27392
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26560
27393
|
}
|
|
26561
27394
|
/**
|
|
26562
27395
|
* Get the maximum amount of assets that can be withdrawn
|
|
@@ -26634,7 +27467,7 @@ var Erc4626Service = class {
|
|
|
26634
27467
|
if (raw) {
|
|
26635
27468
|
return rawTx;
|
|
26636
27469
|
}
|
|
26637
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27470
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26638
27471
|
}
|
|
26639
27472
|
/**
|
|
26640
27473
|
* Get the maximum amount of shares that can be redeemed
|
|
@@ -26712,7 +27545,7 @@ var Erc4626Service = class {
|
|
|
26712
27545
|
if (raw) {
|
|
26713
27546
|
return rawTx;
|
|
26714
27547
|
}
|
|
26715
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27548
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID });
|
|
26716
27549
|
}
|
|
26717
27550
|
/**
|
|
26718
27551
|
* Encodes a deposit transaction for a vault.
|
|
@@ -26789,6 +27622,7 @@ var Erc4626Service = class {
|
|
|
26789
27622
|
};
|
|
26790
27623
|
}
|
|
26791
27624
|
};
|
|
27625
|
+
var HUB_CHAIN_ID2 = getEvmViemChain(ChainKeys.SONIC_MAINNET).id;
|
|
26792
27626
|
var Permit2Service = class _Permit2Service {
|
|
26793
27627
|
constructor() {
|
|
26794
27628
|
}
|
|
@@ -26877,7 +27711,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26877
27711
|
if (raw) {
|
|
26878
27712
|
return rawTx;
|
|
26879
27713
|
}
|
|
26880
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27714
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26881
27715
|
}
|
|
26882
27716
|
/**
|
|
26883
27717
|
* Execute a permit for a single token
|
|
@@ -26902,7 +27736,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26902
27736
|
if (raw) {
|
|
26903
27737
|
return rawTx;
|
|
26904
27738
|
}
|
|
26905
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27739
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26906
27740
|
}
|
|
26907
27741
|
/**
|
|
26908
27742
|
* Execute a permit for multiple tokens
|
|
@@ -26927,7 +27761,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26927
27761
|
if (raw) {
|
|
26928
27762
|
return rawTx;
|
|
26929
27763
|
}
|
|
26930
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27764
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26931
27765
|
}
|
|
26932
27766
|
/**
|
|
26933
27767
|
* Transfer tokens from one address to another using Permit2
|
|
@@ -26953,7 +27787,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26953
27787
|
if (raw) {
|
|
26954
27788
|
return rawTx;
|
|
26955
27789
|
}
|
|
26956
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27790
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26957
27791
|
}
|
|
26958
27792
|
/**
|
|
26959
27793
|
* Transfer multiple tokens in a batch using Permit2
|
|
@@ -26976,7 +27810,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26976
27810
|
if (raw) {
|
|
26977
27811
|
return rawTx;
|
|
26978
27812
|
}
|
|
26979
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27813
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
26980
27814
|
}
|
|
26981
27815
|
/**
|
|
26982
27816
|
* Lockdown approvals to prevent malicious usage
|
|
@@ -26999,7 +27833,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
26999
27833
|
if (raw) {
|
|
27000
27834
|
return rawTx;
|
|
27001
27835
|
}
|
|
27002
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27836
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
27003
27837
|
}
|
|
27004
27838
|
/**
|
|
27005
27839
|
* Invalidate nonces to prevent replay attacks
|
|
@@ -27024,7 +27858,7 @@ var Permit2Service = class _Permit2Service {
|
|
|
27024
27858
|
if (raw) {
|
|
27025
27859
|
return rawTx;
|
|
27026
27860
|
}
|
|
27027
|
-
return walletProvider.sendTransaction(rawTx);
|
|
27861
|
+
return walletProvider.sendTransaction(rawTx, { expectedChainId: HUB_CHAIN_ID2 });
|
|
27028
27862
|
}
|
|
27029
27863
|
/**
|
|
27030
27864
|
* Encodes an approve transaction for Permit2.
|
|
@@ -27866,9 +28700,38 @@ var TokensByChainMapSchema = v.custom(
|
|
|
27866
28700
|
);
|
|
27867
28701
|
var TokensListSchema = v.array(XTokenSchema);
|
|
27868
28702
|
var ReserveAssetsSchema = v.array(AddressSchema);
|
|
28703
|
+
var ORACLE_CANDLE_INTERVALS = ["1m", "5m", "1h", "1d"];
|
|
28704
|
+
var OracleCandleIntervalSchema = v.picklist(ORACLE_CANDLE_INTERVALS);
|
|
28705
|
+
var OracleMarketsResponseSchema = v.object({
|
|
28706
|
+
quote: v.string(),
|
|
28707
|
+
intervals: v.array(
|
|
28708
|
+
v.object({
|
|
28709
|
+
key: v.string(),
|
|
28710
|
+
label: v.string(),
|
|
28711
|
+
seconds: v.number()
|
|
28712
|
+
})
|
|
28713
|
+
),
|
|
28714
|
+
symbols: v.array(v.string())
|
|
28715
|
+
});
|
|
28716
|
+
var OracleCandlesResponseSchema = v.object({
|
|
28717
|
+
symbol: v.string(),
|
|
28718
|
+
quote: v.string(),
|
|
28719
|
+
interval: OracleCandleIntervalSchema,
|
|
28720
|
+
candles: v.array(
|
|
28721
|
+
v.object({
|
|
28722
|
+
timestamp: v.number(),
|
|
28723
|
+
open: v.string(),
|
|
28724
|
+
high: v.string(),
|
|
28725
|
+
low: v.string(),
|
|
28726
|
+
close: v.string(),
|
|
28727
|
+
final: v.optional(v.boolean())
|
|
28728
|
+
})
|
|
28729
|
+
)
|
|
28730
|
+
});
|
|
27869
28731
|
|
|
27870
28732
|
// src/backendApi/guards.ts
|
|
27871
28733
|
var isFillEvent = (value) => v.is(FillEventSchema, value);
|
|
28734
|
+
var isOracleCandleInterval = (value) => v.is(OracleCandleIntervalSchema, value);
|
|
27872
28735
|
function decodePacketIntentTarget(payload) {
|
|
27873
28736
|
try {
|
|
27874
28737
|
const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
|
|
@@ -30253,7 +31116,9 @@ var BalnSwapService = class {
|
|
|
30253
31116
|
if (walletProviderSlot.raw) {
|
|
30254
31117
|
return tx;
|
|
30255
31118
|
}
|
|
30256
|
-
return walletProviderSlot.walletProvider.sendTransaction(tx
|
|
31119
|
+
return walletProviderSlot.walletProvider.sendTransaction(tx, {
|
|
31120
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
31121
|
+
});
|
|
30257
31122
|
}
|
|
30258
31123
|
};
|
|
30259
31124
|
|
|
@@ -31392,6 +32257,9 @@ function resolveSponsoringApiConfig(layers) {
|
|
|
31392
32257
|
function resolveBridgeApiConfig(layers) {
|
|
31393
32258
|
return resolveSharedApiConfig(layers);
|
|
31394
32259
|
}
|
|
32260
|
+
function resolveLeverageYieldApiConfig(layers) {
|
|
32261
|
+
return resolveSharedApiConfig(layers);
|
|
32262
|
+
}
|
|
31395
32263
|
var SwapsApiService = class _SwapsApiService {
|
|
31396
32264
|
// Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
|
|
31397
32265
|
// `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
|
|
@@ -32117,6 +32985,623 @@ var BridgeApiService = class {
|
|
|
32117
32985
|
return this.config.timeout;
|
|
32118
32986
|
}
|
|
32119
32987
|
};
|
|
32988
|
+
var LsdSourceSchema = v.object({
|
|
32989
|
+
poolId: v.string(),
|
|
32990
|
+
fallbackAprPct: v.number(),
|
|
32991
|
+
label: v.string()
|
|
32992
|
+
});
|
|
32993
|
+
var LeverageVaultSchema = v.object({
|
|
32994
|
+
name: v.string(),
|
|
32995
|
+
vault: v.string(),
|
|
32996
|
+
asset: v.string(),
|
|
32997
|
+
borrowToken: v.string(),
|
|
32998
|
+
lsdSource: v.optional(LsdSourceSchema)
|
|
32999
|
+
});
|
|
33000
|
+
var GetLeverageVaultsResponseSchema = v.array(LeverageVaultSchema);
|
|
33001
|
+
var GetLeverageVaultResponseSchema = LeverageVaultSchema;
|
|
33002
|
+
var VaultAssetResponseSchema = v.object({
|
|
33003
|
+
asset: v.string()
|
|
33004
|
+
});
|
|
33005
|
+
var LeverageYieldPositionSchema = v.object({
|
|
33006
|
+
collateral: v.string(),
|
|
33007
|
+
debt: v.string(),
|
|
33008
|
+
ltv: v.string(),
|
|
33009
|
+
healthFactor: v.string(),
|
|
33010
|
+
idleAsset: v.string()
|
|
33011
|
+
});
|
|
33012
|
+
var LeverageYieldAprSchema = v.object({
|
|
33013
|
+
supplyAprRay: v.string(),
|
|
33014
|
+
borrowAprRay: v.string(),
|
|
33015
|
+
targetLtvBps: v.string(),
|
|
33016
|
+
leverageMultiplierWad: v.string(),
|
|
33017
|
+
netAprRay: v.string()
|
|
33018
|
+
});
|
|
33019
|
+
var LeverageYieldLsdAprSchema = v.object({
|
|
33020
|
+
aprRay: v.string(),
|
|
33021
|
+
label: v.string(),
|
|
33022
|
+
stale: v.boolean()
|
|
33023
|
+
});
|
|
33024
|
+
var LeverageYieldEffectiveAprSchema = v.object({
|
|
33025
|
+
supplyAprRay: v.string(),
|
|
33026
|
+
borrowAprRay: v.string(),
|
|
33027
|
+
targetLtvBps: v.string(),
|
|
33028
|
+
leverageMultiplierWad: v.string(),
|
|
33029
|
+
netAprRay: v.string(),
|
|
33030
|
+
lsdApr: LeverageYieldLsdAprSchema,
|
|
33031
|
+
effectiveSupplyAprRay: v.string(),
|
|
33032
|
+
effectiveNetAprRay: v.string()
|
|
33033
|
+
});
|
|
33034
|
+
var VaultTotalAssetsResponseSchema = v.object({
|
|
33035
|
+
totalAssets: v.string()
|
|
33036
|
+
});
|
|
33037
|
+
var PreviewDepositResponseSchema = v.object({
|
|
33038
|
+
shares: v.string()
|
|
33039
|
+
});
|
|
33040
|
+
var PreviewWithdrawResponseSchema = v.object({
|
|
33041
|
+
shares: v.string()
|
|
33042
|
+
});
|
|
33043
|
+
var PreviewRedeemResponseSchema = v.object({
|
|
33044
|
+
assets: v.string()
|
|
33045
|
+
});
|
|
33046
|
+
var ShareBalanceResponseSchema = v.object({
|
|
33047
|
+
balance: v.string()
|
|
33048
|
+
});
|
|
33049
|
+
var MaxWithdrawResponseSchema = v.object({
|
|
33050
|
+
maxWithdraw: v.string()
|
|
33051
|
+
});
|
|
33052
|
+
|
|
33053
|
+
// src/backendApi/LeverageYieldApiService.ts
|
|
33054
|
+
var LeverageYieldApiService = class _LeverageYieldApiService {
|
|
33055
|
+
// Fully-resolved API config supplied by the caller (BackendApiService resolves the ApiConfig
|
|
33056
|
+
// union via `resolveBaseApiConfig`); leverage-yield endpoints are sub-paths under the base URL.
|
|
33057
|
+
config;
|
|
33058
|
+
headers;
|
|
33059
|
+
logger;
|
|
33060
|
+
/** See {@link LeverageYieldApiServiceOptions.trimLegacyOverrides}. */
|
|
33061
|
+
trimsLegacyOverrides;
|
|
33062
|
+
constructor(config, logger = consoleLogger, options = {}) {
|
|
33063
|
+
this.config = config;
|
|
33064
|
+
this.headers = { ...config.headers };
|
|
33065
|
+
this.logger = logger;
|
|
33066
|
+
this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
|
|
33067
|
+
}
|
|
33068
|
+
/**
|
|
33069
|
+
* Issues a single HTTP request, validates the JSON body against `schema`, and wraps the
|
|
33070
|
+
* result in `Result<T>`. Mirrors `SwapsApiService.request`; every public method delegates here.
|
|
33071
|
+
*/
|
|
33072
|
+
async request(endpoint, config, schema, overrideConfig) {
|
|
33073
|
+
try {
|
|
33074
|
+
const raw = await makeRequest({
|
|
33075
|
+
endpoint,
|
|
33076
|
+
config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
|
|
33077
|
+
// Normalized like a configured base URL: the override is the gateway root, so a legacy
|
|
33078
|
+
// `/be`-suffixed value must not nest `/leverage-yield/*` under the data API's mount — unless the
|
|
33079
|
+
// config opted out of the legacy trim, in which case the per-call value is left as given.
|
|
33080
|
+
overrideConfig: this.trimsLegacyOverrides ? normalizeOverrideBaseURL(overrideConfig) : overrideConfig,
|
|
33081
|
+
logger: this.logger,
|
|
33082
|
+
serviceLabel: "LeverageYieldApiService"
|
|
33083
|
+
});
|
|
33084
|
+
const parsed = v.safeParse(schema, raw);
|
|
33085
|
+
if (!parsed.success) {
|
|
33086
|
+
return {
|
|
33087
|
+
ok: false,
|
|
33088
|
+
error: toInvalidResponseShapeError({
|
|
33089
|
+
api: "leverageYield",
|
|
33090
|
+
feature: "backend",
|
|
33091
|
+
endpoint,
|
|
33092
|
+
issues: v.flatten(parsed.issues)
|
|
33093
|
+
})
|
|
33094
|
+
};
|
|
33095
|
+
}
|
|
33096
|
+
return { ok: true, value: parsed.output };
|
|
33097
|
+
} catch (error) {
|
|
33098
|
+
return { ok: false, error: toExternalApiError({ api: "leverageYield", feature: "backend", endpoint, error }) };
|
|
33099
|
+
}
|
|
33100
|
+
}
|
|
33101
|
+
/**
|
|
33102
|
+
* Drop the SDK-only display field `feeAmount` before an intent reaches the strict wire serializer.
|
|
33103
|
+
* `sodax.leverageYield.createVaultIntent` returns `Intent & FeeAmount`, which is structurally
|
|
33104
|
+
* assignable to the wire `IntentRequestV2` and so gets passed straight into the intent-carrying
|
|
33105
|
+
* endpoints; the lenient JSON serializer would send the extra bigint wholesale. Mirrors
|
|
33106
|
+
* `SwapsApiService.toWireIntent`; a no-op for an already-clean `IntentRequestV2`.
|
|
33107
|
+
*/
|
|
33108
|
+
static toWireIntent(intent) {
|
|
33109
|
+
const { feeAmount: _feeAmount, ...rest } = intent;
|
|
33110
|
+
return rest;
|
|
33111
|
+
}
|
|
33112
|
+
/** Append `params` to `base` as a query string, returning `base` unchanged when `params` is empty. */
|
|
33113
|
+
withQuery(base2, params) {
|
|
33114
|
+
const queryString = new URLSearchParams(params).toString();
|
|
33115
|
+
return queryString.length > 0 ? `${base2}?${queryString}` : base2;
|
|
33116
|
+
}
|
|
33117
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33118
|
+
// Vault registry
|
|
33119
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33120
|
+
/**
|
|
33121
|
+
* Fetch the registry of deployed leverage-yield vaults.
|
|
33122
|
+
*
|
|
33123
|
+
* @returns `Result<GetLeverageVaultsResponseV2>` — array of vault descriptors.
|
|
33124
|
+
*/
|
|
33125
|
+
async getVaults(config) {
|
|
33126
|
+
return this.request("/leverage-yield/vaults", { method: "GET" }, GetLeverageVaultsResponseSchema, config);
|
|
33127
|
+
}
|
|
33128
|
+
/**
|
|
33129
|
+
* Fetch a single vault descriptor by its lsoda* share-token name (e.g. `lsodaWEETH`).
|
|
33130
|
+
*
|
|
33131
|
+
* @returns `Result<GetLeverageVaultResponseV2>` — the vault descriptor.
|
|
33132
|
+
*/
|
|
33133
|
+
async getVault(name, config) {
|
|
33134
|
+
return this.request(
|
|
33135
|
+
`/leverage-yield/vaults/${name}`,
|
|
33136
|
+
{ method: "GET" },
|
|
33137
|
+
GetLeverageVaultResponseSchema,
|
|
33138
|
+
config
|
|
33139
|
+
);
|
|
33140
|
+
}
|
|
33141
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33142
|
+
// Vault reads
|
|
33143
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33144
|
+
/**
|
|
33145
|
+
* Get the vault's underlying hub asset (Sodax vault-token wrapper).
|
|
33146
|
+
*
|
|
33147
|
+
* @returns `Result<VaultAssetResponseV2>` — `{ asset }`.
|
|
33148
|
+
*/
|
|
33149
|
+
async getAsset(query, config) {
|
|
33150
|
+
return this.request(
|
|
33151
|
+
this.withQuery("/leverage-yield/asset", { vault: query.vault }),
|
|
33152
|
+
{ method: "GET" },
|
|
33153
|
+
VaultAssetResponseSchema,
|
|
33154
|
+
config
|
|
33155
|
+
);
|
|
33156
|
+
}
|
|
33157
|
+
/**
|
|
33158
|
+
* Get a leveraged-position snapshot for the vault.
|
|
33159
|
+
*
|
|
33160
|
+
* @returns `Result<LeverageYieldPositionV2>` — `{ collateral, debt, ltv, healthFactor, idleAsset }` (decimal strings).
|
|
33161
|
+
*/
|
|
33162
|
+
async getPosition(query, config) {
|
|
33163
|
+
return this.request(
|
|
33164
|
+
this.withQuery("/leverage-yield/position", { vault: query.vault }),
|
|
33165
|
+
{ method: "GET" },
|
|
33166
|
+
LeverageYieldPositionSchema,
|
|
33167
|
+
config
|
|
33168
|
+
);
|
|
33169
|
+
}
|
|
33170
|
+
/**
|
|
33171
|
+
* Get the AAVE-only steady-state APR for the vault (goes negative when the LSD yield is the alpha).
|
|
33172
|
+
*
|
|
33173
|
+
* @returns `Result<LeverageYieldAprV2>` — RAY-denominated rates as decimal strings.
|
|
33174
|
+
*/
|
|
33175
|
+
async getApr(query, config) {
|
|
33176
|
+
return this.request(
|
|
33177
|
+
this.withQuery("/leverage-yield/apr", { vault: query.vault }),
|
|
33178
|
+
{ method: "GET" },
|
|
33179
|
+
LeverageYieldAprSchema,
|
|
33180
|
+
config
|
|
33181
|
+
);
|
|
33182
|
+
}
|
|
33183
|
+
/**
|
|
33184
|
+
* Get the honest combined AAVE + LSD effective APR for the vault.
|
|
33185
|
+
*
|
|
33186
|
+
* @returns `Result<LeverageYieldEffectiveAprV2>` — includes `effectiveNetAprRay` (the headline number).
|
|
33187
|
+
*/
|
|
33188
|
+
async getEffectiveApr(query, config) {
|
|
33189
|
+
return this.request(
|
|
33190
|
+
this.withQuery("/leverage-yield/apr/effective", { vault: query.vault }),
|
|
33191
|
+
{ method: "GET" },
|
|
33192
|
+
LeverageYieldEffectiveAprSchema,
|
|
33193
|
+
config
|
|
33194
|
+
);
|
|
33195
|
+
}
|
|
33196
|
+
/**
|
|
33197
|
+
* Get the off-chain LSD staking-APR snapshot for the vault's underlying asset.
|
|
33198
|
+
*
|
|
33199
|
+
* @returns `Result<LeverageYieldLsdAprV2>` — `{ aprRay, label, stale }`.
|
|
33200
|
+
*/
|
|
33201
|
+
async getLsdApr(query, config) {
|
|
33202
|
+
return this.request(
|
|
33203
|
+
this.withQuery("/leverage-yield/apr/lsd", { vault: query.vault }),
|
|
33204
|
+
{ method: "GET" },
|
|
33205
|
+
LeverageYieldLsdAprSchema,
|
|
33206
|
+
config
|
|
33207
|
+
);
|
|
33208
|
+
}
|
|
33209
|
+
/**
|
|
33210
|
+
* Get the total assets managed by the vault.
|
|
33211
|
+
*
|
|
33212
|
+
* @returns `Result<VaultTotalAssetsResponseV2>` — `{ totalAssets }` (decimal string).
|
|
33213
|
+
*/
|
|
33214
|
+
async getTotalAssets(query, config) {
|
|
33215
|
+
return this.request(
|
|
33216
|
+
this.withQuery("/leverage-yield/total-assets", { vault: query.vault }),
|
|
33217
|
+
{ method: "GET" },
|
|
33218
|
+
VaultTotalAssetsResponseSchema,
|
|
33219
|
+
config
|
|
33220
|
+
);
|
|
33221
|
+
}
|
|
33222
|
+
/**
|
|
33223
|
+
* Preview the shares minted for depositing `assets` into the vault (ERC-4626 `previewDeposit`).
|
|
33224
|
+
*
|
|
33225
|
+
* @returns `Result<PreviewDepositResponseV2>` — `{ shares }` (decimal string).
|
|
33226
|
+
*/
|
|
33227
|
+
async previewDeposit(query, config) {
|
|
33228
|
+
return this.request(
|
|
33229
|
+
this.withQuery("/leverage-yield/preview/deposit", { vault: query.vault, assets: query.assets }),
|
|
33230
|
+
{ method: "GET" },
|
|
33231
|
+
PreviewDepositResponseSchema,
|
|
33232
|
+
config
|
|
33233
|
+
);
|
|
33234
|
+
}
|
|
33235
|
+
/**
|
|
33236
|
+
* Preview the shares burned to withdraw `assets` from the vault (ERC-4626 `previewWithdraw`).
|
|
33237
|
+
*
|
|
33238
|
+
* @returns `Result<PreviewWithdrawResponseV2>` — `{ shares }` (decimal string).
|
|
33239
|
+
*/
|
|
33240
|
+
async previewWithdraw(query, config) {
|
|
33241
|
+
return this.request(
|
|
33242
|
+
this.withQuery("/leverage-yield/preview/withdraw", { vault: query.vault, assets: query.assets }),
|
|
33243
|
+
{ method: "GET" },
|
|
33244
|
+
PreviewWithdrawResponseSchema,
|
|
33245
|
+
config
|
|
33246
|
+
);
|
|
33247
|
+
}
|
|
33248
|
+
/**
|
|
33249
|
+
* Preview the assets returned for redeeming `shares` from the vault (ERC-4626 `previewRedeem`).
|
|
33250
|
+
*
|
|
33251
|
+
* @returns `Result<PreviewRedeemResponseV2>` — `{ assets }` (decimal string).
|
|
33252
|
+
*/
|
|
33253
|
+
async previewRedeem(query, config) {
|
|
33254
|
+
return this.request(
|
|
33255
|
+
this.withQuery("/leverage-yield/preview/redeem", { vault: query.vault, shares: query.shares }),
|
|
33256
|
+
{ method: "GET" },
|
|
33257
|
+
PreviewRedeemResponseSchema,
|
|
33258
|
+
config
|
|
33259
|
+
);
|
|
33260
|
+
}
|
|
33261
|
+
/**
|
|
33262
|
+
* Get an owner's vault share (lsoda*) balance.
|
|
33263
|
+
*
|
|
33264
|
+
* @returns `Result<ShareBalanceResponseV2>` — `{ balance }` (decimal string).
|
|
33265
|
+
*/
|
|
33266
|
+
async getShareBalance(query, config) {
|
|
33267
|
+
return this.request(
|
|
33268
|
+
this.withQuery("/leverage-yield/share-balance", { vault: query.vault, owner: query.owner }),
|
|
33269
|
+
{ method: "GET" },
|
|
33270
|
+
ShareBalanceResponseSchema,
|
|
33271
|
+
config
|
|
33272
|
+
);
|
|
33273
|
+
}
|
|
33274
|
+
/**
|
|
33275
|
+
* Get an owner's RAW ERC-4626 `maxWithdraw` — NOT dust-trimmed, unlike the SDK-local
|
|
33276
|
+
* `sodax.leverageYield.getMaxWithdrawForUser`. Apply a margin before using it as a withdraw amount.
|
|
33277
|
+
*
|
|
33278
|
+
* @returns `Result<MaxWithdrawResponseV2>` — `{ maxWithdraw }` (decimal string).
|
|
33279
|
+
*/
|
|
33280
|
+
async getMaxWithdraw(query, config) {
|
|
33281
|
+
return this.request(
|
|
33282
|
+
this.withQuery("/leverage-yield/max-withdraw", { vault: query.vault, owner: query.owner }),
|
|
33283
|
+
{ method: "GET" },
|
|
33284
|
+
MaxWithdrawResponseSchema,
|
|
33285
|
+
config
|
|
33286
|
+
);
|
|
33287
|
+
}
|
|
33288
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33289
|
+
// Quote · deadline
|
|
33290
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33291
|
+
/**
|
|
33292
|
+
* Quote a swap-style deposit: any solver-supported `tokenSrc` → the vault's lsoda* shares.
|
|
33293
|
+
* Pass `query.includeTxData = true` to also build the unsigned create-intent tx (`srcAddress`
|
|
33294
|
+
* required in the body then).
|
|
33295
|
+
*
|
|
33296
|
+
* @returns `Result<QuoteResponseV2>` — `quotedAmount` (shares) and optional `txData`.
|
|
33297
|
+
*/
|
|
33298
|
+
async getDepositQuote(body, query, config) {
|
|
33299
|
+
const endpoint = query?.includeTxData ? "/leverage-yield/quote/deposit?includeTxData=true" : "/leverage-yield/quote/deposit";
|
|
33300
|
+
const txSchema = rawTxSchemaForChainKey$1(body.tokenSrcChainKey);
|
|
33301
|
+
return this.request(
|
|
33302
|
+
endpoint,
|
|
33303
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33304
|
+
makeQuoteResponseSchema(txSchema),
|
|
33305
|
+
config
|
|
33306
|
+
);
|
|
33307
|
+
}
|
|
33308
|
+
/**
|
|
33309
|
+
* Quote a swap-style withdraw: the vault's lsoda* shares → any solver-supported `tokenDst`.
|
|
33310
|
+
* Pass `query.includeTxData = true` to also build the unsigned tx (signed on `srcChainKey`;
|
|
33311
|
+
* `srcAddress`/`dstAddress` required in the body then).
|
|
33312
|
+
*
|
|
33313
|
+
* @returns `Result<QuoteResponseV2>` — `quotedAmount` (output token) and optional `txData`.
|
|
33314
|
+
*/
|
|
33315
|
+
async getWithdrawQuote(body, query, config) {
|
|
33316
|
+
const endpoint = query?.includeTxData ? "/leverage-yield/quote/withdraw?includeTxData=true" : "/leverage-yield/quote/withdraw";
|
|
33317
|
+
const txSchema = rawTxSchemaForChainKey$1(body.srcChainKey);
|
|
33318
|
+
return this.request(
|
|
33319
|
+
endpoint,
|
|
33320
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33321
|
+
makeQuoteResponseSchema(txSchema),
|
|
33322
|
+
config
|
|
33323
|
+
);
|
|
33324
|
+
}
|
|
33325
|
+
/**
|
|
33326
|
+
* Compute a deposit/withdraw deadline (hub timestamp + `offsetSeconds`, default 300s).
|
|
33327
|
+
*
|
|
33328
|
+
* @returns `Result<DeadlineResponseV2>` — unix-seconds deadline (decimal string).
|
|
33329
|
+
*/
|
|
33330
|
+
async getDeadline(query, config) {
|
|
33331
|
+
const params = {};
|
|
33332
|
+
if (query?.offsetSeconds !== void 0) params.offsetSeconds = String(query.offsetSeconds);
|
|
33333
|
+
return this.request(
|
|
33334
|
+
this.withQuery("/leverage-yield/deadline", params),
|
|
33335
|
+
{ method: "GET" },
|
|
33336
|
+
DeadlineResponseSchema,
|
|
33337
|
+
config
|
|
33338
|
+
);
|
|
33339
|
+
}
|
|
33340
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33341
|
+
// Deposit allowance · approve · create intent (deposit / withdraw)
|
|
33342
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33343
|
+
/**
|
|
33344
|
+
* Check whether the deposit input-token allowance is already sufficient for the intent.
|
|
33345
|
+
* (Withdraw needs no spoke allowance — it spends lsoda* from the hub wallet.)
|
|
33346
|
+
*
|
|
33347
|
+
* @returns `Result<AllowanceCheckResponseV2>` — `{ valid }`.
|
|
33348
|
+
*/
|
|
33349
|
+
async checkAllowance(body, config) {
|
|
33350
|
+
return this.request(
|
|
33351
|
+
"/leverage-yield/allowance/check",
|
|
33352
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33353
|
+
AllowanceCheckResponseSchema,
|
|
33354
|
+
config
|
|
33355
|
+
);
|
|
33356
|
+
}
|
|
33357
|
+
/**
|
|
33358
|
+
* Build an unsigned token-approval transaction for the deposit input token.
|
|
33359
|
+
*
|
|
33360
|
+
* @returns `Result<ApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
|
|
33361
|
+
*/
|
|
33362
|
+
async approve(body, config) {
|
|
33363
|
+
const txSchema = rawTxSchemaForChainKey$1(body.srcChainKey);
|
|
33364
|
+
return this.request(
|
|
33365
|
+
"/leverage-yield/approve",
|
|
33366
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33367
|
+
makeApproveResponseSchema(txSchema),
|
|
33368
|
+
config
|
|
33369
|
+
);
|
|
33370
|
+
}
|
|
33371
|
+
/**
|
|
33372
|
+
* Build an unsigned deposit create-intent transaction (any token → lsoda* shares).
|
|
33373
|
+
*
|
|
33374
|
+
* @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
|
|
33375
|
+
*/
|
|
33376
|
+
async createDepositIntent(body, config) {
|
|
33377
|
+
const txSchema = rawTxSchemaForChainKey$1(body.srcChainKey);
|
|
33378
|
+
return this.request(
|
|
33379
|
+
"/leverage-yield/intents/deposit",
|
|
33380
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33381
|
+
makeCreateIntentResponseSchema(txSchema),
|
|
33382
|
+
config
|
|
33383
|
+
);
|
|
33384
|
+
}
|
|
33385
|
+
/**
|
|
33386
|
+
* Build an unsigned withdraw create-intent transaction (lsoda* shares → any token). The backend
|
|
33387
|
+
* sets `hubWalletSwap` internally so the swap spends the lsoda* held in the user's hub wallet.
|
|
33388
|
+
*
|
|
33389
|
+
* @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
|
|
33390
|
+
*/
|
|
33391
|
+
async createWithdrawIntent(body, config) {
|
|
33392
|
+
const txSchema = rawTxSchemaForChainKey$1(body.srcChainKey);
|
|
33393
|
+
return this.request(
|
|
33394
|
+
"/leverage-yield/intents/withdraw",
|
|
33395
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33396
|
+
makeCreateIntentResponseSchema(txSchema),
|
|
33397
|
+
config
|
|
33398
|
+
);
|
|
33399
|
+
}
|
|
33400
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33401
|
+
// Intent lifecycle: submit · status · cancel · hash · packet · extra-data
|
|
33402
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33403
|
+
/**
|
|
33404
|
+
* Submit the broadcast intent tx to the relay.
|
|
33405
|
+
*
|
|
33406
|
+
* @returns `Result<SubmitIntentResponseV2>` — `{ result }` (opaque relay response).
|
|
33407
|
+
*/
|
|
33408
|
+
async submitIntent(body, config) {
|
|
33409
|
+
return this.request(
|
|
33410
|
+
"/leverage-yield/intents/submit",
|
|
33411
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33412
|
+
SubmitIntentResponseSchema,
|
|
33413
|
+
config
|
|
33414
|
+
);
|
|
33415
|
+
}
|
|
33416
|
+
/**
|
|
33417
|
+
* Poll the solver for intent execution status.
|
|
33418
|
+
*
|
|
33419
|
+
* @returns `Result<StatusResponseV2>` — `{ status, fillTxHash? }`.
|
|
33420
|
+
*/
|
|
33421
|
+
async getStatus(body, config) {
|
|
33422
|
+
return this.request(
|
|
33423
|
+
"/leverage-yield/intents/status",
|
|
33424
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33425
|
+
StatusResponseSchema,
|
|
33426
|
+
config
|
|
33427
|
+
);
|
|
33428
|
+
}
|
|
33429
|
+
/**
|
|
33430
|
+
* Build an unsigned cancel-intent transaction. The `intent` field carries `bigint` numerics —
|
|
33431
|
+
* {@link toJsonBody} serializes them to decimal strings.
|
|
33432
|
+
*
|
|
33433
|
+
* @returns `Result<CancelIntentResponseV2>` — `{ tx }`.
|
|
33434
|
+
*/
|
|
33435
|
+
async cancelIntent(body, config) {
|
|
33436
|
+
const txSchema = rawTxSchemaForChainKey$1(body.srcChainKey);
|
|
33437
|
+
return this.request(
|
|
33438
|
+
"/leverage-yield/intents/cancel",
|
|
33439
|
+
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
33440
|
+
makeCancelIntentResponseSchema(txSchema),
|
|
33441
|
+
config
|
|
33442
|
+
);
|
|
33443
|
+
}
|
|
33444
|
+
/**
|
|
33445
|
+
* Compute the keccak256 hash of an Intent struct. The `intent` field carries `bigint` numerics.
|
|
33446
|
+
*
|
|
33447
|
+
* @returns `Result<IntentHashResponseV2>` — `{ hash }`.
|
|
33448
|
+
*/
|
|
33449
|
+
async getIntentHash(body, config) {
|
|
33450
|
+
return this.request(
|
|
33451
|
+
"/leverage-yield/intents/hash",
|
|
33452
|
+
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
33453
|
+
IntentHashResponseSchema,
|
|
33454
|
+
config
|
|
33455
|
+
);
|
|
33456
|
+
}
|
|
33457
|
+
/**
|
|
33458
|
+
* Long-poll the relayer until the fill packet lands on the destination chain.
|
|
33459
|
+
*
|
|
33460
|
+
* @returns `Result<IntentPacketResponseV2>` — delivered packet data.
|
|
33461
|
+
*/
|
|
33462
|
+
async getSolvedIntentPacket(body, config) {
|
|
33463
|
+
return this.request(
|
|
33464
|
+
"/leverage-yield/intents/packet",
|
|
33465
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33466
|
+
IntentPacketResponseSchema,
|
|
33467
|
+
config
|
|
33468
|
+
);
|
|
33469
|
+
}
|
|
33470
|
+
/**
|
|
33471
|
+
* Recover the relay extra data needed by `/leverage-yield/intents/submit`. Provide EITHER
|
|
33472
|
+
* `txHash` OR `intent` (whose `bigint` numerics {@link toJsonBody} serializes).
|
|
33473
|
+
*
|
|
33474
|
+
* @returns `Result<IntentExtraDataResponseV2>` — `{ address, payload }`.
|
|
33475
|
+
*/
|
|
33476
|
+
async getIntentSubmitTxExtraData(body, config) {
|
|
33477
|
+
const normalized = body.intent ? { ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) } : body;
|
|
33478
|
+
return this.request(
|
|
33479
|
+
"/leverage-yield/intents/extra-data",
|
|
33480
|
+
{ method: "POST", body: toJsonBody(normalized) },
|
|
33481
|
+
RelayExtraDataResponseSchema$1,
|
|
33482
|
+
config
|
|
33483
|
+
);
|
|
33484
|
+
}
|
|
33485
|
+
/**
|
|
33486
|
+
* Get the on-chain fill state for an intent by its hub-chain tx hash.
|
|
33487
|
+
*
|
|
33488
|
+
* @returns `Result<IntentStateV2>` — `{ exists, remainingInput, receivedOutput, pendingPayment }`.
|
|
33489
|
+
*/
|
|
33490
|
+
async getFilledIntent(txHash, config) {
|
|
33491
|
+
return this.request(
|
|
33492
|
+
`/leverage-yield/intents/${txHash}/fill`,
|
|
33493
|
+
{ method: "GET" },
|
|
33494
|
+
IntentStateSchema,
|
|
33495
|
+
config
|
|
33496
|
+
);
|
|
33497
|
+
}
|
|
33498
|
+
/**
|
|
33499
|
+
* Look up an Intent struct by its hub-chain creation tx hash.
|
|
33500
|
+
*
|
|
33501
|
+
* @returns `Result<GetIntentResponseV2>` — the decoded intent (bigint fields as decimal strings).
|
|
33502
|
+
*/
|
|
33503
|
+
async getIntent(txHash, config) {
|
|
33504
|
+
return this.request(`/leverage-yield/intents/${txHash}`, { method: "GET" }, IntentResponseSchema$1, config);
|
|
33505
|
+
}
|
|
33506
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33507
|
+
// Gas · fees
|
|
33508
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33509
|
+
/**
|
|
33510
|
+
* Estimate gas for a raw transaction on a spoke chain.
|
|
33511
|
+
*
|
|
33512
|
+
* @returns `Result<GasEstimateResponseV2>` — `{ gas }` (chain-specific shape).
|
|
33513
|
+
*/
|
|
33514
|
+
async estimateGas(body, config) {
|
|
33515
|
+
return this.request(
|
|
33516
|
+
"/leverage-yield/gas/estimate",
|
|
33517
|
+
{ method: "POST", body: toJsonBody(body) },
|
|
33518
|
+
GasEstimateResponseSchema,
|
|
33519
|
+
config
|
|
33520
|
+
);
|
|
33521
|
+
}
|
|
33522
|
+
/**
|
|
33523
|
+
* Compute the partner fee for a given input amount.
|
|
33524
|
+
*
|
|
33525
|
+
* @returns `Result<FeeResponseV2>` — `{ fee }` (decimal string).
|
|
33526
|
+
*/
|
|
33527
|
+
async getPartnerFee(query, config) {
|
|
33528
|
+
return this.request(
|
|
33529
|
+
this.withQuery("/leverage-yield/fees/partner", { amount: query.amount }),
|
|
33530
|
+
{ method: "GET" },
|
|
33531
|
+
FeeResponseSchema,
|
|
33532
|
+
config
|
|
33533
|
+
);
|
|
33534
|
+
}
|
|
33535
|
+
/**
|
|
33536
|
+
* Compute the protocol (solver) fee for a given input amount.
|
|
33537
|
+
*
|
|
33538
|
+
* @returns `Result<FeeResponseV2>` — `{ fee }` (decimal string).
|
|
33539
|
+
*/
|
|
33540
|
+
async getSolverFee(query, config) {
|
|
33541
|
+
return this.request(
|
|
33542
|
+
this.withQuery("/leverage-yield/fees/solver", { amount: query.amount }),
|
|
33543
|
+
{ method: "GET" },
|
|
33544
|
+
FeeResponseSchema,
|
|
33545
|
+
config
|
|
33546
|
+
);
|
|
33547
|
+
}
|
|
33548
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33549
|
+
// Submit-tx state machine
|
|
33550
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33551
|
+
/**
|
|
33552
|
+
* Submit a vault-swap transaction to be processed (relay, post-execution, etc.). The `intent`
|
|
33553
|
+
* field carries `bigint` numerics — {@link toJsonBody} serializes them. Idempotent on
|
|
33554
|
+
* `(txHash, srcChainKey)`.
|
|
33555
|
+
*
|
|
33556
|
+
* @returns `Result<SubmitTxResponseV2>` — `{ success, data: { status, message } }`.
|
|
33557
|
+
*/
|
|
33558
|
+
async submitTx(body, config) {
|
|
33559
|
+
return this.request(
|
|
33560
|
+
"/leverage-yield/submit-tx",
|
|
33561
|
+
{ method: "POST", body: toJsonBody({ ...body, intent: _LeverageYieldApiService.toWireIntent(body.intent) }) },
|
|
33562
|
+
SubmitTxResponseSchema,
|
|
33563
|
+
config
|
|
33564
|
+
);
|
|
33565
|
+
}
|
|
33566
|
+
/**
|
|
33567
|
+
* Get the processing status of a submitted vault-swap transaction by `(txHash, srcChainKey)`.
|
|
33568
|
+
*
|
|
33569
|
+
* @returns `Result<SubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
|
|
33570
|
+
*/
|
|
33571
|
+
async getSubmitTxStatus(query, config) {
|
|
33572
|
+
return this.request(
|
|
33573
|
+
this.withQuery("/leverage-yield/submit-tx/status", { txHash: query.txHash, srcChainKey: query.srcChainKey }),
|
|
33574
|
+
{ method: "GET" },
|
|
33575
|
+
SubmitTxStatusResponseSchema,
|
|
33576
|
+
config
|
|
33577
|
+
);
|
|
33578
|
+
}
|
|
33579
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33580
|
+
// Utilities (parity with SwapsApiService)
|
|
33581
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
33582
|
+
/**
|
|
33583
|
+
* Merge additional headers into the service's default header set. Existing keys are
|
|
33584
|
+
* overwritten; keys absent from `headers` are preserved.
|
|
33585
|
+
*/
|
|
33586
|
+
setHeaders(headers) {
|
|
33587
|
+
assignHeaders(this.headers, headers);
|
|
33588
|
+
}
|
|
33589
|
+
/** Return the base URL the service is currently pointing at. */
|
|
33590
|
+
getBaseURL() {
|
|
33591
|
+
return this.config.baseURL;
|
|
33592
|
+
}
|
|
33593
|
+
/**
|
|
33594
|
+
* Return the effective per-request timeout (ms).
|
|
33595
|
+
*
|
|
33596
|
+
* Callers bounding a request tighter than this need it as the CEILING, because a
|
|
33597
|
+
* `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it: an override
|
|
33598
|
+
* derived from a caller budget alone would raise the bound whenever that budget is the larger of the
|
|
33599
|
+
* two. `SubmitTxAttempt.requestTimeout` clamps against both (`min(budget left in the attempt, this)`).
|
|
33600
|
+
*/
|
|
33601
|
+
getTimeout() {
|
|
33602
|
+
return this.config.timeout;
|
|
33603
|
+
}
|
|
33604
|
+
};
|
|
32120
33605
|
|
|
32121
33606
|
// src/backendApi/BackendApiService.ts
|
|
32122
33607
|
var BackendApiService = class {
|
|
@@ -32124,6 +33609,7 @@ var BackendApiService = class {
|
|
|
32124
33609
|
swaps;
|
|
32125
33610
|
sponsoring;
|
|
32126
33611
|
bridge;
|
|
33612
|
+
leverageYield;
|
|
32127
33613
|
// resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on
|
|
32128
33614
|
// top. `baseURL` is the gateway root; `basePath` is this service's own mount below it.
|
|
32129
33615
|
config;
|
|
@@ -32152,6 +33638,7 @@ var BackendApiService = class {
|
|
|
32152
33638
|
const swapsConfig2 = resolveSwapsApiConfig(config);
|
|
32153
33639
|
const sponsoringConfig = resolveSponsoringApiConfig(config);
|
|
32154
33640
|
const bridgeConfig2 = resolveBridgeApiConfig(config);
|
|
33641
|
+
const leverageYieldConfig2 = resolveLeverageYieldApiConfig(config);
|
|
32155
33642
|
const shortRoots = [
|
|
32156
33643
|
["backendApi", this.config.baseURL],
|
|
32157
33644
|
["api.swaps", swapsConfig2.baseURL],
|
|
@@ -32176,6 +33663,11 @@ var BackendApiService = class {
|
|
|
32176
33663
|
inheritedApiKeyBaseURLs: [DEFAULT_SPONSORING_API_ENDPOINT, this.config.baseURL]
|
|
32177
33664
|
});
|
|
32178
33665
|
this.bridge = new BridgeApiService(withApiKey(bridgeConfig2, options.apiKey), this.logger, overrideOptions);
|
|
33666
|
+
this.leverageYield = new LeverageYieldApiService(
|
|
33667
|
+
withApiKey(leverageYieldConfig2, options.apiKey),
|
|
33668
|
+
this.logger,
|
|
33669
|
+
overrideOptions
|
|
33670
|
+
);
|
|
32179
33671
|
}
|
|
32180
33672
|
/**
|
|
32181
33673
|
* Issue the HTTP call for a route.
|
|
@@ -32401,6 +33893,46 @@ var BackendApiService = class {
|
|
|
32401
33893
|
const endpoint = `/moneymarket/borrowers?${queryString}`;
|
|
32402
33894
|
return this.request(endpoint, { ...config, method: "GET" }, MoneyMarketBorrowersSchema);
|
|
32403
33895
|
}
|
|
33896
|
+
// Oracle endpoints
|
|
33897
|
+
/**
|
|
33898
|
+
* Fetch the oracle candle store's discovery payload: the quote currency (currently always
|
|
33899
|
+
* `"USD"`), the selectable candle intervals, and the canonical symbols that have candle data.
|
|
33900
|
+
*
|
|
33901
|
+
* Use this to populate a symbol picker and interval switcher before calling
|
|
33902
|
+
* {@link getOracleCandles}.
|
|
33903
|
+
*
|
|
33904
|
+
* @returns `Result<OracleMarketsResponse>` — on success, `{ quote, intervals, symbols }`.
|
|
33905
|
+
*/
|
|
33906
|
+
async getOracleMarkets(config) {
|
|
33907
|
+
return this.request("/oracle/markets", { ...config, method: "GET" }, OracleMarketsResponseSchema);
|
|
33908
|
+
}
|
|
33909
|
+
/**
|
|
33910
|
+
* Fetch USD OHLC candles for a symbol over the half-open time range `[from, to)`.
|
|
33911
|
+
*
|
|
33912
|
+
* `from` and `to` are UNIX **seconds** (integers); `to` is exclusive and must exceed `from`,
|
|
33913
|
+
* and the range may cover at most 5000 buckets of the requested interval (invalid or wider
|
|
33914
|
+
* ranges fail with HTTP 400). A valid range with no stored candles resolves `ok` with
|
|
33915
|
+
* `candles: []`; an unknown symbol currently does the same rather than returning 404. The last
|
|
33916
|
+
* candle may still be forming; re-poll while its `final === false`.
|
|
33917
|
+
* Responses are cached server-side for roughly 10 seconds per distinct URL.
|
|
33918
|
+
*
|
|
33919
|
+
* @param params.symbol - Canonical symbol, exact case, from {@link getOracleMarkets} (e.g. `"ETH"`).
|
|
33920
|
+
* @param params.interval - Candle bucket size: `'1m' | '5m' | '1h' | '1d'`.
|
|
33921
|
+
* @param params.from - Range start, UNIX seconds, inclusive.
|
|
33922
|
+
* @param params.to - Range end, UNIX seconds, exclusive.
|
|
33923
|
+
* @returns `Result<OracleCandlesResponse>` — on success, the echoed query dimensions and
|
|
33924
|
+
* oldest-first candles with USD decimal-string prices (no volume field).
|
|
33925
|
+
*/
|
|
33926
|
+
async getOracleCandles(params, config) {
|
|
33927
|
+
const queryParams = new URLSearchParams();
|
|
33928
|
+
queryParams.append("symbol", params.symbol);
|
|
33929
|
+
queryParams.append("interval", params.interval);
|
|
33930
|
+
queryParams.append("from", String(params.from));
|
|
33931
|
+
queryParams.append("to", String(params.to));
|
|
33932
|
+
const queryString = queryParams.toString();
|
|
33933
|
+
const endpoint = `/oracle/candles?${queryString}`;
|
|
33934
|
+
return this.request(endpoint, { ...config, method: "GET" }, OracleCandlesResponseSchema);
|
|
33935
|
+
}
|
|
32404
33936
|
/**
|
|
32405
33937
|
* Fetch the complete SODAX runtime configuration in a single request.
|
|
32406
33938
|
*
|
|
@@ -32539,15 +34071,17 @@ var BackendApiService = class {
|
|
|
32539
34071
|
* without constructing a new service instance. Existing header keys are
|
|
32540
34072
|
* overwritten; keys absent from `headers` are preserved.
|
|
32541
34073
|
*
|
|
32542
|
-
* Headers also reach `swaps` and `
|
|
32543
|
-
* base-API credentials must not be forwarded to whatever origin it points at. Note
|
|
32544
|
-
* retargeted to another origin via `swapsApiConfig`, in which case a header set
|
|
34074
|
+
* Headers also reach `swaps`, `bridge` and `leverageYield`, but never `sponsoring`: it is configured
|
|
34075
|
+
* independently, so base-API credentials must not be forwarded to whatever origin it points at. Note
|
|
34076
|
+
* `swaps` can also be retargeted to another origin via `swapsApiConfig`, in which case a header set
|
|
34077
|
+
* here follows it.
|
|
32545
34078
|
*
|
|
32546
34079
|
* @param headers - Key-value pairs to add or overwrite in the default headers.
|
|
32547
34080
|
*/
|
|
32548
34081
|
setHeaders(headers) {
|
|
32549
34082
|
assignHeaders(this.headers, headers);
|
|
32550
34083
|
this.swaps.setHeaders(headers);
|
|
34084
|
+
this.leverageYield.setHeaders(headers);
|
|
32551
34085
|
this.bridge.setHeaders(headers);
|
|
32552
34086
|
}
|
|
32553
34087
|
/**
|
|
@@ -35489,7 +37023,7 @@ var AssetService = class {
|
|
|
35489
37023
|
ok: true,
|
|
35490
37024
|
value: {
|
|
35491
37025
|
tx: txResult.value,
|
|
35492
|
-
relayData: { address:
|
|
37026
|
+
relayData: { address: fromHubWallet, payload: data }
|
|
35493
37027
|
}
|
|
35494
37028
|
};
|
|
35495
37029
|
} catch (error) {
|
|
@@ -40773,7 +42307,9 @@ var PartnerFeeClaimService = class {
|
|
|
40773
42307
|
isEvmWalletProviderType(walletProvider),
|
|
40774
42308
|
"PartnerFeeClaimService only supports Evm (sonic) wallet provider"
|
|
40775
42309
|
);
|
|
40776
|
-
const txHash = await walletProvider.sendTransaction(rawTx
|
|
42310
|
+
const txHash = await walletProvider.sendTransaction(rawTx, {
|
|
42311
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
42312
|
+
});
|
|
40777
42313
|
return {
|
|
40778
42314
|
ok: true,
|
|
40779
42315
|
value: txHash
|
|
@@ -40968,7 +42504,9 @@ var PartnerFeeClaimService = class {
|
|
|
40968
42504
|
value: rawTx
|
|
40969
42505
|
};
|
|
40970
42506
|
}
|
|
40971
|
-
const txHash = await _params.walletProvider.sendTransaction(rawTx
|
|
42507
|
+
const txHash = await _params.walletProvider.sendTransaction(rawTx, {
|
|
42508
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
42509
|
+
});
|
|
40972
42510
|
return {
|
|
40973
42511
|
ok: true,
|
|
40974
42512
|
value: txHash
|
|
@@ -41115,7 +42653,9 @@ var PartnerFeeClaimService = class {
|
|
|
41115
42653
|
value: rawTx
|
|
41116
42654
|
};
|
|
41117
42655
|
}
|
|
41118
|
-
const txHash = await _params.walletProvider.sendTransaction(rawTx
|
|
42656
|
+
const txHash = await _params.walletProvider.sendTransaction(rawTx, {
|
|
42657
|
+
expectedChainId: getEvmViemChain(ChainKeys.SONIC_MAINNET).id
|
|
42658
|
+
});
|
|
41119
42659
|
return {
|
|
41120
42660
|
ok: true,
|
|
41121
42661
|
value: txHash
|
|
@@ -41492,10 +43032,20 @@ var LeverageYieldService = class {
|
|
|
41492
43032
|
hubProvider;
|
|
41493
43033
|
config;
|
|
41494
43034
|
spoke;
|
|
41495
|
-
|
|
43035
|
+
backendApi;
|
|
43036
|
+
/**
|
|
43037
|
+
* Effective backend submit-tx flow (`leverageYield.useBackendSubmitTx`, default off). Read live off
|
|
43038
|
+
* `ConfigService`, like `config.leverageYieldPartnerFee`, so the config object and the behavior can
|
|
43039
|
+
* never disagree.
|
|
43040
|
+
*/
|
|
43041
|
+
get useBackendSubmitTx() {
|
|
43042
|
+
return this.config.leverageYieldUseBackendSubmitTx;
|
|
43043
|
+
}
|
|
43044
|
+
constructor({ hubProvider, config, spoke, backendApi }) {
|
|
41496
43045
|
this.hubProvider = hubProvider;
|
|
41497
43046
|
this.config = config;
|
|
41498
43047
|
this.spoke = spoke;
|
|
43048
|
+
this.backendApi = backendApi;
|
|
41499
43049
|
}
|
|
41500
43050
|
// ─── Registry ──────────────────────────────────────────────────────────
|
|
41501
43051
|
/** Returns the static registry of known leverage-yield vaults. */
|
|
@@ -41504,7 +43054,7 @@ var LeverageYieldService = class {
|
|
|
41504
43054
|
}
|
|
41505
43055
|
/** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
|
|
41506
43056
|
getVault(name) {
|
|
41507
|
-
return this.listVaults().find((
|
|
43057
|
+
return this.listVaults().find((v12) => v12.name === name);
|
|
41508
43058
|
}
|
|
41509
43059
|
/**
|
|
41510
43060
|
* Looks up a registered vault by its on-chain proxy address (case-insensitive).
|
|
@@ -41512,7 +43062,7 @@ var LeverageYieldService = class {
|
|
|
41512
43062
|
*/
|
|
41513
43063
|
getVaultByAddress(address) {
|
|
41514
43064
|
const normalized = address.toLowerCase();
|
|
41515
|
-
return this.listVaults().find((
|
|
43065
|
+
return this.listVaults().find((v12) => v12.vault.toLowerCase() === normalized);
|
|
41516
43066
|
}
|
|
41517
43067
|
/**
|
|
41518
43068
|
* Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
|
|
@@ -41935,62 +43485,21 @@ var LeverageYieldService = class {
|
|
|
41935
43485
|
"vaultSwap",
|
|
41936
43486
|
async () => {
|
|
41937
43487
|
try {
|
|
41938
|
-
const timeout = _params.timeout;
|
|
41939
43488
|
const createIntentResult = await this.createVaultIntent(_params);
|
|
41940
43489
|
if (!createIntentResult.ok) {
|
|
41941
43490
|
return { ok: false, error: createIntentResult.error };
|
|
41942
43491
|
}
|
|
41943
|
-
const
|
|
41944
|
-
const
|
|
41945
|
-
|
|
41946
|
-
|
|
41947
|
-
|
|
41948
|
-
|
|
41949
|
-
|
|
41950
|
-
|
|
41951
|
-
|
|
41952
|
-
};
|
|
41953
|
-
}
|
|
41954
|
-
let dstIntentTxHash;
|
|
41955
|
-
if (isHubChainKeyType(srcChainKey)) {
|
|
41956
|
-
dstIntentTxHash = spokeTxHash;
|
|
41957
|
-
} else {
|
|
41958
|
-
const packet = await relayTxAndWaitPacket({
|
|
41959
|
-
srcTxHash: spokeTxHash,
|
|
41960
|
-
data: relayData,
|
|
41961
|
-
chainKey: srcChainKey,
|
|
41962
|
-
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
41963
|
-
timeout
|
|
41964
|
-
});
|
|
41965
|
-
if (!packet.ok) {
|
|
41966
|
-
return {
|
|
41967
|
-
ok: false,
|
|
41968
|
-
error: mapRelayFailure(packet.error, { feature: "leverageYield", ...baseCtx })
|
|
41969
|
-
};
|
|
41970
|
-
}
|
|
41971
|
-
dstIntentTxHash = packet.value.dst_tx_hash;
|
|
41972
|
-
}
|
|
41973
|
-
const postExecResult = await this.notifySolver({
|
|
41974
|
-
intent_tx_hash: dstIntentTxHash
|
|
41975
|
-
});
|
|
41976
|
-
if (!postExecResult.ok) {
|
|
41977
|
-
return { ok: false, error: postExecResult.error };
|
|
43492
|
+
const created = createIntentResult.value;
|
|
43493
|
+
const timeoutMs = resolveTimeoutMs(_params.timeout, DEFAULT_RELAY_TX_TIMEOUT);
|
|
43494
|
+
if (this.useBackendSubmitTx) {
|
|
43495
|
+
const submitted = await this.submitTx(_params, created, createSubmitTxAttempt(timeoutMs));
|
|
43496
|
+
if (submitted.ok) return submitted;
|
|
43497
|
+
this.config.logger.warn(
|
|
43498
|
+
"[leverageYield] backend submit-tx did not complete; falling back to the client-side relay",
|
|
43499
|
+
{ error: submitted.error }
|
|
43500
|
+
);
|
|
41978
43501
|
}
|
|
41979
|
-
return
|
|
41980
|
-
ok: true,
|
|
41981
|
-
value: {
|
|
41982
|
-
solverExecutionResponse: postExecResult.value,
|
|
41983
|
-
intent,
|
|
41984
|
-
intentDeliveryInfo: {
|
|
41985
|
-
srcChainKey,
|
|
41986
|
-
srcTxHash: spokeTxHash,
|
|
41987
|
-
srcAddress: params.srcAddress,
|
|
41988
|
-
dstChainKey: params.dstChainKey,
|
|
41989
|
-
dstTxHash: dstIntentTxHash,
|
|
41990
|
-
dstAddress: params.dstAddress
|
|
41991
|
-
}
|
|
41992
|
-
}
|
|
41993
|
-
};
|
|
43502
|
+
return this.fallbackVaultSwapSteps(_params, created, timeoutMs);
|
|
41994
43503
|
} catch (error) {
|
|
41995
43504
|
if (isLeverageYieldSwapError(error)) return { ok: false, error };
|
|
41996
43505
|
return {
|
|
@@ -42018,6 +43527,129 @@ var LeverageYieldService = class {
|
|
|
42018
43527
|
}
|
|
42019
43528
|
);
|
|
42020
43529
|
}
|
|
43530
|
+
/**
|
|
43531
|
+
* Client-side vault-swap completion (the default path): verify the broadcast intent tx landed,
|
|
43532
|
+
* relay it to the hub (Sonic) — or use it directly when the source IS the hub — then notify the
|
|
43533
|
+
* solver via {@link LeverageYieldService.notifySolver} and build the {@link VaultSwapResponse}.
|
|
43534
|
+
* Extracted from `vaultSwap()` so the opt-in backend 2-step path ({@link LeverageYieldService.submitTx})
|
|
43535
|
+
* can fall back to it on any non-success. Leverage-yield copy of `SwapService.fallbackSwapSteps`.
|
|
43536
|
+
*/
|
|
43537
|
+
async fallbackVaultSwapSteps(_params, created, timeoutMs) {
|
|
43538
|
+
const { params } = _params;
|
|
43539
|
+
const srcChainKey = params.srcChainKey;
|
|
43540
|
+
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey, action: "vaultSwap" };
|
|
43541
|
+
const { tx: spokeTxHash, intent, relayData } = created;
|
|
43542
|
+
const verifyTxHashResult = await this.spoke.verifyTxHash({
|
|
43543
|
+
txHash: spokeTxHash,
|
|
43544
|
+
chainKey: srcChainKey
|
|
43545
|
+
});
|
|
43546
|
+
if (!verifyTxHashResult.ok) {
|
|
43547
|
+
return { ok: false, error: verifyFailed("leverageYield", verifyTxHashResult.error, baseCtx) };
|
|
43548
|
+
}
|
|
43549
|
+
let dstIntentTxHash;
|
|
43550
|
+
if (isHubChainKeyType(srcChainKey)) {
|
|
43551
|
+
dstIntentTxHash = spokeTxHash;
|
|
43552
|
+
} else {
|
|
43553
|
+
const packet = await relayTxAndWaitPacket({
|
|
43554
|
+
srcTxHash: spokeTxHash,
|
|
43555
|
+
data: relayData,
|
|
43556
|
+
chainKey: srcChainKey,
|
|
43557
|
+
relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
|
|
43558
|
+
// The caller's full `timeout`, starting HERE — whether this runs as the only path or as the
|
|
43559
|
+
// backend's fallback, so a stalled backend attempt cannot shorten the relay wait. The floor
|
|
43560
|
+
// covers a sub-floor caller `timeout`: `relayTxAndWaitPacket` SUBMITS before `timeout` bounds
|
|
43561
|
+
// anything, so a zero budget would strand an already-landed tx unrelayed.
|
|
43562
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS)
|
|
43563
|
+
});
|
|
43564
|
+
if (!packet.ok) {
|
|
43565
|
+
return { ok: false, error: mapRelayFailure(packet.error, { feature: "leverageYield", ...baseCtx }) };
|
|
43566
|
+
}
|
|
43567
|
+
dstIntentTxHash = packet.value.dst_tx_hash;
|
|
43568
|
+
}
|
|
43569
|
+
const postExecResult = await this.notifySolver({
|
|
43570
|
+
intent_tx_hash: dstIntentTxHash
|
|
43571
|
+
});
|
|
43572
|
+
if (!postExecResult.ok) {
|
|
43573
|
+
return { ok: false, error: postExecResult.error };
|
|
43574
|
+
}
|
|
43575
|
+
return {
|
|
43576
|
+
ok: true,
|
|
43577
|
+
value: {
|
|
43578
|
+
solverExecutionResponse: postExecResult.value,
|
|
43579
|
+
intent,
|
|
43580
|
+
intentDeliveryInfo: {
|
|
43581
|
+
srcChainKey,
|
|
43582
|
+
srcTxHash: spokeTxHash,
|
|
43583
|
+
srcAddress: params.srcAddress,
|
|
43584
|
+
dstChainKey: params.dstChainKey,
|
|
43585
|
+
dstTxHash: dstIntentTxHash,
|
|
43586
|
+
dstAddress: params.dstAddress
|
|
43587
|
+
}
|
|
43588
|
+
}
|
|
43589
|
+
};
|
|
43590
|
+
}
|
|
43591
|
+
/**
|
|
43592
|
+
* Backend 2-step vault-swap path (opt-in via `leverageYield.useBackendSubmitTx`): hand the
|
|
43593
|
+
* broadcast intent tx to the leverage-yield API (`POST /leverage-yield/submit-tx`); the backend
|
|
43594
|
+
* relays + post-executes server-side. Polls `getSubmitTxStatus` until `solved`, then reconstructs
|
|
43595
|
+
* the same {@link VaultSwapResponse} the client-side path returns.
|
|
43596
|
+
*
|
|
43597
|
+
* Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, a 200 the backend did not
|
|
43598
|
+
* accept, terminal `failed` / abandoned, or poll timeout) so `vaultSwap()` falls back to
|
|
43599
|
+
* {@link LeverageYieldService.fallbackVaultSwapSteps}. Falling back is safe: re-relaying / re-posting
|
|
43600
|
+
* an already-processed vault swap is idempotent (the relay dedups the `executed` packet and the solver
|
|
43601
|
+
* re-affirms the intent — no double-fill), and load-bearing rather than belt-and-braces: the backend
|
|
43602
|
+
* keeps processing after this attempt gives up, so the fallback's relay can race the backend's own.
|
|
43603
|
+
*
|
|
43604
|
+
* The attempt itself — POST, budget clamps, status poll — is {@link runBackendSubmitTx}, shared with
|
|
43605
|
+
* swaps and bridge. What is leverage-yield-specific and lives here: the request body (including the
|
|
43606
|
+
* `operation` discriminator), the `solved` terminal status, the mapping to a
|
|
43607
|
+
* {@link VaultSwapResponse}, and the leverage-yield error taxonomy.
|
|
43608
|
+
*
|
|
43609
|
+
* `attempt` bounds this attempt alone — the POST and every status request draw on it, and the
|
|
43610
|
+
* client-side fallback holds a separate fresh `timeout`.
|
|
43611
|
+
*/
|
|
43612
|
+
async submitTx(_params, created, attempt) {
|
|
43613
|
+
const { params } = _params;
|
|
43614
|
+
const srcChainKey = params.srcChainKey;
|
|
43615
|
+
const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey, action: "vaultSwap" };
|
|
43616
|
+
const { tx: spokeTxHash, intent, relayData } = created;
|
|
43617
|
+
try {
|
|
43618
|
+
const outcome = await runBackendSubmitTx({
|
|
43619
|
+
attempt,
|
|
43620
|
+
api: this.backendApi.leverageYield,
|
|
43621
|
+
body: {
|
|
43622
|
+
txHash: spokeTxHash,
|
|
43623
|
+
srcChainKey,
|
|
43624
|
+
walletAddress: params.srcAddress,
|
|
43625
|
+
intent,
|
|
43626
|
+
relayData: relayData.payload,
|
|
43627
|
+
// `withdraw` sets `hubWalletSwap: true` (spends the hub-wallet lsoda*); a plain deposit doesn't.
|
|
43628
|
+
operation: _params.hubWalletSwap ? "withdraw" : "deposit"
|
|
43629
|
+
},
|
|
43630
|
+
statusQuery: { txHash: spokeTxHash, srcChainKey },
|
|
43631
|
+
// A vault deposit/withdraw IS a solver swap, so terminal success is `solved` — not bridge's
|
|
43632
|
+
// `executed`.
|
|
43633
|
+
terminalStatus: "solved",
|
|
43634
|
+
onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
|
|
43635
|
+
// Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
|
|
43636
|
+
solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
|
|
43637
|
+
intent,
|
|
43638
|
+
intentDeliveryInfo: {
|
|
43639
|
+
srcChainKey,
|
|
43640
|
+
srcTxHash: spokeTxHash,
|
|
43641
|
+
srcAddress: params.srcAddress,
|
|
43642
|
+
dstChainKey: params.dstChainKey,
|
|
43643
|
+
dstTxHash: result.dstIntentTxHash,
|
|
43644
|
+
dstAddress: params.dstAddress
|
|
43645
|
+
}
|
|
43646
|
+
} : void 0
|
|
43647
|
+
});
|
|
43648
|
+
return outcome.ok ? { ok: true, value: outcome.value } : { ok: false, error: executionFailed("leverageYield", outcome.cause, baseCtx) };
|
|
43649
|
+
} catch (error) {
|
|
43650
|
+
return { ok: false, error: unknownFailed("leverageYield", error, baseCtx) };
|
|
43651
|
+
}
|
|
43652
|
+
}
|
|
42021
43653
|
/**
|
|
42022
43654
|
* Notifies the solver that the vault intent landed on the hub, triggering it to fill.
|
|
42023
43655
|
* Leverage-yield copy of the swap domain's `postExecution` — emits only
|
|
@@ -42591,7 +44223,7 @@ function xlmDecimalToStroops(amount) {
|
|
|
42591
44223
|
const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
|
|
42592
44224
|
return BigInt(scaled);
|
|
42593
44225
|
}
|
|
42594
|
-
var
|
|
44226
|
+
var STELLAR_BASE_RESERVE_STROOPS2 = 5000000n;
|
|
42595
44227
|
var BASE_RESERVE_UNITS = 2;
|
|
42596
44228
|
function parseBaseReserveStroops(ledger) {
|
|
42597
44229
|
const value = ledger?.base_reserve_in_stroops;
|
|
@@ -42618,7 +44250,7 @@ var SPONSOR_CONFIG_TTL_MS = 6e4;
|
|
|
42618
44250
|
var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
|
|
42619
44251
|
var DEFAULT_MAX_HORIZON_RETRIES = 2;
|
|
42620
44252
|
var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
|
|
42621
|
-
var STELLAR_TRUSTLINE_MIN_XLM_STROOPS =
|
|
44253
|
+
var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS2 + STELLAR_FEE_HEADROOM_STROOPS;
|
|
42622
44254
|
var SponsoringService = class {
|
|
42623
44255
|
config;
|
|
42624
44256
|
spoke;
|
|
@@ -42721,7 +44353,7 @@ var SponsoringService = class {
|
|
|
42721
44353
|
reason: messageOf(error, String(error))
|
|
42722
44354
|
});
|
|
42723
44355
|
}
|
|
42724
|
-
return
|
|
44356
|
+
return STELLAR_BASE_RESERVE_STROOPS2;
|
|
42725
44357
|
};
|
|
42726
44358
|
const request = read().then((value) => {
|
|
42727
44359
|
this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
|
|
@@ -43029,7 +44661,8 @@ var Sodax = class {
|
|
|
43029
44661
|
this.leverageYield = new LeverageYieldService({
|
|
43030
44662
|
hubProvider: this.hubProvider,
|
|
43031
44663
|
config: this.config,
|
|
43032
|
-
spoke: this.spoke
|
|
44664
|
+
spoke: this.spoke,
|
|
44665
|
+
backendApi: this.backendApi
|
|
43033
44666
|
});
|
|
43034
44667
|
this.sponsoring = new SponsoringService({
|
|
43035
44668
|
config: this.config,
|
|
@@ -43077,4 +44710,4 @@ var isPartnerError = isCodeMember(PARTNER_CODES);
|
|
|
43077
44710
|
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
43078
44711
|
*/
|
|
43079
44712
|
|
|
43080
|
-
export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BACKEND_API_BASE_PATH, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BITCOIN_DUST_SATS, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BackendHttpError, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeApiService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_API_BASE_URL, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DEFAULT_SPONSORING_API_ENDPOINT, DETAILED_STATUS_NOT_DELIVERED, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RELAY_FALLBACK_FLOOR_MS, RELAY_REQUEST_TIMEOUT_MS, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, SPEED_TIER_SECONDS, SPEED_TIER_THRESHOLDS, SPONSORING_API_ERROR_CODES, SPONSORING_API_STELLAR_BASE_PATH, SPONSOR_CONFIG_TTL_MS, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_BASE_RESERVE_TTL_MS, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, SponsoringApiService, SponsoringService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiGrpcTransport, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, classifySponsorError, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, erc20Abi, erc4626Abi, estimateBitcoinTxSize, estimateSwapSpeedTier, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isApprovalSupportedChainKeyType, isAuthFailure, isAuthStatus, isBackendHttpError, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isFillEvent, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeBitcoinToken, isNativeBitcoinTransfer, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isSponsoringConfigError, isSponsoringLookupError, isSponsoringOrchestrationError, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, robinhoodChain, robinhoodSupportedTokens, serializeAddressData, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, sponsoringInvariant, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, toCreateBridgeIntentParamsV2, toSuiExecutionResult, toSuiExecutionStatus, toSuiPaginatedCoins, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
|
|
44713
|
+
export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BACKEND_API_BASE_PATH, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BITCOIN_DUST_SATS, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BackendHttpError, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeApiService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_API_BASE_URL, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DEFAULT_SPONSORING_API_ENDPOINT, DETAILED_STATUS_NOT_DELIVERED, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldApiService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, ORACLE_CANDLE_INTERVALS, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RELAY_FALLBACK_FLOOR_MS, RELAY_REQUEST_TIMEOUT_MS, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, SPEED_TIER_SECONDS, SPEED_TIER_THRESHOLDS, SPONSORING_API_ERROR_CODES, SPONSORING_API_STELLAR_BASE_PATH, SPONSOR_CONFIG_TTL_MS, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_BASE_RESERVE_TTL_MS, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, SponsoringApiService, SponsoringService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiGrpcTransport, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, canonicalizeBitcoinAddress, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, classifySponsorError, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createBalanceCollector, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, encodeTokenIdentifier, erc20Abi, erc4626Abi, estimateBitcoinTxSize, estimateSwapSpeedTier, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isApprovalSupportedChainKeyType, isAuthFailure, isAuthStatus, isBackendHttpError, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isFillEvent, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeBitcoinToken, isNativeBitcoinTransfer, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isOracleCandleInterval, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isSponsoringConfigError, isSponsoringLookupError, isSponsoringOrchestrationError, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidBitcoinAddress, isValidInjectiveAddress, isValidNearAccountId, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, robinhoodChain, robinhoodSupportedTokens, serializeAddressData, settleWalletBalances, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, sponsoringInvariant, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, toCreateBridgeIntentParamsV2, toSuiExecutionResult, toSuiExecutionStatus, toSuiPaginatedCoins, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
|