@sodax/sdk 2.1.0 → 2.2.0-rc.2

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
@@ -3556,7 +3556,9 @@ var spokeChainConfig = {
3556
3556
  },
3557
3557
  chain: baseChainInfo[ChainKeys.BITCOIN_MAINNET],
3558
3558
  bnUSD: "no",
3559
- nativeToken: "BTC",
3559
+ // Must equal bitcoinSupportedTokens.BTC.address: isNativeToken compares a token's `address`
3560
+ // against this value, so a symbol here classifies native BTC as a contract token.
3561
+ nativeToken: "0:0",
3560
3562
  supportedTokens: bitcoinSupportedTokens,
3561
3563
  radfi: {
3562
3564
  walletMode: "TRADING",
@@ -3724,7 +3726,7 @@ var spokeChainConfig = {
3724
3726
  }
3725
3727
  },
3726
3728
  [ChainKeys.NEAR_MAINNET]: {
3727
- rpcUrl: "https://1rpc.io/near",
3729
+ rpcUrl: "https://free.rpc.fastnear.com",
3728
3730
  chain: baseChainInfo[ChainKeys.NEAR_MAINNET],
3729
3731
  nativeToken: "NEAR",
3730
3732
  addresses: {
@@ -4106,8 +4108,12 @@ var moneyMarketSupportedTokens = {
4106
4108
  spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.USDS,
4107
4109
  spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.XLM
4108
4110
  ],
4109
- // Robinhood Chain: lending/borrowing deferred at launch (swaps + bridging only)
4110
- [ChainKeys.ROBINHOOD_MAINNET]: []
4111
+ [ChainKeys.ROBINHOOD_MAINNET]: [
4112
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.ETH,
4113
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.bnUSD,
4114
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.SODA,
4115
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.USDG
4116
+ ]
4111
4117
  };
4112
4118
  var moneyMarketReserveAssets = [
4113
4119
  ...Object.values(SodaTokens).map((vault) => vault.address),
@@ -4886,7 +4892,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4886
4892
  }
4887
4893
 
4888
4894
  // ../types/dist/index.js
4889
- var CONFIG_VERSION = 230;
4895
+ var CONFIG_VERSION = 232;
4890
4896
 
4891
4897
  // src/shared/utils/resolveTimeoutMs.ts
4892
4898
  function resolveTimeoutMs(timeout, fallbackMs) {
@@ -5435,6 +5441,12 @@ function isFeatureError(feature) {
5435
5441
  function isCodeMember(codes) {
5436
5442
  return (e) => isSodaxError(e) && codes.has(e.code);
5437
5443
  }
5444
+ function isAuthStatus(status) {
5445
+ return status === 401 || status === 403;
5446
+ }
5447
+ function isAuthFailure(error) {
5448
+ return isSodaxError(error) && isAuthStatus(error.context?.status);
5449
+ }
5438
5450
 
5439
5451
  // src/errors/wrappers.ts
5440
5452
  function messageOf(error, fallback2) {
@@ -14492,6 +14504,13 @@ var ConfigService = class {
14492
14504
  * a client-side option set via `new Sodax({ fee })`. Per-feature overrides live on the feature config.
14493
14505
  */
14494
14506
  fee;
14507
+ /**
14508
+ * Global backend API key. Resolved once at construction and kept independent of {@link sodax} so
14509
+ * that {@link initialize}'s dynamic-config swap never clobbers it. The backend never supplies it —
14510
+ * it is a client-side option set via `new Sodax({ apiKey })`. Never logged; read here by the swap,
14511
+ * leverage-yield, and partner solver flows, whose transport does not go through `BackendApiService`.
14512
+ */
14513
+ apiKey;
14495
14514
  /**
14496
14515
  * RadFi/Bound request signer. Resolved once at construction and kept independent of {@link sodax}
14497
14516
  * so that {@link initialize}'s dynamic-config swap never clobbers it. Read by `BitcoinSpokeService`
@@ -14512,11 +14531,21 @@ var ConfigService = class {
14512
14531
  hubAssetToXTokenMap;
14513
14532
  // `api` / `userConfig` are accepted but unused while initialize()'s dynamic fetch is disabled
14514
14533
  // (see TODO(config-v2) below); restore their assignments when re-enabling.
14515
- constructor({ api, config, userConfig, logger, analytics, fee, radfiSigner }) {
14534
+ constructor({
14535
+ api,
14536
+ config,
14537
+ userConfig,
14538
+ logger,
14539
+ analytics,
14540
+ fee,
14541
+ apiKey,
14542
+ radfiSigner
14543
+ }) {
14516
14544
  this.sodax = config;
14517
14545
  this.logger = logger ?? resolveLogger(void 0);
14518
14546
  this.analytics = analytics ?? noopAnalytics;
14519
14547
  this.fee = fee;
14548
+ this.apiKey = apiKey;
14520
14549
  this.radfiSigner = radfiSigner;
14521
14550
  this.loadSodaxConfigDataStructures(config);
14522
14551
  }
@@ -14710,7 +14739,9 @@ var ConfigService = class {
14710
14739
  ])
14711
14740
  );
14712
14741
  this.loadSpokeChainConfigDataStructures(sodaxConfig2);
14713
- this.moneyMarketReserveAssetsSet = new Set(sodaxConfig2.moneyMarket.supportedReserveAssets);
14742
+ this.moneyMarketReserveAssetsSet = new Set(
14743
+ sodaxConfig2.moneyMarket.supportedReserveAssets.map((address) => address.toLowerCase())
14744
+ );
14714
14745
  this.stakedATokenAddressesSet = new Set(
14715
14746
  Object.keys(sodaxConfig2.dex.statATokenAddresses).map((address) => address.toLowerCase())
14716
14747
  );
@@ -15425,10 +15456,54 @@ var EvmAssetManagerService = class _EvmAssetManagerService {
15425
15456
  });
15426
15457
  }
15427
15458
  };
15459
+
15460
+ // src/shared/services/spoke/balance-utils.ts
15461
+ function createBalanceCollector({ logger, chainKey }) {
15462
+ const balances = {};
15463
+ let attempted = 0;
15464
+ let failed = 0;
15465
+ return {
15466
+ ok(tokenAddress, value) {
15467
+ attempted++;
15468
+ balances[tokenAddress] = value;
15469
+ },
15470
+ fail(tokenAddress, reason) {
15471
+ attempted++;
15472
+ failed++;
15473
+ logger.warn("[getWalletBalances] balance read failed, reporting 0n", {
15474
+ chainKey,
15475
+ token: tokenAddress,
15476
+ error: reason instanceof Error ? reason.message : String(reason)
15477
+ });
15478
+ balances[tokenAddress] = 0n;
15479
+ },
15480
+ finish() {
15481
+ if (attempted > 0 && failed === attempted) {
15482
+ throw new Error(`[getWalletBalances] every balance read failed on ${chainKey} (${failed}/${attempted})`);
15483
+ }
15484
+ return balances;
15485
+ }
15486
+ };
15487
+ }
15488
+ async function settleWalletBalances(collector, tokens, read) {
15489
+ const settled = await Promise.allSettled(tokens.map((token) => read(token)));
15490
+ tokens.forEach((token, index) => {
15491
+ const outcome = settled[index];
15492
+ if (!outcome) return;
15493
+ if (outcome.status === "fulfilled") {
15494
+ collector.ok(token.address, outcome.value);
15495
+ } else {
15496
+ collector.fail(token.address, outcome.reason);
15497
+ }
15498
+ });
15499
+ }
15428
15500
  var HEDERA_NATIVE_VALUE_SCALE = 10n ** 10n;
15429
15501
  function scaleNativeMsgValue(chainKey, amount) {
15430
15502
  return chainKey === ChainKeys.HEDERA_MAINNET ? amount * HEDERA_NATIVE_VALUE_SCALE : amount;
15431
15503
  }
15504
+ function scaleNativeBalance(chainKey, amount) {
15505
+ return chainKey === ChainKeys.HEDERA_MAINNET ? amount / HEDERA_NATIVE_VALUE_SCALE : amount;
15506
+ }
15432
15507
  var EvmSpokeService = class {
15433
15508
  config;
15434
15509
  // map containing the public clients for each evm spoke chain, lazy loaded on demand
@@ -15545,6 +15620,79 @@ var EvmSpokeService = class {
15545
15620
  args: [this.config.getChainConfig(params.srcChainKey).addresses.assetManager]
15546
15621
  });
15547
15622
  }
15623
+ /**
15624
+ * Get the user's own wallet balance of a token on an EVM spoke chain, in smallest units.
15625
+ * Native coin via `eth_getBalance` (Hedera scaled to canonical decimals); erc20 via `balanceOf`.
15626
+ * @param {GetBalanceParams<EvmSpokeOnlyChainKey>} params - The chain key, user address, and token.
15627
+ * @returns {Promise<bigint>} The token balance in smallest units.
15628
+ */
15629
+ async getWalletBalance(params) {
15630
+ const { srcChainKey, srcAddress, token } = params;
15631
+ const publicClient = this.getPublicClient(srcChainKey);
15632
+ if (isNativeToken(srcChainKey, token)) {
15633
+ const balance2 = await publicClient.getBalance({ address: srcAddress });
15634
+ return scaleNativeBalance(srcChainKey, balance2);
15635
+ }
15636
+ const balance = await publicClient.readContract({
15637
+ address: token.address,
15638
+ abi: erc20Abi,
15639
+ functionName: "balanceOf",
15640
+ args: [srcAddress]
15641
+ });
15642
+ return balance ?? 0n;
15643
+ }
15644
+ /**
15645
+ * Get the user's own wallet balances of multiple tokens on an EVM spoke chain, in smallest
15646
+ * units. Non-native tokens are batched via multicall3 when the chain supports it, otherwise
15647
+ * read in parallel.
15648
+ * @param {GetBalancesParams<EvmSpokeOnlyChainKey>} params - The chain key, user address, and tokens.
15649
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
15650
+ */
15651
+ async getWalletBalances(params) {
15652
+ const { srcChainKey, srcAddress, tokens } = params;
15653
+ const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
15654
+ const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
15655
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
15656
+ await settleWalletBalances(
15657
+ collector,
15658
+ nativeTokens,
15659
+ (token) => this.getWalletBalance({ srcChainKey, srcAddress, token })
15660
+ );
15661
+ if (nonNativeTokens.length === 0) {
15662
+ return collector.finish();
15663
+ }
15664
+ const publicClient = this.getPublicClient(srcChainKey);
15665
+ if (getEvmViemChain(srcChainKey).contracts?.multicall3) {
15666
+ const results = await publicClient.multicall({
15667
+ contracts: nonNativeTokens.map((token) => ({
15668
+ abi: erc20Abi,
15669
+ address: token.address,
15670
+ functionName: "balanceOf",
15671
+ args: [srcAddress]
15672
+ }))
15673
+ });
15674
+ nonNativeTokens.forEach((token, index) => {
15675
+ const result = results[index];
15676
+ if (result?.status === "success") {
15677
+ collector.ok(token.address, BigInt(result.result));
15678
+ } else {
15679
+ collector.fail(token.address, result?.error ?? new Error(`missing multicall result for ${token.address}`));
15680
+ }
15681
+ });
15682
+ return collector.finish();
15683
+ }
15684
+ await settleWalletBalances(
15685
+ collector,
15686
+ nonNativeTokens,
15687
+ (token) => publicClient.readContract({
15688
+ address: token.address,
15689
+ abi: erc20Abi,
15690
+ functionName: "balanceOf",
15691
+ args: [srcAddress]
15692
+ })
15693
+ );
15694
+ return collector.finish();
15695
+ }
15548
15696
  /**
15549
15697
  * Sends a message to the hub chain.
15550
15698
  * @param {SendMessageParams} params - Includes dstChainKey, the chain key of the hub chain.
@@ -15739,6 +15887,31 @@ var StacksSpokeService = class {
15739
15887
  }
15740
15888
  return this.readTokenBalance(params.token, assetManager);
15741
15889
  }
15890
+ /**
15891
+ * Get the user's own wallet balance of a token on Stacks, in smallest units. Native STX via the
15892
+ * Hiro REST `/extended/v1/address/{addr}/balances` endpoint; SIP-010 fungible tokens via the
15893
+ * read-only `get-balance` contract call. Unlike {@link getDeposit}, this reads the holding of
15894
+ * `srcAddress` (the user), not the protocol asset manager.
15895
+ * @param {GetBalanceParams<StacksChainKey>} params - The chain key, user address, and token.
15896
+ * @returns {Promise<bigint>} The token balance in smallest units.
15897
+ */
15898
+ async getWalletBalance(params) {
15899
+ if (isNativeToken(params.srcChainKey, params.token)) {
15900
+ return this.getSTXBalance(params.srcAddress);
15901
+ }
15902
+ return this.readTokenBalance(params.token.address, params.srcAddress);
15903
+ }
15904
+ /**
15905
+ * Get the user's own wallet balances of multiple tokens on Stacks, in smallest units.
15906
+ * @param {GetBalancesParams<StacksChainKey>} params - The chain key, user address, and tokens.
15907
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
15908
+ */
15909
+ async getWalletBalances(params) {
15910
+ const { srcChainKey, srcAddress, tokens } = params;
15911
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
15912
+ await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
15913
+ return collector.finish();
15914
+ }
15742
15915
  /**
15743
15916
  * Sends a message to the hub chain.
15744
15917
  */
@@ -16299,6 +16472,32 @@ var BitcoinSpokeService = class {
16299
16472
  }
16300
16473
  throw new Error("Token balance queries not yet implemented for non-BTC assets");
16301
16474
  }
16475
+ /**
16476
+ * Get the user's own wallet balance of a token on Bitcoin, in satoshis. Only native BTC is
16477
+ * readable (summed from confirmed/unconfirmed UTXOs). Non-native spoke tokens are Rune ids
16478
+ * (`block:tx`), whose amounts the Esplora UTXO endpoint does not carry, so they resolve to 0n.
16479
+ * @param {GetBalanceParams<BitcoinChainKey>} params - The chain key, user address, and token.
16480
+ * @returns {Promise<bigint>} The balance in satoshis.
16481
+ */
16482
+ async getWalletBalance(params) {
16483
+ const { srcChainKey, srcAddress, token } = params;
16484
+ if (isNativeToken(srcChainKey, token)) {
16485
+ const utxos = await this.fetchUTXOs(srcAddress);
16486
+ return BigInt(utxos.reduce((sum, utxo) => sum + utxo.value, 0));
16487
+ }
16488
+ return 0n;
16489
+ }
16490
+ /**
16491
+ * Get the user's own wallet balances of multiple tokens on Bitcoin, in satoshis.
16492
+ * @param {GetBalancesParams<BitcoinChainKey>} params - The chain key, user address, and tokens.
16493
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
16494
+ */
16495
+ async getWalletBalances(params) {
16496
+ const { srcChainKey, srcAddress, tokens } = params;
16497
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
16498
+ await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
16499
+ return collector.finish();
16500
+ }
16302
16501
  async fetchScriptPubKey(utxo) {
16303
16502
  const txHex = await this.fetchRawTransaction(utxo.txid);
16304
16503
  const tx = bitcoinjsLib.Transaction.fromHex(txHex);
@@ -22845,6 +23044,39 @@ var NearSpokeService = class {
22845
23044
  }
22846
23045
  return BigInt(bal);
22847
23046
  }
23047
+ /**
23048
+ * Get the user's own wallet balance of a token on NEAR, in smallest units (yoctoNEAR for the
23049
+ * native coin). Native NEAR via the account's `viewAccount().amount`; NEP-141 tokens via the
23050
+ * token contract's `ft_balance_of` view. Reads the balance held by `srcAddress` (the user
23051
+ * wallet), not the protocol asset manager. Uses this service's own configured RPC provider.
23052
+ * @param {GetBalanceParams<NearChainKey>} params - The chain key, user address, and token.
23053
+ * @returns {Promise<bigint>} The token balance in smallest units.
23054
+ */
23055
+ async getWalletBalance(params) {
23056
+ if (isNativeToken(params.srcChainKey, params.token)) {
23057
+ const account = await this.rpcProvider.viewAccount({ accountId: params.srcAddress });
23058
+ return BigInt(account.amount);
23059
+ }
23060
+ const bal = await this.queryContract(params.token.address, "ft_balance_of", {
23061
+ account_id: params.srcAddress
23062
+ });
23063
+ if (typeof bal !== "string") {
23064
+ throw new Error("[NearSpokeService.getWalletBalance] Failed to get balance. Unexpected response type.");
23065
+ }
23066
+ return BigInt(bal);
23067
+ }
23068
+ /**
23069
+ * Get the user's own wallet balances of multiple tokens on NEAR, in smallest units. Fans out
23070
+ * over {@link getWalletBalance}, keyed by `token.address`.
23071
+ * @param {GetBalancesParams<NearChainKey>} params - The chain key, user address, and tokens.
23072
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
23073
+ */
23074
+ async getWalletBalances(params) {
23075
+ const { srcChainKey, srcAddress, tokens } = params;
23076
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
23077
+ await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
23078
+ return collector.finish();
23079
+ }
22848
23080
  /**
22849
23081
  * Whether `accountId` is storage-registered on a NEP-141 `token` contract. NEP-141 requires an
22850
23082
  * account to pay a one-time storage bond before it can receive (hold a balance of) the token, so
@@ -23704,6 +23936,76 @@ var SonicSpokeService = class {
23704
23936
  args: [params.token]
23705
23937
  });
23706
23938
  }
23939
+ /**
23940
+ * Get the user's own wallet balance of a token on the hub (Sonic) chain, in smallest units.
23941
+ * Native coin via `eth_getBalance`; erc20 via `balanceOf`.
23942
+ * @param {GetBalanceParams<SonicChainKey>} params - The chain key, user address, and token.
23943
+ * @returns {Promise<bigint>} The token balance in smallest units.
23944
+ */
23945
+ async getWalletBalance(params) {
23946
+ const { srcChainKey, srcAddress, token } = params;
23947
+ if (isNativeToken(srcChainKey, token)) {
23948
+ return this.publicClient.getBalance({ address: srcAddress });
23949
+ }
23950
+ const balance = await this.publicClient.readContract({
23951
+ address: token.address,
23952
+ abi: viem.erc20Abi,
23953
+ functionName: "balanceOf",
23954
+ args: [srcAddress]
23955
+ });
23956
+ return balance ?? 0n;
23957
+ }
23958
+ /**
23959
+ * Get the user's own wallet balances of multiple tokens on the hub (Sonic) chain, in smallest
23960
+ * units. Non-native tokens are batched via multicall3 when the chain supports it, otherwise
23961
+ * read in parallel.
23962
+ * @param {GetBalancesParams<SonicChainKey>} params - The chain key, user address, and tokens.
23963
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
23964
+ */
23965
+ async getWalletBalances(params) {
23966
+ const { srcChainKey, srcAddress, tokens } = params;
23967
+ const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
23968
+ const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
23969
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
23970
+ await settleWalletBalances(
23971
+ collector,
23972
+ nativeTokens,
23973
+ (token) => this.getWalletBalance({ srcChainKey, srcAddress, token })
23974
+ );
23975
+ if (nonNativeTokens.length === 0) {
23976
+ return collector.finish();
23977
+ }
23978
+ if (getEvmViemChain(srcChainKey).contracts?.multicall3) {
23979
+ const results = await this.publicClient.multicall({
23980
+ contracts: nonNativeTokens.map((token) => ({
23981
+ abi: viem.erc20Abi,
23982
+ address: token.address,
23983
+ functionName: "balanceOf",
23984
+ args: [srcAddress]
23985
+ }))
23986
+ });
23987
+ nonNativeTokens.forEach((token, index) => {
23988
+ const result = results[index];
23989
+ if (result?.status === "success") {
23990
+ collector.ok(token.address, BigInt(result.result));
23991
+ } else {
23992
+ collector.fail(token.address, result?.error ?? new Error(`missing multicall result for ${token.address}`));
23993
+ }
23994
+ });
23995
+ return collector.finish();
23996
+ }
23997
+ await settleWalletBalances(
23998
+ collector,
23999
+ nonNativeTokens,
24000
+ (token) => this.publicClient.readContract({
24001
+ address: token.address,
24002
+ abi: viem.erc20Abi,
24003
+ functionName: "balanceOf",
24004
+ args: [srcAddress]
24005
+ })
24006
+ );
24007
+ return collector.finish();
24008
+ }
23707
24009
  /**
23708
24010
  * Execute a batch of contract calls through the Sonic wallet contract.
23709
24011
  * @param {Hex} payload - The encoded payload containing the calls array
@@ -23802,8 +24104,8 @@ var SuiGrpcTransport = class {
23802
24104
  this.endpoint = endpoint;
23803
24105
  this.client = new grpc.SuiGrpcClient({ network: "mainnet", baseUrl: endpoint });
23804
24106
  }
23805
- async getCoins(owner, coinType, limit = DEFAULT_GET_COINS_LIMIT) {
23806
- const response = await this.client.core.listCoins({ owner, coinType, limit });
24107
+ async getCoins(owner, coinType, limit = DEFAULT_GET_COINS_LIMIT, cursor) {
24108
+ const response = await this.client.core.listCoins({ owner, coinType, limit, cursor: cursor ?? void 0 });
23807
24109
  return toSuiPaginatedCoins(response, coinType);
23808
24110
  }
23809
24111
  async simulate(tx, sender) {
@@ -24043,6 +24345,42 @@ var SuiSpokeService = class {
24043
24345
  const str_u64 = bcs.bcs.U64.parse(Uint8Array.from(val));
24044
24346
  return BigInt(str_u64);
24045
24347
  }
24348
+ /**
24349
+ * Get the user's own wallet balance of a token on Sui, in smallest units. Unlike {@link getDeposit}
24350
+ * (which reads the protocol asset manager holding), this reads the balance held by `params.srcAddress`
24351
+ * itself. Native SUI is read via its canonical `0x2::sui::SUI` coin type; other coins use the token's
24352
+ * Sui coinType (`token.address`).
24353
+ * @param {GetBalanceParams<SuiChainKey>} params - The chain key, user address, and token.
24354
+ * @returns {Promise<bigint>} The token balance in smallest units.
24355
+ */
24356
+ async getWalletBalance(params) {
24357
+ const { srcChainKey, srcAddress, token } = params;
24358
+ let coinType = isNativeToken(srcChainKey, token) ? "0x2::sui::SUI" : token.address;
24359
+ if (coinType === "0x03917a812fe4a6d6bc779c5ab53f8a80ba741f8af04121193fc44e0f662e2ceb::balanced_dollar::BALANCED_DOLLAR") {
24360
+ coinType = "0x3917a812fe4a6d6bc779c5ab53f8a80ba741f8af04121193fc44e0f662e2ceb::balanced_dollar::BALANCED_DOLLAR";
24361
+ }
24362
+ let total = 0n;
24363
+ let cursor;
24364
+ do {
24365
+ const page = await this.transport.getCoins(srcAddress, coinType, void 0, cursor);
24366
+ for (const coin of page.data) {
24367
+ total += BigInt(coin.balance);
24368
+ }
24369
+ cursor = page.hasNextPage ? page.nextCursor : void 0;
24370
+ } while (cursor);
24371
+ return total;
24372
+ }
24373
+ /**
24374
+ * Get the user's own wallet balances of multiple tokens on Sui, in smallest units.
24375
+ * @param {GetBalancesParams<SuiChainKey>} params - The chain key, user address, and tokens.
24376
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
24377
+ */
24378
+ async getWalletBalances(params) {
24379
+ const { srcChainKey, srcAddress, tokens } = params;
24380
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
24381
+ await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
24382
+ return collector.finish();
24383
+ }
24046
24384
  /**
24047
24385
  * Fetch the asset manager config from the spoke chain.
24048
24386
  * @param {SuiChainKey} chainId - The Sui chain key.
@@ -24189,6 +24527,11 @@ var CustomSorobanServer = class extends stellarSdk.rpc.Server {
24189
24527
  return response.json().then((json) => json.result);
24190
24528
  }
24191
24529
  };
24530
+ var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
24531
+ function parseXlmBalanceToStroops(balanceStr) {
24532
+ const [whole = "0", frac = ""] = balanceStr.split(".");
24533
+ return BigInt(whole + frac.padEnd(7, "0").slice(0, 7));
24534
+ }
24192
24535
  var CustomStellarAccount = class {
24193
24536
  accountId;
24194
24537
  sequenceNumber;
@@ -24227,7 +24570,7 @@ var CustomStellarAccount = class {
24227
24570
  }
24228
24571
  };
24229
24572
  var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
24230
- var StellarSpokeService = class {
24573
+ var StellarSpokeService = class _StellarSpokeService {
24231
24574
  config;
24232
24575
  chainConfig;
24233
24576
  server;
@@ -24268,6 +24611,109 @@ var StellarSpokeService = class {
24268
24611
  }
24269
24612
  throw new Error("result undefined");
24270
24613
  }
24614
+ /**
24615
+ * Get the user's own wallet balance of a token on Stellar, in smallest units. Native XLM returns
24616
+ * the spendable amount (total minus the minimum reserve and selling liabilities) via Horizon;
24617
+ * other assets return the Soroban token contract's `balance` for the user.
24618
+ * @param {GetBalanceParams<StellarChainKey>} params - The chain key, user address, and token.
24619
+ * @returns {Promise<bigint>} The token balance in smallest units.
24620
+ */
24621
+ async getWalletBalance(params) {
24622
+ const { srcChainKey, srcAddress, token } = params;
24623
+ if (isNativeToken(srcChainKey, token)) {
24624
+ return _StellarSpokeService.spendableXlmStroops(await this.server.loadAccount(srcAddress));
24625
+ }
24626
+ const [network, sourceAccount] = await Promise.all([
24627
+ this.sorobanServer.getNetwork(),
24628
+ this.sorobanServer.getAccount(srcAddress)
24629
+ ]);
24630
+ return this.simulateTokenBalance(
24631
+ token.address,
24632
+ srcAddress,
24633
+ new CustomStellarAccount({ account_id: sourceAccount.accountId(), sequence: sourceAccount.sequenceNumber() }),
24634
+ network.passphrase
24635
+ );
24636
+ }
24637
+ /**
24638
+ * Spendable XLM in stroops: the account's native balance minus its minimum reserve and selling
24639
+ * liabilities. Reporting the raw balance would let a user try to spend reserves the network
24640
+ * refuses to release.
24641
+ */
24642
+ static spendableXlmStroops(account) {
24643
+ const nativeBalance = account.balances.find(
24644
+ (balance) => balance.asset_type === "native"
24645
+ );
24646
+ if (!nativeBalance) {
24647
+ return 0n;
24648
+ }
24649
+ const rawStroops = parseXlmBalanceToStroops(nativeBalance.balance);
24650
+ const sellingLiabilitiesStroops = nativeBalance.selling_liabilities ? parseXlmBalanceToStroops(nativeBalance.selling_liabilities) : 0n;
24651
+ const reserveCount = Math.max(0, 2 + account.subentry_count + account.num_sponsoring - account.num_sponsored);
24652
+ const minStroops = BigInt(reserveCount) * STELLAR_BASE_RESERVE_STROOPS + sellingLiabilitiesStroops;
24653
+ return rawStroops > minStroops ? rawStroops - minStroops : 0n;
24654
+ }
24655
+ /**
24656
+ * Simulate a Soroban token `balance` call. Takes the network passphrase and source account so a
24657
+ * batch can fetch them once; `getAccountClone()` hands each builder its own `Account`, because
24658
+ * `TransactionBuilder.build()` increments the source's sequence number and concurrent builders
24659
+ * would otherwise interleave on a shared one.
24660
+ */
24661
+ async simulateTokenBalance(tokenAddress, srcAddress, account, networkPassphrase) {
24662
+ const contract = new stellarSdk.Contract(tokenAddress);
24663
+ const tx = new stellarSdk.TransactionBuilder(account.getAccountClone(), { fee: this.baseFee, networkPassphrase }).addOperation(contract.call("balance", stellarSdk.nativeToScVal(srcAddress, { type: "address" }))).setTimeout(stellarSdk.TimeoutInfinite).build();
24664
+ const result = await this.sorobanServer.simulateTransaction(tx);
24665
+ if (!stellarSdk.rpc.Api.isSimulationSuccess(result)) {
24666
+ throw new Error("Failed to simulate transaction");
24667
+ }
24668
+ if (!result.result) {
24669
+ throw new Error("Failed to read token balance: simulation returned no result");
24670
+ }
24671
+ return stellarSdk.scValToBigInt(result.result.retval);
24672
+ }
24673
+ /**
24674
+ * Get the user's own wallet balances of multiple tokens on Stellar, in smallest units.
24675
+ *
24676
+ * The network passphrase and the source account are the same for every token, so they are
24677
+ * fetched once per batch instead of once per token — and only when a partition actually needs
24678
+ * them, so an all-native request issues no Soroban calls at all.
24679
+ * @param {GetBalancesParams<StellarChainKey>} params - The chain key, user address, and tokens.
24680
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
24681
+ */
24682
+ async getWalletBalances(params) {
24683
+ const { srcChainKey, srcAddress, tokens } = params;
24684
+ const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
24685
+ const sorobanTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
24686
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
24687
+ if (nativeTokens.length > 0) {
24688
+ try {
24689
+ const spendable = _StellarSpokeService.spendableXlmStroops(await this.server.loadAccount(srcAddress));
24690
+ for (const token of nativeTokens) {
24691
+ collector.ok(token.address, spendable);
24692
+ }
24693
+ } catch (error) {
24694
+ for (const token of nativeTokens) {
24695
+ collector.fail(token.address, error);
24696
+ }
24697
+ }
24698
+ }
24699
+ if (sorobanTokens.length === 0) {
24700
+ return collector.finish();
24701
+ }
24702
+ const [network, sourceAccount] = await Promise.all([
24703
+ this.sorobanServer.getNetwork(),
24704
+ this.sorobanServer.getAccount(srcAddress)
24705
+ ]);
24706
+ const account = new CustomStellarAccount({
24707
+ account_id: sourceAccount.accountId(),
24708
+ sequence: sourceAccount.sequenceNumber()
24709
+ });
24710
+ await settleWalletBalances(
24711
+ collector,
24712
+ sorobanTokens,
24713
+ (token) => this.simulateTokenBalance(token.address, srcAddress, account, network.passphrase)
24714
+ );
24715
+ return collector.finish();
24716
+ }
24271
24717
  async buildPriorityStellarTransaction(account, network, operation) {
24272
24718
  const simulationForFee = await this.sorobanServer.simulateTransaction(
24273
24719
  new stellarSdk.TransactionBuilder(account.getAccountClone(), {
@@ -24841,6 +25287,48 @@ var SolanaSpokeService = class _SolanaSpokeService {
24841
25287
  const tokenAccount = await _SolanaSpokeService.getTokenAccountBalance(this.connection, vaultToken.pda.toBase58());
24842
25288
  return BigInt(tokenAccount.value.amount);
24843
25289
  }
25290
+ /**
25291
+ * Get the user's own wallet balance of a token on Solana, in smallest units. Native SOL via
25292
+ * `getBalance`; SPL via the associated token account. The mint may belong to the legacy SPL
25293
+ * Token program or Token-2022 (e.g. xStock tokens), which derive different ATAs, so both
25294
+ * candidate ATAs are read in one call and the existing one is used.
25295
+ * @param {GetBalanceParams<SolanaChainKey>} params - The chain key, user address, and token.
25296
+ * @returns {Promise<bigint>} The token balance in smallest units.
25297
+ */
25298
+ async getWalletBalance(params) {
25299
+ const { srcChainKey, srcAddress, token } = params;
25300
+ if (isNativeToken(srcChainKey, token)) {
25301
+ return BigInt(await _SolanaSpokeService.getBalance(this.connection, srcAddress));
25302
+ }
25303
+ const owner = new web3_js.PublicKey(srcAddress);
25304
+ const mint = new web3_js.PublicKey(token.address);
25305
+ const candidates = [splToken.TOKEN_PROGRAM_ID, splToken.TOKEN_2022_PROGRAM_ID].map((programId) => ({
25306
+ programId,
25307
+ ata: splToken.getAssociatedTokenAddressSync(mint, owner, true, programId)
25308
+ }));
25309
+ const accounts = await this.connection.getMultipleAccountsInfo(candidates.map((c) => c.ata));
25310
+ let balance = 0n;
25311
+ for (const [i, candidate] of candidates.entries()) {
25312
+ const info = accounts[i];
25313
+ if (!info) continue;
25314
+ try {
25315
+ balance += splToken.unpackAccount(candidate.ata, info, candidate.programId).amount;
25316
+ } catch {
25317
+ }
25318
+ }
25319
+ return balance;
25320
+ }
25321
+ /**
25322
+ * Get the user's own wallet balances of multiple tokens on Solana, in smallest units.
25323
+ * @param {GetBalancesParams<SolanaChainKey>} params - The chain key, user address, and tokens.
25324
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
25325
+ */
25326
+ async getWalletBalances(params) {
25327
+ const { srcChainKey, srcAddress, tokens } = params;
25328
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
25329
+ await settleWalletBalances(collector, tokens, (token) => this.getWalletBalance({ srcChainKey, srcAddress, token }));
25330
+ return collector.finish();
25331
+ }
24844
25332
  /**
24845
25333
  * Sends a message to the hub chain.
24846
25334
  * @param dstChainKey - The chain key of the hub chain.
@@ -25062,8 +25550,84 @@ var IconSpokeService = class {
25062
25550
  async getDeposit(params) {
25063
25551
  const { token, srcChainKey } = params;
25064
25552
  const transaction = new CallBuilder().to(token).method("balanceOf").params({ _owner: this.config.getChainConfig(srcChainKey).addresses.assetManager }).build();
25553
+ return this.readIrc2Balance(transaction);
25554
+ }
25555
+ /**
25556
+ * Read an int-returning SCORE call. `iconService.call(...)` registers no result converter, so
25557
+ * `execute()` resolves the raw JSON-RPC `result` — a bare hex string for an int, not `{ value }`.
25558
+ */
25559
+ async readIrc2Balance(transaction) {
25065
25560
  const result = await this.iconService.call(transaction).execute();
25066
- return BigInt(result.value);
25561
+ if (typeof result !== "string") {
25562
+ throw new Error(`[IconSpokeService] Unexpected balanceOf response: ${JSON.stringify(result)}`);
25563
+ }
25564
+ return hexToBigInt(result);
25565
+ }
25566
+ /**
25567
+ * Get the user's own wallet balance of a token on ICON, in smallest units. Native ICX is read
25568
+ * via `iconService.getBalance`; IRC-2 tokens via a `balanceOf(_owner)` call on the token contract.
25569
+ * @param {GetBalanceParams<IconChainKey>} params - The chain key, user address, and token.
25570
+ * @returns {Promise<bigint>} The token balance in smallest units.
25571
+ */
25572
+ async getWalletBalance(params) {
25573
+ const { srcChainKey, srcAddress, token } = params;
25574
+ if (isNativeToken(srcChainKey, token)) {
25575
+ const balance = await this.iconService.getBalance(srcAddress).execute();
25576
+ return BigInt(balance.toFixed());
25577
+ }
25578
+ const transaction = new CallBuilder().to(token.address).method("balanceOf").params({ _owner: srcAddress }).build();
25579
+ return this.readIrc2Balance(transaction);
25580
+ }
25581
+ /**
25582
+ * Get the user's own wallet balances of multiple tokens on ICON, in smallest units. Native ICX
25583
+ * is read via `iconService.getBalance`; IRC-2 balances are batched into a single `tryAggregate`
25584
+ * multicall so every `balanceOf(_owner)` read shares one round-trip.
25585
+ * @param {GetBalancesParams<IconChainKey>} params - The chain key, user address, and tokens.
25586
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
25587
+ */
25588
+ async getWalletBalances(params) {
25589
+ const { srcChainKey, srcAddress, tokens } = params;
25590
+ const nativeTokens = tokens.filter((token) => isNativeToken(srcChainKey, token));
25591
+ const nonNativeTokens = tokens.filter((token) => !isNativeToken(srcChainKey, token));
25592
+ const collector = createBalanceCollector({ logger: this.config.logger, chainKey: srcChainKey });
25593
+ if (nativeTokens.length > 0) {
25594
+ try {
25595
+ const balance = await this.iconService.getBalance(srcAddress).execute();
25596
+ for (const token of nativeTokens) {
25597
+ collector.ok(token.address, BigInt(balance.toFixed()));
25598
+ }
25599
+ } catch (error) {
25600
+ for (const token of nativeTokens) {
25601
+ collector.fail(token.address, error);
25602
+ }
25603
+ }
25604
+ }
25605
+ if (nonNativeTokens.length === 0) {
25606
+ return collector.finish();
25607
+ }
25608
+ const multicallAddress = "cxa4aa9185e23558cff990f494c1fd2845f6cbf741";
25609
+ const calls = nonNativeTokens.map((token) => ({
25610
+ target: token.address,
25611
+ method: "balanceOf",
25612
+ params: [srcAddress]
25613
+ }));
25614
+ const transaction = new CallBuilder().to(multicallAddress).method("tryAggregate").params({ requireSuccess: Converter.toHex(0), calls }).build();
25615
+ const result = await this.iconService.call(transaction).execute();
25616
+ const aggregated = result.returnData;
25617
+ if (!Array.isArray(aggregated) || aggregated.length !== nonNativeTokens.length) {
25618
+ throw new Error(
25619
+ `[IconSpokeService] tryAggregate returned ${Array.isArray(aggregated) ? aggregated.length : "no"} entries for ${nonNativeTokens.length} tokens`
25620
+ );
25621
+ }
25622
+ nonNativeTokens.forEach((token, index) => {
25623
+ const agg = aggregated[index];
25624
+ if (agg && agg.success !== "0x0" && typeof agg.returnData === "string") {
25625
+ collector.ok(token.address, hexToBigInt(agg.returnData));
25626
+ } else {
25627
+ collector.fail(token.address, new Error(`balanceOf failed for ${token.address}: ${agg?.returnData}`));
25628
+ }
25629
+ });
25630
+ return collector.finish();
25067
25631
  }
25068
25632
  /**
25069
25633
  * Sends a message to the hub chain.
@@ -25129,6 +25693,7 @@ var GAS_PRICE_REGEX = /^(\d+)(.*)$/;
25129
25693
  var InjectiveSpokeService = class {
25130
25694
  config;
25131
25695
  chainGrpcWasmApi;
25696
+ indexerGrpcAccountPortfolioApi;
25132
25697
  txClient;
25133
25698
  endpoints;
25134
25699
  pollingIntervalMs;
@@ -25138,6 +25703,7 @@ var InjectiveSpokeService = class {
25138
25703
  this.config = config;
25139
25704
  this.endpoints = networks.getNetworkEndpoints(networks.Network.Mainnet);
25140
25705
  this.chainGrpcWasmApi = new sdkTs.ChainGrpcWasmApi(this.endpoints.grpc);
25706
+ this.indexerGrpcAccountPortfolioApi = new sdkTs.IndexerGrpcAccountPortfolioApi(this.endpoints.indexer);
25141
25707
  this.txClient = new sdkTs.TxGrpcApi(this.endpoints.grpc);
25142
25708
  this.pollingIntervalMs = this.config.sodaxConfig.chains[ChainKeys.INJECTIVE_MAINNET].pollingConfig.pollingIntervalMs;
25143
25709
  this.maxTimeoutMs = this.config.sodaxConfig.chains[ChainKeys.INJECTIVE_MAINNET].pollingConfig.maxTimeoutMs;
@@ -25221,6 +25787,37 @@ var InjectiveSpokeService = class {
25221
25787
  );
25222
25788
  return BigInt(sdkTs.fromBase64(response.data));
25223
25789
  }
25790
+ /**
25791
+ * Get the user's own wallet balance of a token on Injective, in smallest units. On Injective every
25792
+ * asset is a bank coin, so the native coin (`inj`) and factory/peggy/IBC tokens are all read from the
25793
+ * account's portfolio bank balances and matched by denom. The denom is the chain's native denom for
25794
+ * the native coin and `params.token.address` for standard tokens.
25795
+ * @param {GetBalanceParams<InjectiveChainKey>} params - The chain key, user address, and token.
25796
+ * @returns {Promise<bigint>} The token balance in smallest units, or 0n when the account holds none.
25797
+ */
25798
+ async getWalletBalance(params) {
25799
+ const denom = isNativeToken(params.srcChainKey, params.token) ? this.config.getChainConfig(params.srcChainKey).nativeToken : params.token.address;
25800
+ const portfolio = await this.indexerGrpcAccountPortfolioApi.fetchAccountPortfolioBalances(params.srcAddress);
25801
+ const balance = portfolio.bankBalancesList.find((_balance) => _balance.denom === denom);
25802
+ return balance ? BigInt(balance.amount) : 0n;
25803
+ }
25804
+ /**
25805
+ * Get the user's own wallet balances of multiple tokens on Injective, in smallest units.
25806
+ * @param {GetBalancesParams<InjectiveChainKey>} params - The chain key, user address, and tokens.
25807
+ * @returns {Promise<WalletBalanceMap>} A map of token address to balance in smallest units.
25808
+ */
25809
+ async getWalletBalances(params) {
25810
+ const { srcChainKey, srcAddress, tokens } = params;
25811
+ const portfolio = await this.indexerGrpcAccountPortfolioApi.fetchAccountPortfolioBalances(srcAddress);
25812
+ const amountByDenom = new Map(portfolio.bankBalancesList.map((balance) => [balance.denom, BigInt(balance.amount)]));
25813
+ const nativeDenom = this.config.getChainConfig(srcChainKey).nativeToken;
25814
+ const balances = {};
25815
+ for (const token of tokens) {
25816
+ const denom = isNativeToken(srcChainKey, token) ? nativeDenom : token.address;
25817
+ balances[token.address] = amountByDenom.get(denom) ?? 0n;
25818
+ }
25819
+ return balances;
25820
+ }
25224
25821
  async getRawTransaction(chainId, senderAddress, contractAddress, msg, memo, funds = []) {
25225
25822
  const msgExec = sdkTs.MsgExecuteContract.fromJSON({
25226
25823
  contractAddress,
@@ -26028,6 +26625,138 @@ var SpokeService = class _SpokeService {
26028
26625
  return { ok: false, error };
26029
26626
  }
26030
26627
  }
26628
+ /**
26629
+ * Get a user's own wallet balance of a single token on a spoke chain, in smallest units.
26630
+ * Chain-agnostic: dispatches to the per-chain service, which reads the native coin or the
26631
+ * chain's token standard (EVM erc20, Solana SPL, …). Unlike {@link getDeposit}, this reads
26632
+ * `srcAddress` itself, not the protocol asset manager.
26633
+ * @param {GetBalanceParams<C>} params - The chain key, user address, and token.
26634
+ * @returns {Promise<Result<bigint>>} The token balance in smallest units.
26635
+ */
26636
+ async getWalletBalance(params) {
26637
+ try {
26638
+ if (isHubChainKeyType(params.srcChainKey)) {
26639
+ const value = await this.sonic.getWalletBalance(params);
26640
+ return { ok: true, value };
26641
+ }
26642
+ const chainType = getChainType(params.srcChainKey);
26643
+ switch (chainType) {
26644
+ case "EVM": {
26645
+ const value = await this.evm.getWalletBalance(params);
26646
+ return { ok: true, value };
26647
+ }
26648
+ case "INJECTIVE": {
26649
+ const value = await this.injective.getWalletBalance(params);
26650
+ return { ok: true, value };
26651
+ }
26652
+ case "STELLAR": {
26653
+ const value = await this.stellar.getWalletBalance(params);
26654
+ return { ok: true, value };
26655
+ }
26656
+ case "SUI": {
26657
+ const value = await this.sui.getWalletBalance(params);
26658
+ return { ok: true, value };
26659
+ }
26660
+ case "ICON": {
26661
+ const value = await this.icon.getWalletBalance(params);
26662
+ return { ok: true, value };
26663
+ }
26664
+ case "SOLANA": {
26665
+ const value = await this.solana.getWalletBalance(params);
26666
+ return { ok: true, value };
26667
+ }
26668
+ case "STACKS": {
26669
+ const value = await this.stacks.getWalletBalance(params);
26670
+ return { ok: true, value };
26671
+ }
26672
+ case "BITCOIN": {
26673
+ const value = await this.bitcoin.getWalletBalance(params);
26674
+ return { ok: true, value };
26675
+ }
26676
+ case "NEAR": {
26677
+ const value = await this.near.getWalletBalance(params);
26678
+ return { ok: true, value };
26679
+ }
26680
+ default: {
26681
+ const exhaustiveCheck = chainType;
26682
+ this.config.logger.debug("Unhandled exhaustive case", { value: exhaustiveCheck });
26683
+ return {
26684
+ ok: false,
26685
+ error: new Error(`[getWalletBalance] Invalid chain type. Valid chain types: ${ChainTypeArr.join(", ")}`)
26686
+ };
26687
+ }
26688
+ }
26689
+ } catch (error) {
26690
+ return { ok: false, error };
26691
+ }
26692
+ }
26693
+ /**
26694
+ * Get a user's own wallet balances of multiple tokens on a spoke chain, in smallest units.
26695
+ * Chain-agnostic sibling of {@link getWalletBalance}; per-chain services batch the reads where the
26696
+ * chain supports it (e.g. EVM multicall3, ICON aggregated call data).
26697
+ * @param {GetBalancesParams<C>} params - The chain key, user address, and tokens.
26698
+ * @returns {Promise<Result<WalletBalanceMap>>} A map of token address to balance in smallest
26699
+ * units. A token that could not be read is logged and reported as `0n`; the `Result` fails when
26700
+ * the whole batch is unusable — invalid chain, a shared round-trip every token depends on, or a
26701
+ * batch in which no token could be read at all.
26702
+ */
26703
+ async getWalletBalances(params) {
26704
+ try {
26705
+ if (isHubChainKeyType(params.srcChainKey)) {
26706
+ const value = await this.sonic.getWalletBalances(params);
26707
+ return { ok: true, value };
26708
+ }
26709
+ const chainType = getChainType(params.srcChainKey);
26710
+ switch (chainType) {
26711
+ case "EVM": {
26712
+ const value = await this.evm.getWalletBalances(params);
26713
+ return { ok: true, value };
26714
+ }
26715
+ case "INJECTIVE": {
26716
+ const value = await this.injective.getWalletBalances(params);
26717
+ return { ok: true, value };
26718
+ }
26719
+ case "STELLAR": {
26720
+ const value = await this.stellar.getWalletBalances(params);
26721
+ return { ok: true, value };
26722
+ }
26723
+ case "SUI": {
26724
+ const value = await this.sui.getWalletBalances(params);
26725
+ return { ok: true, value };
26726
+ }
26727
+ case "ICON": {
26728
+ const value = await this.icon.getWalletBalances(params);
26729
+ return { ok: true, value };
26730
+ }
26731
+ case "SOLANA": {
26732
+ const value = await this.solana.getWalletBalances(params);
26733
+ return { ok: true, value };
26734
+ }
26735
+ case "STACKS": {
26736
+ const value = await this.stacks.getWalletBalances(params);
26737
+ return { ok: true, value };
26738
+ }
26739
+ case "BITCOIN": {
26740
+ const value = await this.bitcoin.getWalletBalances(params);
26741
+ return { ok: true, value };
26742
+ }
26743
+ case "NEAR": {
26744
+ const value = await this.near.getWalletBalances(params);
26745
+ return { ok: true, value };
26746
+ }
26747
+ default: {
26748
+ const exhaustiveCheck = chainType;
26749
+ this.config.logger.debug("Unhandled exhaustive case", { value: exhaustiveCheck });
26750
+ return {
26751
+ ok: false,
26752
+ error: new Error(`[getWalletBalances] Invalid chain type. Valid chain types: ${ChainTypeArr.join(", ")}`)
26753
+ };
26754
+ }
26755
+ }
26756
+ } catch (error) {
26757
+ return { ok: false, error };
26758
+ }
26759
+ }
26031
26760
  /**
26032
26761
  * Calls the connection contract on the spoke chain to send a message to the hub wallet, which then executes the message's payload.
26033
26762
  * @param {HubAddress} from - The address of the user on the hub chain.
@@ -27324,6 +28053,119 @@ var EvmHubProvider = class {
27324
28053
  }
27325
28054
  };
27326
28055
 
28056
+ // src/backendApi/api-utils.ts
28057
+ var API_KEY_HEADER = "x-api-key";
28058
+ function apiKeyHeader(apiKey) {
28059
+ return apiKey ? { [API_KEY_HEADER]: apiKey } : {};
28060
+ }
28061
+ function mergeHeaders(...sources) {
28062
+ const byName = /* @__PURE__ */ new Map();
28063
+ for (const source of sources) {
28064
+ for (const entry of Object.entries(source ?? {})) byName.set(entry[0].toLowerCase(), entry);
28065
+ }
28066
+ return Object.fromEntries(byName.values());
28067
+ }
28068
+ function withApiKey(config, apiKey) {
28069
+ return { ...config, headers: mergeHeaders(apiKeyHeader(apiKey), config.headers) };
28070
+ }
28071
+ function assignHeaders(target, source) {
28072
+ const merged = mergeHeaders(target, source);
28073
+ for (const name of Object.keys(target)) delete target[name];
28074
+ Object.assign(target, merged);
28075
+ }
28076
+ var BackendHttpError = class extends Error {
28077
+ status;
28078
+ bodyText;
28079
+ /** Parsed JSON, or `undefined` for empty or malformed bodies. */
28080
+ body;
28081
+ constructor(status, bodyText) {
28082
+ super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
28083
+ this.name = "BackendHttpError";
28084
+ this.status = status;
28085
+ this.bodyText = bodyText;
28086
+ this.body = safeJsonParse(bodyText);
28087
+ }
28088
+ };
28089
+ function isBackendHttpError(error) {
28090
+ if (error instanceof BackendHttpError) return true;
28091
+ return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
28092
+ }
28093
+ function safeJsonParse(text) {
28094
+ if (text.length === 0) return void 0;
28095
+ try {
28096
+ return JSON.parse(text);
28097
+ } catch {
28098
+ return void 0;
28099
+ }
28100
+ }
28101
+ function trimTrailingSlashes(baseURL) {
28102
+ let end = baseURL.length;
28103
+ while (end > 0 && baseURL[end - 1] === "/") end -= 1;
28104
+ return baseURL.slice(0, end);
28105
+ }
28106
+ var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
28107
+ async function makeRequest(params) {
28108
+ const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
28109
+ const baseURL = overrideConfig.baseURL || config.baseURL || "";
28110
+ const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
28111
+ const headers = mergeHeaders(config.headers, apiKeyHeader(overrideConfig.apiKey), overrideConfig.headers);
28112
+ const controller = new AbortController();
28113
+ const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
28114
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
28115
+ try {
28116
+ const response = await fetch(url, {
28117
+ method: config.method,
28118
+ headers,
28119
+ body: config.body,
28120
+ signal: controller.signal
28121
+ });
28122
+ if (!response.ok) {
28123
+ const errorText = await response.text();
28124
+ throw new BackendHttpError(response.status, errorText);
28125
+ }
28126
+ const data = await response.json();
28127
+ return data;
28128
+ } catch (error) {
28129
+ if (error instanceof Error) {
28130
+ if (error.name === "AbortError") {
28131
+ throw new Error("REQUEST_TIMEOUT", { cause: new Error(`Request timeout after ${timeout}ms`) });
28132
+ }
28133
+ logger.error(`[${serviceLabel}] Request error`, error);
28134
+ throw error;
28135
+ }
28136
+ logger.error(`[${serviceLabel}] Unknown error`, error);
28137
+ throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
28138
+ } finally {
28139
+ clearTimeout(timeoutId);
28140
+ }
28141
+ }
28142
+ function resolveRequestConfig(config, defaults) {
28143
+ const { baseURL, timeout, headers, apiKey, ...rest } = config;
28144
+ return {
28145
+ ...rest,
28146
+ baseURL: baseURL || defaults.baseURL,
28147
+ timeout: timeout ?? defaults.timeout,
28148
+ headers: mergeHeaders(defaults.headers, apiKeyHeader(apiKey), headers)
28149
+ };
28150
+ }
28151
+ function toExternalApiError(params) {
28152
+ const { api, feature, endpoint, error } = params;
28153
+ const context = { api, endpoint };
28154
+ if (isBackendHttpError(error)) context.status = error.status;
28155
+ return new SodaxError(
28156
+ "EXTERNAL_API_ERROR",
28157
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
28158
+ { feature, cause: error, context }
28159
+ );
28160
+ }
28161
+ function toInvalidResponseShapeError(params) {
28162
+ const { api, feature, endpoint, issues } = params;
28163
+ return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
28164
+ feature,
28165
+ context: { api, endpoint, reason: "invalid_response_shape", issues }
28166
+ });
28167
+ }
28168
+
27327
28169
  // src/swap/SolverApiService.ts
27328
28170
  var bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
27329
28171
  var SolverApiService = class {
@@ -27370,9 +28212,7 @@ var SolverApiService = class {
27370
28212
  try {
27371
28213
  const response = await fetch(`${config.solverApiEndpoint}/quote`, {
27372
28214
  method: "POST",
27373
- headers: {
27374
- "Content-Type": "application/json"
27375
- },
28215
+ headers: mergeHeaders({ "Content-Type": "application/json" }, apiKeyHeader(configService.apiKey)),
27376
28216
  body: JSON.stringify({
27377
28217
  token_src: tokenSrc,
27378
28218
  token_dst: tokenDst,
@@ -27418,16 +28258,16 @@ var SolverApiService = class {
27418
28258
  *
27419
28259
  * @param request - Object containing `intent_tx_hash` (the hub-chain tx hash of the created intent).
27420
28260
  * @param config - Solver endpoint configuration.
28261
+ * @param logger - Diagnostics sink; defaults to the silent logger.
28262
+ * @param apiKey - Configured backend API key (`config.apiKey`), sent as the `x-api-key` header.
27421
28263
  * @returns A `Result` containing `{ answer: 'OK', intent_hash: Hex }` on success.
27422
28264
  */
27423
- static async postExecution(request, config, logger = silentLogger) {
28265
+ static async postExecution(request, config, logger = silentLogger, apiKey) {
27424
28266
  try {
27425
28267
  const response = await retry(
27426
28268
  () => fetch(`${config.solverApiEndpoint}/execute`, {
27427
28269
  method: "POST",
27428
- headers: {
27429
- "Content-Type": "application/json"
27430
- },
28270
+ headers: mergeHeaders({ "Content-Type": "application/json" }, apiKeyHeader(apiKey)),
27431
28271
  body: JSON.stringify(request)
27432
28272
  })
27433
28273
  );
@@ -27471,11 +28311,12 @@ var SolverApiService = class {
27471
28311
  * request instantly. A non-positive one is a real budget of zero: the request aborts at once.
27472
28312
  * The relay's `getTransactionPackets` takes the same parameter but degrades a non-finite value
27473
28313
  * to its own per-request budget instead; the divergence is deliberate, and explained inline.
28314
+ * @param apiKey - Configured backend API key (`config.apiKey`), sent as the `x-api-key` header.
27474
28315
  * @returns A `Result` containing `{ status: SolverIntentStatusCode, fill_tx_hash?: string }`.
27475
28316
  * `fill_tx_hash` is set only when `status === SolverIntentStatusCode.SOLVED (3)`.
27476
28317
  * @throws Invariant error if `intent_tx_hash` is empty (thrown before the async request).
27477
28318
  */
27478
- static async getStatus(request, config, logger = silentLogger, timeoutMs) {
28319
+ static async getStatus(request, config, logger = silentLogger, timeoutMs, apiKey) {
27479
28320
  invariant(request.intent_tx_hash.length > 0, "Empty intent_tx_hash");
27480
28321
  const budgetMs = timeoutMs !== void 0 && Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : void 0;
27481
28322
  const controller = budgetMs === void 0 ? void 0 : new AbortController();
@@ -27483,9 +28324,7 @@ var SolverApiService = class {
27483
28324
  try {
27484
28325
  const response = await fetch(`${config.solverApiEndpoint}/status`, {
27485
28326
  method: "POST",
27486
- headers: {
27487
- "Content-Type": "application/json"
27488
- },
28327
+ headers: mergeHeaders({ "Content-Type": "application/json" }, apiKeyHeader(apiKey)),
27489
28328
  body: JSON.stringify(request),
27490
28329
  signal: controller?.signal
27491
28330
  });
@@ -27546,6 +28385,12 @@ async function pollBackendSubmitTx({
27546
28385
  }
27547
28386
  } else {
27548
28387
  lastStatusError = statusResult.error;
28388
+ if (isAuthFailure(statusResult.error)) {
28389
+ return {
28390
+ ok: false,
28391
+ cause: new Error("backend submit-tx status rejected the API key", { cause: statusResult.error })
28392
+ };
28393
+ }
27549
28394
  }
27550
28395
  if (attempt.remaining() <= intervalMs) break;
27551
28396
  await sleep(intervalMs);
@@ -27587,12 +28432,13 @@ async function runBackendSubmitTx({
27587
28432
  body,
27588
28433
  statusQuery,
27589
28434
  terminalStatus,
27590
- onExecuted
28435
+ onExecuted,
28436
+ overrideConfig
27591
28437
  }) {
27592
28438
  const serviceTimeoutMs = api.getTimeout();
27593
28439
  const requestTimeout = attempt.requestTimeout(serviceTimeoutMs);
27594
28440
  if (requestTimeout === null) return { ok: false, cause: noRequestBudgetCause(serviceTimeoutMs) };
27595
- const submitted = await api.submitTx(body, { timeout: requestTimeout });
28441
+ const submitted = await api.submitTx(body, { ...overrideConfig, timeout: requestTimeout });
27596
28442
  if (!submitted.ok) return { ok: false, cause: submitted.error };
27597
28443
  if (!submitted.value.success) {
27598
28444
  return { ok: false, cause: new Error(`backend submit-tx not accepted: ${submitted.value.data.message}`) };
@@ -27600,7 +28446,8 @@ async function runBackendSubmitTx({
27600
28446
  const polled = await pollBackendSubmitTx({
27601
28447
  attempt,
27602
28448
  terminalStatus,
27603
- getStatus: (override) => api.getSubmitTxStatus(statusQuery, override),
28449
+ // The poll's own override (its per-request timeout) wins over the per-action fields.
28450
+ getStatus: (override) => api.getSubmitTxStatus(statusQuery, { ...overrideConfig, ...override }),
27604
28451
  onExecuted,
27605
28452
  // While this ceiling is the smaller bound the poll retries within the attempt; once the attempt's
27606
28453
  // remainder falls below it, one stalled request can spend the rest.
@@ -27751,9 +28598,38 @@ var TokensByChainMapSchema = v__namespace.custom(
27751
28598
  );
27752
28599
  var TokensListSchema = v__namespace.array(XTokenSchema);
27753
28600
  var ReserveAssetsSchema = v__namespace.array(AddressSchema);
28601
+ var ORACLE_CANDLE_INTERVALS = ["1m", "5m", "1h", "1d"];
28602
+ var OracleCandleIntervalSchema = v__namespace.picklist(ORACLE_CANDLE_INTERVALS);
28603
+ var OracleMarketsResponseSchema = v__namespace.object({
28604
+ quote: v__namespace.string(),
28605
+ intervals: v__namespace.array(
28606
+ v__namespace.object({
28607
+ key: v__namespace.string(),
28608
+ label: v__namespace.string(),
28609
+ seconds: v__namespace.number()
28610
+ })
28611
+ ),
28612
+ symbols: v__namespace.array(v__namespace.string())
28613
+ });
28614
+ var OracleCandlesResponseSchema = v__namespace.object({
28615
+ symbol: v__namespace.string(),
28616
+ quote: v__namespace.string(),
28617
+ interval: OracleCandleIntervalSchema,
28618
+ candles: v__namespace.array(
28619
+ v__namespace.object({
28620
+ timestamp: v__namespace.number(),
28621
+ open: v__namespace.string(),
28622
+ high: v__namespace.string(),
28623
+ low: v__namespace.string(),
28624
+ close: v__namespace.string(),
28625
+ final: v__namespace.optional(v__namespace.boolean())
28626
+ })
28627
+ )
28628
+ });
27754
28629
 
27755
28630
  // src/backendApi/guards.ts
27756
28631
  var isFillEvent = (value) => v__namespace.is(FillEventSchema, value);
28632
+ var isOracleCandleInterval = (value) => v__namespace.is(OracleCandleIntervalSchema, value);
27757
28633
  function decodePacketIntentTarget(payload) {
27758
28634
  try {
27759
28635
  const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
@@ -27773,6 +28649,34 @@ function selectSolvedIntentPacket(packets, intentsContract) {
27773
28649
  return packets.reduce((highest, packet) => packet.conn_sn > highest.conn_sn ? packet : highest);
27774
28650
  }
27775
28651
 
28652
+ // src/swap/speed-tier.ts
28653
+ var SPEED_TIER_SECONDS = {
28654
+ /** Either token maps to a money-market-reserve (sodaAsset) hub asset. */
28655
+ sodaAsset: 15,
28656
+ /** Anything else / default. */
28657
+ default: 35,
28658
+ /** Added once when either src or dst is an Ethereum asset. */
28659
+ ethereumPenalty: 10
28660
+ };
28661
+ var SPEED_TIER_THRESHOLDS = {
28662
+ fast: 20,
28663
+ normal: 30
28664
+ };
28665
+ var isEthereumToken = (token) => token.chainKey === ChainKeys.ETHEREUM_MAINNET;
28666
+ var secondsToTier = (seconds) => {
28667
+ if (seconds <= SPEED_TIER_THRESHOLDS.fast) return "fast";
28668
+ if (seconds <= SPEED_TIER_THRESHOLDS.normal) return "normal";
28669
+ return "slow";
28670
+ };
28671
+ function estimateSwapSpeedTier({ srcToken, dstToken }, isSodaAssetRelated) {
28672
+ const eitherSodaAsset = isSodaAssetRelated(srcToken.hubAsset) || isSodaAssetRelated(dstToken.hubAsset);
28673
+ let estimatedSeconds = eitherSodaAsset ? SPEED_TIER_SECONDS.sodaAsset : SPEED_TIER_SECONDS.default;
28674
+ if (isEthereumToken(srcToken) || isEthereumToken(dstToken)) {
28675
+ estimatedSeconds += SPEED_TIER_SECONDS.ethereumPenalty;
28676
+ }
28677
+ return { tier: secondsToTier(estimatedSeconds), estimatedSeconds };
28678
+ }
28679
+
27776
28680
  // src/swap/detailedStatus.ts
27777
28681
  var DETAILED_STATUS_NOT_DELIVERED = "relay_not_delivered";
27778
28682
  function isBackendSubmitTxAbandoned(data) {
@@ -27929,7 +28833,13 @@ var SwapService = class {
27929
28833
  * falls through to carries its own {@link RECONCILE_TIMEOUT_MS}, so a bounded call can cost both.
27930
28834
  */
27931
28835
  async resolveSolverStatus(request, timeoutMs) {
27932
- const solverResult = await SolverApiService.getStatus(request, this.solver, this.config.logger, timeoutMs);
28836
+ const solverResult = await SolverApiService.getStatus(
28837
+ request,
28838
+ this.solver,
28839
+ this.config.logger,
28840
+ timeoutMs,
28841
+ this.config.apiKey
28842
+ );
27933
28843
  const forgotten = !solverResult.ok || solverResult.value.status === exports.SolverIntentStatusCode.NOT_FOUND;
27934
28844
  if (!forgotten) return solverResult;
27935
28845
  const timeout = Math.min(RECONCILE_TIMEOUT_MS, this.backendApi.requestTimeoutMs);
@@ -28078,7 +28988,7 @@ var SwapService = class {
28078
28988
  */
28079
28989
  async postExecution(request) {
28080
28990
  try {
28081
- const result = await SolverApiService.postExecution(request, this.solver, this.config.logger);
28991
+ const result = await SolverApiService.postExecution(request, this.solver, this.config.logger, this.config.apiKey);
28082
28992
  if (result.ok) return result;
28083
28993
  const detail = result.error?.detail ?? {
28084
28994
  code: -999,
@@ -28309,6 +29219,9 @@ var SwapService = class {
28309
29219
  const outcome = await runBackendSubmitTx({
28310
29220
  attempt,
28311
29221
  api: this.backendApi.swaps,
29222
+ // The configured key is already baked into the SwapsApiService headers, so only this
29223
+ // per-action override (mirroring `extras.partnerFee`) travels per call.
29224
+ overrideConfig: { apiKey: _params.extras?.apiKey },
28312
29225
  body: {
28313
29226
  txHash: spokeTxHash,
28314
29227
  srcChainKey,
@@ -29057,6 +29970,19 @@ var SwapService = class {
29057
29970
  getSupportedSwapTokens() {
29058
29971
  return this.config.getSupportedSwapTokens();
29059
29972
  }
29973
+ /**
29974
+ * Offline, rule-based estimate of how fast a `srcToken`→`dstToken` swap will settle.
29975
+ *
29976
+ * Derived purely from SDK config (no network / on-chain / backend call): tokens tied to a
29977
+ * money-market-reserve sodaAsset settle faster, and an Ethereum leg adds a fixed penalty. See
29978
+ * {@link estimateSwapSpeedTier} for the rules.
29979
+ *
29980
+ * @param params `{ srcToken, dstToken }` spoke token pair to estimate
29981
+ * @returns the estimated `tier` bucket and `estimatedSeconds`
29982
+ */
29983
+ getSwapSpeedTier(params) {
29984
+ return estimateSwapSpeedTier(params, (hubAsset) => this.config.isMoneyMarketReserveHubAsset(hubAsset));
29985
+ }
29060
29986
  };
29061
29987
 
29062
29988
  // src/migration/errors.ts
@@ -31135,100 +32061,6 @@ var MigrationService = class {
31135
32061
  }
31136
32062
  };
31137
32063
 
31138
- // src/backendApi/api-utils.ts
31139
- var BackendHttpError = class extends Error {
31140
- status;
31141
- bodyText;
31142
- /** Parsed JSON, or `undefined` for empty or malformed bodies. */
31143
- body;
31144
- constructor(status, bodyText) {
31145
- super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
31146
- this.name = "BackendHttpError";
31147
- this.status = status;
31148
- this.bodyText = bodyText;
31149
- this.body = safeJsonParse(bodyText);
31150
- }
31151
- };
31152
- function isBackendHttpError(error) {
31153
- if (error instanceof BackendHttpError) return true;
31154
- return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
31155
- }
31156
- function safeJsonParse(text) {
31157
- if (text.length === 0) return void 0;
31158
- try {
31159
- return JSON.parse(text);
31160
- } catch {
31161
- return void 0;
31162
- }
31163
- }
31164
- function trimTrailingSlashes(baseURL) {
31165
- let end = baseURL.length;
31166
- while (end > 0 && baseURL[end - 1] === "/") end -= 1;
31167
- return baseURL.slice(0, end);
31168
- }
31169
- var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
31170
- async function makeRequest(params) {
31171
- const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
31172
- const baseURL = overrideConfig.baseURL || config.baseURL || "";
31173
- const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
31174
- const headers = { ...config.headers, ...overrideConfig.headers };
31175
- const controller = new AbortController();
31176
- const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
31177
- const timeoutId = setTimeout(() => controller.abort(), timeout);
31178
- try {
31179
- const response = await fetch(url, {
31180
- method: config.method,
31181
- headers,
31182
- body: config.body,
31183
- signal: controller.signal
31184
- });
31185
- if (!response.ok) {
31186
- const errorText = await response.text();
31187
- throw new BackendHttpError(response.status, errorText);
31188
- }
31189
- const data = await response.json();
31190
- return data;
31191
- } catch (error) {
31192
- if (error instanceof Error) {
31193
- if (error.name === "AbortError") {
31194
- throw new Error("REQUEST_TIMEOUT", { cause: new Error(`Request timeout after ${timeout}ms`) });
31195
- }
31196
- logger.error(`[${serviceLabel}] Request error`, error);
31197
- throw error;
31198
- }
31199
- logger.error(`[${serviceLabel}] Unknown error`, error);
31200
- throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
31201
- } finally {
31202
- clearTimeout(timeoutId);
31203
- }
31204
- }
31205
- function resolveRequestConfig(config, defaults) {
31206
- const { baseURL, timeout, headers, ...rest } = config;
31207
- return {
31208
- ...rest,
31209
- baseURL: baseURL || defaults.baseURL,
31210
- timeout: timeout ?? defaults.timeout,
31211
- headers: { ...defaults.headers, ...headers }
31212
- };
31213
- }
31214
- function toExternalApiError(params) {
31215
- const { api, feature, endpoint, error } = params;
31216
- const context = { api, endpoint };
31217
- if (isBackendHttpError(error)) context.status = error.status;
31218
- return new SodaxError(
31219
- "EXTERNAL_API_ERROR",
31220
- error instanceof Error ? error.message : `Request to ${endpoint} failed`,
31221
- { feature, cause: error, context }
31222
- );
31223
- }
31224
- function toInvalidResponseShapeError(params) {
31225
- const { api, feature, endpoint, issues } = params;
31226
- return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
31227
- feature,
31228
- context: { api, endpoint, reason: "invalid_response_shape", issues }
31229
- });
31230
- }
31231
-
31232
32064
  // src/backendApi/apiConfig.ts
31233
32065
  function flatLayer({ baseURL, timeout, headers }) {
31234
32066
  return { baseURL, timeout, headers };
@@ -31331,7 +32163,7 @@ var SwapsApiService = class _SwapsApiService {
31331
32163
  trimsLegacyOverrides;
31332
32164
  constructor(config, logger = consoleLogger, options = {}) {
31333
32165
  this.config = config;
31334
- this.headers = { ...config.headers };
32166
+ this.headers = mergeHeaders(config.headers);
31335
32167
  this.logger = logger;
31336
32168
  this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
31337
32169
  }
@@ -31347,7 +32179,7 @@ var SwapsApiService = class _SwapsApiService {
31347
32179
  const override = overrideConfig?.baseURL;
31348
32180
  const baseUrl = override ? this.trimsLegacyOverrides ? stripLegacyBackendMount(override) : override : this.config.baseURL;
31349
32181
  const timeout = overrideConfig?.timeout ?? this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
31350
- const headers = { ...this.headers, ...overrideConfig?.headers };
32182
+ const headers = mergeHeaders(this.headers, apiKeyHeader(overrideConfig?.apiKey), overrideConfig?.headers);
31351
32183
  return new swapsApi.SwapsApi({ baseUrl, headers, timeout });
31352
32184
  }
31353
32185
  /**
@@ -31373,6 +32205,11 @@ var SwapsApiService = class _SwapsApiService {
31373
32205
  context.issues = issues instanceof v__namespace.ValiError ? v__namespace.flatten(issues.issues) : issues;
31374
32206
  }
31375
32207
  if (error.context.status !== void 0) context.status = error.context.status;
32208
+ if (isAuthStatus(error.context.status)) {
32209
+ this.logger.warn(
32210
+ `[SwapsApiService] ${endpoint} was rejected by the swaps API key guard (${error.context.status}). Configure a valid partner API key \u2014 new Sodax({ apiKey }) \u2014 see docs/CONFIGURE_SDK.md.`
32211
+ );
32212
+ }
31376
32213
  }
31377
32214
  this.logger.error(`[SwapsApiService] Request to ${endpoint} failed`, error);
31378
32215
  return {
@@ -31524,9 +32361,7 @@ var SwapsApiService = class _SwapsApiService {
31524
32361
  * every subsequent call (the delegated client is rebuilt per call).
31525
32362
  */
31526
32363
  setHeaders(headers) {
31527
- Object.entries(headers).forEach(([key, value]) => {
31528
- this.headers[key] = value;
31529
- });
32364
+ assignHeaders(this.headers, headers);
31530
32365
  }
31531
32366
  /** Return the base URL the service is currently pointing at. */
31532
32367
  getBaseURL() {
@@ -31567,13 +32402,22 @@ var SponsoringApiService = class {
31567
32402
  config;
31568
32403
  headers;
31569
32404
  logger;
31570
- constructor(config, logger = consoleLogger) {
32405
+ inheritedApiKey;
32406
+ inheritedApiKeyBaseURLs;
32407
+ constructor(config, logger = consoleLogger, options = {}) {
31571
32408
  this.config = config;
31572
- this.headers = {
31573
- ...config.apiKey !== void 0 ? { "x-api-key": config.apiKey } : {},
31574
- ...config.headers
31575
- };
32409
+ this.headers = mergeHeaders(apiKeyHeader(config.apiKey), config.headers);
31576
32410
  this.logger = logger;
32411
+ this.inheritedApiKey = options.inheritedApiKey;
32412
+ this.inheritedApiKeyBaseURLs = (options.inheritedApiKeyBaseURLs ?? []).map(trimTrailingSlashes);
32413
+ }
32414
+ /**
32415
+ * The inherited instance key, but only for a request whose effective target is an allowed root.
32416
+ * Evaluated per call because a `RequestOverrideConfig.baseURL` retargets the request.
32417
+ */
32418
+ inheritedKeyFor(baseURL) {
32419
+ if (!this.inheritedApiKey) return void 0;
32420
+ return this.inheritedApiKeyBaseURLs.includes(trimTrailingSlashes(baseURL)) ? this.inheritedApiKey : void 0;
31577
32421
  }
31578
32422
  /**
31579
32423
  * Validate a response while preserving HTTP failures on `error.cause` for
@@ -31581,9 +32425,10 @@ var SponsoringApiService = class {
31581
32425
  */
31582
32426
  async request(endpoint, config, schema) {
31583
32427
  try {
32428
+ const inherited = apiKeyHeader(this.inheritedKeyFor(config.baseURL || this.config.baseURL));
31584
32429
  const raw = await makeRequest({
31585
32430
  endpoint,
31586
- config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
32431
+ config: resolveRequestConfig(config, { ...this.config, headers: mergeHeaders(inherited, this.headers) }),
31587
32432
  logger: this.logger,
31588
32433
  serviceLabel: "SponsoringApiService"
31589
32434
  });
@@ -31625,9 +32470,7 @@ var SponsoringApiService = class {
31625
32470
  );
31626
32471
  }
31627
32472
  setHeaders(headers) {
31628
- Object.entries(headers).forEach(([key, value]) => {
31629
- this.headers[key] = value;
31630
- });
32473
+ assignHeaders(this.headers, headers);
31631
32474
  }
31632
32475
  getBaseURL() {
31633
32476
  return this.config.baseURL;
@@ -31858,18 +32701,7 @@ var BridgeApiService = class {
31858
32701
  }
31859
32702
  return { ok: true, value: parsed.output };
31860
32703
  } catch (error) {
31861
- return {
31862
- ok: false,
31863
- error: new SodaxError(
31864
- "EXTERNAL_API_ERROR",
31865
- error instanceof Error ? error.message : `Request to ${endpoint} failed`,
31866
- {
31867
- feature: "backend",
31868
- cause: error,
31869
- context: { api: "bridge", endpoint }
31870
- }
31871
- )
31872
- };
32704
+ return { ok: false, error: toExternalApiError({ api: "bridge", feature: "backend", endpoint, error }) };
31873
32705
  }
31874
32706
  }
31875
32707
  // ──────────────────────────────────────────────────────────────────────
@@ -32028,9 +32860,7 @@ var BridgeApiService = class {
32028
32860
  * keys are overwritten; keys absent from `headers` are preserved.
32029
32861
  */
32030
32862
  setHeaders(headers) {
32031
- Object.entries(headers).forEach(([key, value]) => {
32032
- this.headers[key] = value;
32033
- });
32863
+ assignHeaders(this.headers, headers);
32034
32864
  }
32035
32865
  /** Return the base URL the service is currently pointing at. */
32036
32866
  getBaseURL() {
@@ -32075,8 +32905,8 @@ var BackendApiService = class {
32075
32905
  * left exactly as given rather than having a real path segment eaten.
32076
32906
  */
32077
32907
  trimsLegacyOverrides;
32078
- constructor(config, logger = consoleLogger) {
32079
- this.config = resolveBaseApiConfig(config);
32908
+ constructor(config, logger = consoleLogger, options = {}) {
32909
+ this.config = withApiKey(resolveBaseApiConfig(config), options.apiKey);
32080
32910
  this.headers = { ...this.config.headers };
32081
32911
  this.logger = logger;
32082
32912
  this.trimsLegacyOverrides = !hasExplicitBasePath(config);
@@ -32101,9 +32931,12 @@ var BackendApiService = class {
32101
32931
  );
32102
32932
  }
32103
32933
  const overrideOptions = { trimLegacyOverrides: this.trimsLegacyOverrides };
32104
- this.swaps = new SwapsApiService(swapsConfig2, this.logger, overrideOptions);
32105
- this.sponsoring = new SponsoringApiService(sponsoringConfig, this.logger);
32106
- this.bridge = new BridgeApiService(bridgeConfig2, this.logger, overrideOptions);
32934
+ this.swaps = new SwapsApiService(withApiKey(swapsConfig2, options.apiKey), this.logger, overrideOptions);
32935
+ this.sponsoring = new SponsoringApiService(sponsoringConfig, this.logger, {
32936
+ inheritedApiKey: options.apiKey,
32937
+ inheritedApiKeyBaseURLs: [DEFAULT_SPONSORING_API_ENDPOINT, this.config.baseURL]
32938
+ });
32939
+ this.bridge = new BridgeApiService(withApiKey(bridgeConfig2, options.apiKey), this.logger, overrideOptions);
32107
32940
  }
32108
32941
  /**
32109
32942
  * Issue the HTTP call for a route.
@@ -32329,6 +33162,46 @@ var BackendApiService = class {
32329
33162
  const endpoint = `/moneymarket/borrowers?${queryString}`;
32330
33163
  return this.request(endpoint, { ...config, method: "GET" }, MoneyMarketBorrowersSchema);
32331
33164
  }
33165
+ // Oracle endpoints
33166
+ /**
33167
+ * Fetch the oracle candle store's discovery payload: the quote currency (currently always
33168
+ * `"USD"`), the selectable candle intervals, and the canonical symbols that have candle data.
33169
+ *
33170
+ * Use this to populate a symbol picker and interval switcher before calling
33171
+ * {@link getOracleCandles}.
33172
+ *
33173
+ * @returns `Result<OracleMarketsResponse>` — on success, `{ quote, intervals, symbols }`.
33174
+ */
33175
+ async getOracleMarkets(config) {
33176
+ return this.request("/oracle/markets", { ...config, method: "GET" }, OracleMarketsResponseSchema);
33177
+ }
33178
+ /**
33179
+ * Fetch USD OHLC candles for a symbol over the half-open time range `[from, to)`.
33180
+ *
33181
+ * `from` and `to` are UNIX **seconds** (integers); `to` is exclusive and must exceed `from`,
33182
+ * and the range may cover at most 5000 buckets of the requested interval (invalid or wider
33183
+ * ranges fail with HTTP 400). A valid range with no stored candles resolves `ok` with
33184
+ * `candles: []`; an unknown symbol currently does the same rather than returning 404. The last
33185
+ * candle may still be forming; re-poll while its `final === false`.
33186
+ * Responses are cached server-side for roughly 10 seconds per distinct URL.
33187
+ *
33188
+ * @param params.symbol - Canonical symbol, exact case, from {@link getOracleMarkets} (e.g. `"ETH"`).
33189
+ * @param params.interval - Candle bucket size: `'1m' | '5m' | '1h' | '1d'`.
33190
+ * @param params.from - Range start, UNIX seconds, inclusive.
33191
+ * @param params.to - Range end, UNIX seconds, exclusive.
33192
+ * @returns `Result<OracleCandlesResponse>` — on success, the echoed query dimensions and
33193
+ * oldest-first candles with USD decimal-string prices (no volume field).
33194
+ */
33195
+ async getOracleCandles(params, config) {
33196
+ const queryParams = new URLSearchParams();
33197
+ queryParams.append("symbol", params.symbol);
33198
+ queryParams.append("interval", params.interval);
33199
+ queryParams.append("from", String(params.from));
33200
+ queryParams.append("to", String(params.to));
33201
+ const queryString = queryParams.toString();
33202
+ const endpoint = `/oracle/candles?${queryString}`;
33203
+ return this.request(endpoint, { ...config, method: "GET" }, OracleCandlesResponseSchema);
33204
+ }
32332
33205
  /**
32333
33206
  * Fetch the complete SODAX runtime configuration in a single request.
32334
33207
  *
@@ -32474,9 +33347,7 @@ var BackendApiService = class {
32474
33347
  * @param headers - Key-value pairs to add or overwrite in the default headers.
32475
33348
  */
32476
33349
  setHeaders(headers) {
32477
- Object.entries(headers).forEach(([key, value]) => {
32478
- this.headers[key] = value;
32479
- });
33350
+ assignHeaders(this.headers, headers);
32480
33351
  this.swaps.setHeaders(headers);
32481
33352
  this.bridge.setHeaders(headers);
32482
33353
  }
@@ -32945,6 +33816,9 @@ var BridgeService = class {
32945
33816
  const outcome = await runBackendSubmitTx({
32946
33817
  attempt,
32947
33818
  api: this.backendApi.bridge,
33819
+ // The configured key is already baked into the BridgeApiService headers, so only this
33820
+ // per-action override (mirroring `extras.partnerFee`) travels per call.
33821
+ overrideConfig: { apiKey: _params.extras?.apiKey },
32948
33822
  body: {
32949
33823
  txHash: spokeTxHash,
32950
33824
  srcChainKey,
@@ -40957,7 +41831,8 @@ var PartnerFeeClaimService = class {
40957
41831
  const solverExecutionResponse = await SolverApiService.postExecution(
40958
41832
  { intent_tx_hash: intentTxHash },
40959
41833
  this.config.solver,
40960
- this.config.logger
41834
+ this.config.logger,
41835
+ this.config.apiKey
40961
41836
  );
40962
41837
  if (!solverExecutionResponse.ok) {
40963
41838
  return solverExecutionResponse;
@@ -41961,7 +42836,12 @@ var LeverageYieldService = class {
41961
42836
  */
41962
42837
  async notifySolver(request) {
41963
42838
  try {
41964
- const result = await SolverApiService.postExecution(request, this.config.solver, this.config.logger);
42839
+ const result = await SolverApiService.postExecution(
42840
+ request,
42841
+ this.config.solver,
42842
+ this.config.logger,
42843
+ this.config.apiKey
42844
+ );
41965
42845
  if (result.ok) return result;
41966
42846
  const detail = result.error?.detail ?? {
41967
42847
  code: -999,
@@ -42512,7 +43392,7 @@ function xlmDecimalToStroops(amount) {
42512
43392
  const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
42513
43393
  return BigInt(scaled);
42514
43394
  }
42515
- var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
43395
+ var STELLAR_BASE_RESERVE_STROOPS2 = 5000000n;
42516
43396
  var BASE_RESERVE_UNITS = 2;
42517
43397
  function parseBaseReserveStroops(ledger) {
42518
43398
  const value = ledger?.base_reserve_in_stroops;
@@ -42539,7 +43419,7 @@ var SPONSOR_CONFIG_TTL_MS = 6e4;
42539
43419
  var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
42540
43420
  var DEFAULT_MAX_HORIZON_RETRIES = 2;
42541
43421
  var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
42542
- var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS + STELLAR_FEE_HEADROOM_STROOPS;
43422
+ var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS2 + STELLAR_FEE_HEADROOM_STROOPS;
42543
43423
  var SponsoringService = class {
42544
43424
  config;
42545
43425
  spoke;
@@ -42642,7 +43522,7 @@ var SponsoringService = class {
42642
43522
  reason: messageOf(error, String(error))
42643
43523
  });
42644
43524
  }
42645
- return STELLAR_BASE_RESERVE_STROOPS;
43525
+ return STELLAR_BASE_RESERVE_STROOPS2;
42646
43526
  };
42647
43527
  const request = read().then((value) => {
42648
43528
  this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
@@ -42654,18 +43534,18 @@ var SponsoringService = class {
42654
43534
  return request;
42655
43535
  }
42656
43536
  /**
42657
- * Cache key for a config request: the resolved base URL plus any per-call
42658
- * headers. Headers can select a different response from the same URL — an API
42659
- * key scoped to another deployment, or a test harness's scenario header — so
42660
- * folding them in stops one caller's override from being served to, or
42661
- * overwriting, the default path. Kept in memory as a Map key only.
43537
+ * Cache key for a config request: the resolved base URL plus the per-call headers the request will
43538
+ * actually carry, `apiKey` included. Headers can select a different response from the same URL — an
43539
+ * API key scoped to another deployment, or a test harness's scenario header — so folding them in
43540
+ * stops one caller's override from being served to, or overwriting, the default path. Names are
43541
+ * lower-cased before sorting and serialized as JSON so casing and delimiters cannot collide two
43542
+ * distinct header sets onto one key. Kept in memory as a Map key only.
42662
43543
  */
42663
43544
  configCacheKey(requestConfig) {
42664
43545
  const baseURL = requestConfig?.baseURL || this.api.sponsoring.getBaseURL();
42665
- const headers = requestConfig?.headers;
42666
- if (!headers) return baseURL;
42667
- const normalized = Object.keys(headers).sort().map((name) => `${name.toLowerCase()}=${headers[name]}`).join("&");
42668
- return normalized.length === 0 ? baseURL : `${baseURL}|${normalized}`;
43546
+ const headers = mergeHeaders(apiKeyHeader(requestConfig?.apiKey), requestConfig?.headers);
43547
+ const entries = Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
43548
+ return entries.length === 0 ? baseURL : `${baseURL}|${JSON.stringify(entries)}`;
42669
43549
  }
42670
43550
  /**
42671
43551
  * Fetch sponsor config with per-endpoint caching and in-flight deduplication.
@@ -42891,17 +43771,20 @@ var Sodax = class {
42891
43771
  const logger = resolveLogger(options?.logger);
42892
43772
  const analytics = resolveAnalytics(options?.analytics);
42893
43773
  const fee = options?.fee;
43774
+ const apiKey = options?.apiKey || void 0;
42894
43775
  const radfiSigner = options?.radfi?.signRequest;
42895
- this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
42896
- this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
43776
+ const mergeOptions = options ? { ...options, apiKey: void 0 } : void 0;
43777
+ this.instanceConfig = mergeOptions ? mergeSodaxConfig(sodaxConfig, mergeOptions) : sodaxConfig;
43778
+ this.backendApi = new BackendApiService(this.instanceConfig.api, logger, { apiKey });
42897
43779
  this.api = this.backendApi;
42898
43780
  this.config = new ConfigService({
42899
43781
  api: this.backendApi,
42900
43782
  config: this.instanceConfig,
42901
- userConfig: options,
43783
+ userConfig: mergeOptions,
42902
43784
  logger,
42903
43785
  analytics,
42904
43786
  fee,
43787
+ apiKey,
42905
43788
  radfiSigner
42906
43789
  });
42907
43790
  this.hubProvider = new EvmHubProvider({ config: this.config });
@@ -43093,6 +43976,7 @@ exports.NEAR_CHAIN_KEYS_SET = NEAR_CHAIN_KEYS_SET;
43093
43976
  exports.NEAR_DEFAULT_GAS = NEAR_DEFAULT_GAS;
43094
43977
  exports.NEAR_STORAGE_DEPOSIT = NEAR_STORAGE_DEPOSIT;
43095
43978
  exports.NearSpokeService = NearSpokeService;
43979
+ exports.ORACLE_CANDLE_INTERVALS = ORACLE_CANDLE_INTERVALS;
43096
43980
  exports.PartnerFeeClaimService = PartnerFeeClaimService;
43097
43981
  exports.PartnerService = PartnerService;
43098
43982
  exports.Permit2Service = Permit2Service;
@@ -43113,6 +43997,8 @@ exports.SOLANA_CHAIN_KEYS = SOLANA_CHAIN_KEYS;
43113
43997
  exports.SOLANA_CHAIN_KEYS_SET = SOLANA_CHAIN_KEYS_SET;
43114
43998
  exports.SONIC_CHAIN_KEYS = SONIC_CHAIN_KEYS;
43115
43999
  exports.SONIC_CHAIN_KEYS_SET = SONIC_CHAIN_KEYS_SET;
44000
+ exports.SPEED_TIER_SECONDS = SPEED_TIER_SECONDS;
44001
+ exports.SPEED_TIER_THRESHOLDS = SPEED_TIER_THRESHOLDS;
43116
44002
  exports.SPONSORING_API_ERROR_CODES = SPONSORING_API_ERROR_CODES;
43117
44003
  exports.SPONSORING_API_STELLAR_BASE_PATH = SPONSORING_API_STELLAR_BASE_PATH;
43118
44004
  exports.SPONSOR_CONFIG_TTL_MS = SPONSOR_CONFIG_TTL_MS;
@@ -43189,6 +44075,7 @@ exports.concentratedLiquidityConfig = concentratedLiquidityConfig;
43189
44075
  exports.connectionAbi = connectionAbi;
43190
44076
  exports.consoleLogger = consoleLogger;
43191
44077
  exports.convertTransactionInstructionToRaw = convertTransactionInstructionToRaw;
44078
+ exports.createBalanceCollector = createBalanceCollector;
43192
44079
  exports.createInvariant = createInvariant;
43193
44080
  exports.deepMerge = deepMerge;
43194
44081
  exports.defaultHookAbi = defaultHookAbi;
@@ -43202,6 +44089,7 @@ exports.encodeContractCalls = encodeContractCalls;
43202
44089
  exports.erc20Abi = erc20Abi;
43203
44090
  exports.erc4626Abi = erc4626Abi;
43204
44091
  exports.estimateBitcoinTxSize = estimateBitcoinTxSize;
44092
+ exports.estimateSwapSpeedTier = estimateSwapSpeedTier;
43205
44093
  exports.ethereumSupportedTokens = ethereumSupportedTokens;
43206
44094
  exports.executionFailed = executionFailed;
43207
44095
  exports.formatBasisPoints = formatBasisPoints;
@@ -43254,6 +44142,8 @@ exports.iconSupportedTokens = iconSupportedTokens;
43254
44142
  exports.injectiveSupportedTokens = injectiveSupportedTokens;
43255
44143
  exports.intentCreationFailed = intentCreationFailed;
43256
44144
  exports.isApprovalSupportedChainKeyType = isApprovalSupportedChainKeyType;
44145
+ exports.isAuthFailure = isAuthFailure;
44146
+ exports.isAuthStatus = isAuthStatus;
43257
44147
  exports.isBackendHttpError = isBackendHttpError;
43258
44148
  exports.isBalnMigrateParams = isBalnMigrateParams;
43259
44149
  exports.isBitcoinChainKey = isBitcoinChainKey;
@@ -43319,6 +44209,7 @@ exports.isNewbnUSDToken = isNewbnUSDToken;
43319
44209
  exports.isOptionalBitcoinWalletProviderType = isOptionalBitcoinWalletProviderType;
43320
44210
  exports.isOptionalEvmWalletProviderType = isOptionalEvmWalletProviderType;
43321
44211
  exports.isOptionalStellarWalletProviderType = isOptionalStellarWalletProviderType;
44212
+ exports.isOracleCandleInterval = isOracleCandleInterval;
43322
44213
  exports.isPartnerError = isPartnerError;
43323
44214
  exports.isPartnerFeeAmount = isPartnerFeeAmount;
43324
44215
  exports.isPartnerFeePercentage = isPartnerFeePercentage;
@@ -43420,6 +44311,7 @@ exports.reverseEncodeAddress = reverseEncodeAddress;
43420
44311
  exports.robinhoodChain = robinhoodChain;
43421
44312
  exports.robinhoodSupportedTokens = robinhoodSupportedTokens;
43422
44313
  exports.serializeAddressData = serializeAddressData;
44314
+ exports.settleWalletBalances = settleWalletBalances;
43423
44315
  exports.silentLogger = silentLogger;
43424
44316
  exports.sleep = sleep;
43425
44317
  exports.sodaxConfig = sodaxConfig;