@sodax/sdk 0.0.1-rc.26 → 0.0.1-rc.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,21 +1,21 @@
1
- import { getAbiItem, encodeAbiParameters, parseAbiParameters, toHex, erc20Abi as erc20Abi$1, encodeFunctionData, fromHex, createPublicClient, http, decodeAbiParameters, encodePacked, parseEventLogs, keccak256, isAddress } from 'viem';
2
- import invariant11 from 'tiny-invariant';
3
- import { bcs } from '@mysten/sui/bcs';
4
- import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram } from '@solana/web3.js';
5
- import { SorobanRpc, Address, Horizon, Contract, TransactionBuilder, BASE_FEE, nativeToScVal, TimeoutInfinite, rpc, scValToBigInt, Operation, Account, FeeBumpTransaction } from '@stellar/stellar-sdk';
1
+ import { getAbiItem, encodeAbiParameters, parseAbiParameters, fromHex, createPublicClient, http, toHex, erc20Abi as erc20Abi$1, encodeFunctionData, decodeAbiParameters, encodePacked, parseEventLogs, keccak256, isAddress } from 'viem';
6
2
  import { nibiru, polygon, bsc, optimism, base, arbitrum, avalanche, sonic } from 'viem/chains';
7
3
  import { SPOKE_CHAIN_IDS, ICON_MAINNET_CHAIN_ID, SUI_MAINNET_CHAIN_ID, STELLAR_MAINNET_CHAIN_ID, INJECTIVE_MAINNET_CHAIN_ID, POLYGON_MAINNET_CHAIN_ID, BSC_MAINNET_CHAIN_ID, OPTIMISM_MAINNET_CHAIN_ID, BASE_MAINNET_CHAIN_ID, ARBITRUM_MAINNET_CHAIN_ID, NIBIRU_MAINNET_CHAIN_ID, AVALANCHE_MAINNET_CHAIN_ID, SOLANA_MAINNET_CHAIN_ID, SONIC_MAINNET_CHAIN_ID } from '@sodax/types';
8
4
  export * from '@sodax/types';
9
5
  import { ChainGrpcWasmApi, TxGrpcApi, toBase64 } from '@injectivelabs/sdk-ts';
10
6
  import { getNetworkEndpoints, Network } from '@injectivelabs/networks';
11
7
  import * as IconSdkRaw from 'icon-sdk-js';
8
+ import { SorobanRpc, Horizon, Contract, TransactionBuilder, BASE_FEE, nativeToScVal, TimeoutInfinite, rpc, scValToBigInt, Operation, Address, Account, FeeBumpTransaction } from '@stellar/stellar-sdk';
9
+ import { bcs } from '@mysten/sui/bcs';
12
10
  import { SuiClient, getFullnodeUrl } from '@mysten/sui/client';
13
11
  import { Transaction } from '@mysten/sui/transactions';
12
+ import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram } from '@solana/web3.js';
14
13
  import { CosmosTxV1Beta1Tx } from '@injectivelabs/core-proto-ts';
15
14
  import * as rlp from 'rlp';
16
15
  import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
17
16
  import * as anchor from '@coral-xyz/anchor';
18
17
  import BN from 'bn.js';
18
+ import invariant11 from 'tiny-invariant';
19
19
  import BigNumber4, { BigNumber } from 'bignumber.js';
20
20
 
21
21
  // src/abis/asset-manager.abi.ts
@@ -6104,107 +6104,6 @@ function encodeContractCalls(calls) {
6104
6104
  async function waitForTransactionReceipt(hash, provider) {
6105
6105
  return provider.waitForTransactionReceipt(hash);
6106
6106
  }
6107
- async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
6108
- do {
6109
- try {
6110
- return await action(retryCount);
6111
- } catch (e) {
6112
- retryCount--;
6113
- if (retryCount <= 0) {
6114
- console.error(`Failed to perform operation even after ${DEFAULT_MAX_RETRY} attempts.. Throwing origin error..`);
6115
- throw e;
6116
- }
6117
- }
6118
- await new Promise((resolve) => setTimeout(resolve, delayMs));
6119
- } while (retryCount > 0);
6120
- throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
6121
- }
6122
- function getRandomBytes(length) {
6123
- const array = new Uint8Array(length);
6124
- for (let i = 0; i < length; i++) {
6125
- array[i] = Math.floor(Math.random() * 256);
6126
- }
6127
- return array;
6128
- }
6129
- function randomUint256() {
6130
- const bytes = getRandomBytes(32);
6131
- let hex = "";
6132
- for (const byte of bytes) {
6133
- hex += byte.toString(16).padStart(2, "0") ?? "";
6134
- }
6135
- return BigInt(`0x${hex}`);
6136
- }
6137
- function calculatePercentageFeeAmount(amount, percentage) {
6138
- return amount * BigInt(percentage) / FEE_PERCENTAGE_SCALE;
6139
- }
6140
- function calculateFeeAmount(inputAmount, fee) {
6141
- if (!fee) {
6142
- return 0n;
6143
- }
6144
- invariant11(inputAmount > 0n, "Input amount must be greater than 0");
6145
- let feeAmount = 0n;
6146
- if (isPartnerFeeAmount(fee)) {
6147
- invariant11(
6148
- fee.amount >= 0 && fee.amount <= inputAmount,
6149
- `Fee amount must be greater than 0 and less than or equal to the input amount: ${fee.amount}`
6150
- );
6151
- feeAmount = fee.amount;
6152
- } else if (isPartnerFeePercentage(fee)) {
6153
- invariant11(
6154
- fee.percentage >= 0 && fee.percentage <= FEE_PERCENTAGE_SCALE,
6155
- `Fee percentage must be between 0 and ${FEE_PERCENTAGE_SCALE}}`
6156
- );
6157
- feeAmount = calculatePercentageFeeAmount(inputAmount, fee.percentage);
6158
- }
6159
- return feeAmount;
6160
- }
6161
- function adjustAmountByFee(amount, fee, quoteType) {
6162
- invariant11(amount > 0n, "Amount must be greater than 0");
6163
- invariant11(quoteType === "exact_input" || quoteType === "exact_output", "Invalid quote type");
6164
- if (quoteType === "exact_input") {
6165
- return amount - calculateFeeAmount(amount, fee);
6166
- }
6167
- if (quoteType === "exact_output") {
6168
- return amount + calculateFeeAmount(amount, fee);
6169
- }
6170
- throw new Error("Invalid quote type");
6171
- }
6172
- function BigIntToHex(value) {
6173
- return `0x${value.toString(16)}`;
6174
- }
6175
- function encodeAddress(spokeChainId, address) {
6176
- switch (spokeChainId) {
6177
- case "0xa86a.avax":
6178
- case "0x2105.base":
6179
- case "0xa.optimism":
6180
- case "0x38.bsc":
6181
- case "0x89.polygon":
6182
- case "0xa4b1.arbitrum":
6183
- case "sonic":
6184
- return address;
6185
- case "injective-1":
6186
- return toHex(Buffer.from(address, "utf-8"));
6187
- case "0x1.icon":
6188
- return toHex(Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex"));
6189
- case "sui":
6190
- return toHex(bcs.Address.serialize(address).toBytes());
6191
- case "solana":
6192
- return toHex(Buffer.from(new PublicKey(address).toBytes()));
6193
- case "stellar":
6194
- return `0x${Address.fromString(address).toScVal().toXDR("hex")}`;
6195
- default:
6196
- return address;
6197
- }
6198
- }
6199
- function hexToBigInt(hex) {
6200
- const trimmed = hex.trim().toLowerCase();
6201
- const isValid = /^(0x)?[0-9a-f]+$/.test(trimmed);
6202
- if (!isValid) {
6203
- throw new Error(`Invalid hex string: "${hex}"`);
6204
- }
6205
- const normalized = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
6206
- return BigInt(normalized);
6207
- }
6208
6107
  var DEFAULT_MAX_RETRY = 3;
6209
6108
  var DEFAULT_RELAY_TX_TIMEOUT = 6e4;
6210
6109
  var DEFAULT_RETRY_DELAY_MS = 2e3;
@@ -6213,6 +6112,7 @@ var MAX_UINT256 = (1n << 256n) - 1n;
6213
6112
  var FEE_PERCENTAGE_SCALE = 10000n;
6214
6113
  var STELLAR_PRIORITY_FEE = "10000";
6215
6114
  var STELLAR_DEFAULT_TX_TIMEOUT_SECONDS = 100;
6115
+ var DEFAULT_DEADLINE_OFFSET = 300n;
6216
6116
  var VAULT_TOKEN_DECIMALS = 18;
6217
6117
  var INTENT_RELAY_CHAIN_IDS = {
6218
6118
  AVAX: 6n,
@@ -7909,660 +7809,257 @@ var isNativeToken = (chainId, token) => {
7909
7809
  }
7910
7810
  return token.address.toLowerCase() === spokeChainConfig[chainId].nativeToken.toLowerCase();
7911
7811
  };
7912
- var Erc20Service = class {
7913
- constructor() {
7812
+ var InjectiveSpokeProvider = class {
7813
+ walletProvider;
7814
+ chainConfig;
7815
+ chainGrpcWasmApi;
7816
+ txClient;
7817
+ constructor(conf, walletProvider) {
7818
+ this.chainConfig = conf;
7819
+ this.walletProvider = walletProvider;
7820
+ const endpoints = getNetworkEndpoints(Network.Mainnet);
7821
+ this.chainGrpcWasmApi = new ChainGrpcWasmApi(endpoints.grpc);
7822
+ this.txClient = new TxGrpcApi(endpoints.grpc);
7914
7823
  }
7915
- /**
7916
- * Check if spender has enough ERC20 allowance for given amount
7917
- * @param token - ERC20 token address
7918
- * @param amount - Amount to check allowance for
7919
- * @param owner - User wallet address
7920
- * @param spender - Spender address
7921
- * @param spokeProvider - EVM Spoke provider
7922
- * @return - True if spender is allowed to spend amount on behalf of owner
7923
- */
7924
- static async isAllowanceValid(token, amount, owner, spender, spokeProvider) {
7925
- try {
7926
- if (token.toLowerCase() === spokeProvider.chainConfig.nativeToken.toLowerCase()) {
7927
- return {
7928
- ok: true,
7929
- value: true
7930
- };
7931
- }
7932
- const allowedAmount = await spokeProvider.publicClient.readContract({
7933
- address: token,
7934
- abi: erc20Abi$1,
7935
- functionName: "allowance",
7936
- args: [owner, spender]
7937
- });
7938
- return {
7939
- ok: true,
7940
- value: allowedAmount >= amount
7941
- };
7942
- } catch (e) {
7943
- return {
7944
- ok: false,
7945
- error: e
7946
- };
7947
- }
7824
+ // Query Methods
7825
+ async getState() {
7826
+ return this.chainGrpcWasmApi.fetchSmartContractState(
7827
+ this.chainConfig.addresses.assetManager,
7828
+ toBase64({
7829
+ get_state: {}
7830
+ })
7831
+ );
7948
7832
  }
7949
- /**
7950
- * Approve ERC20 amount spending
7951
- * @param token - ERC20 token address
7952
- * @param amount - Amount to approve
7953
- * @param spender - Spender address
7954
- * @param provider - EVM Provider
7955
- */
7956
- static async approve(token, amount, spender, spokeProvider, raw) {
7957
- const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
7958
- const rawTx = {
7959
- from: walletAddress,
7960
- to: token,
7961
- value: 0n,
7962
- data: encodeFunctionData({
7963
- abi: erc20Abi$1,
7964
- functionName: "approve",
7965
- args: [spender, amount]
7833
+ async getBalance(token) {
7834
+ return this.chainGrpcWasmApi.fetchSmartContractState(
7835
+ this.chainConfig.addresses.assetManager,
7836
+ toBase64({
7837
+ get_balance: { denom: token }
7966
7838
  })
7839
+ );
7840
+ }
7841
+ // Execute Methods (requires SigningCosmWasmClient)
7842
+ /**
7843
+ * Deposit tokens including native token to Injective Asset Manager.
7844
+ **/
7845
+ static async deposit(sender, token_address, to, amount, data = "0x", spokeProvider, raw) {
7846
+ const toBytes = fromHex(to, "bytes");
7847
+ const dataBytes = fromHex(data, "bytes");
7848
+ const msg = {
7849
+ transfer: {
7850
+ token: token_address,
7851
+ to: Array.from(toBytes),
7852
+ amount,
7853
+ data: Array.from(dataBytes)
7854
+ }
7967
7855
  };
7856
+ const funds = [{ amount, denom: token_address }];
7968
7857
  if (raw) {
7969
- return rawTx;
7858
+ return await spokeProvider.walletProvider.getRawTransaction(
7859
+ spokeProvider.chainConfig.networkId,
7860
+ spokeProvider.chainConfig.prefix,
7861
+ sender,
7862
+ spokeProvider.chainConfig.addresses.assetManager,
7863
+ msg
7864
+ );
7970
7865
  }
7971
- return spokeProvider.walletProvider.sendTransaction(rawTx);
7866
+ const res = await spokeProvider.walletProvider.execute(
7867
+ sender,
7868
+ spokeProvider.chainConfig.addresses.assetManager,
7869
+ msg,
7870
+ funds
7871
+ );
7872
+ return res.transactionHash;
7972
7873
  }
7973
- /**
7974
- * Encodes a transfer transaction for a token.
7975
- * @param token - The address of the token.
7976
- * @param to - The address to transfer the token to.
7977
- * @param amount - The amount of the token to transfer.
7978
- * @returns The encoded contract call.
7979
- */
7980
- static encodeTransfer(token, to, amount) {
7981
- return {
7982
- address: token,
7983
- value: 0n,
7984
- data: encodeFunctionData({
7985
- abi: erc20Abi$1,
7986
- functionName: "transfer",
7987
- args: [to, amount]
7988
- })
7874
+ async receiveMessage(senderAddress, srcChainId, srcAddress, connSn, payload, signatures) {
7875
+ const msg = {
7876
+ recv_message: {
7877
+ src_chain_id: srcChainId,
7878
+ src_address: srcAddress,
7879
+ conn_sn: connSn,
7880
+ payload,
7881
+ signatures
7882
+ }
7989
7883
  };
7884
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
7990
7885
  }
7991
- /**
7992
- * Encodes a transferFrom transaction for a token.
7993
- * @param token - The address of the token.
7994
- * @param from - The address to transfer the token from.
7995
- * @param to - The address to transfer the token to.
7996
- * @param amount - The amount of the token to transfer.
7997
- * @returns The encoded contract call.
7998
- */
7999
- static encodeTransferFrom(token, from, to, amount) {
8000
- return {
8001
- address: token,
8002
- value: 0n,
8003
- data: encodeFunctionData({
8004
- abi: erc20Abi$1,
8005
- functionName: "transferFrom",
8006
- args: [from, to, amount]
8007
- })
7886
+ async setRateLimit(senderAddress, rateLimit) {
7887
+ const msg = {
7888
+ set_rate_limit: {
7889
+ rate_limit: rateLimit
7890
+ }
8008
7891
  };
7892
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8009
7893
  }
8010
- /**
8011
- * Encodes an approval transaction for a token.
8012
- * @param token - The address of the token.
8013
- * @param to - The address to approve the token to.
8014
- * @param amount - The amount of the token to approve.
8015
- * @returns The encoded contract call.
8016
- */
8017
- static encodeApprove(token, to, amount) {
8018
- return {
8019
- address: token,
8020
- value: 0n,
8021
- data: encodeFunctionData({
8022
- abi: erc20Abi$1,
8023
- functionName: "approve",
8024
- args: [to, amount]
8025
- })
7894
+ async setConnection(senderAddress, connection) {
7895
+ const msg = {
7896
+ set_connection: {
7897
+ connection
7898
+ }
8026
7899
  };
7900
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8027
7901
  }
8028
- };
8029
- var EvmVaultTokenService = class {
8030
- constructor() {
8031
- }
8032
- /**
8033
- * Fetches token information for a specific token in the vault.
8034
- * @param vault - The address of the vault.
8035
- * @param token - The address of the token.
8036
- * @param publicClient - PublicClient<HttpTransport>
8037
- * @returns Token information as a TokenInfo object.
8038
- */
8039
- static async getTokenInfo(vault, token, publicClient) {
8040
- const [decimals, depositFee, withdrawalFee, maxDeposit, isSupported] = await publicClient.readContract({
8041
- address: vault,
8042
- abi: vaultTokenAbi,
8043
- functionName: "tokenInfo",
8044
- args: [token]
8045
- });
8046
- return { decimals, depositFee, withdrawalFee, maxDeposit, isSupported };
8047
- }
8048
- /**
8049
- * Retrieves the reserves of the vault.
8050
- * @param vault - The address of the vault.
8051
- * @param publicClient - PublicClient<HttpTransport>
8052
- * @returns An object containing tokens and their balances.
8053
- */
8054
- static async getVaultReserves(vault, publicClient) {
8055
- const [tokens, balances] = await publicClient.readContract({
8056
- address: vault,
8057
- abi: vaultTokenAbi,
8058
- functionName: "getVaultReserves",
8059
- args: []
8060
- });
8061
- return {
8062
- tokens,
8063
- balances
7902
+ async setOwner(senderAddress, owner) {
7903
+ const msg = {
7904
+ set_owner: {
7905
+ owner
7906
+ }
8064
7907
  };
7908
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8065
7909
  }
8066
- /**
8067
- * Retrieves all token information for the vault.
8068
- * @param vault - The address of the vault.
8069
- * @param publicClient - PublicClient<HttpTransport>
8070
- * @returns A promise that resolves to an object containing tokens, their infos, and reserves.
8071
- */
8072
- async getAllTokenInfo(vault, publicClient) {
8073
- const [tokens, infos, reserves] = await publicClient.readContract({
8074
- address: vault,
8075
- abi: vaultTokenAbi,
8076
- functionName: "getAllTokenInfo",
8077
- args: []
8078
- });
8079
- return {
8080
- tokens,
8081
- infos,
8082
- reserves
7910
+ async send_message(sender, dst_chain_id, dst_address, payload, raw) {
7911
+ const msg = {
7912
+ send_message: {
7913
+ dst_chain_id: Number.parseInt(dst_chain_id),
7914
+ dst_address: Array.from(fromHex(dst_address, "bytes")),
7915
+ payload: Array.from(fromHex(payload, "bytes"))
7916
+ }
8083
7917
  };
7918
+ if (raw) {
7919
+ return await this.walletProvider.getRawTransaction(
7920
+ this.chainConfig.networkId,
7921
+ this.chainConfig.prefix,
7922
+ sender,
7923
+ this.chainConfig.addresses.connection,
7924
+ msg
7925
+ );
7926
+ }
7927
+ const res = await this.walletProvider.execute(sender, this.chainConfig.addresses.connection, msg);
7928
+ return res.transactionHash;
8084
7929
  }
8085
- /**
8086
- * Deposits a specified amount of a token into the vault.
8087
- * @param vault - The address of the vault.
8088
- * @param token - The address of the token to deposit.
8089
- * @param amount - The amount of the token to deposit.
8090
- * @param walletProvider - IEvmWalletProvider
8091
- * @returns Transaction hash
8092
- */
8093
- static async deposit(vault, token, amount, walletProvider) {
8094
- const from = await walletProvider.getWalletAddress();
8095
- return walletProvider.sendTransaction({
8096
- from,
8097
- to: vault,
8098
- value: 0n,
8099
- data: encodeFunctionData({
8100
- abi: vaultTokenAbi,
8101
- functionName: "deposit",
8102
- args: [token, amount]
8103
- })
8104
- });
8105
- }
8106
- /**
8107
- * Withdraws a specified amount of a token from the vault.
8108
- * @param vault - The address of the vault.
8109
- * @param token - The address of the token to withdraw.
8110
- * @param amount - The amount of the token to withdraw.
8111
- * @param provider - EvmWalletProvider
8112
- * @returns Transaction hash
8113
- */
8114
- static async withdraw(vault, token, amount, provider) {
8115
- const from = await provider.getWalletAddress();
8116
- return provider.sendTransaction({
8117
- from,
8118
- to: vault,
8119
- value: 0n,
8120
- data: encodeFunctionData({
8121
- abi: vaultTokenAbi,
8122
- functionName: "withdraw",
8123
- args: [token, amount]
8124
- })
8125
- });
8126
- }
8127
- /**
8128
- * Encodes the deposit transaction data for the vault.
8129
- * @param vault - The address of the vault.
8130
- * @param token - The address of the token to deposit.
8131
- * @param amount - The amount of the token to deposit.
8132
- * @returns The encoded contract call data.
8133
- */
8134
- static encodeDeposit(vault, token, amount) {
8135
- return {
8136
- address: vault,
8137
- value: 0n,
8138
- data: encodeFunctionData({
8139
- abi: vaultTokenAbi,
8140
- functionName: "deposit",
8141
- args: [token, amount]
8142
- })
8143
- };
7930
+ // Helper Methods
7931
+ static stringToUint8Array(str) {
7932
+ return new TextEncoder().encode(str);
8144
7933
  }
8145
- /**
8146
- * Encodes the withdraw transaction data for the vault.
8147
- * @param vault - The address of the vault.
8148
- * @param token - The address of the token to withdraw.
8149
- * @param amount - The amount of the token to withdraw.
8150
- * @returns The encoded contract call data.
8151
- */
8152
- static encodeWithdraw(vault, token, amount) {
8153
- return {
8154
- address: vault,
8155
- value: 0n,
8156
- data: encodeFunctionData({
8157
- abi: vaultTokenAbi,
8158
- functionName: "withdraw",
8159
- args: [token, amount]
8160
- })
8161
- };
7934
+ static uint8ArrayToString(arr) {
7935
+ return new TextDecoder().decode(arr);
8162
7936
  }
8163
- /**
8164
- * Translates token amounts from their native decimals to 18 decimals
8165
- * @param decimals - The number of decimals of the token
8166
- * @param amount - The amount to translate
8167
- * @returns The translated amount
8168
- */
8169
- static translateIncomingDecimals(decimals, amount) {
8170
- if (decimals <= 18) {
8171
- return amount * BigInt(10 ** (18 - decimals));
8172
- }
8173
- return amount / BigInt(10 ** (decimals - 18));
7937
+ static toBigIntString(num) {
7938
+ return num.toString();
8174
7939
  }
8175
- /**
8176
- * Translates token amounts from 18 decimals back to their native decimals
8177
- * @param decimals - The number of decimals of the token
8178
- * @param amount - The amount to translate
8179
- * @returns The translated amount
8180
- */
8181
- static translateOutgoingDecimals(decimals, amount) {
8182
- if (decimals <= 18) {
8183
- return amount / BigInt(10 ** (18 - decimals));
8184
- }
8185
- return amount * BigInt(10 ** (decimals - 18));
7940
+ };
7941
+ var IconSdk = "default" in IconSdkRaw.default ? IconSdkRaw.default : IconSdkRaw;
7942
+ var IconSpokeProvider = class {
7943
+ walletProvider;
7944
+ chainConfig;
7945
+ iconService;
7946
+ debugRpcUrl;
7947
+ constructor(walletProvider, chainConfig, rpcUrl = "https://ctz.solidwallet.io/api/v3", debugRpcUrl = "https://ctz.solidwallet.io/api/v3d") {
7948
+ this.walletProvider = walletProvider;
7949
+ this.chainConfig = chainConfig;
7950
+ this.iconService = new IconSdk.IconService(new IconSdk.IconService.HttpProvider(rpcUrl));
7951
+ this.debugRpcUrl = debugRpcUrl;
8186
7952
  }
8187
7953
  };
8188
7954
 
8189
- // src/services/hub/EvmAssetManagerService.ts
8190
- var EvmAssetManagerService = class _EvmAssetManagerService {
8191
- constructor() {
7955
+ // src/entities/icon/utils.ts
7956
+ function getIconAddressBytes(address) {
7957
+ return `0x${Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex").toString("hex")}`;
7958
+ }
7959
+
7960
+ // src/entities/Providers.ts
7961
+ var EvmHubProvider = class {
7962
+ publicClient;
7963
+ chainConfig;
7964
+ constructor(config) {
7965
+ if (config) {
7966
+ this.publicClient = createPublicClient({
7967
+ transport: http(config.hubRpcUrl),
7968
+ chain: getEvmViemChain(config.chainConfig.chain.id)
7969
+ });
7970
+ this.chainConfig = config.chainConfig;
7971
+ } else {
7972
+ this.publicClient = createPublicClient({
7973
+ transport: http("https://rpc.soniclabs.com"),
7974
+ chain: getEvmViemChain(SONIC_MAINNET_CHAIN_ID)
7975
+ });
7976
+ this.chainConfig = getHubChainConfig(SONIC_MAINNET_CHAIN_ID);
7977
+ }
8192
7978
  }
8193
- /**
8194
- * Get asset information for a given asset address
8195
- * @param asset - The address of the asset contract
8196
- * @param assetManager - The address of the asset manager contract
8197
- * @param client - The Viem public client
8198
- * @returns Object containing chainID and spoke address for the asset
8199
- */
8200
- static async getAssetInfo(asset, assetManager, client) {
8201
- const [chainId, spokeAddress] = await client.readContract({
8202
- address: assetManager,
8203
- abi: assetManagerAbi,
8204
- functionName: "assetInfo",
8205
- args: [asset]
8206
- });
8207
- return {
8208
- chainId,
8209
- spokeAddress
8210
- };
8211
- }
8212
- /**
8213
- * Encodes a transfer transaction for an asset.
8214
- * @param token - The address of the token.
8215
- * @param to - The address to transfer the token to.
8216
- * @param amount - The amount of the token to transfer.
8217
- * @param assetManager
8218
- * @returns The encoded contract call.
8219
- */
8220
- static encodeTransfer(token, to, amount, assetManager) {
8221
- return {
8222
- address: assetManager,
8223
- value: 0n,
8224
- data: encodeFunctionData({
8225
- abi: assetManagerAbi,
8226
- functionName: "transfer",
8227
- args: [token, to, amount, "0x"]
8228
- })
8229
- };
8230
- }
8231
- /**
8232
- * Constructs the data for depositing tokens to the spoke chain.
8233
- * @param {EvmDepositToDataParams} params - The address of the token to deposit.
8234
- * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
8235
- * @returns {Hex} Encoded contract calls for the deposit transaction.
8236
- * @throws Will throw an error if the asset or vault address is not found.
8237
- */
8238
- static depositToData(params, spokeChainId) {
8239
- const calls = [];
8240
- const assetConfig = getHubAssetInfo(spokeChainId, params.token);
8241
- if (!assetConfig) {
8242
- throw new Error("[depositToData] Hub asset not found");
7979
+ };
7980
+ var SonicSpokeProvider = class {
7981
+ walletProvider;
7982
+ chainConfig;
7983
+ publicClient;
7984
+ constructor(walletProvider, chainConfig, rpcUrl) {
7985
+ this.walletProvider = walletProvider;
7986
+ this.chainConfig = chainConfig;
7987
+ if (rpcUrl) {
7988
+ this.publicClient = createPublicClient({
7989
+ transport: http(rpcUrl),
7990
+ chain: getEvmViemChain(chainConfig.chain.id)
7991
+ });
7992
+ } else {
7993
+ this.publicClient = createPublicClient({
7994
+ transport: http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
7995
+ chain: getEvmViemChain(chainConfig.chain.id)
7996
+ });
8243
7997
  }
8244
- const assetAddress = assetConfig.asset;
8245
- const vaultAddress = assetConfig.vault;
8246
- calls.push(Erc20Service.encodeApprove(assetAddress, vaultAddress, params.amount));
8247
- calls.push(EvmVaultTokenService.encodeDeposit(vaultAddress, assetAddress, params.amount));
8248
- const translatedAmount = EvmVaultTokenService.translateIncomingDecimals(assetConfig.decimal, params.amount);
8249
- calls.push(Erc20Service.encodeTransfer(vaultAddress, params.to, translatedAmount));
8250
- return encodeContractCalls(calls);
8251
7998
  }
8252
- /**
8253
- * Withdraw tokens from the spoke chain.
8254
- * @param {EvmWithdrawAssetDataParams} params - Parameters for the withdrawal.
8255
- * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
8256
- * @param {EvmHubProvider} hubProvider - The provider for the hub chain.
8257
- * @returns {Hex} Encoded contract calls for the withdrawal transaction.
8258
- * @throws Will throw an error if the asset address is not found.
8259
- */
8260
- static withdrawAssetData(params, hubProvider, spokeChainId) {
8261
- const calls = [];
8262
- const assetConfig = getHubAssetInfo(spokeChainId, params.token);
8263
- if (!assetConfig) {
8264
- throw new Error("[withdrawAssetData] Hub asset not found");
7999
+ };
8000
+ var EvmSpokeProvider = class {
8001
+ walletProvider;
8002
+ chainConfig;
8003
+ publicClient;
8004
+ constructor(walletProvider, chainConfig, rpcUrl) {
8005
+ this.walletProvider = walletProvider;
8006
+ this.chainConfig = chainConfig;
8007
+ if (rpcUrl) {
8008
+ this.publicClient = createPublicClient({
8009
+ transport: http(rpcUrl),
8010
+ chain: getEvmViemChain(chainConfig.chain.id)
8011
+ });
8012
+ } else {
8013
+ this.publicClient = createPublicClient({
8014
+ transport: http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8015
+ chain: getEvmViemChain(chainConfig.chain.id)
8016
+ });
8265
8017
  }
8266
- const assetAddress = assetConfig.asset;
8267
- calls.push(
8268
- _EvmAssetManagerService.encodeTransfer(
8269
- assetAddress,
8270
- params.to,
8271
- params.amount,
8272
- hubProvider.chainConfig.addresses.assetManager
8273
- )
8274
- );
8275
- return encodeContractCalls(calls);
8276
- }
8277
- /**
8278
- * Get asset address for a given chain ID and spoke address
8279
- * @param chainId Chain ID where the asset exists
8280
- * @param spokeAddress Address of the asset on the spoke chain
8281
- * @param assetManager Address of the asset manager contract
8282
- * @param client The Viem public client
8283
- * @returns The asset's address on the hub chain
8284
- */
8285
- async getAssetAddress(chainId, spokeAddress, assetManager, client) {
8286
- return client.readContract({
8287
- address: assetManager,
8288
- abi: assetManagerAbi,
8289
- functionName: "assets",
8290
- args: [chainId, spokeAddress]
8291
- });
8292
8018
  }
8293
8019
  };
8294
-
8295
- // src/services/hub/EvmWalletAbstraction.ts
8296
- var EvmWalletAbstraction = class {
8297
- constructor() {
8020
+ var CustomStellarAccount = class {
8021
+ accountId;
8022
+ sequenceNumber;
8023
+ startingSequenceNumber;
8024
+ constructor({ account_id, sequence }) {
8025
+ this.accountId = account_id;
8026
+ this.sequenceNumber = BigInt(sequence);
8027
+ this.startingSequenceNumber = BigInt(sequence);
8298
8028
  }
8299
- /**
8300
- * Get the hub wallet address for a given spoke chain and address.
8301
- * @param chainId - The spoke chain ID.
8302
- * @param address - The address on the spoke chain.
8303
- * @param hubProvider - The hub provider.
8304
- * @returns The hub wallet address.
8305
- */
8306
- static async getUserHubWalletAddress(chainId, address, hubProvider) {
8307
- return hubProvider.publicClient.readContract({
8308
- address: hubProvider.chainConfig.addresses.hubWallet,
8309
- abi: walletFactoryAbi,
8310
- functionName: "getDeployedAddress",
8311
- args: [BigInt(getIntentRelayChainId(chainId)), address]
8312
- });
8029
+ getSequenceNumber() {
8030
+ return this.sequenceNumber;
8313
8031
  }
8314
- };
8315
- var InjectiveSpokeProvider = class {
8316
- walletProvider;
8317
- chainConfig;
8318
- chainGrpcWasmApi;
8319
- txClient;
8320
- constructor(conf, walletProvider) {
8321
- this.chainConfig = conf;
8322
- this.walletProvider = walletProvider;
8323
- const endpoints = getNetworkEndpoints(Network.Mainnet);
8324
- this.chainGrpcWasmApi = new ChainGrpcWasmApi(endpoints.grpc);
8325
- this.txClient = new TxGrpcApi(endpoints.grpc);
8032
+ getStartingSequenceNumber() {
8033
+ return this.startingSequenceNumber;
8326
8034
  }
8327
- // Query Methods
8328
- async getState() {
8329
- return this.chainGrpcWasmApi.fetchSmartContractState(
8330
- this.chainConfig.addresses.assetManager,
8331
- toBase64({
8332
- get_state: {}
8333
- })
8334
- );
8035
+ getAccountId() {
8036
+ return this.accountId;
8335
8037
  }
8336
- async getBalance(token) {
8337
- return this.chainGrpcWasmApi.fetchSmartContractState(
8338
- this.chainConfig.addresses.assetManager,
8339
- toBase64({
8340
- get_balance: { denom: token }
8341
- })
8342
- );
8038
+ getAccountClone() {
8039
+ return new Account(this.accountId, this.sequenceNumber.toString());
8343
8040
  }
8344
- // Execute Methods (requires SigningCosmWasmClient)
8345
- /**
8346
- * Deposit tokens including native token to Injective Asset Manager.
8347
- **/
8348
- static async deposit(sender, token_address, to, amount, data = "0x", spokeProvider, raw) {
8349
- const toBytes = fromHex(to, "bytes");
8350
- const dataBytes = fromHex(data, "bytes");
8351
- const msg = {
8352
- transfer: {
8353
- token: token_address,
8354
- to: Array.from(toBytes),
8355
- amount,
8356
- data: Array.from(dataBytes)
8357
- }
8358
- };
8359
- const funds = [{ amount, denom: token_address }];
8360
- if (raw) {
8361
- return await spokeProvider.walletProvider.getRawTransaction(
8362
- spokeProvider.chainConfig.networkId,
8363
- spokeProvider.chainConfig.prefix,
8364
- sender,
8365
- spokeProvider.chainConfig.addresses.assetManager,
8366
- msg
8367
- );
8041
+ incrementSequenceNumber() {
8042
+ this.sequenceNumber++;
8043
+ }
8044
+ decrementSequenceNumber() {
8045
+ if (this.sequenceNumber > this.startingSequenceNumber) {
8046
+ this.sequenceNumber--;
8368
8047
  }
8369
- const res = await spokeProvider.walletProvider.execute(
8370
- sender,
8371
- spokeProvider.chainConfig.addresses.assetManager,
8372
- msg,
8373
- funds
8048
+ throw new Error(
8049
+ `Sequence number cannot be decremented below the starting sequence number: ${this.startingSequenceNumber}`
8374
8050
  );
8375
- return res.transactionHash;
8376
8051
  }
8377
- async receiveMessage(senderAddress, srcChainId, srcAddress, connSn, payload, signatures) {
8378
- const msg = {
8379
- recv_message: {
8380
- src_chain_id: srcChainId,
8381
- src_address: srcAddress,
8382
- conn_sn: connSn,
8383
- payload,
8384
- signatures
8385
- }
8386
- };
8387
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8052
+ resetSequenceNumber() {
8053
+ this.sequenceNumber = this.startingSequenceNumber;
8388
8054
  }
8389
- async setRateLimit(senderAddress, rateLimit) {
8390
- const msg = {
8391
- set_rate_limit: {
8392
- rate_limit: rateLimit
8393
- }
8394
- };
8395
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8396
- }
8397
- async setConnection(senderAddress, connection) {
8398
- const msg = {
8399
- set_connection: {
8400
- connection
8401
- }
8402
- };
8403
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8404
- }
8405
- async setOwner(senderAddress, owner) {
8406
- const msg = {
8407
- set_owner: {
8408
- owner
8409
- }
8410
- };
8411
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8412
- }
8413
- async send_message(sender, dst_chain_id, dst_address, payload, raw) {
8414
- const msg = {
8415
- send_message: {
8416
- dst_chain_id: Number.parseInt(dst_chain_id),
8417
- dst_address: Array.from(fromHex(dst_address, "bytes")),
8418
- payload: Array.from(fromHex(payload, "bytes"))
8419
- }
8420
- };
8421
- if (raw) {
8422
- return await this.walletProvider.getRawTransaction(
8423
- this.chainConfig.networkId,
8424
- this.chainConfig.prefix,
8425
- sender,
8426
- this.chainConfig.addresses.connection,
8427
- msg
8428
- );
8429
- }
8430
- const res = await this.walletProvider.execute(sender, this.chainConfig.addresses.connection, msg);
8431
- return res.transactionHash;
8432
- }
8433
- // Helper Methods
8434
- static stringToUint8Array(str) {
8435
- return new TextEncoder().encode(str);
8436
- }
8437
- static uint8ArrayToString(arr) {
8438
- return new TextDecoder().decode(arr);
8439
- }
8440
- static toBigIntString(num) {
8441
- return num.toString();
8442
- }
8443
- };
8444
- var IconSdk = "default" in IconSdkRaw.default ? IconSdkRaw.default : IconSdkRaw;
8445
- var IconSpokeProvider = class {
8446
- walletProvider;
8447
- chainConfig;
8448
- iconService;
8449
- debugRpcUrl;
8450
- constructor(walletProvider, chainConfig, rpcUrl = "https://ctz.solidwallet.io/api/v3", debugRpcUrl = "https://ctz.solidwallet.io/api/v3d") {
8451
- this.walletProvider = walletProvider;
8452
- this.chainConfig = chainConfig;
8453
- this.iconService = new IconSdk.IconService(new IconSdk.IconService.HttpProvider(rpcUrl));
8454
- this.debugRpcUrl = debugRpcUrl;
8455
- }
8456
- };
8457
-
8458
- // src/entities/icon/utils.ts
8459
- function getIconAddressBytes(address) {
8460
- return `0x${Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex").toString("hex")}`;
8461
- }
8462
-
8463
- // src/entities/Providers.ts
8464
- var EvmHubProvider = class {
8465
- publicClient;
8466
- chainConfig;
8467
- constructor(config) {
8468
- if (config) {
8469
- this.publicClient = createPublicClient({
8470
- transport: http(config.hubRpcUrl),
8471
- chain: getEvmViemChain(config.chainConfig.chain.id)
8472
- });
8473
- this.chainConfig = config.chainConfig;
8474
- } else {
8475
- this.publicClient = createPublicClient({
8476
- transport: http("https://rpc.soniclabs.com"),
8477
- chain: getEvmViemChain(SONIC_MAINNET_CHAIN_ID)
8478
- });
8479
- this.chainConfig = getHubChainConfig(SONIC_MAINNET_CHAIN_ID);
8480
- }
8481
- }
8482
- };
8483
- var SonicSpokeProvider = class {
8484
- walletProvider;
8485
- chainConfig;
8486
- publicClient;
8487
- constructor(walletProvider, chainConfig, rpcUrl) {
8488
- this.walletProvider = walletProvider;
8489
- this.chainConfig = chainConfig;
8490
- if (rpcUrl) {
8491
- this.publicClient = createPublicClient({
8492
- transport: http(rpcUrl),
8493
- chain: getEvmViemChain(chainConfig.chain.id)
8494
- });
8495
- } else {
8496
- this.publicClient = createPublicClient({
8497
- transport: http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8498
- chain: getEvmViemChain(chainConfig.chain.id)
8499
- });
8500
- }
8501
- }
8502
- };
8503
- var EvmSpokeProvider = class {
8504
- walletProvider;
8505
- chainConfig;
8506
- publicClient;
8507
- constructor(walletProvider, chainConfig, rpcUrl) {
8508
- this.walletProvider = walletProvider;
8509
- this.chainConfig = chainConfig;
8510
- if (rpcUrl) {
8511
- this.publicClient = createPublicClient({
8512
- transport: http(rpcUrl),
8513
- chain: getEvmViemChain(chainConfig.chain.id)
8514
- });
8515
- } else {
8516
- this.publicClient = createPublicClient({
8517
- transport: http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8518
- chain: getEvmViemChain(chainConfig.chain.id)
8519
- });
8520
- }
8521
- }
8522
- };
8523
- var CustomStellarAccount = class {
8524
- accountId;
8525
- sequenceNumber;
8526
- startingSequenceNumber;
8527
- constructor({ account_id, sequence }) {
8528
- this.accountId = account_id;
8529
- this.sequenceNumber = BigInt(sequence);
8530
- this.startingSequenceNumber = BigInt(sequence);
8531
- }
8532
- getSequenceNumber() {
8533
- return this.sequenceNumber;
8534
- }
8535
- getStartingSequenceNumber() {
8536
- return this.startingSequenceNumber;
8537
- }
8538
- getAccountId() {
8539
- return this.accountId;
8540
- }
8541
- getAccountClone() {
8542
- return new Account(this.accountId, this.sequenceNumber.toString());
8543
- }
8544
- incrementSequenceNumber() {
8545
- this.sequenceNumber++;
8546
- }
8547
- decrementSequenceNumber() {
8548
- if (this.sequenceNumber > this.startingSequenceNumber) {
8549
- this.sequenceNumber--;
8550
- }
8551
- throw new Error(
8552
- `Sequence number cannot be decremented below the starting sequence number: ${this.startingSequenceNumber}`
8553
- );
8554
- }
8555
- resetSequenceNumber() {
8556
- this.sequenceNumber = this.startingSequenceNumber;
8557
- }
8558
- };
8559
- var CustomSorobanServer = class extends SorobanRpc.Server {
8560
- customHeaders;
8561
- constructor(serverUrl, customHeaders) {
8562
- super(serverUrl, {
8563
- allowHttp: true
8564
- });
8565
- this.customHeaders = customHeaders;
8055
+ };
8056
+ var CustomSorobanServer = class extends SorobanRpc.Server {
8057
+ customHeaders;
8058
+ constructor(serverUrl, customHeaders) {
8059
+ super(serverUrl, {
8060
+ allowHttp: true
8061
+ });
8062
+ this.customHeaders = customHeaders;
8566
8063
  }
8567
8064
  async getNetwork() {
8568
8065
  const requestOptions = {
@@ -9150,8 +8647,411 @@ function requestJsonRpc(rawTransaction, id = 99999) {
9150
8647
  }
9151
8648
  })
9152
8649
  );
9153
- });
9154
- }
8650
+ });
8651
+ }
8652
+ var Erc20Service = class {
8653
+ constructor() {
8654
+ }
8655
+ /**
8656
+ * Check if spender has enough ERC20 allowance for given amount
8657
+ * @param token - ERC20 token address
8658
+ * @param amount - Amount to check allowance for
8659
+ * @param owner - User wallet address
8660
+ * @param spender - Spender address
8661
+ * @param spokeProvider - EVM Spoke provider
8662
+ * @return - True if spender is allowed to spend amount on behalf of owner
8663
+ */
8664
+ static async isAllowanceValid(token, amount, owner, spender, spokeProvider) {
8665
+ try {
8666
+ if (token.toLowerCase() === spokeProvider.chainConfig.nativeToken.toLowerCase()) {
8667
+ return {
8668
+ ok: true,
8669
+ value: true
8670
+ };
8671
+ }
8672
+ const allowedAmount = await spokeProvider.publicClient.readContract({
8673
+ address: token,
8674
+ abi: erc20Abi$1,
8675
+ functionName: "allowance",
8676
+ args: [owner, spender]
8677
+ });
8678
+ return {
8679
+ ok: true,
8680
+ value: allowedAmount >= amount
8681
+ };
8682
+ } catch (e) {
8683
+ return {
8684
+ ok: false,
8685
+ error: e
8686
+ };
8687
+ }
8688
+ }
8689
+ /**
8690
+ * Approve ERC20 amount spending
8691
+ * @param token - ERC20 token address
8692
+ * @param amount - Amount to approve
8693
+ * @param spender - Spender address
8694
+ * @param provider - EVM Provider
8695
+ */
8696
+ static async approve(token, amount, spender, spokeProvider, raw) {
8697
+ const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
8698
+ const rawTx = {
8699
+ from: walletAddress,
8700
+ to: token,
8701
+ value: 0n,
8702
+ data: encodeFunctionData({
8703
+ abi: erc20Abi$1,
8704
+ functionName: "approve",
8705
+ args: [spender, amount]
8706
+ })
8707
+ };
8708
+ if (raw) {
8709
+ return rawTx;
8710
+ }
8711
+ return spokeProvider.walletProvider.sendTransaction(rawTx);
8712
+ }
8713
+ /**
8714
+ * Encodes a transfer transaction for a token.
8715
+ * @param token - The address of the token.
8716
+ * @param to - The address to transfer the token to.
8717
+ * @param amount - The amount of the token to transfer.
8718
+ * @returns The encoded contract call.
8719
+ */
8720
+ static encodeTransfer(token, to, amount) {
8721
+ return {
8722
+ address: token,
8723
+ value: 0n,
8724
+ data: encodeFunctionData({
8725
+ abi: erc20Abi$1,
8726
+ functionName: "transfer",
8727
+ args: [to, amount]
8728
+ })
8729
+ };
8730
+ }
8731
+ /**
8732
+ * Encodes a transferFrom transaction for a token.
8733
+ * @param token - The address of the token.
8734
+ * @param from - The address to transfer the token from.
8735
+ * @param to - The address to transfer the token to.
8736
+ * @param amount - The amount of the token to transfer.
8737
+ * @returns The encoded contract call.
8738
+ */
8739
+ static encodeTransferFrom(token, from, to, amount) {
8740
+ return {
8741
+ address: token,
8742
+ value: 0n,
8743
+ data: encodeFunctionData({
8744
+ abi: erc20Abi$1,
8745
+ functionName: "transferFrom",
8746
+ args: [from, to, amount]
8747
+ })
8748
+ };
8749
+ }
8750
+ /**
8751
+ * Encodes an approval transaction for a token.
8752
+ * @param token - The address of the token.
8753
+ * @param to - The address to approve the token to.
8754
+ * @param amount - The amount of the token to approve.
8755
+ * @returns The encoded contract call.
8756
+ */
8757
+ static encodeApprove(token, to, amount) {
8758
+ return {
8759
+ address: token,
8760
+ value: 0n,
8761
+ data: encodeFunctionData({
8762
+ abi: erc20Abi$1,
8763
+ functionName: "approve",
8764
+ args: [to, amount]
8765
+ })
8766
+ };
8767
+ }
8768
+ };
8769
+ var EvmVaultTokenService = class {
8770
+ constructor() {
8771
+ }
8772
+ /**
8773
+ * Fetches token information for a specific token in the vault.
8774
+ * @param vault - The address of the vault.
8775
+ * @param token - The address of the token.
8776
+ * @param publicClient - PublicClient<HttpTransport>
8777
+ * @returns Token information as a TokenInfo object.
8778
+ */
8779
+ static async getTokenInfo(vault, token, publicClient) {
8780
+ const [decimals, depositFee, withdrawalFee, maxDeposit, isSupported] = await publicClient.readContract({
8781
+ address: vault,
8782
+ abi: vaultTokenAbi,
8783
+ functionName: "tokenInfo",
8784
+ args: [token]
8785
+ });
8786
+ return { decimals, depositFee, withdrawalFee, maxDeposit, isSupported };
8787
+ }
8788
+ /**
8789
+ * Retrieves the reserves of the vault.
8790
+ * @param vault - The address of the vault.
8791
+ * @param publicClient - PublicClient<HttpTransport>
8792
+ * @returns An object containing tokens and their balances.
8793
+ */
8794
+ static async getVaultReserves(vault, publicClient) {
8795
+ const [tokens, balances] = await publicClient.readContract({
8796
+ address: vault,
8797
+ abi: vaultTokenAbi,
8798
+ functionName: "getVaultReserves",
8799
+ args: []
8800
+ });
8801
+ return {
8802
+ tokens,
8803
+ balances
8804
+ };
8805
+ }
8806
+ /**
8807
+ * Retrieves all token information for the vault.
8808
+ * @param vault - The address of the vault.
8809
+ * @param publicClient - PublicClient<HttpTransport>
8810
+ * @returns A promise that resolves to an object containing tokens, their infos, and reserves.
8811
+ */
8812
+ async getAllTokenInfo(vault, publicClient) {
8813
+ const [tokens, infos, reserves] = await publicClient.readContract({
8814
+ address: vault,
8815
+ abi: vaultTokenAbi,
8816
+ functionName: "getAllTokenInfo",
8817
+ args: []
8818
+ });
8819
+ return {
8820
+ tokens,
8821
+ infos,
8822
+ reserves
8823
+ };
8824
+ }
8825
+ /**
8826
+ * Deposits a specified amount of a token into the vault.
8827
+ * @param vault - The address of the vault.
8828
+ * @param token - The address of the token to deposit.
8829
+ * @param amount - The amount of the token to deposit.
8830
+ * @param walletProvider - IEvmWalletProvider
8831
+ * @returns Transaction hash
8832
+ */
8833
+ static async deposit(vault, token, amount, walletProvider) {
8834
+ const from = await walletProvider.getWalletAddress();
8835
+ return walletProvider.sendTransaction({
8836
+ from,
8837
+ to: vault,
8838
+ value: 0n,
8839
+ data: encodeFunctionData({
8840
+ abi: vaultTokenAbi,
8841
+ functionName: "deposit",
8842
+ args: [token, amount]
8843
+ })
8844
+ });
8845
+ }
8846
+ /**
8847
+ * Withdraws a specified amount of a token from the vault.
8848
+ * @param vault - The address of the vault.
8849
+ * @param token - The address of the token to withdraw.
8850
+ * @param amount - The amount of the token to withdraw.
8851
+ * @param provider - EvmWalletProvider
8852
+ * @returns Transaction hash
8853
+ */
8854
+ static async withdraw(vault, token, amount, provider) {
8855
+ const from = await provider.getWalletAddress();
8856
+ return provider.sendTransaction({
8857
+ from,
8858
+ to: vault,
8859
+ value: 0n,
8860
+ data: encodeFunctionData({
8861
+ abi: vaultTokenAbi,
8862
+ functionName: "withdraw",
8863
+ args: [token, amount]
8864
+ })
8865
+ });
8866
+ }
8867
+ /**
8868
+ * Encodes the deposit transaction data for the vault.
8869
+ * @param vault - The address of the vault.
8870
+ * @param token - The address of the token to deposit.
8871
+ * @param amount - The amount of the token to deposit.
8872
+ * @returns The encoded contract call data.
8873
+ */
8874
+ static encodeDeposit(vault, token, amount) {
8875
+ return {
8876
+ address: vault,
8877
+ value: 0n,
8878
+ data: encodeFunctionData({
8879
+ abi: vaultTokenAbi,
8880
+ functionName: "deposit",
8881
+ args: [token, amount]
8882
+ })
8883
+ };
8884
+ }
8885
+ /**
8886
+ * Encodes the withdraw transaction data for the vault.
8887
+ * @param vault - The address of the vault.
8888
+ * @param token - The address of the token to withdraw.
8889
+ * @param amount - The amount of the token to withdraw.
8890
+ * @returns The encoded contract call data.
8891
+ */
8892
+ static encodeWithdraw(vault, token, amount) {
8893
+ return {
8894
+ address: vault,
8895
+ value: 0n,
8896
+ data: encodeFunctionData({
8897
+ abi: vaultTokenAbi,
8898
+ functionName: "withdraw",
8899
+ args: [token, amount]
8900
+ })
8901
+ };
8902
+ }
8903
+ /**
8904
+ * Translates token amounts from their native decimals to 18 decimals
8905
+ * @param decimals - The number of decimals of the token
8906
+ * @param amount - The amount to translate
8907
+ * @returns The translated amount
8908
+ */
8909
+ static translateIncomingDecimals(decimals, amount) {
8910
+ if (decimals <= 18) {
8911
+ return amount * BigInt(10 ** (18 - decimals));
8912
+ }
8913
+ return amount / BigInt(10 ** (decimals - 18));
8914
+ }
8915
+ /**
8916
+ * Translates token amounts from 18 decimals back to their native decimals
8917
+ * @param decimals - The number of decimals of the token
8918
+ * @param amount - The amount to translate
8919
+ * @returns The translated amount
8920
+ */
8921
+ static translateOutgoingDecimals(decimals, amount) {
8922
+ if (decimals <= 18) {
8923
+ return amount / BigInt(10 ** (18 - decimals));
8924
+ }
8925
+ return amount * BigInt(10 ** (decimals - 18));
8926
+ }
8927
+ };
8928
+
8929
+ // src/services/hub/EvmAssetManagerService.ts
8930
+ var EvmAssetManagerService = class _EvmAssetManagerService {
8931
+ constructor() {
8932
+ }
8933
+ /**
8934
+ * Get asset information for a given asset address
8935
+ * @param asset - The address of the asset contract
8936
+ * @param assetManager - The address of the asset manager contract
8937
+ * @param client - The Viem public client
8938
+ * @returns Object containing chainID and spoke address for the asset
8939
+ */
8940
+ static async getAssetInfo(asset, assetManager, client) {
8941
+ const [chainId, spokeAddress] = await client.readContract({
8942
+ address: assetManager,
8943
+ abi: assetManagerAbi,
8944
+ functionName: "assetInfo",
8945
+ args: [asset]
8946
+ });
8947
+ return {
8948
+ chainId,
8949
+ spokeAddress
8950
+ };
8951
+ }
8952
+ /**
8953
+ * Encodes a transfer transaction for an asset.
8954
+ * @param token - The address of the token.
8955
+ * @param to - The address to transfer the token to.
8956
+ * @param amount - The amount of the token to transfer.
8957
+ * @param assetManager
8958
+ * @returns The encoded contract call.
8959
+ */
8960
+ static encodeTransfer(token, to, amount, assetManager) {
8961
+ return {
8962
+ address: assetManager,
8963
+ value: 0n,
8964
+ data: encodeFunctionData({
8965
+ abi: assetManagerAbi,
8966
+ functionName: "transfer",
8967
+ args: [token, to, amount, "0x"]
8968
+ })
8969
+ };
8970
+ }
8971
+ /**
8972
+ * Constructs the data for depositing tokens to the spoke chain.
8973
+ * @param {EvmDepositToDataParams} params - The address of the token to deposit.
8974
+ * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
8975
+ * @returns {Hex} Encoded contract calls for the deposit transaction.
8976
+ * @throws Will throw an error if the asset or vault address is not found.
8977
+ */
8978
+ static depositToData(params, spokeChainId) {
8979
+ const calls = [];
8980
+ const assetConfig = getHubAssetInfo(spokeChainId, params.token);
8981
+ if (!assetConfig) {
8982
+ throw new Error("[depositToData] Hub asset not found");
8983
+ }
8984
+ const assetAddress = assetConfig.asset;
8985
+ const vaultAddress = assetConfig.vault;
8986
+ calls.push(Erc20Service.encodeApprove(assetAddress, vaultAddress, params.amount));
8987
+ calls.push(EvmVaultTokenService.encodeDeposit(vaultAddress, assetAddress, params.amount));
8988
+ const translatedAmount = EvmVaultTokenService.translateIncomingDecimals(assetConfig.decimal, params.amount);
8989
+ calls.push(Erc20Service.encodeTransfer(vaultAddress, params.to, translatedAmount));
8990
+ return encodeContractCalls(calls);
8991
+ }
8992
+ /**
8993
+ * Withdraw tokens from the spoke chain.
8994
+ * @param {EvmWithdrawAssetDataParams} params - Parameters for the withdrawal.
8995
+ * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
8996
+ * @param {EvmHubProvider} hubProvider - The provider for the hub chain.
8997
+ * @returns {Hex} Encoded contract calls for the withdrawal transaction.
8998
+ * @throws Will throw an error if the asset address is not found.
8999
+ */
9000
+ static withdrawAssetData(params, hubProvider, spokeChainId) {
9001
+ const calls = [];
9002
+ const assetConfig = getHubAssetInfo(spokeChainId, params.token);
9003
+ if (!assetConfig) {
9004
+ throw new Error("[withdrawAssetData] Hub asset not found");
9005
+ }
9006
+ const assetAddress = assetConfig.asset;
9007
+ calls.push(
9008
+ _EvmAssetManagerService.encodeTransfer(
9009
+ assetAddress,
9010
+ params.to,
9011
+ params.amount,
9012
+ hubProvider.chainConfig.addresses.assetManager
9013
+ )
9014
+ );
9015
+ return encodeContractCalls(calls);
9016
+ }
9017
+ /**
9018
+ * Get asset address for a given chain ID and spoke address
9019
+ * @param chainId Chain ID where the asset exists
9020
+ * @param spokeAddress Address of the asset on the spoke chain
9021
+ * @param assetManager Address of the asset manager contract
9022
+ * @param client The Viem public client
9023
+ * @returns The asset's address on the hub chain
9024
+ */
9025
+ async getAssetAddress(chainId, spokeAddress, assetManager, client) {
9026
+ return client.readContract({
9027
+ address: assetManager,
9028
+ abi: assetManagerAbi,
9029
+ functionName: "assets",
9030
+ args: [chainId, spokeAddress]
9031
+ });
9032
+ }
9033
+ };
9034
+
9035
+ // src/services/hub/EvmWalletAbstraction.ts
9036
+ var EvmWalletAbstraction = class {
9037
+ constructor() {
9038
+ }
9039
+ /**
9040
+ * Get the hub wallet address for a given spoke chain and address.
9041
+ * @param chainId - The spoke chain ID.
9042
+ * @param address - The address on the spoke chain.
9043
+ * @param hubProvider - The hub provider.
9044
+ * @returns The hub wallet address.
9045
+ */
9046
+ static async getUserHubWalletAddress(chainId, address, hubProvider) {
9047
+ return hubProvider.publicClient.readContract({
9048
+ address: hubProvider.chainConfig.addresses.hubWallet,
9049
+ abi: walletFactoryAbi,
9050
+ functionName: "getDeployedAddress",
9051
+ args: [BigInt(getIntentRelayChainId(chainId)), address]
9052
+ });
9053
+ }
9054
+ };
9155
9055
  var EvmSpokeService = class _EvmSpokeService {
9156
9056
  constructor() {
9157
9057
  }
@@ -9548,9 +9448,10 @@ var IconSpokeService = class _IconSpokeService {
9548
9448
  getIconAddressBytes(params.from),
9549
9449
  hubProvider
9550
9450
  );
9451
+ const token = isNativeToken(spokeProvider.chainConfig.chain.id, params.token) ? spokeProvider.chainConfig.addresses.wICX : params.token;
9551
9452
  return {
9552
9453
  spokeChainID: spokeProvider.chainConfig.chain.id,
9553
- token: encodeAddress(spokeProvider.chainConfig.chain.id, params.token),
9454
+ token: encodeAddress(spokeProvider.chainConfig.chain.id, token),
9554
9455
  from: encodeAddress(spokeProvider.chainConfig.chain.id, params.from),
9555
9456
  to,
9556
9457
  amount: params.amount,
@@ -9971,7 +9872,7 @@ var StellarSpokeService = class _StellarSpokeService {
9971
9872
  return {
9972
9873
  spokeChainID: spokeProvider.chainConfig.chain.id,
9973
9874
  token: encodeAddress(spokeProvider.chainConfig.chain.id, params.token),
9974
- from: params.from,
9875
+ from: encodeAddress(spokeProvider.chainConfig.chain.id, params.from),
9975
9876
  to,
9976
9877
  amount: params.amount,
9977
9878
  data: params.data,
@@ -10183,6 +10084,7 @@ var SonicSpokeService = class _SonicSpokeService {
10183
10084
  * @returns {PromiseEvmTxReturnType<R>} A promise that resolves to the transaction hash
10184
10085
  */
10185
10086
  static async deposit(params, spokeProvider, raw) {
10087
+ invariant11(spokeProvider instanceof SonicSpokeProvider, "[SonicSpokeService] invalid spoke provider");
10186
10088
  const userHubAddress = params.to ?? await _SonicSpokeService.getUserRouter(params.from, spokeProvider);
10187
10089
  const calls = Array.from(
10188
10090
  decodeAbiParameters(
@@ -10237,7 +10139,7 @@ var SonicSpokeService = class _SonicSpokeService {
10237
10139
  value: params.token.toLowerCase() === spokeProvider.chainConfig.nativeToken.toLowerCase() ? params.amount : 0n
10238
10140
  };
10239
10141
  if (raw) {
10240
- return rawTx;
10142
+ return Promise.resolve(rawTx);
10241
10143
  }
10242
10144
  return spokeProvider.walletProvider.sendTransaction(rawTx);
10243
10145
  }
@@ -10314,6 +10216,7 @@ var SonicSpokeService = class _SonicSpokeService {
10314
10216
  * @returns {PromiseEvmTxReturnType<R>} A promise that resolves to the transaction hash
10315
10217
  */
10316
10218
  static async callWallet(payload, spokeProvider, raw) {
10219
+ invariant11(spokeProvider instanceof SonicSpokeProvider, "[SonicSpokeService] invalid spoke provider");
10317
10220
  const calls = decodeAbiParameters(
10318
10221
  [
10319
10222
  {
@@ -10348,7 +10251,7 @@ var SonicSpokeService = class _SonicSpokeService {
10348
10251
  if (raw) {
10349
10252
  return rawTx;
10350
10253
  }
10351
- return spokeProvider.walletProvider.sendTransaction(rawTx);
10254
+ return await spokeProvider.walletProvider.sendTransaction(rawTx);
10352
10255
  }
10353
10256
  /**
10354
10257
  * Get withdraw information for a given token
@@ -10953,7 +10856,11 @@ var SpokeService = class _SpokeService {
10953
10856
  */
10954
10857
  static async callWallet(from, payload, spokeProvider, hubProvider, raw, skipSimulation = false) {
10955
10858
  if (isSonicSpokeProvider(spokeProvider)) {
10956
- return await SonicSpokeService.callWallet(payload, spokeProvider, raw);
10859
+ return await SonicSpokeService.callWallet(
10860
+ payload,
10861
+ spokeProvider,
10862
+ raw
10863
+ );
10957
10864
  }
10958
10865
  if (isEvmSpokeProvider(spokeProvider)) {
10959
10866
  await _SpokeService.verifySimulation(from, payload, spokeProvider, hubProvider, skipSimulation);
@@ -12085,7 +11992,7 @@ var SolverService = class {
12085
11992
  params.srcAddress.toLowerCase() === walletAddress.toLowerCase(),
12086
11993
  "srcAddress must be the same as wallet address"
12087
11994
  );
12088
- const creatorHubWalletAddress = spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id ? walletAddress : await WalletAbstractionService.getUserHubWalletAddress(walletAddress, spokeProvider, this.hubProvider);
11995
+ const creatorHubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
12089
11996
  if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id) {
12090
11997
  const [txResult, intent, feeAmount, data] = await SonicSpokeService.createSwapIntent(
12091
11998
  params,
@@ -12158,7 +12065,7 @@ var SolverService = class {
12158
12065
  invariant11(isValidIntentRelayChainId(intent.srcChain), `Invalid intent.srcChain: ${intent.srcChain}`);
12159
12066
  invariant11(isValidIntentRelayChainId(intent.dstChain), `Invalid intent.dstChain: ${intent.dstChain}`);
12160
12067
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
12161
- const creatorHubWalletAddress = spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id ? walletAddress : await WalletAbstractionService.getUserHubWalletAddress(walletAddress, spokeProvider, this.hubProvider);
12068
+ const creatorHubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
12162
12069
  const calls = [];
12163
12070
  const intentsContract = this.config.intentsContract;
12164
12071
  calls.push(EvmSolverService.encodeCancelIntent(intent, intentsContract));
@@ -12197,6 +12104,19 @@ var SolverService = class {
12197
12104
  getIntentHash(intent) {
12198
12105
  return EvmSolverService.getIntentHash(intent);
12199
12106
  }
12107
+ /**
12108
+ * Gets the deadline for a swap by querying hub chain block timestamp and adding the deadline offset
12109
+ * @param {bigint} deadline (default: 5 minutes) - The deadline offset in seconds for the swap to be cancelled
12110
+ * @returns {bigint} The deadline for the swap as a sum of hub chain block timestamp and deadline offset
12111
+ */
12112
+ async getSwapDeadline(deadline = DEFAULT_DEADLINE_OFFSET) {
12113
+ invariant11(deadline > 0n, "Deadline must be greater than 0");
12114
+ const block = await this.hubProvider.publicClient.getBlock({
12115
+ includeTransactions: false,
12116
+ blockTag: "latest"
12117
+ });
12118
+ return block.timestamp + deadline;
12119
+ }
12200
12120
  };
12201
12121
 
12202
12122
  // src/abis/icxSwap.abi.ts
@@ -13874,8 +13794,6 @@ var Sodax = class {
13874
13794
 
13875
13795
  // src/services/hub/WalletAbstractionService.ts
13876
13796
  var WalletAbstractionService = class {
13877
- constructor() {
13878
- }
13879
13797
  /**
13880
13798
  * Gets the hub wallet address for a user based on their spoke chain address.
13881
13799
  * @param address - The user's address on the spoke chain
@@ -13883,14 +13801,14 @@ var WalletAbstractionService = class {
13883
13801
  * @param hubProvider - The provider for interacting with the hub chain
13884
13802
  * @returns The user's hub wallet address
13885
13803
  */
13886
- static async getUserHubWalletAddress(address, spokeProvider, hubProvider) {
13804
+ static async getUserAbstractedWalletAddress(address, spokeProvider, hubProvider) {
13887
13805
  const encodedAddress = encodeAddress(spokeProvider.chainConfig.chain.id, address);
13888
13806
  if (spokeProvider.chainConfig.chain.id === hubProvider.chainConfig.chain.id) {
13889
13807
  if (spokeProvider instanceof SonicSpokeProvider) {
13890
13808
  return SonicSpokeService.getUserRouter(encodedAddress, spokeProvider);
13891
13809
  }
13892
13810
  throw new Error(
13893
- "[WalletAbstractionService.getUserHubWalletAddress] Invalid spoke provider. Sonic spoke provider is required."
13811
+ "[getUserHubWalletAddress] Invalid spoke provider for matching hub id. Sonic spoke provider is required."
13894
13812
  );
13895
13813
  }
13896
13814
  return EvmWalletAbstraction.getUserHubWalletAddress(
@@ -13900,6 +13818,111 @@ var WalletAbstractionService = class {
13900
13818
  );
13901
13819
  }
13902
13820
  };
13821
+ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
13822
+ do {
13823
+ try {
13824
+ return await action(retryCount);
13825
+ } catch (e) {
13826
+ retryCount--;
13827
+ if (retryCount <= 0) {
13828
+ console.error(`Failed to perform operation even after ${DEFAULT_MAX_RETRY} attempts.. Throwing origin error..`);
13829
+ throw e;
13830
+ }
13831
+ }
13832
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
13833
+ } while (retryCount > 0);
13834
+ throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
13835
+ }
13836
+ function getRandomBytes(length) {
13837
+ const array = new Uint8Array(length);
13838
+ for (let i = 0; i < length; i++) {
13839
+ array[i] = Math.floor(Math.random() * 256);
13840
+ }
13841
+ return array;
13842
+ }
13843
+ function randomUint256() {
13844
+ const bytes = getRandomBytes(32);
13845
+ let hex = "";
13846
+ for (const byte of bytes) {
13847
+ hex += byte.toString(16).padStart(2, "0") ?? "";
13848
+ }
13849
+ return BigInt(`0x${hex}`);
13850
+ }
13851
+ function calculatePercentageFeeAmount(amount, percentage) {
13852
+ return amount * BigInt(percentage) / FEE_PERCENTAGE_SCALE;
13853
+ }
13854
+ function calculateFeeAmount(inputAmount, fee) {
13855
+ if (!fee) {
13856
+ return 0n;
13857
+ }
13858
+ invariant11(inputAmount > 0n, "Input amount must be greater than 0");
13859
+ let feeAmount = 0n;
13860
+ if (isPartnerFeeAmount(fee)) {
13861
+ invariant11(
13862
+ fee.amount >= 0 && fee.amount <= inputAmount,
13863
+ `Fee amount must be greater than 0 and less than or equal to the input amount: ${fee.amount}`
13864
+ );
13865
+ feeAmount = fee.amount;
13866
+ } else if (isPartnerFeePercentage(fee)) {
13867
+ invariant11(
13868
+ fee.percentage >= 0 && fee.percentage <= FEE_PERCENTAGE_SCALE,
13869
+ `Fee percentage must be between 0 and ${FEE_PERCENTAGE_SCALE}}`
13870
+ );
13871
+ feeAmount = calculatePercentageFeeAmount(inputAmount, fee.percentage);
13872
+ }
13873
+ return feeAmount;
13874
+ }
13875
+ function adjustAmountByFee(amount, fee, quoteType) {
13876
+ invariant11(amount > 0n, "Amount must be greater than 0");
13877
+ invariant11(quoteType === "exact_input" || quoteType === "exact_output", "Invalid quote type");
13878
+ if (quoteType === "exact_input") {
13879
+ return amount - calculateFeeAmount(amount, fee);
13880
+ }
13881
+ if (quoteType === "exact_output") {
13882
+ return amount + calculateFeeAmount(amount, fee);
13883
+ }
13884
+ throw new Error("Invalid quote type");
13885
+ }
13886
+ function BigIntToHex(value) {
13887
+ return `0x${value.toString(16)}`;
13888
+ }
13889
+ function encodeAddress(spokeChainId, address) {
13890
+ switch (spokeChainId) {
13891
+ case "0xa86a.avax":
13892
+ case "0x2105.base":
13893
+ case "0xa.optimism":
13894
+ case "0x38.bsc":
13895
+ case "0x89.polygon":
13896
+ case "0xa4b1.arbitrum":
13897
+ case "sonic":
13898
+ return address;
13899
+ case "injective-1":
13900
+ return toHex(Buffer.from(address, "utf-8"));
13901
+ case "0x1.icon":
13902
+ return toHex(Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex"));
13903
+ case "sui":
13904
+ return toHex(bcs.Address.serialize(address).toBytes());
13905
+ case "solana":
13906
+ return toHex(Buffer.from(new PublicKey(address).toBytes()));
13907
+ case "stellar":
13908
+ return `0x${Address.fromString(address).toScVal().toXDR("hex")}`;
13909
+ default:
13910
+ return address;
13911
+ }
13912
+ }
13913
+ function hexToBigInt(hex) {
13914
+ const trimmed = hex.trim().toLowerCase();
13915
+ const isValid = /^(0x)?[0-9a-f]+$/.test(trimmed);
13916
+ if (!isValid) {
13917
+ throw new Error(`Invalid hex string: "${hex}"`);
13918
+ }
13919
+ const normalized = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
13920
+ return BigInt(normalized);
13921
+ }
13922
+ async function deriveUserWalletAddress(spokeProvider, hubProvider, walletAddress) {
13923
+ const address = walletAddress ?? await spokeProvider.walletProvider.getWalletAddress();
13924
+ return spokeProvider.chainConfig.chain.id === hubProvider.chainConfig.chain.id ? address : await WalletAbstractionService.getUserAbstractedWalletAddress(address, spokeProvider, hubProvider);
13925
+ }
13903
13926
  var BigNumberZeroDecimal = BigNumber.clone({
13904
13927
  DECIMAL_PLACES: 0,
13905
13928
  ROUNDING_MODE: BigNumber.ROUND_DOWN
@@ -15260,11 +15283,7 @@ var MoneyMarketDataService = class {
15260
15283
  */
15261
15284
  async getUserReservesData(spokeProvider) {
15262
15285
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15263
- const hubWalletAddress = await WalletAbstractionService.getUserHubWalletAddress(
15264
- walletAddress,
15265
- spokeProvider,
15266
- this.hubProvider
15267
- );
15286
+ const hubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15268
15287
  return this.uiPoolDataProviderService.getUserReservesData(hubWalletAddress);
15269
15288
  }
15270
15289
  /**
@@ -15295,11 +15314,7 @@ var MoneyMarketDataService = class {
15295
15314
  */
15296
15315
  async getUserReservesHumanized(spokeProvider) {
15297
15316
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15298
- const hubWalletAddress = await WalletAbstractionService.getUserHubWalletAddress(
15299
- walletAddress,
15300
- spokeProvider,
15301
- this.hubProvider
15302
- );
15317
+ const hubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15303
15318
  return this.uiPoolDataProviderService.getUserReservesHumanized(hubWalletAddress);
15304
15319
  }
15305
15320
  /**
@@ -15741,34 +15756,44 @@ var MoneyMarketService = class _MoneyMarketService {
15741
15756
  `Unsupported spoke chain (${spokeProvider.chainConfig.chain.id}) token: ${params.token}`
15742
15757
  );
15743
15758
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15744
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
15745
- walletAddress,
15746
- spokeProvider,
15747
- this.hubProvider
15748
- );
15759
+ const abstractedWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15749
15760
  const data = this.buildSupplyData(
15750
15761
  params.token,
15751
- hubWallet,
15762
+ abstractedWalletAddress,
15752
15763
  params.amount,
15753
15764
  spokeProvider.chainConfig.chain.id
15754
15765
  );
15755
- const txResult = await SpokeService.deposit(
15756
- {
15757
- from: walletAddress,
15758
- to: hubWallet,
15759
- token: params.token,
15760
- amount: params.amount,
15761
- data
15762
- },
15763
- spokeProvider,
15764
- this.hubProvider,
15765
- raw
15766
- );
15766
+ let txResult;
15767
+ if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id && spokeProvider instanceof SonicSpokeProvider) {
15768
+ txResult = await SonicSpokeService.deposit(
15769
+ {
15770
+ from: walletAddress,
15771
+ token: params.token,
15772
+ amount: params.amount,
15773
+ data
15774
+ },
15775
+ spokeProvider,
15776
+ raw
15777
+ );
15778
+ } else {
15779
+ txResult = await SpokeService.deposit(
15780
+ {
15781
+ from: walletAddress,
15782
+ to: abstractedWalletAddress,
15783
+ token: params.token,
15784
+ amount: params.amount,
15785
+ data
15786
+ },
15787
+ spokeProvider,
15788
+ this.hubProvider,
15789
+ raw
15790
+ );
15791
+ }
15767
15792
  return {
15768
15793
  ok: true,
15769
15794
  value: txResult,
15770
15795
  data: {
15771
- address: hubWallet,
15796
+ address: abstractedWalletAddress,
15772
15797
  payload: data
15773
15798
  }
15774
15799
  };
@@ -15897,11 +15922,7 @@ var MoneyMarketService = class _MoneyMarketService {
15897
15922
  );
15898
15923
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15899
15924
  const encodedAddress = encodeAddress(spokeProvider.chainConfig.chain.id, walletAddress);
15900
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
15901
- walletAddress,
15902
- spokeProvider,
15903
- this.hubProvider
15904
- );
15925
+ const hubWallet = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15905
15926
  const data = this.buildBorrowData(
15906
15927
  hubWallet,
15907
15928
  encodedAddress,
@@ -15909,7 +15930,12 @@ var MoneyMarketService = class _MoneyMarketService {
15909
15930
  params.amount,
15910
15931
  spokeProvider.chainConfig.chain.id
15911
15932
  );
15912
- const txResult = await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
15933
+ let txResult;
15934
+ if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id) {
15935
+ txResult = await SonicSpokeService.callWallet(data, spokeProvider);
15936
+ } else {
15937
+ txResult = await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
15938
+ }
15913
15939
  return {
15914
15940
  ok: true,
15915
15941
  value: txResult,
@@ -16032,11 +16058,7 @@ var MoneyMarketService = class _MoneyMarketService {
16032
16058
  );
16033
16059
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
16034
16060
  const encodedAddress = encodeAddress(spokeProvider.chainConfig.chain.id, walletAddress);
16035
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
16036
- walletAddress,
16037
- spokeProvider,
16038
- this.hubProvider
16039
- );
16061
+ const hubWallet = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
16040
16062
  let data;
16041
16063
  if (spokeProvider instanceof SonicSpokeProvider) {
16042
16064
  const withdrawInfo = await SonicSpokeService.getWithdrawInfo(
@@ -16062,7 +16084,7 @@ var MoneyMarketService = class _MoneyMarketService {
16062
16084
  spokeProvider.chainConfig.chain.id
16063
16085
  );
16064
16086
  }
16065
- const txResult = await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
16087
+ const txResult = spokeProvider instanceof SonicSpokeProvider ? await SonicSpokeService.callWallet(data, spokeProvider, raw) : await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
16066
16088
  return {
16067
16089
  ok: true,
16068
16090
  value: txResult,
@@ -16186,24 +16208,34 @@ var MoneyMarketService = class _MoneyMarketService {
16186
16208
  `Unsupported spoke chain (${spokeProvider.chainConfig.chain.id}) token: ${params.token}`
16187
16209
  );
16188
16210
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
16189
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
16190
- walletAddress,
16191
- spokeProvider,
16192
- this.hubProvider
16193
- );
16211
+ const hubWallet = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
16194
16212
  const data = this.buildRepayData(params.token, hubWallet, params.amount, spokeProvider.chainConfig.chain.id);
16195
- const txResult = await SpokeService.deposit(
16196
- {
16197
- from: walletAddress,
16198
- to: hubWallet,
16199
- token: params.token,
16200
- amount: params.amount,
16201
- data
16202
- },
16203
- spokeProvider,
16204
- this.hubProvider,
16205
- raw
16206
- );
16213
+ let txResult;
16214
+ if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id && spokeProvider instanceof SonicSpokeProvider) {
16215
+ txResult = await SonicSpokeService.deposit(
16216
+ {
16217
+ from: walletAddress,
16218
+ token: params.token,
16219
+ amount: params.amount,
16220
+ data
16221
+ },
16222
+ spokeProvider,
16223
+ raw
16224
+ );
16225
+ } else {
16226
+ txResult = await SpokeService.deposit(
16227
+ {
16228
+ from: walletAddress,
16229
+ to: hubWallet,
16230
+ token: params.token,
16231
+ amount: params.amount,
16232
+ data
16233
+ },
16234
+ spokeProvider,
16235
+ this.hubProvider,
16236
+ raw
16237
+ );
16238
+ }
16207
16239
  return {
16208
16240
  ok: true,
16209
16241
  value: txResult,
@@ -16585,6 +16617,6 @@ var SolverIntentErrorCode = /* @__PURE__ */ ((SolverIntentErrorCode2) => {
16585
16617
  return SolverIntentErrorCode2;
16586
16618
  })(SolverIntentErrorCode || {});
16587
16619
 
16588
- export { BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BnUSDMigrationService, ChainIdToIntentRelayChainId, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, EVM_CHAIN_IDS, EVM_SPOKE_CHAIN_IDS, Erc20Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeProvider, EvmSpokeService, EvmVaultTokenService, EvmWalletAbstraction, FEE_PERCENTAGE_SCALE, HALF_RAY, HALF_WAD, HubVaultSymbols, ICON_TX_RESULT_WAIT_MAX_RETRY, INTENT_RELAY_CHAIN_IDS, IconSpokeProvider, IcxMigrationService, InjectiveSpokeProvider, IntentCreatedEventAbi, IntentDataType, IntentsAbi, LTV_PRECISION, LendingPoolService, LockupMultiplier, LockupPeriod, MAX_UINT256, MigrationService, MoneyMarketDataService, MoneyMarketService, RAY, RAY_DECIMALS, SECONDS_PER_YEAR, STELLAR_DEFAULT_TX_TIMEOUT_SECONDS, STELLAR_PRIORITY_FEE, Sodax, SolanaSpokeProvider, SolverIntentErrorCode, SolverIntentStatusCode, SolverService, SonicSpokeProvider, SonicSpokeService, SpokeService, StellarSpokeProvider, SuiSpokeProvider, SupportedMigrationTokens, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, WalletAbstractionService, adjustAmountByFee, assetManagerAbi, balnSwapAbi, binomialApproximatedRayPow, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bnUSDNewTokens, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, chainIdToHubAssetsMap, connectionAbi, encodeAddress, encodeContractCalls, erc20Abi, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getCompoundedBalance, getEvmViemChain, getHubAssetInfo, getHubChainConfig, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getMoneyMarketConfig, getOriginalAssetAddress, getPacket, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeChainIdFromIntentRelayChainId, getSupportedMoneyMarketTokens, getSupportedSolverTokens, getTransactionPackets, hexToBigInt, hubAssetToOriginalAssetMap, hubAssets, hubVaults, hubVaultsAddressSet, intentRelayChainIdToSpokeChainIdMap, isBalnMigrateParams, isConfiguredMoneyMarketConfig, isConfiguredSolverConfig, isEvmHubChainConfig, isEvmInitializedConfig, isEvmSpokeChainConfig, isEvmSpokeProvider, isEvmUninitializedBrowserConfig, isEvmUninitializedConfig, isEvmUninitializedPrivateKeyConfig, isIconAddress, isIconSpokeProvider, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveSpokeProvider, isIntentCreationFailedError, isIntentCreationUnknownError, isIntentPostExecutionFailedError, isIntentRelayChainId, isIntentSubmitTxFailedError, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isMoneyMarketBorrowUnknownError, isMoneyMarketCreateBorrowIntentFailedError, isMoneyMarketCreateRepayIntentFailedError, isMoneyMarketCreateSupplyIntentFailedError, isMoneyMarketCreateWithdrawIntentFailedError, isMoneyMarketRelayTimeoutError, isMoneyMarketRepayUnknownError, isMoneyMarketReserveAsset, isMoneyMarketReserveHubAsset, isMoneyMarketSubmitTxFailedError, isMoneyMarketSupplyUnknownError, isMoneyMarketSupportedToken, isMoneyMarketWithdrawUnknownError, isNativeToken, isNewbnUSDChainId, isNewbnUSDToken, isPartnerFeeAmount, isPartnerFeePercentage, isResponseAddressType, isResponseSigningType, isSolanaSpokeProvider, isSolverSupportedToken, isSonicSpokeProvider, isStellarSpokeProvider, isSuiSpokeProvider, isUnifiedBnUSDMigrateParams, isValidChainHubAsset, isValidHubAsset, isValidIntentRelayChainId, isValidOriginalAssetAddress, isValidSpokeChainId, isWaitUntilIntentExecutedFailed, moneyMarketReserveAssets, moneyMarketReserveHubAssetsSet, moneyMarketSupportedTokens, nativeToUSD, newbnUSDSpokeChainIds, normalize, normalizeBN, normalizedToUsd, originalAssetTohubAssetMap, poolAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, retry, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainIdsSet, submitTransaction, supportedHubAssets, supportedHubChains, supportedSpokeChains, supportedTokensPerChain, uiPoolDataAbi, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, wadToRay, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
16620
+ export { BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BnUSDMigrationService, ChainIdToIntentRelayChainId, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, EVM_CHAIN_IDS, EVM_SPOKE_CHAIN_IDS, Erc20Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeProvider, EvmSpokeService, EvmVaultTokenService, EvmWalletAbstraction, FEE_PERCENTAGE_SCALE, HALF_RAY, HALF_WAD, HubVaultSymbols, ICON_TX_RESULT_WAIT_MAX_RETRY, INTENT_RELAY_CHAIN_IDS, IconSpokeProvider, IcxMigrationService, InjectiveSpokeProvider, IntentCreatedEventAbi, IntentDataType, IntentsAbi, LTV_PRECISION, LendingPoolService, LockupMultiplier, LockupPeriod, MAX_UINT256, MigrationService, MoneyMarketDataService, MoneyMarketService, RAY, RAY_DECIMALS, SECONDS_PER_YEAR, STELLAR_DEFAULT_TX_TIMEOUT_SECONDS, STELLAR_PRIORITY_FEE, Sodax, SolanaSpokeProvider, SolverIntentErrorCode, SolverIntentStatusCode, SolverService, SonicSpokeProvider, SonicSpokeService, SpokeService, StellarSpokeProvider, SuiSpokeProvider, SupportedMigrationTokens, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, WalletAbstractionService, adjustAmountByFee, assetManagerAbi, balnSwapAbi, binomialApproximatedRayPow, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bnUSDNewTokens, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, chainIdToHubAssetsMap, connectionAbi, deriveUserWalletAddress, encodeAddress, encodeContractCalls, erc20Abi, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getCompoundedBalance, getEvmViemChain, getHubAssetInfo, getHubChainConfig, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getMoneyMarketConfig, getOriginalAssetAddress, getPacket, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeChainIdFromIntentRelayChainId, getSupportedMoneyMarketTokens, getSupportedSolverTokens, getTransactionPackets, hexToBigInt, hubAssetToOriginalAssetMap, hubAssets, hubVaults, hubVaultsAddressSet, intentRelayChainIdToSpokeChainIdMap, isBalnMigrateParams, isConfiguredMoneyMarketConfig, isConfiguredSolverConfig, isEvmHubChainConfig, isEvmInitializedConfig, isEvmSpokeChainConfig, isEvmSpokeProvider, isEvmUninitializedBrowserConfig, isEvmUninitializedConfig, isEvmUninitializedPrivateKeyConfig, isIconAddress, isIconSpokeProvider, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveSpokeProvider, isIntentCreationFailedError, isIntentCreationUnknownError, isIntentPostExecutionFailedError, isIntentRelayChainId, isIntentSubmitTxFailedError, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isMoneyMarketBorrowUnknownError, isMoneyMarketCreateBorrowIntentFailedError, isMoneyMarketCreateRepayIntentFailedError, isMoneyMarketCreateSupplyIntentFailedError, isMoneyMarketCreateWithdrawIntentFailedError, isMoneyMarketRelayTimeoutError, isMoneyMarketRepayUnknownError, isMoneyMarketReserveAsset, isMoneyMarketReserveHubAsset, isMoneyMarketSubmitTxFailedError, isMoneyMarketSupplyUnknownError, isMoneyMarketSupportedToken, isMoneyMarketWithdrawUnknownError, isNativeToken, isNewbnUSDChainId, isNewbnUSDToken, isPartnerFeeAmount, isPartnerFeePercentage, isResponseAddressType, isResponseSigningType, isSolanaSpokeProvider, isSolverSupportedToken, isSonicSpokeProvider, isStellarSpokeProvider, isSuiSpokeProvider, isUnifiedBnUSDMigrateParams, isValidChainHubAsset, isValidHubAsset, isValidIntentRelayChainId, isValidOriginalAssetAddress, isValidSpokeChainId, isWaitUntilIntentExecutedFailed, moneyMarketReserveAssets, moneyMarketReserveHubAssetsSet, moneyMarketSupportedTokens, nativeToUSD, newbnUSDSpokeChainIds, normalize, normalizeBN, normalizedToUsd, originalAssetTohubAssetMap, poolAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, retry, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainIdsSet, submitTransaction, supportedHubAssets, supportedHubChains, supportedSpokeChains, supportedTokensPerChain, uiPoolDataAbi, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, wadToRay, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
16589
16621
  //# sourceMappingURL=index.mjs.map
16590
16622
  //# sourceMappingURL=index.mjs.map