@sodax/sdk 0.0.1-rc.27 → 0.0.1-rc.29

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.cjs CHANGED
@@ -1,22 +1,22 @@
1
1
  'use strict';
2
2
 
3
3
  var viem = require('viem');
4
- var invariant11 = require('tiny-invariant');
5
- var bcs = require('@mysten/sui/bcs');
6
- var web3_js = require('@solana/web3.js');
7
- var stellarSdk = require('@stellar/stellar-sdk');
8
4
  var chains = require('viem/chains');
9
5
  var types = require('@sodax/types');
10
6
  var sdkTs = require('@injectivelabs/sdk-ts');
11
7
  var networks = require('@injectivelabs/networks');
12
8
  var IconSdkRaw = require('icon-sdk-js');
9
+ var stellarSdk = require('@stellar/stellar-sdk');
10
+ var bcs = require('@mysten/sui/bcs');
13
11
  var client = require('@mysten/sui/client');
14
12
  var transactions = require('@mysten/sui/transactions');
13
+ var web3_js = require('@solana/web3.js');
15
14
  var coreProtoTs = require('@injectivelabs/core-proto-ts');
16
15
  var rlp = require('rlp');
17
16
  var splToken = require('@solana/spl-token');
18
17
  var anchor = require('@coral-xyz/anchor');
19
18
  var BN = require('bn.js');
19
+ var invariant11 = require('tiny-invariant');
20
20
  var BigNumber4 = require('bignumber.js');
21
21
 
22
22
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -39,11 +39,11 @@ function _interopNamespace(e) {
39
39
  return Object.freeze(n);
40
40
  }
41
41
 
42
- var invariant11__default = /*#__PURE__*/_interopDefault(invariant11);
43
42
  var IconSdkRaw__namespace = /*#__PURE__*/_interopNamespace(IconSdkRaw);
44
43
  var rlp__namespace = /*#__PURE__*/_interopNamespace(rlp);
45
44
  var anchor__namespace = /*#__PURE__*/_interopNamespace(anchor);
46
45
  var BN__default = /*#__PURE__*/_interopDefault(BN);
46
+ var invariant11__default = /*#__PURE__*/_interopDefault(invariant11);
47
47
  var BigNumber4__default = /*#__PURE__*/_interopDefault(BigNumber4);
48
48
 
49
49
  // src/abis/asset-manager.abi.ts
@@ -6132,107 +6132,6 @@ function encodeContractCalls(calls) {
6132
6132
  async function waitForTransactionReceipt(hash, provider) {
6133
6133
  return provider.waitForTransactionReceipt(hash);
6134
6134
  }
6135
- async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
6136
- do {
6137
- try {
6138
- return await action(retryCount);
6139
- } catch (e) {
6140
- retryCount--;
6141
- if (retryCount <= 0) {
6142
- console.error(`Failed to perform operation even after ${DEFAULT_MAX_RETRY} attempts.. Throwing origin error..`);
6143
- throw e;
6144
- }
6145
- }
6146
- await new Promise((resolve) => setTimeout(resolve, delayMs));
6147
- } while (retryCount > 0);
6148
- throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
6149
- }
6150
- function getRandomBytes(length) {
6151
- const array = new Uint8Array(length);
6152
- for (let i = 0; i < length; i++) {
6153
- array[i] = Math.floor(Math.random() * 256);
6154
- }
6155
- return array;
6156
- }
6157
- function randomUint256() {
6158
- const bytes = getRandomBytes(32);
6159
- let hex = "";
6160
- for (const byte of bytes) {
6161
- hex += byte.toString(16).padStart(2, "0") ?? "";
6162
- }
6163
- return BigInt(`0x${hex}`);
6164
- }
6165
- function calculatePercentageFeeAmount(amount, percentage) {
6166
- return amount * BigInt(percentage) / FEE_PERCENTAGE_SCALE;
6167
- }
6168
- function calculateFeeAmount(inputAmount, fee) {
6169
- if (!fee) {
6170
- return 0n;
6171
- }
6172
- invariant11__default.default(inputAmount > 0n, "Input amount must be greater than 0");
6173
- let feeAmount = 0n;
6174
- if (isPartnerFeeAmount(fee)) {
6175
- invariant11__default.default(
6176
- fee.amount >= 0 && fee.amount <= inputAmount,
6177
- `Fee amount must be greater than 0 and less than or equal to the input amount: ${fee.amount}`
6178
- );
6179
- feeAmount = fee.amount;
6180
- } else if (isPartnerFeePercentage(fee)) {
6181
- invariant11__default.default(
6182
- fee.percentage >= 0 && fee.percentage <= FEE_PERCENTAGE_SCALE,
6183
- `Fee percentage must be between 0 and ${FEE_PERCENTAGE_SCALE}}`
6184
- );
6185
- feeAmount = calculatePercentageFeeAmount(inputAmount, fee.percentage);
6186
- }
6187
- return feeAmount;
6188
- }
6189
- function adjustAmountByFee(amount, fee, quoteType) {
6190
- invariant11__default.default(amount > 0n, "Amount must be greater than 0");
6191
- invariant11__default.default(quoteType === "exact_input" || quoteType === "exact_output", "Invalid quote type");
6192
- if (quoteType === "exact_input") {
6193
- return amount - calculateFeeAmount(amount, fee);
6194
- }
6195
- if (quoteType === "exact_output") {
6196
- return amount + calculateFeeAmount(amount, fee);
6197
- }
6198
- throw new Error("Invalid quote type");
6199
- }
6200
- function BigIntToHex(value) {
6201
- return `0x${value.toString(16)}`;
6202
- }
6203
- function encodeAddress(spokeChainId, address) {
6204
- switch (spokeChainId) {
6205
- case "0xa86a.avax":
6206
- case "0x2105.base":
6207
- case "0xa.optimism":
6208
- case "0x38.bsc":
6209
- case "0x89.polygon":
6210
- case "0xa4b1.arbitrum":
6211
- case "sonic":
6212
- return address;
6213
- case "injective-1":
6214
- return viem.toHex(Buffer.from(address, "utf-8"));
6215
- case "0x1.icon":
6216
- return viem.toHex(Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex"));
6217
- case "sui":
6218
- return viem.toHex(bcs.bcs.Address.serialize(address).toBytes());
6219
- case "solana":
6220
- return viem.toHex(Buffer.from(new web3_js.PublicKey(address).toBytes()));
6221
- case "stellar":
6222
- return `0x${stellarSdk.Address.fromString(address).toScVal().toXDR("hex")}`;
6223
- default:
6224
- return address;
6225
- }
6226
- }
6227
- function hexToBigInt(hex) {
6228
- const trimmed = hex.trim().toLowerCase();
6229
- const isValid = /^(0x)?[0-9a-f]+$/.test(trimmed);
6230
- if (!isValid) {
6231
- throw new Error(`Invalid hex string: "${hex}"`);
6232
- }
6233
- const normalized = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
6234
- return BigInt(normalized);
6235
- }
6236
6135
  var DEFAULT_MAX_RETRY = 3;
6237
6136
  var DEFAULT_RELAY_TX_TIMEOUT = 6e4;
6238
6137
  var DEFAULT_RETRY_DELAY_MS = 2e3;
@@ -6241,6 +6140,7 @@ var MAX_UINT256 = (1n << 256n) - 1n;
6241
6140
  var FEE_PERCENTAGE_SCALE = 10000n;
6242
6141
  var STELLAR_PRIORITY_FEE = "10000";
6243
6142
  var STELLAR_DEFAULT_TX_TIMEOUT_SECONDS = 100;
6143
+ var DEFAULT_DEADLINE_OFFSET = 300n;
6244
6144
  var VAULT_TOKEN_DECIMALS = 18;
6245
6145
  var INTENT_RELAY_CHAIN_IDS = {
6246
6146
  AVAX: 6n,
@@ -7937,651 +7837,248 @@ var isNativeToken = (chainId, token) => {
7937
7837
  }
7938
7838
  return token.address.toLowerCase() === spokeChainConfig[chainId].nativeToken.toLowerCase();
7939
7839
  };
7940
- var Erc20Service = class {
7941
- constructor() {
7840
+ var InjectiveSpokeProvider = class {
7841
+ walletProvider;
7842
+ chainConfig;
7843
+ chainGrpcWasmApi;
7844
+ txClient;
7845
+ constructor(conf, walletProvider) {
7846
+ this.chainConfig = conf;
7847
+ this.walletProvider = walletProvider;
7848
+ const endpoints = networks.getNetworkEndpoints(networks.Network.Mainnet);
7849
+ this.chainGrpcWasmApi = new sdkTs.ChainGrpcWasmApi(endpoints.grpc);
7850
+ this.txClient = new sdkTs.TxGrpcApi(endpoints.grpc);
7942
7851
  }
7943
- /**
7944
- * Check if spender has enough ERC20 allowance for given amount
7945
- * @param token - ERC20 token address
7946
- * @param amount - Amount to check allowance for
7947
- * @param owner - User wallet address
7948
- * @param spender - Spender address
7949
- * @param spokeProvider - EVM Spoke provider
7950
- * @return - True if spender is allowed to spend amount on behalf of owner
7951
- */
7952
- static async isAllowanceValid(token, amount, owner, spender, spokeProvider) {
7953
- try {
7954
- if (token.toLowerCase() === spokeProvider.chainConfig.nativeToken.toLowerCase()) {
7955
- return {
7956
- ok: true,
7957
- value: true
7958
- };
7959
- }
7960
- const allowedAmount = await spokeProvider.publicClient.readContract({
7961
- address: token,
7962
- abi: viem.erc20Abi,
7963
- functionName: "allowance",
7964
- args: [owner, spender]
7965
- });
7966
- return {
7967
- ok: true,
7968
- value: allowedAmount >= amount
7969
- };
7970
- } catch (e) {
7971
- return {
7972
- ok: false,
7973
- error: e
7974
- };
7975
- }
7852
+ // Query Methods
7853
+ async getState() {
7854
+ return this.chainGrpcWasmApi.fetchSmartContractState(
7855
+ this.chainConfig.addresses.assetManager,
7856
+ sdkTs.toBase64({
7857
+ get_state: {}
7858
+ })
7859
+ );
7976
7860
  }
7977
- /**
7978
- * Approve ERC20 amount spending
7979
- * @param token - ERC20 token address
7980
- * @param amount - Amount to approve
7981
- * @param spender - Spender address
7982
- * @param provider - EVM Provider
7983
- */
7984
- static async approve(token, amount, spender, spokeProvider, raw) {
7985
- const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
7986
- const rawTx = {
7987
- from: walletAddress,
7988
- to: token,
7989
- value: 0n,
7990
- data: viem.encodeFunctionData({
7991
- abi: viem.erc20Abi,
7992
- functionName: "approve",
7993
- args: [spender, amount]
7861
+ async getBalance(token) {
7862
+ return this.chainGrpcWasmApi.fetchSmartContractState(
7863
+ this.chainConfig.addresses.assetManager,
7864
+ sdkTs.toBase64({
7865
+ get_balance: { denom: token }
7994
7866
  })
7867
+ );
7868
+ }
7869
+ // Execute Methods (requires SigningCosmWasmClient)
7870
+ /**
7871
+ * Deposit tokens including native token to Injective Asset Manager.
7872
+ **/
7873
+ static async deposit(sender, token_address, to, amount, data = "0x", spokeProvider, raw) {
7874
+ const toBytes = viem.fromHex(to, "bytes");
7875
+ const dataBytes = viem.fromHex(data, "bytes");
7876
+ const msg = {
7877
+ transfer: {
7878
+ token: token_address,
7879
+ to: Array.from(toBytes),
7880
+ amount,
7881
+ data: Array.from(dataBytes)
7882
+ }
7995
7883
  };
7884
+ const funds = [{ amount, denom: token_address }];
7996
7885
  if (raw) {
7997
- return rawTx;
7886
+ return await spokeProvider.walletProvider.getRawTransaction(
7887
+ spokeProvider.chainConfig.networkId,
7888
+ spokeProvider.chainConfig.prefix,
7889
+ sender,
7890
+ spokeProvider.chainConfig.addresses.assetManager,
7891
+ msg
7892
+ );
7998
7893
  }
7999
- return spokeProvider.walletProvider.sendTransaction(rawTx);
7894
+ const res = await spokeProvider.walletProvider.execute(
7895
+ sender,
7896
+ spokeProvider.chainConfig.addresses.assetManager,
7897
+ msg,
7898
+ funds
7899
+ );
7900
+ return res.transactionHash;
8000
7901
  }
8001
- /**
8002
- * Encodes a transfer transaction for a token.
8003
- * @param token - The address of the token.
8004
- * @param to - The address to transfer the token to.
8005
- * @param amount - The amount of the token to transfer.
8006
- * @returns The encoded contract call.
8007
- */
8008
- static encodeTransfer(token, to, amount) {
8009
- return {
8010
- address: token,
8011
- value: 0n,
8012
- data: viem.encodeFunctionData({
8013
- abi: viem.erc20Abi,
8014
- functionName: "transfer",
8015
- args: [to, amount]
8016
- })
7902
+ async receiveMessage(senderAddress, srcChainId, srcAddress, connSn, payload, signatures) {
7903
+ const msg = {
7904
+ recv_message: {
7905
+ src_chain_id: srcChainId,
7906
+ src_address: srcAddress,
7907
+ conn_sn: connSn,
7908
+ payload,
7909
+ signatures
7910
+ }
8017
7911
  };
7912
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8018
7913
  }
8019
- /**
8020
- * Encodes a transferFrom transaction for a token.
8021
- * @param token - The address of the token.
8022
- * @param from - The address to transfer the token from.
8023
- * @param to - The address to transfer the token to.
8024
- * @param amount - The amount of the token to transfer.
8025
- * @returns The encoded contract call.
8026
- */
8027
- static encodeTransferFrom(token, from, to, amount) {
8028
- return {
8029
- address: token,
8030
- value: 0n,
8031
- data: viem.encodeFunctionData({
8032
- abi: viem.erc20Abi,
8033
- functionName: "transferFrom",
8034
- args: [from, to, amount]
8035
- })
7914
+ async setRateLimit(senderAddress, rateLimit) {
7915
+ const msg = {
7916
+ set_rate_limit: {
7917
+ rate_limit: rateLimit
7918
+ }
8036
7919
  };
7920
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8037
7921
  }
8038
- /**
8039
- * Encodes an approval transaction for a token.
8040
- * @param token - The address of the token.
8041
- * @param to - The address to approve the token to.
8042
- * @param amount - The amount of the token to approve.
8043
- * @returns The encoded contract call.
8044
- */
8045
- static encodeApprove(token, to, amount) {
8046
- return {
8047
- address: token,
8048
- value: 0n,
8049
- data: viem.encodeFunctionData({
8050
- abi: viem.erc20Abi,
8051
- functionName: "approve",
8052
- args: [to, amount]
8053
- })
7922
+ async setConnection(senderAddress, connection) {
7923
+ const msg = {
7924
+ set_connection: {
7925
+ connection
7926
+ }
8054
7927
  };
7928
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8055
7929
  }
8056
- };
8057
- var EvmVaultTokenService = class {
8058
- constructor() {
8059
- }
8060
- /**
8061
- * Fetches token information for a specific token in the vault.
8062
- * @param vault - The address of the vault.
8063
- * @param token - The address of the token.
8064
- * @param publicClient - PublicClient<HttpTransport>
8065
- * @returns Token information as a TokenInfo object.
8066
- */
8067
- static async getTokenInfo(vault, token, publicClient) {
8068
- const [decimals, depositFee, withdrawalFee, maxDeposit, isSupported] = await publicClient.readContract({
8069
- address: vault,
8070
- abi: vaultTokenAbi,
8071
- functionName: "tokenInfo",
8072
- args: [token]
8073
- });
8074
- return { decimals, depositFee, withdrawalFee, maxDeposit, isSupported };
8075
- }
8076
- /**
8077
- * Retrieves the reserves of the vault.
8078
- * @param vault - The address of the vault.
8079
- * @param publicClient - PublicClient<HttpTransport>
8080
- * @returns An object containing tokens and their balances.
8081
- */
8082
- static async getVaultReserves(vault, publicClient) {
8083
- const [tokens, balances] = await publicClient.readContract({
8084
- address: vault,
8085
- abi: vaultTokenAbi,
8086
- functionName: "getVaultReserves",
8087
- args: []
8088
- });
8089
- return {
8090
- tokens,
8091
- balances
7930
+ async setOwner(senderAddress, owner) {
7931
+ const msg = {
7932
+ set_owner: {
7933
+ owner
7934
+ }
8092
7935
  };
7936
+ return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8093
7937
  }
8094
- /**
8095
- * Retrieves all token information for the vault.
8096
- * @param vault - The address of the vault.
8097
- * @param publicClient - PublicClient<HttpTransport>
8098
- * @returns A promise that resolves to an object containing tokens, their infos, and reserves.
8099
- */
8100
- async getAllTokenInfo(vault, publicClient) {
8101
- const [tokens, infos, reserves] = await publicClient.readContract({
8102
- address: vault,
8103
- abi: vaultTokenAbi,
8104
- functionName: "getAllTokenInfo",
8105
- args: []
8106
- });
8107
- return {
8108
- tokens,
8109
- infos,
8110
- reserves
7938
+ async send_message(sender, dst_chain_id, dst_address, payload, raw) {
7939
+ const msg = {
7940
+ send_message: {
7941
+ dst_chain_id: Number.parseInt(dst_chain_id),
7942
+ dst_address: Array.from(viem.fromHex(dst_address, "bytes")),
7943
+ payload: Array.from(viem.fromHex(payload, "bytes"))
7944
+ }
8111
7945
  };
7946
+ if (raw) {
7947
+ return await this.walletProvider.getRawTransaction(
7948
+ this.chainConfig.networkId,
7949
+ this.chainConfig.prefix,
7950
+ sender,
7951
+ this.chainConfig.addresses.connection,
7952
+ msg
7953
+ );
7954
+ }
7955
+ const res = await this.walletProvider.execute(sender, this.chainConfig.addresses.connection, msg);
7956
+ return res.transactionHash;
8112
7957
  }
8113
- /**
8114
- * Deposits a specified amount of a token into the vault.
8115
- * @param vault - The address of the vault.
8116
- * @param token - The address of the token to deposit.
8117
- * @param amount - The amount of the token to deposit.
8118
- * @param walletProvider - IEvmWalletProvider
8119
- * @returns Transaction hash
8120
- */
8121
- static async deposit(vault, token, amount, walletProvider) {
8122
- const from = await walletProvider.getWalletAddress();
8123
- return walletProvider.sendTransaction({
8124
- from,
8125
- to: vault,
8126
- value: 0n,
8127
- data: viem.encodeFunctionData({
8128
- abi: vaultTokenAbi,
8129
- functionName: "deposit",
8130
- args: [token, amount]
8131
- })
8132
- });
8133
- }
8134
- /**
8135
- * Withdraws a specified amount of a token from the vault.
8136
- * @param vault - The address of the vault.
8137
- * @param token - The address of the token to withdraw.
8138
- * @param amount - The amount of the token to withdraw.
8139
- * @param provider - EvmWalletProvider
8140
- * @returns Transaction hash
8141
- */
8142
- static async withdraw(vault, token, amount, provider) {
8143
- const from = await provider.getWalletAddress();
8144
- return provider.sendTransaction({
8145
- from,
8146
- to: vault,
8147
- value: 0n,
8148
- data: viem.encodeFunctionData({
8149
- abi: vaultTokenAbi,
8150
- functionName: "withdraw",
8151
- args: [token, amount]
8152
- })
8153
- });
8154
- }
8155
- /**
8156
- * Encodes the deposit transaction data for the vault.
8157
- * @param vault - The address of the vault.
8158
- * @param token - The address of the token to deposit.
8159
- * @param amount - The amount of the token to deposit.
8160
- * @returns The encoded contract call data.
8161
- */
8162
- static encodeDeposit(vault, token, amount) {
8163
- return {
8164
- address: vault,
8165
- value: 0n,
8166
- data: viem.encodeFunctionData({
8167
- abi: vaultTokenAbi,
8168
- functionName: "deposit",
8169
- args: [token, amount]
8170
- })
8171
- };
7958
+ // Helper Methods
7959
+ static stringToUint8Array(str) {
7960
+ return new TextEncoder().encode(str);
8172
7961
  }
8173
- /**
8174
- * Encodes the withdraw transaction data for the vault.
8175
- * @param vault - The address of the vault.
8176
- * @param token - The address of the token to withdraw.
8177
- * @param amount - The amount of the token to withdraw.
8178
- * @returns The encoded contract call data.
8179
- */
8180
- static encodeWithdraw(vault, token, amount) {
8181
- return {
8182
- address: vault,
8183
- value: 0n,
8184
- data: viem.encodeFunctionData({
8185
- abi: vaultTokenAbi,
8186
- functionName: "withdraw",
8187
- args: [token, amount]
8188
- })
8189
- };
7962
+ static uint8ArrayToString(arr) {
7963
+ return new TextDecoder().decode(arr);
8190
7964
  }
8191
- /**
8192
- * Translates token amounts from their native decimals to 18 decimals
8193
- * @param decimals - The number of decimals of the token
8194
- * @param amount - The amount to translate
8195
- * @returns The translated amount
8196
- */
8197
- static translateIncomingDecimals(decimals, amount) {
8198
- if (decimals <= 18) {
8199
- return amount * BigInt(10 ** (18 - decimals));
8200
- }
8201
- return amount / BigInt(10 ** (decimals - 18));
7965
+ static toBigIntString(num) {
7966
+ return num.toString();
8202
7967
  }
8203
- /**
8204
- * Translates token amounts from 18 decimals back to their native decimals
8205
- * @param decimals - The number of decimals of the token
8206
- * @param amount - The amount to translate
8207
- * @returns The translated amount
8208
- */
8209
- static translateOutgoingDecimals(decimals, amount) {
8210
- if (decimals <= 18) {
8211
- return amount / BigInt(10 ** (18 - decimals));
8212
- }
8213
- return amount * BigInt(10 ** (decimals - 18));
7968
+ };
7969
+ var IconSdk = "default" in IconSdkRaw__namespace.default ? IconSdkRaw__namespace.default : IconSdkRaw__namespace;
7970
+ var IconSpokeProvider = class {
7971
+ walletProvider;
7972
+ chainConfig;
7973
+ iconService;
7974
+ debugRpcUrl;
7975
+ constructor(walletProvider, chainConfig, rpcUrl = "https://ctz.solidwallet.io/api/v3", debugRpcUrl = "https://ctz.solidwallet.io/api/v3d") {
7976
+ this.walletProvider = walletProvider;
7977
+ this.chainConfig = chainConfig;
7978
+ this.iconService = new IconSdk.IconService(new IconSdk.IconService.HttpProvider(rpcUrl));
7979
+ this.debugRpcUrl = debugRpcUrl;
8214
7980
  }
8215
7981
  };
8216
7982
 
8217
- // src/services/hub/EvmAssetManagerService.ts
8218
- var EvmAssetManagerService = class _EvmAssetManagerService {
8219
- constructor() {
7983
+ // src/entities/icon/utils.ts
7984
+ function getIconAddressBytes(address) {
7985
+ return `0x${Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex").toString("hex")}`;
7986
+ }
7987
+
7988
+ // src/entities/Providers.ts
7989
+ var EvmHubProvider = class {
7990
+ publicClient;
7991
+ chainConfig;
7992
+ constructor(config) {
7993
+ if (config) {
7994
+ this.publicClient = viem.createPublicClient({
7995
+ transport: viem.http(config.hubRpcUrl),
7996
+ chain: getEvmViemChain(config.chainConfig.chain.id)
7997
+ });
7998
+ this.chainConfig = config.chainConfig;
7999
+ } else {
8000
+ this.publicClient = viem.createPublicClient({
8001
+ transport: viem.http("https://rpc.soniclabs.com"),
8002
+ chain: getEvmViemChain(types.SONIC_MAINNET_CHAIN_ID)
8003
+ });
8004
+ this.chainConfig = getHubChainConfig(types.SONIC_MAINNET_CHAIN_ID);
8005
+ }
8220
8006
  }
8221
- /**
8222
- * Get asset information for a given asset address
8223
- * @param asset - The address of the asset contract
8224
- * @param assetManager - The address of the asset manager contract
8225
- * @param client - The Viem public client
8226
- * @returns Object containing chainID and spoke address for the asset
8227
- */
8228
- static async getAssetInfo(asset, assetManager, client) {
8229
- const [chainId, spokeAddress] = await client.readContract({
8230
- address: assetManager,
8231
- abi: assetManagerAbi,
8232
- functionName: "assetInfo",
8233
- args: [asset]
8234
- });
8235
- return {
8236
- chainId,
8237
- spokeAddress
8238
- };
8239
- }
8240
- /**
8241
- * Encodes a transfer transaction for an asset.
8242
- * @param token - The address of the token.
8243
- * @param to - The address to transfer the token to.
8244
- * @param amount - The amount of the token to transfer.
8245
- * @param assetManager
8246
- * @returns The encoded contract call.
8247
- */
8248
- static encodeTransfer(token, to, amount, assetManager) {
8249
- return {
8250
- address: assetManager,
8251
- value: 0n,
8252
- data: viem.encodeFunctionData({
8253
- abi: assetManagerAbi,
8254
- functionName: "transfer",
8255
- args: [token, to, amount, "0x"]
8256
- })
8257
- };
8258
- }
8259
- /**
8260
- * Constructs the data for depositing tokens to the spoke chain.
8261
- * @param {EvmDepositToDataParams} params - The address of the token to deposit.
8262
- * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
8263
- * @returns {Hex} Encoded contract calls for the deposit transaction.
8264
- * @throws Will throw an error if the asset or vault address is not found.
8265
- */
8266
- static depositToData(params, spokeChainId) {
8267
- const calls = [];
8268
- const assetConfig = getHubAssetInfo(spokeChainId, params.token);
8269
- if (!assetConfig) {
8270
- throw new Error("[depositToData] Hub asset not found");
8007
+ };
8008
+ var SonicSpokeProvider = class {
8009
+ walletProvider;
8010
+ chainConfig;
8011
+ publicClient;
8012
+ constructor(walletProvider, chainConfig, rpcUrl) {
8013
+ this.walletProvider = walletProvider;
8014
+ this.chainConfig = chainConfig;
8015
+ if (rpcUrl) {
8016
+ this.publicClient = viem.createPublicClient({
8017
+ transport: viem.http(rpcUrl),
8018
+ chain: getEvmViemChain(chainConfig.chain.id)
8019
+ });
8020
+ } else {
8021
+ this.publicClient = viem.createPublicClient({
8022
+ transport: viem.http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8023
+ chain: getEvmViemChain(chainConfig.chain.id)
8024
+ });
8271
8025
  }
8272
- const assetAddress = assetConfig.asset;
8273
- const vaultAddress = assetConfig.vault;
8274
- calls.push(Erc20Service.encodeApprove(assetAddress, vaultAddress, params.amount));
8275
- calls.push(EvmVaultTokenService.encodeDeposit(vaultAddress, assetAddress, params.amount));
8276
- const translatedAmount = EvmVaultTokenService.translateIncomingDecimals(assetConfig.decimal, params.amount);
8277
- calls.push(Erc20Service.encodeTransfer(vaultAddress, params.to, translatedAmount));
8278
- return encodeContractCalls(calls);
8279
8026
  }
8280
- /**
8281
- * Withdraw tokens from the spoke chain.
8282
- * @param {EvmWithdrawAssetDataParams} params - Parameters for the withdrawal.
8283
- * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
8284
- * @param {EvmHubProvider} hubProvider - The provider for the hub chain.
8285
- * @returns {Hex} Encoded contract calls for the withdrawal transaction.
8286
- * @throws Will throw an error if the asset address is not found.
8287
- */
8288
- static withdrawAssetData(params, hubProvider, spokeChainId) {
8289
- const calls = [];
8290
- const assetConfig = getHubAssetInfo(spokeChainId, params.token);
8291
- if (!assetConfig) {
8292
- throw new Error("[withdrawAssetData] Hub asset not found");
8027
+ };
8028
+ var EvmSpokeProvider = class {
8029
+ walletProvider;
8030
+ chainConfig;
8031
+ publicClient;
8032
+ constructor(walletProvider, chainConfig, rpcUrl) {
8033
+ this.walletProvider = walletProvider;
8034
+ this.chainConfig = chainConfig;
8035
+ if (rpcUrl) {
8036
+ this.publicClient = viem.createPublicClient({
8037
+ transport: viem.http(rpcUrl),
8038
+ chain: getEvmViemChain(chainConfig.chain.id)
8039
+ });
8040
+ } else {
8041
+ this.publicClient = viem.createPublicClient({
8042
+ transport: viem.http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8043
+ chain: getEvmViemChain(chainConfig.chain.id)
8044
+ });
8293
8045
  }
8294
- const assetAddress = assetConfig.asset;
8295
- calls.push(
8296
- _EvmAssetManagerService.encodeTransfer(
8297
- assetAddress,
8298
- params.to,
8299
- params.amount,
8300
- hubProvider.chainConfig.addresses.assetManager
8301
- )
8302
- );
8303
- return encodeContractCalls(calls);
8304
- }
8305
- /**
8306
- * Get asset address for a given chain ID and spoke address
8307
- * @param chainId Chain ID where the asset exists
8308
- * @param spokeAddress Address of the asset on the spoke chain
8309
- * @param assetManager Address of the asset manager contract
8310
- * @param client The Viem public client
8311
- * @returns The asset's address on the hub chain
8312
- */
8313
- async getAssetAddress(chainId, spokeAddress, assetManager, client) {
8314
- return client.readContract({
8315
- address: assetManager,
8316
- abi: assetManagerAbi,
8317
- functionName: "assets",
8318
- args: [chainId, spokeAddress]
8319
- });
8320
8046
  }
8321
8047
  };
8322
-
8323
- // src/services/hub/EvmWalletAbstraction.ts
8324
- var EvmWalletAbstraction = class {
8325
- constructor() {
8048
+ var CustomStellarAccount = class {
8049
+ accountId;
8050
+ sequenceNumber;
8051
+ startingSequenceNumber;
8052
+ constructor({ account_id, sequence }) {
8053
+ this.accountId = account_id;
8054
+ this.sequenceNumber = BigInt(sequence);
8055
+ this.startingSequenceNumber = BigInt(sequence);
8326
8056
  }
8327
- /**
8328
- * Get the hub wallet address for a given spoke chain and address.
8329
- * @param chainId - The spoke chain ID.
8330
- * @param address - The address on the spoke chain.
8331
- * @param hubProvider - The hub provider.
8332
- * @returns The hub wallet address.
8333
- */
8334
- static async getUserHubWalletAddress(chainId, address, hubProvider) {
8335
- return hubProvider.publicClient.readContract({
8336
- address: hubProvider.chainConfig.addresses.hubWallet,
8337
- abi: walletFactoryAbi,
8338
- functionName: "getDeployedAddress",
8339
- args: [BigInt(getIntentRelayChainId(chainId)), address]
8340
- });
8057
+ getSequenceNumber() {
8058
+ return this.sequenceNumber;
8341
8059
  }
8342
- };
8343
- var InjectiveSpokeProvider = class {
8344
- walletProvider;
8345
- chainConfig;
8346
- chainGrpcWasmApi;
8347
- txClient;
8348
- constructor(conf, walletProvider) {
8349
- this.chainConfig = conf;
8350
- this.walletProvider = walletProvider;
8351
- const endpoints = networks.getNetworkEndpoints(networks.Network.Mainnet);
8352
- this.chainGrpcWasmApi = new sdkTs.ChainGrpcWasmApi(endpoints.grpc);
8353
- this.txClient = new sdkTs.TxGrpcApi(endpoints.grpc);
8060
+ getStartingSequenceNumber() {
8061
+ return this.startingSequenceNumber;
8354
8062
  }
8355
- // Query Methods
8356
- async getState() {
8357
- return this.chainGrpcWasmApi.fetchSmartContractState(
8358
- this.chainConfig.addresses.assetManager,
8359
- sdkTs.toBase64({
8360
- get_state: {}
8361
- })
8362
- );
8063
+ getAccountId() {
8064
+ return this.accountId;
8363
8065
  }
8364
- async getBalance(token) {
8365
- return this.chainGrpcWasmApi.fetchSmartContractState(
8366
- this.chainConfig.addresses.assetManager,
8367
- sdkTs.toBase64({
8368
- get_balance: { denom: token }
8369
- })
8370
- );
8066
+ getAccountClone() {
8067
+ return new stellarSdk.Account(this.accountId, this.sequenceNumber.toString());
8371
8068
  }
8372
- // Execute Methods (requires SigningCosmWasmClient)
8373
- /**
8374
- * Deposit tokens including native token to Injective Asset Manager.
8375
- **/
8376
- static async deposit(sender, token_address, to, amount, data = "0x", spokeProvider, raw) {
8377
- const toBytes = viem.fromHex(to, "bytes");
8378
- const dataBytes = viem.fromHex(data, "bytes");
8379
- const msg = {
8380
- transfer: {
8381
- token: token_address,
8382
- to: Array.from(toBytes),
8383
- amount,
8384
- data: Array.from(dataBytes)
8385
- }
8386
- };
8387
- const funds = [{ amount, denom: token_address }];
8388
- if (raw) {
8389
- return await spokeProvider.walletProvider.getRawTransaction(
8390
- spokeProvider.chainConfig.networkId,
8391
- spokeProvider.chainConfig.prefix,
8392
- sender,
8393
- spokeProvider.chainConfig.addresses.assetManager,
8394
- msg
8395
- );
8069
+ incrementSequenceNumber() {
8070
+ this.sequenceNumber++;
8071
+ }
8072
+ decrementSequenceNumber() {
8073
+ if (this.sequenceNumber > this.startingSequenceNumber) {
8074
+ this.sequenceNumber--;
8396
8075
  }
8397
- const res = await spokeProvider.walletProvider.execute(
8398
- sender,
8399
- spokeProvider.chainConfig.addresses.assetManager,
8400
- msg,
8401
- funds
8076
+ throw new Error(
8077
+ `Sequence number cannot be decremented below the starting sequence number: ${this.startingSequenceNumber}`
8402
8078
  );
8403
- return res.transactionHash;
8404
- }
8405
- async receiveMessage(senderAddress, srcChainId, srcAddress, connSn, payload, signatures) {
8406
- const msg = {
8407
- recv_message: {
8408
- src_chain_id: srcChainId,
8409
- src_address: srcAddress,
8410
- conn_sn: connSn,
8411
- payload,
8412
- signatures
8413
- }
8414
- };
8415
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8416
8079
  }
8417
- async setRateLimit(senderAddress, rateLimit) {
8418
- const msg = {
8419
- set_rate_limit: {
8420
- rate_limit: rateLimit
8421
- }
8422
- };
8423
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8424
- }
8425
- async setConnection(senderAddress, connection) {
8426
- const msg = {
8427
- set_connection: {
8428
- connection
8429
- }
8430
- };
8431
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8432
- }
8433
- async setOwner(senderAddress, owner) {
8434
- const msg = {
8435
- set_owner: {
8436
- owner
8437
- }
8438
- };
8439
- return await this.walletProvider.execute(senderAddress, this.chainConfig.addresses.assetManager, msg);
8440
- }
8441
- async send_message(sender, dst_chain_id, dst_address, payload, raw) {
8442
- const msg = {
8443
- send_message: {
8444
- dst_chain_id: Number.parseInt(dst_chain_id),
8445
- dst_address: Array.from(viem.fromHex(dst_address, "bytes")),
8446
- payload: Array.from(viem.fromHex(payload, "bytes"))
8447
- }
8448
- };
8449
- if (raw) {
8450
- return await this.walletProvider.getRawTransaction(
8451
- this.chainConfig.networkId,
8452
- this.chainConfig.prefix,
8453
- sender,
8454
- this.chainConfig.addresses.connection,
8455
- msg
8456
- );
8457
- }
8458
- const res = await this.walletProvider.execute(sender, this.chainConfig.addresses.connection, msg);
8459
- return res.transactionHash;
8460
- }
8461
- // Helper Methods
8462
- static stringToUint8Array(str) {
8463
- return new TextEncoder().encode(str);
8464
- }
8465
- static uint8ArrayToString(arr) {
8466
- return new TextDecoder().decode(arr);
8467
- }
8468
- static toBigIntString(num) {
8469
- return num.toString();
8470
- }
8471
- };
8472
- var IconSdk = "default" in IconSdkRaw__namespace.default ? IconSdkRaw__namespace.default : IconSdkRaw__namespace;
8473
- var IconSpokeProvider = class {
8474
- walletProvider;
8475
- chainConfig;
8476
- iconService;
8477
- debugRpcUrl;
8478
- constructor(walletProvider, chainConfig, rpcUrl = "https://ctz.solidwallet.io/api/v3", debugRpcUrl = "https://ctz.solidwallet.io/api/v3d") {
8479
- this.walletProvider = walletProvider;
8480
- this.chainConfig = chainConfig;
8481
- this.iconService = new IconSdk.IconService(new IconSdk.IconService.HttpProvider(rpcUrl));
8482
- this.debugRpcUrl = debugRpcUrl;
8483
- }
8484
- };
8485
-
8486
- // src/entities/icon/utils.ts
8487
- function getIconAddressBytes(address) {
8488
- return `0x${Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex").toString("hex")}`;
8489
- }
8490
-
8491
- // src/entities/Providers.ts
8492
- var EvmHubProvider = class {
8493
- publicClient;
8494
- chainConfig;
8495
- constructor(config) {
8496
- if (config) {
8497
- this.publicClient = viem.createPublicClient({
8498
- transport: viem.http(config.hubRpcUrl),
8499
- chain: getEvmViemChain(config.chainConfig.chain.id)
8500
- });
8501
- this.chainConfig = config.chainConfig;
8502
- } else {
8503
- this.publicClient = viem.createPublicClient({
8504
- transport: viem.http("https://rpc.soniclabs.com"),
8505
- chain: getEvmViemChain(types.SONIC_MAINNET_CHAIN_ID)
8506
- });
8507
- this.chainConfig = getHubChainConfig(types.SONIC_MAINNET_CHAIN_ID);
8508
- }
8509
- }
8510
- };
8511
- var SonicSpokeProvider = class {
8512
- walletProvider;
8513
- chainConfig;
8514
- publicClient;
8515
- constructor(walletProvider, chainConfig, rpcUrl) {
8516
- this.walletProvider = walletProvider;
8517
- this.chainConfig = chainConfig;
8518
- if (rpcUrl) {
8519
- this.publicClient = viem.createPublicClient({
8520
- transport: viem.http(rpcUrl),
8521
- chain: getEvmViemChain(chainConfig.chain.id)
8522
- });
8523
- } else {
8524
- this.publicClient = viem.createPublicClient({
8525
- transport: viem.http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8526
- chain: getEvmViemChain(chainConfig.chain.id)
8527
- });
8528
- }
8529
- }
8530
- };
8531
- var EvmSpokeProvider = class {
8532
- walletProvider;
8533
- chainConfig;
8534
- publicClient;
8535
- constructor(walletProvider, chainConfig, rpcUrl) {
8536
- this.walletProvider = walletProvider;
8537
- this.chainConfig = chainConfig;
8538
- if (rpcUrl) {
8539
- this.publicClient = viem.createPublicClient({
8540
- transport: viem.http(rpcUrl),
8541
- chain: getEvmViemChain(chainConfig.chain.id)
8542
- });
8543
- } else {
8544
- this.publicClient = viem.createPublicClient({
8545
- transport: viem.http(getEvmViemChain(chainConfig.chain.id).rpcUrls.default.http[0]),
8546
- chain: getEvmViemChain(chainConfig.chain.id)
8547
- });
8548
- }
8549
- }
8550
- };
8551
- var CustomStellarAccount = class {
8552
- accountId;
8553
- sequenceNumber;
8554
- startingSequenceNumber;
8555
- constructor({ account_id, sequence }) {
8556
- this.accountId = account_id;
8557
- this.sequenceNumber = BigInt(sequence);
8558
- this.startingSequenceNumber = BigInt(sequence);
8559
- }
8560
- getSequenceNumber() {
8561
- return this.sequenceNumber;
8562
- }
8563
- getStartingSequenceNumber() {
8564
- return this.startingSequenceNumber;
8565
- }
8566
- getAccountId() {
8567
- return this.accountId;
8568
- }
8569
- getAccountClone() {
8570
- return new stellarSdk.Account(this.accountId, this.sequenceNumber.toString());
8571
- }
8572
- incrementSequenceNumber() {
8573
- this.sequenceNumber++;
8574
- }
8575
- decrementSequenceNumber() {
8576
- if (this.sequenceNumber > this.startingSequenceNumber) {
8577
- this.sequenceNumber--;
8578
- }
8579
- throw new Error(
8580
- `Sequence number cannot be decremented below the starting sequence number: ${this.startingSequenceNumber}`
8581
- );
8582
- }
8583
- resetSequenceNumber() {
8584
- this.sequenceNumber = this.startingSequenceNumber;
8080
+ resetSequenceNumber() {
8081
+ this.sequenceNumber = this.startingSequenceNumber;
8585
8082
  }
8586
8083
  };
8587
8084
  var CustomSorobanServer = class extends stellarSdk.SorobanRpc.Server {
@@ -9178,8 +8675,411 @@ function requestJsonRpc(rawTransaction, id = 99999) {
9178
8675
  }
9179
8676
  })
9180
8677
  );
9181
- });
9182
- }
8678
+ });
8679
+ }
8680
+ var Erc20Service = class {
8681
+ constructor() {
8682
+ }
8683
+ /**
8684
+ * Check if spender has enough ERC20 allowance for given amount
8685
+ * @param token - ERC20 token address
8686
+ * @param amount - Amount to check allowance for
8687
+ * @param owner - User wallet address
8688
+ * @param spender - Spender address
8689
+ * @param spokeProvider - EVM Spoke provider
8690
+ * @return - True if spender is allowed to spend amount on behalf of owner
8691
+ */
8692
+ static async isAllowanceValid(token, amount, owner, spender, spokeProvider) {
8693
+ try {
8694
+ if (token.toLowerCase() === spokeProvider.chainConfig.nativeToken.toLowerCase()) {
8695
+ return {
8696
+ ok: true,
8697
+ value: true
8698
+ };
8699
+ }
8700
+ const allowedAmount = await spokeProvider.publicClient.readContract({
8701
+ address: token,
8702
+ abi: viem.erc20Abi,
8703
+ functionName: "allowance",
8704
+ args: [owner, spender]
8705
+ });
8706
+ return {
8707
+ ok: true,
8708
+ value: allowedAmount >= amount
8709
+ };
8710
+ } catch (e) {
8711
+ return {
8712
+ ok: false,
8713
+ error: e
8714
+ };
8715
+ }
8716
+ }
8717
+ /**
8718
+ * Approve ERC20 amount spending
8719
+ * @param token - ERC20 token address
8720
+ * @param amount - Amount to approve
8721
+ * @param spender - Spender address
8722
+ * @param provider - EVM Provider
8723
+ */
8724
+ static async approve(token, amount, spender, spokeProvider, raw) {
8725
+ const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
8726
+ const rawTx = {
8727
+ from: walletAddress,
8728
+ to: token,
8729
+ value: 0n,
8730
+ data: viem.encodeFunctionData({
8731
+ abi: viem.erc20Abi,
8732
+ functionName: "approve",
8733
+ args: [spender, amount]
8734
+ })
8735
+ };
8736
+ if (raw) {
8737
+ return rawTx;
8738
+ }
8739
+ return spokeProvider.walletProvider.sendTransaction(rawTx);
8740
+ }
8741
+ /**
8742
+ * Encodes a transfer transaction for a token.
8743
+ * @param token - The address of the token.
8744
+ * @param to - The address to transfer the token to.
8745
+ * @param amount - The amount of the token to transfer.
8746
+ * @returns The encoded contract call.
8747
+ */
8748
+ static encodeTransfer(token, to, amount) {
8749
+ return {
8750
+ address: token,
8751
+ value: 0n,
8752
+ data: viem.encodeFunctionData({
8753
+ abi: viem.erc20Abi,
8754
+ functionName: "transfer",
8755
+ args: [to, amount]
8756
+ })
8757
+ };
8758
+ }
8759
+ /**
8760
+ * Encodes a transferFrom transaction for a token.
8761
+ * @param token - The address of the token.
8762
+ * @param from - The address to transfer the token from.
8763
+ * @param to - The address to transfer the token to.
8764
+ * @param amount - The amount of the token to transfer.
8765
+ * @returns The encoded contract call.
8766
+ */
8767
+ static encodeTransferFrom(token, from, to, amount) {
8768
+ return {
8769
+ address: token,
8770
+ value: 0n,
8771
+ data: viem.encodeFunctionData({
8772
+ abi: viem.erc20Abi,
8773
+ functionName: "transferFrom",
8774
+ args: [from, to, amount]
8775
+ })
8776
+ };
8777
+ }
8778
+ /**
8779
+ * Encodes an approval transaction for a token.
8780
+ * @param token - The address of the token.
8781
+ * @param to - The address to approve the token to.
8782
+ * @param amount - The amount of the token to approve.
8783
+ * @returns The encoded contract call.
8784
+ */
8785
+ static encodeApprove(token, to, amount) {
8786
+ return {
8787
+ address: token,
8788
+ value: 0n,
8789
+ data: viem.encodeFunctionData({
8790
+ abi: viem.erc20Abi,
8791
+ functionName: "approve",
8792
+ args: [to, amount]
8793
+ })
8794
+ };
8795
+ }
8796
+ };
8797
+ var EvmVaultTokenService = class {
8798
+ constructor() {
8799
+ }
8800
+ /**
8801
+ * Fetches token information for a specific token in the vault.
8802
+ * @param vault - The address of the vault.
8803
+ * @param token - The address of the token.
8804
+ * @param publicClient - PublicClient<HttpTransport>
8805
+ * @returns Token information as a TokenInfo object.
8806
+ */
8807
+ static async getTokenInfo(vault, token, publicClient) {
8808
+ const [decimals, depositFee, withdrawalFee, maxDeposit, isSupported] = await publicClient.readContract({
8809
+ address: vault,
8810
+ abi: vaultTokenAbi,
8811
+ functionName: "tokenInfo",
8812
+ args: [token]
8813
+ });
8814
+ return { decimals, depositFee, withdrawalFee, maxDeposit, isSupported };
8815
+ }
8816
+ /**
8817
+ * Retrieves the reserves of the vault.
8818
+ * @param vault - The address of the vault.
8819
+ * @param publicClient - PublicClient<HttpTransport>
8820
+ * @returns An object containing tokens and their balances.
8821
+ */
8822
+ static async getVaultReserves(vault, publicClient) {
8823
+ const [tokens, balances] = await publicClient.readContract({
8824
+ address: vault,
8825
+ abi: vaultTokenAbi,
8826
+ functionName: "getVaultReserves",
8827
+ args: []
8828
+ });
8829
+ return {
8830
+ tokens,
8831
+ balances
8832
+ };
8833
+ }
8834
+ /**
8835
+ * Retrieves all token information for the vault.
8836
+ * @param vault - The address of the vault.
8837
+ * @param publicClient - PublicClient<HttpTransport>
8838
+ * @returns A promise that resolves to an object containing tokens, their infos, and reserves.
8839
+ */
8840
+ async getAllTokenInfo(vault, publicClient) {
8841
+ const [tokens, infos, reserves] = await publicClient.readContract({
8842
+ address: vault,
8843
+ abi: vaultTokenAbi,
8844
+ functionName: "getAllTokenInfo",
8845
+ args: []
8846
+ });
8847
+ return {
8848
+ tokens,
8849
+ infos,
8850
+ reserves
8851
+ };
8852
+ }
8853
+ /**
8854
+ * Deposits a specified amount of a token into the vault.
8855
+ * @param vault - The address of the vault.
8856
+ * @param token - The address of the token to deposit.
8857
+ * @param amount - The amount of the token to deposit.
8858
+ * @param walletProvider - IEvmWalletProvider
8859
+ * @returns Transaction hash
8860
+ */
8861
+ static async deposit(vault, token, amount, walletProvider) {
8862
+ const from = await walletProvider.getWalletAddress();
8863
+ return walletProvider.sendTransaction({
8864
+ from,
8865
+ to: vault,
8866
+ value: 0n,
8867
+ data: viem.encodeFunctionData({
8868
+ abi: vaultTokenAbi,
8869
+ functionName: "deposit",
8870
+ args: [token, amount]
8871
+ })
8872
+ });
8873
+ }
8874
+ /**
8875
+ * Withdraws a specified amount of a token from the vault.
8876
+ * @param vault - The address of the vault.
8877
+ * @param token - The address of the token to withdraw.
8878
+ * @param amount - The amount of the token to withdraw.
8879
+ * @param provider - EvmWalletProvider
8880
+ * @returns Transaction hash
8881
+ */
8882
+ static async withdraw(vault, token, amount, provider) {
8883
+ const from = await provider.getWalletAddress();
8884
+ return provider.sendTransaction({
8885
+ from,
8886
+ to: vault,
8887
+ value: 0n,
8888
+ data: viem.encodeFunctionData({
8889
+ abi: vaultTokenAbi,
8890
+ functionName: "withdraw",
8891
+ args: [token, amount]
8892
+ })
8893
+ });
8894
+ }
8895
+ /**
8896
+ * Encodes the deposit transaction data for the vault.
8897
+ * @param vault - The address of the vault.
8898
+ * @param token - The address of the token to deposit.
8899
+ * @param amount - The amount of the token to deposit.
8900
+ * @returns The encoded contract call data.
8901
+ */
8902
+ static encodeDeposit(vault, token, amount) {
8903
+ return {
8904
+ address: vault,
8905
+ value: 0n,
8906
+ data: viem.encodeFunctionData({
8907
+ abi: vaultTokenAbi,
8908
+ functionName: "deposit",
8909
+ args: [token, amount]
8910
+ })
8911
+ };
8912
+ }
8913
+ /**
8914
+ * Encodes the withdraw transaction data for the vault.
8915
+ * @param vault - The address of the vault.
8916
+ * @param token - The address of the token to withdraw.
8917
+ * @param amount - The amount of the token to withdraw.
8918
+ * @returns The encoded contract call data.
8919
+ */
8920
+ static encodeWithdraw(vault, token, amount) {
8921
+ return {
8922
+ address: vault,
8923
+ value: 0n,
8924
+ data: viem.encodeFunctionData({
8925
+ abi: vaultTokenAbi,
8926
+ functionName: "withdraw",
8927
+ args: [token, amount]
8928
+ })
8929
+ };
8930
+ }
8931
+ /**
8932
+ * Translates token amounts from their native decimals to 18 decimals
8933
+ * @param decimals - The number of decimals of the token
8934
+ * @param amount - The amount to translate
8935
+ * @returns The translated amount
8936
+ */
8937
+ static translateIncomingDecimals(decimals, amount) {
8938
+ if (decimals <= 18) {
8939
+ return amount * BigInt(10 ** (18 - decimals));
8940
+ }
8941
+ return amount / BigInt(10 ** (decimals - 18));
8942
+ }
8943
+ /**
8944
+ * Translates token amounts from 18 decimals back to their native decimals
8945
+ * @param decimals - The number of decimals of the token
8946
+ * @param amount - The amount to translate
8947
+ * @returns The translated amount
8948
+ */
8949
+ static translateOutgoingDecimals(decimals, amount) {
8950
+ if (decimals <= 18) {
8951
+ return amount / BigInt(10 ** (18 - decimals));
8952
+ }
8953
+ return amount * BigInt(10 ** (decimals - 18));
8954
+ }
8955
+ };
8956
+
8957
+ // src/services/hub/EvmAssetManagerService.ts
8958
+ var EvmAssetManagerService = class _EvmAssetManagerService {
8959
+ constructor() {
8960
+ }
8961
+ /**
8962
+ * Get asset information for a given asset address
8963
+ * @param asset - The address of the asset contract
8964
+ * @param assetManager - The address of the asset manager contract
8965
+ * @param client - The Viem public client
8966
+ * @returns Object containing chainID and spoke address for the asset
8967
+ */
8968
+ static async getAssetInfo(asset, assetManager, client) {
8969
+ const [chainId, spokeAddress] = await client.readContract({
8970
+ address: assetManager,
8971
+ abi: assetManagerAbi,
8972
+ functionName: "assetInfo",
8973
+ args: [asset]
8974
+ });
8975
+ return {
8976
+ chainId,
8977
+ spokeAddress
8978
+ };
8979
+ }
8980
+ /**
8981
+ * Encodes a transfer transaction for an asset.
8982
+ * @param token - The address of the token.
8983
+ * @param to - The address to transfer the token to.
8984
+ * @param amount - The amount of the token to transfer.
8985
+ * @param assetManager
8986
+ * @returns The encoded contract call.
8987
+ */
8988
+ static encodeTransfer(token, to, amount, assetManager) {
8989
+ return {
8990
+ address: assetManager,
8991
+ value: 0n,
8992
+ data: viem.encodeFunctionData({
8993
+ abi: assetManagerAbi,
8994
+ functionName: "transfer",
8995
+ args: [token, to, amount, "0x"]
8996
+ })
8997
+ };
8998
+ }
8999
+ /**
9000
+ * Constructs the data for depositing tokens to the spoke chain.
9001
+ * @param {EvmDepositToDataParams} params - The address of the token to deposit.
9002
+ * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
9003
+ * @returns {Hex} Encoded contract calls for the deposit transaction.
9004
+ * @throws Will throw an error if the asset or vault address is not found.
9005
+ */
9006
+ static depositToData(params, spokeChainId) {
9007
+ const calls = [];
9008
+ const assetConfig = getHubAssetInfo(spokeChainId, params.token);
9009
+ if (!assetConfig) {
9010
+ throw new Error("[depositToData] Hub asset not found");
9011
+ }
9012
+ const assetAddress = assetConfig.asset;
9013
+ const vaultAddress = assetConfig.vault;
9014
+ calls.push(Erc20Service.encodeApprove(assetAddress, vaultAddress, params.amount));
9015
+ calls.push(EvmVaultTokenService.encodeDeposit(vaultAddress, assetAddress, params.amount));
9016
+ const translatedAmount = EvmVaultTokenService.translateIncomingDecimals(assetConfig.decimal, params.amount);
9017
+ calls.push(Erc20Service.encodeTransfer(vaultAddress, params.to, translatedAmount));
9018
+ return encodeContractCalls(calls);
9019
+ }
9020
+ /**
9021
+ * Withdraw tokens from the spoke chain.
9022
+ * @param {EvmWithdrawAssetDataParams} params - Parameters for the withdrawal.
9023
+ * @param {EvmSpokeProvider} spokeProvider - The provider for the spoke chain.
9024
+ * @param {EvmHubProvider} hubProvider - The provider for the hub chain.
9025
+ * @returns {Hex} Encoded contract calls for the withdrawal transaction.
9026
+ * @throws Will throw an error if the asset address is not found.
9027
+ */
9028
+ static withdrawAssetData(params, hubProvider, spokeChainId) {
9029
+ const calls = [];
9030
+ const assetConfig = getHubAssetInfo(spokeChainId, params.token);
9031
+ if (!assetConfig) {
9032
+ throw new Error("[withdrawAssetData] Hub asset not found");
9033
+ }
9034
+ const assetAddress = assetConfig.asset;
9035
+ calls.push(
9036
+ _EvmAssetManagerService.encodeTransfer(
9037
+ assetAddress,
9038
+ params.to,
9039
+ params.amount,
9040
+ hubProvider.chainConfig.addresses.assetManager
9041
+ )
9042
+ );
9043
+ return encodeContractCalls(calls);
9044
+ }
9045
+ /**
9046
+ * Get asset address for a given chain ID and spoke address
9047
+ * @param chainId Chain ID where the asset exists
9048
+ * @param spokeAddress Address of the asset on the spoke chain
9049
+ * @param assetManager Address of the asset manager contract
9050
+ * @param client The Viem public client
9051
+ * @returns The asset's address on the hub chain
9052
+ */
9053
+ async getAssetAddress(chainId, spokeAddress, assetManager, client) {
9054
+ return client.readContract({
9055
+ address: assetManager,
9056
+ abi: assetManagerAbi,
9057
+ functionName: "assets",
9058
+ args: [chainId, spokeAddress]
9059
+ });
9060
+ }
9061
+ };
9062
+
9063
+ // src/services/hub/EvmWalletAbstraction.ts
9064
+ var EvmWalletAbstraction = class {
9065
+ constructor() {
9066
+ }
9067
+ /**
9068
+ * Get the hub wallet address for a given spoke chain and address.
9069
+ * @param chainId - The spoke chain ID.
9070
+ * @param address - The address on the spoke chain.
9071
+ * @param hubProvider - The hub provider.
9072
+ * @returns The hub wallet address.
9073
+ */
9074
+ static async getUserHubWalletAddress(chainId, address, hubProvider) {
9075
+ return hubProvider.publicClient.readContract({
9076
+ address: hubProvider.chainConfig.addresses.hubWallet,
9077
+ abi: walletFactoryAbi,
9078
+ functionName: "getDeployedAddress",
9079
+ args: [BigInt(getIntentRelayChainId(chainId)), address]
9080
+ });
9081
+ }
9082
+ };
9183
9083
  var EvmSpokeService = class _EvmSpokeService {
9184
9084
  constructor() {
9185
9085
  }
@@ -9576,9 +9476,10 @@ var IconSpokeService = class _IconSpokeService {
9576
9476
  getIconAddressBytes(params.from),
9577
9477
  hubProvider
9578
9478
  );
9479
+ const token = isNativeToken(spokeProvider.chainConfig.chain.id, params.token) ? spokeProvider.chainConfig.addresses.wICX : params.token;
9579
9480
  return {
9580
9481
  spokeChainID: spokeProvider.chainConfig.chain.id,
9581
- token: encodeAddress(spokeProvider.chainConfig.chain.id, params.token),
9482
+ token: encodeAddress(spokeProvider.chainConfig.chain.id, token),
9582
9483
  from: encodeAddress(spokeProvider.chainConfig.chain.id, params.from),
9583
9484
  to,
9584
9485
  amount: params.amount,
@@ -9999,7 +9900,7 @@ var StellarSpokeService = class _StellarSpokeService {
9999
9900
  return {
10000
9901
  spokeChainID: spokeProvider.chainConfig.chain.id,
10001
9902
  token: encodeAddress(spokeProvider.chainConfig.chain.id, params.token),
10002
- from: params.from,
9903
+ from: encodeAddress(spokeProvider.chainConfig.chain.id, params.from),
10003
9904
  to,
10004
9905
  amount: params.amount,
10005
9906
  data: params.data,
@@ -10211,6 +10112,7 @@ var SonicSpokeService = class _SonicSpokeService {
10211
10112
  * @returns {PromiseEvmTxReturnType<R>} A promise that resolves to the transaction hash
10212
10113
  */
10213
10114
  static async deposit(params, spokeProvider, raw) {
10115
+ invariant11__default.default(spokeProvider instanceof SonicSpokeProvider, "[SonicSpokeService] invalid spoke provider");
10214
10116
  const userHubAddress = params.to ?? await _SonicSpokeService.getUserRouter(params.from, spokeProvider);
10215
10117
  const calls = Array.from(
10216
10118
  viem.decodeAbiParameters(
@@ -10265,7 +10167,7 @@ var SonicSpokeService = class _SonicSpokeService {
10265
10167
  value: params.token.toLowerCase() === spokeProvider.chainConfig.nativeToken.toLowerCase() ? params.amount : 0n
10266
10168
  };
10267
10169
  if (raw) {
10268
- return rawTx;
10170
+ return Promise.resolve(rawTx);
10269
10171
  }
10270
10172
  return spokeProvider.walletProvider.sendTransaction(rawTx);
10271
10173
  }
@@ -10342,6 +10244,7 @@ var SonicSpokeService = class _SonicSpokeService {
10342
10244
  * @returns {PromiseEvmTxReturnType<R>} A promise that resolves to the transaction hash
10343
10245
  */
10344
10246
  static async callWallet(payload, spokeProvider, raw) {
10247
+ invariant11__default.default(spokeProvider instanceof SonicSpokeProvider, "[SonicSpokeService] invalid spoke provider");
10345
10248
  const calls = viem.decodeAbiParameters(
10346
10249
  [
10347
10250
  {
@@ -10376,7 +10279,7 @@ var SonicSpokeService = class _SonicSpokeService {
10376
10279
  if (raw) {
10377
10280
  return rawTx;
10378
10281
  }
10379
- return spokeProvider.walletProvider.sendTransaction(rawTx);
10282
+ return await spokeProvider.walletProvider.sendTransaction(rawTx);
10380
10283
  }
10381
10284
  /**
10382
10285
  * Get withdraw information for a given token
@@ -10850,6 +10753,7 @@ var SpokeService = class _SpokeService {
10850
10753
  return InjectiveSpokeService.deposit(params, spokeProvider, hubProvider, raw);
10851
10754
  }
10852
10755
  if (spokeProvider instanceof IconSpokeProvider) {
10756
+ await _SpokeService.verifyDepositSimulation(params, spokeProvider, hubProvider, skipSimulation);
10853
10757
  return IconSpokeService.deposit(
10854
10758
  params,
10855
10759
  spokeProvider,
@@ -10876,6 +10780,7 @@ var SpokeService = class _SpokeService {
10876
10780
  );
10877
10781
  }
10878
10782
  if (spokeProvider instanceof StellarSpokeProvider) {
10783
+ await _SpokeService.verifyDepositSimulation(params, spokeProvider, hubProvider, skipSimulation);
10879
10784
  return StellarSpokeService.deposit(
10880
10785
  params,
10881
10786
  spokeProvider,
@@ -10979,7 +10884,11 @@ var SpokeService = class _SpokeService {
10979
10884
  */
10980
10885
  static async callWallet(from, payload, spokeProvider, hubProvider, raw, skipSimulation = false) {
10981
10886
  if (isSonicSpokeProvider(spokeProvider)) {
10982
- return await SonicSpokeService.callWallet(payload, spokeProvider, raw);
10887
+ return await SonicSpokeService.callWallet(
10888
+ payload,
10889
+ spokeProvider,
10890
+ raw
10891
+ );
10983
10892
  }
10984
10893
  if (isEvmSpokeProvider(spokeProvider)) {
10985
10894
  await _SpokeService.verifySimulation(from, payload, spokeProvider, hubProvider, skipSimulation);
@@ -11862,7 +11771,18 @@ var SolverService = class {
11862
11771
  ok: false,
11863
11772
  error: {
11864
11773
  code: "POST_EXECUTION_FAILED",
11865
- data: result.error
11774
+ data: {
11775
+ ...result.error,
11776
+ intent,
11777
+ intentDeliveryInfo: {
11778
+ srcChainId: params.srcChain,
11779
+ srcTxHash: spokeTxHash,
11780
+ srcAddress: params.srcAddress,
11781
+ dstChainId: params.dstChain,
11782
+ dstTxHash: dstIntentTxHash,
11783
+ dstAddress: params.dstAddress
11784
+ }
11785
+ }
11866
11786
  }
11867
11787
  };
11868
11788
  }
@@ -12111,7 +12031,7 @@ var SolverService = class {
12111
12031
  params.srcAddress.toLowerCase() === walletAddress.toLowerCase(),
12112
12032
  "srcAddress must be the same as wallet address"
12113
12033
  );
12114
- const creatorHubWalletAddress = spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id ? walletAddress : await WalletAbstractionService.getUserHubWalletAddress(walletAddress, spokeProvider, this.hubProvider);
12034
+ const creatorHubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
12115
12035
  if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id) {
12116
12036
  const [txResult, intent, feeAmount, data] = await SonicSpokeService.createSwapIntent(
12117
12037
  params,
@@ -12184,7 +12104,7 @@ var SolverService = class {
12184
12104
  invariant11__default.default(isValidIntentRelayChainId(intent.srcChain), `Invalid intent.srcChain: ${intent.srcChain}`);
12185
12105
  invariant11__default.default(isValidIntentRelayChainId(intent.dstChain), `Invalid intent.dstChain: ${intent.dstChain}`);
12186
12106
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
12187
- const creatorHubWalletAddress = spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id ? walletAddress : await WalletAbstractionService.getUserHubWalletAddress(walletAddress, spokeProvider, this.hubProvider);
12107
+ const creatorHubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
12188
12108
  const calls = [];
12189
12109
  const intentsContract = this.config.intentsContract;
12190
12110
  calls.push(EvmSolverService.encodeCancelIntent(intent, intentsContract));
@@ -12223,6 +12143,19 @@ var SolverService = class {
12223
12143
  getIntentHash(intent) {
12224
12144
  return EvmSolverService.getIntentHash(intent);
12225
12145
  }
12146
+ /**
12147
+ * Gets the deadline for a swap by querying hub chain block timestamp and adding the deadline offset
12148
+ * @param {bigint} deadline (default: 5 minutes) - The deadline offset in seconds for the swap to be cancelled
12149
+ * @returns {bigint} The deadline for the swap as a sum of hub chain block timestamp and deadline offset
12150
+ */
12151
+ async getSwapDeadline(deadline = DEFAULT_DEADLINE_OFFSET) {
12152
+ invariant11__default.default(deadline > 0n, "Deadline must be greater than 0");
12153
+ const block = await this.hubProvider.publicClient.getBlock({
12154
+ includeTransactions: false,
12155
+ blockTag: "latest"
12156
+ });
12157
+ return block.timestamp + deadline;
12158
+ }
12226
12159
  };
12227
12160
 
12228
12161
  // src/abis/icxSwap.abi.ts
@@ -13900,8 +13833,6 @@ var Sodax = class {
13900
13833
 
13901
13834
  // src/services/hub/WalletAbstractionService.ts
13902
13835
  var WalletAbstractionService = class {
13903
- constructor() {
13904
- }
13905
13836
  /**
13906
13837
  * Gets the hub wallet address for a user based on their spoke chain address.
13907
13838
  * @param address - The user's address on the spoke chain
@@ -13909,14 +13840,14 @@ var WalletAbstractionService = class {
13909
13840
  * @param hubProvider - The provider for interacting with the hub chain
13910
13841
  * @returns The user's hub wallet address
13911
13842
  */
13912
- static async getUserHubWalletAddress(address, spokeProvider, hubProvider) {
13843
+ static async getUserAbstractedWalletAddress(address, spokeProvider, hubProvider) {
13913
13844
  const encodedAddress = encodeAddress(spokeProvider.chainConfig.chain.id, address);
13914
13845
  if (spokeProvider.chainConfig.chain.id === hubProvider.chainConfig.chain.id) {
13915
13846
  if (spokeProvider instanceof SonicSpokeProvider) {
13916
13847
  return SonicSpokeService.getUserRouter(encodedAddress, spokeProvider);
13917
13848
  }
13918
13849
  throw new Error(
13919
- "[WalletAbstractionService.getUserHubWalletAddress] Invalid spoke provider. Sonic spoke provider is required."
13850
+ "[getUserHubWalletAddress] Invalid spoke provider for matching hub id. Sonic spoke provider is required."
13920
13851
  );
13921
13852
  }
13922
13853
  return EvmWalletAbstraction.getUserHubWalletAddress(
@@ -13926,6 +13857,111 @@ var WalletAbstractionService = class {
13926
13857
  );
13927
13858
  }
13928
13859
  };
13860
+ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
13861
+ do {
13862
+ try {
13863
+ return await action(retryCount);
13864
+ } catch (e) {
13865
+ retryCount--;
13866
+ if (retryCount <= 0) {
13867
+ console.error(`Failed to perform operation even after ${DEFAULT_MAX_RETRY} attempts.. Throwing origin error..`);
13868
+ throw e;
13869
+ }
13870
+ }
13871
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
13872
+ } while (retryCount > 0);
13873
+ throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
13874
+ }
13875
+ function getRandomBytes(length) {
13876
+ const array = new Uint8Array(length);
13877
+ for (let i = 0; i < length; i++) {
13878
+ array[i] = Math.floor(Math.random() * 256);
13879
+ }
13880
+ return array;
13881
+ }
13882
+ function randomUint256() {
13883
+ const bytes = getRandomBytes(32);
13884
+ let hex = "";
13885
+ for (const byte of bytes) {
13886
+ hex += byte.toString(16).padStart(2, "0") ?? "";
13887
+ }
13888
+ return BigInt(`0x${hex}`);
13889
+ }
13890
+ function calculatePercentageFeeAmount(amount, percentage) {
13891
+ return amount * BigInt(percentage) / FEE_PERCENTAGE_SCALE;
13892
+ }
13893
+ function calculateFeeAmount(inputAmount, fee) {
13894
+ if (!fee) {
13895
+ return 0n;
13896
+ }
13897
+ invariant11__default.default(inputAmount > 0n, "Input amount must be greater than 0");
13898
+ let feeAmount = 0n;
13899
+ if (isPartnerFeeAmount(fee)) {
13900
+ invariant11__default.default(
13901
+ fee.amount >= 0 && fee.amount <= inputAmount,
13902
+ `Fee amount must be greater than 0 and less than or equal to the input amount: ${fee.amount}`
13903
+ );
13904
+ feeAmount = fee.amount;
13905
+ } else if (isPartnerFeePercentage(fee)) {
13906
+ invariant11__default.default(
13907
+ fee.percentage >= 0 && fee.percentage <= FEE_PERCENTAGE_SCALE,
13908
+ `Fee percentage must be between 0 and ${FEE_PERCENTAGE_SCALE}}`
13909
+ );
13910
+ feeAmount = calculatePercentageFeeAmount(inputAmount, fee.percentage);
13911
+ }
13912
+ return feeAmount;
13913
+ }
13914
+ function adjustAmountByFee(amount, fee, quoteType) {
13915
+ invariant11__default.default(amount > 0n, "Amount must be greater than 0");
13916
+ invariant11__default.default(quoteType === "exact_input" || quoteType === "exact_output", "Invalid quote type");
13917
+ if (quoteType === "exact_input") {
13918
+ return amount - calculateFeeAmount(amount, fee);
13919
+ }
13920
+ if (quoteType === "exact_output") {
13921
+ return amount + calculateFeeAmount(amount, fee);
13922
+ }
13923
+ throw new Error("Invalid quote type");
13924
+ }
13925
+ function BigIntToHex(value) {
13926
+ return `0x${value.toString(16)}`;
13927
+ }
13928
+ function encodeAddress(spokeChainId, address) {
13929
+ switch (spokeChainId) {
13930
+ case "0xa86a.avax":
13931
+ case "0x2105.base":
13932
+ case "0xa.optimism":
13933
+ case "0x38.bsc":
13934
+ case "0x89.polygon":
13935
+ case "0xa4b1.arbitrum":
13936
+ case "sonic":
13937
+ return address;
13938
+ case "injective-1":
13939
+ return viem.toHex(Buffer.from(address, "utf-8"));
13940
+ case "0x1.icon":
13941
+ return viem.toHex(Buffer.from(address.replace("cx", "01").replace("hx", "00") ?? "f8", "hex"));
13942
+ case "sui":
13943
+ return viem.toHex(bcs.bcs.Address.serialize(address).toBytes());
13944
+ case "solana":
13945
+ return viem.toHex(Buffer.from(new web3_js.PublicKey(address).toBytes()));
13946
+ case "stellar":
13947
+ return `0x${stellarSdk.Address.fromString(address).toScVal().toXDR("hex")}`;
13948
+ default:
13949
+ return address;
13950
+ }
13951
+ }
13952
+ function hexToBigInt(hex) {
13953
+ const trimmed = hex.trim().toLowerCase();
13954
+ const isValid = /^(0x)?[0-9a-f]+$/.test(trimmed);
13955
+ if (!isValid) {
13956
+ throw new Error(`Invalid hex string: "${hex}"`);
13957
+ }
13958
+ const normalized = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
13959
+ return BigInt(normalized);
13960
+ }
13961
+ async function deriveUserWalletAddress(spokeProvider, hubProvider, walletAddress) {
13962
+ const address = walletAddress ?? await spokeProvider.walletProvider.getWalletAddress();
13963
+ return spokeProvider.chainConfig.chain.id === hubProvider.chainConfig.chain.id ? address : await WalletAbstractionService.getUserAbstractedWalletAddress(address, spokeProvider, hubProvider);
13964
+ }
13929
13965
  var BigNumberZeroDecimal = BigNumber4.BigNumber.clone({
13930
13966
  DECIMAL_PLACES: 0,
13931
13967
  ROUNDING_MODE: BigNumber4.BigNumber.ROUND_DOWN
@@ -15286,11 +15322,7 @@ var MoneyMarketDataService = class {
15286
15322
  */
15287
15323
  async getUserReservesData(spokeProvider) {
15288
15324
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15289
- const hubWalletAddress = await WalletAbstractionService.getUserHubWalletAddress(
15290
- walletAddress,
15291
- spokeProvider,
15292
- this.hubProvider
15293
- );
15325
+ const hubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15294
15326
  return this.uiPoolDataProviderService.getUserReservesData(hubWalletAddress);
15295
15327
  }
15296
15328
  /**
@@ -15321,11 +15353,7 @@ var MoneyMarketDataService = class {
15321
15353
  */
15322
15354
  async getUserReservesHumanized(spokeProvider) {
15323
15355
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15324
- const hubWalletAddress = await WalletAbstractionService.getUserHubWalletAddress(
15325
- walletAddress,
15326
- spokeProvider,
15327
- this.hubProvider
15328
- );
15356
+ const hubWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15329
15357
  return this.uiPoolDataProviderService.getUserReservesHumanized(hubWalletAddress);
15330
15358
  }
15331
15359
  /**
@@ -15767,34 +15795,44 @@ var MoneyMarketService = class _MoneyMarketService {
15767
15795
  `Unsupported spoke chain (${spokeProvider.chainConfig.chain.id}) token: ${params.token}`
15768
15796
  );
15769
15797
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15770
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
15771
- walletAddress,
15772
- spokeProvider,
15773
- this.hubProvider
15774
- );
15798
+ const abstractedWalletAddress = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15775
15799
  const data = this.buildSupplyData(
15776
15800
  params.token,
15777
- hubWallet,
15801
+ abstractedWalletAddress,
15778
15802
  params.amount,
15779
15803
  spokeProvider.chainConfig.chain.id
15780
15804
  );
15781
- const txResult = await SpokeService.deposit(
15782
- {
15783
- from: walletAddress,
15784
- to: hubWallet,
15785
- token: params.token,
15786
- amount: params.amount,
15787
- data
15788
- },
15789
- spokeProvider,
15790
- this.hubProvider,
15791
- raw
15792
- );
15805
+ let txResult;
15806
+ if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id && spokeProvider instanceof SonicSpokeProvider) {
15807
+ txResult = await SonicSpokeService.deposit(
15808
+ {
15809
+ from: walletAddress,
15810
+ token: params.token,
15811
+ amount: params.amount,
15812
+ data
15813
+ },
15814
+ spokeProvider,
15815
+ raw
15816
+ );
15817
+ } else {
15818
+ txResult = await SpokeService.deposit(
15819
+ {
15820
+ from: walletAddress,
15821
+ to: abstractedWalletAddress,
15822
+ token: params.token,
15823
+ amount: params.amount,
15824
+ data
15825
+ },
15826
+ spokeProvider,
15827
+ this.hubProvider,
15828
+ raw
15829
+ );
15830
+ }
15793
15831
  return {
15794
15832
  ok: true,
15795
15833
  value: txResult,
15796
15834
  data: {
15797
- address: hubWallet,
15835
+ address: abstractedWalletAddress,
15798
15836
  payload: data
15799
15837
  }
15800
15838
  };
@@ -15923,11 +15961,7 @@ var MoneyMarketService = class _MoneyMarketService {
15923
15961
  );
15924
15962
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
15925
15963
  const encodedAddress = encodeAddress(spokeProvider.chainConfig.chain.id, walletAddress);
15926
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
15927
- walletAddress,
15928
- spokeProvider,
15929
- this.hubProvider
15930
- );
15964
+ const hubWallet = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
15931
15965
  const data = this.buildBorrowData(
15932
15966
  hubWallet,
15933
15967
  encodedAddress,
@@ -15935,7 +15969,12 @@ var MoneyMarketService = class _MoneyMarketService {
15935
15969
  params.amount,
15936
15970
  spokeProvider.chainConfig.chain.id
15937
15971
  );
15938
- const txResult = await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
15972
+ let txResult;
15973
+ if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id) {
15974
+ txResult = await SonicSpokeService.callWallet(data, spokeProvider);
15975
+ } else {
15976
+ txResult = await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
15977
+ }
15939
15978
  return {
15940
15979
  ok: true,
15941
15980
  value: txResult,
@@ -16058,11 +16097,7 @@ var MoneyMarketService = class _MoneyMarketService {
16058
16097
  );
16059
16098
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
16060
16099
  const encodedAddress = encodeAddress(spokeProvider.chainConfig.chain.id, walletAddress);
16061
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
16062
- walletAddress,
16063
- spokeProvider,
16064
- this.hubProvider
16065
- );
16100
+ const hubWallet = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
16066
16101
  let data;
16067
16102
  if (spokeProvider instanceof SonicSpokeProvider) {
16068
16103
  const withdrawInfo = await SonicSpokeService.getWithdrawInfo(
@@ -16088,7 +16123,7 @@ var MoneyMarketService = class _MoneyMarketService {
16088
16123
  spokeProvider.chainConfig.chain.id
16089
16124
  );
16090
16125
  }
16091
- const txResult = await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
16126
+ const txResult = spokeProvider instanceof SonicSpokeProvider ? await SonicSpokeService.callWallet(data, spokeProvider, raw) : await SpokeService.callWallet(hubWallet, data, spokeProvider, this.hubProvider, raw);
16092
16127
  return {
16093
16128
  ok: true,
16094
16129
  value: txResult,
@@ -16212,24 +16247,34 @@ var MoneyMarketService = class _MoneyMarketService {
16212
16247
  `Unsupported spoke chain (${spokeProvider.chainConfig.chain.id}) token: ${params.token}`
16213
16248
  );
16214
16249
  const walletAddress = await spokeProvider.walletProvider.getWalletAddress();
16215
- const hubWallet = await WalletAbstractionService.getUserHubWalletAddress(
16216
- walletAddress,
16217
- spokeProvider,
16218
- this.hubProvider
16219
- );
16250
+ const hubWallet = await deriveUserWalletAddress(spokeProvider, this.hubProvider, walletAddress);
16220
16251
  const data = this.buildRepayData(params.token, hubWallet, params.amount, spokeProvider.chainConfig.chain.id);
16221
- const txResult = await SpokeService.deposit(
16222
- {
16223
- from: walletAddress,
16224
- to: hubWallet,
16225
- token: params.token,
16226
- amount: params.amount,
16227
- data
16228
- },
16229
- spokeProvider,
16230
- this.hubProvider,
16231
- raw
16232
- );
16252
+ let txResult;
16253
+ if (spokeProvider.chainConfig.chain.id === this.hubProvider.chainConfig.chain.id && spokeProvider instanceof SonicSpokeProvider) {
16254
+ txResult = await SonicSpokeService.deposit(
16255
+ {
16256
+ from: walletAddress,
16257
+ token: params.token,
16258
+ amount: params.amount,
16259
+ data
16260
+ },
16261
+ spokeProvider,
16262
+ raw
16263
+ );
16264
+ } else {
16265
+ txResult = await SpokeService.deposit(
16266
+ {
16267
+ from: walletAddress,
16268
+ to: hubWallet,
16269
+ token: params.token,
16270
+ amount: params.amount,
16271
+ data
16272
+ },
16273
+ spokeProvider,
16274
+ this.hubProvider,
16275
+ raw
16276
+ );
16277
+ }
16233
16278
  return {
16234
16279
  ok: true,
16235
16280
  value: txResult,
@@ -16616,6 +16661,7 @@ exports.BigIntToHex = BigIntToHex;
16616
16661
  exports.BigNumberZeroDecimal = BigNumberZeroDecimal;
16617
16662
  exports.BnUSDMigrationService = BnUSDMigrationService;
16618
16663
  exports.ChainIdToIntentRelayChainId = ChainIdToIntentRelayChainId;
16664
+ exports.DEFAULT_DEADLINE_OFFSET = DEFAULT_DEADLINE_OFFSET;
16619
16665
  exports.DEFAULT_MAX_RETRY = DEFAULT_MAX_RETRY;
16620
16666
  exports.DEFAULT_RELAYER_API_ENDPOINT = DEFAULT_RELAYER_API_ENDPOINT;
16621
16667
  exports.DEFAULT_RELAY_TX_TIMEOUT = DEFAULT_RELAY_TX_TIMEOUT;
@@ -16692,6 +16738,7 @@ exports.calculateLinearInterest = calculateLinearInterest;
16692
16738
  exports.calculatePercentageFeeAmount = calculatePercentageFeeAmount;
16693
16739
  exports.chainIdToHubAssetsMap = chainIdToHubAssetsMap;
16694
16740
  exports.connectionAbi = connectionAbi;
16741
+ exports.deriveUserWalletAddress = deriveUserWalletAddress;
16695
16742
  exports.encodeAddress = encodeAddress;
16696
16743
  exports.encodeContractCalls = encodeContractCalls;
16697
16744
  exports.erc20Abi = erc20Abi;