@sodax/sdk 2.0.0 → 2.1.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.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getAbiItem, parseAbi, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, defineChain, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, stringToBytes, fromHex, encodePacked, decodeAbiParameters, parseEventLogs, maxUint160, maxUint48, fallback } from 'viem';
2
2
  import { bcs } from '@mysten/sui/bcs';
3
3
  import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram, TransactionMessage, TransactionInstruction } from '@solana/web3.js';
4
- import { rpc, Address, xdr, Account, Horizon, Contract, TransactionBuilder, nativeToScVal, TimeoutInfinite, scValToBigInt, Operation, Asset, FeeBumpTransaction } from '@stellar/stellar-sdk';
4
+ import { rpc, Address, xdr, Account, Horizon, Contract, TransactionBuilder, nativeToScVal, TimeoutInfinite, scValToBigInt, Operation, Asset, FeeBumpTransaction, NotFoundError, Networks, Keypair } from '@stellar/stellar-sdk';
5
5
  import { serializeCV, Cl, deserializeCV, cvToString, createNetwork, fetchFeeEstimateTransaction, fetchCallReadOnlyFunction, parseContractId, PostConditionMode, noneCV, someCV, uintCV, getAddressFromPublicKey, makeUnsignedContractCall, serializePayloadBytes } from '@sodax/libs/stacks/core';
6
6
  import { hedera, kaia, redbellyMainnet, mainnet, lightlinkPhoenix, polygon, bsc, optimism, base, arbitrum, avalanche, sonic } from 'viem/chains';
7
7
  import * as rlp from 'rlp';
@@ -17,7 +17,7 @@ import * as IconSdkRaw from 'icon-sdk-js';
17
17
  import { ChainGrpcWasmApi, TxGrpcApi, toBase64, fromBase64, MsgExecuteContract, ChainRestAuthApi, BaseAccount, createTransaction } from '@injectivelabs/sdk-ts';
18
18
  import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
19
19
  import { getNetworkEndpoints, Network } from '@injectivelabs/networks';
20
- import * as v2 from 'valibot';
20
+ import * as v7 from 'valibot';
21
21
  import { SwapsApi, SwapsApiError } from '@sodax/swaps-api';
22
22
  export { SwapsApiError } from '@sodax/swaps-api';
23
23
  import BigNumber5, { BigNumber } from 'bignumber.js';
@@ -94,8 +94,8 @@ function serializeCause(cause, depth) {
94
94
  }
95
95
  function sanitizeContext(value, depth) {
96
96
  const out = {};
97
- for (const [key, v4] of Object.entries(value)) {
98
- out[key] = sanitizeValue(v4, depth + 1);
97
+ for (const [key, v9] of Object.entries(value)) {
98
+ out[key] = sanitizeValue(v9, depth + 1);
99
99
  }
100
100
  return out;
101
101
  }
@@ -106,13 +106,13 @@ function sanitizeValue(value, depth) {
106
106
  if (t === "bigint") return value.toString();
107
107
  if (t === "string" || t === "number" || t === "boolean") return value;
108
108
  if (t === "function" || t === "symbol") return safeString(value);
109
- if (Array.isArray(value)) return value.map((v4) => sanitizeValue(v4, depth + 1));
109
+ if (Array.isArray(value)) return value.map((v9) => sanitizeValue(v9, depth + 1));
110
110
  if (value instanceof Date) return value.toISOString();
111
111
  if (value instanceof Map) {
112
- return Array.from(value.entries()).map(([k, v4]) => [sanitizeValue(k, depth + 1), sanitizeValue(v4, depth + 1)]);
112
+ return Array.from(value.entries()).map(([k, v9]) => [sanitizeValue(k, depth + 1), sanitizeValue(v9, depth + 1)]);
113
113
  }
114
114
  if (value instanceof Set) {
115
- return Array.from(value.values()).map((v4) => sanitizeValue(v4, depth + 1));
115
+ return Array.from(value.values()).map((v9) => sanitizeValue(v9, depth + 1));
116
116
  }
117
117
  if (value instanceof Error) return { name: value.name, message: value.message };
118
118
  if (t === "object") {
@@ -124,9 +124,9 @@ function sanitizeValue(value, depth) {
124
124
  }
125
125
  return safeString(value);
126
126
  }
127
- function safeString(v4) {
127
+ function safeString(v9) {
128
128
  try {
129
- return String(v4);
129
+ return String(v9);
130
130
  } catch {
131
131
  return "[unserializable]";
132
132
  }
@@ -182,6 +182,7 @@ var SODAX_FEATURES = [
182
182
  "partner",
183
183
  "recovery",
184
184
  "backend",
185
+ "sponsoring",
185
186
  "leverageYield"
186
187
  ];
187
188
 
@@ -484,7 +485,7 @@ var SodaTokens = {
484
485
  name: "Soda RBNT",
485
486
  decimals: 18,
486
487
  address: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac",
487
- chainKey: ChainKeys.REDBELLY_MAINNET,
488
+ chainKey: ChainKeys.SONIC_MAINNET,
488
489
  hubAsset: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac",
489
490
  vault: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac"
490
491
  },
@@ -3496,6 +3497,8 @@ var DEFAULT_BACKEND_API_HEADERS = {
3496
3497
  };
3497
3498
  var DEFAULT_RELAYER_API_ENDPOINT = "https://xcall-relay.nw.iconblockchain.xyz";
3498
3499
  var VAULT_TOKEN_DECIMALS = 18;
3500
+ var DEFAULT_SPONSORING_API_ENDPOINT = "https://api.sodax.com/v1";
3501
+ var SPONSORING_API_STELLAR_BASE_PATH = "/sponsorships/stellar";
3499
3502
  var apiConfig = {
3500
3503
  baseURL: DEFAULT_BACKEND_API_ENDPOINT,
3501
3504
  timeout: DEFAULT_BACKEND_API_TIMEOUT,
@@ -4229,7 +4232,23 @@ var sodaxConfig = {
4229
4232
  relay: relayConfig
4230
4233
  };
4231
4234
 
4235
+ // ../types/dist/backend/sponsoringApi.js
4236
+ var SPONSORING_API_ERROR_CODES = [
4237
+ "INVALID_SPONSOR_XDR",
4238
+ "INVALID_RESERVE_DATA",
4239
+ "SPONSOR_SEQUENCE_CONFLICT",
4240
+ "SPONSOR_TRANSACTION_REJECTED",
4241
+ "HORIZON_UNAVAILABLE",
4242
+ "SPONSOR_RATE_LIMITED",
4243
+ "SPONSOR_BUDGET_EXHAUSTED"
4244
+ ];
4245
+
4232
4246
  // ../types/dist/bitcoin/bitcoin.js
4247
+ var BITCOIN_DUST_SATS = 546n;
4248
+ function isNativeBitcoinToken(chainConfig, token) {
4249
+ const nativeBtcTokens = new Set(["btc", chainConfig.nativeToken, chainConfig.supportedTokens.BTC?.address].filter((value) => !!value).map((value) => value.toLowerCase()));
4250
+ return nativeBtcTokens.has(token.toLowerCase());
4251
+ }
4233
4252
  function isSupportedBitcoinAddressType(addressType) {
4234
4253
  return BTC_ADDRESS_TYPES.includes(addressType);
4235
4254
  }
@@ -4389,7 +4408,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4389
4408
  }
4390
4409
 
4391
4410
  // ../types/dist/index.js
4392
- var CONFIG_VERSION = 220;
4411
+ var CONFIG_VERSION = 222;
4393
4412
  function isEvmSpokeChainConfig(value) {
4394
4413
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
4395
4414
  }
@@ -4500,6 +4519,9 @@ function isUndefinedOrValidWalletProviderForChainKey(chainKey, walletProvider) {
4500
4519
  function isOptionalBitcoinWalletProviderType(walletProvider) {
4501
4520
  return walletProvider === void 0 || isBitcoinWalletProviderType(walletProvider);
4502
4521
  }
4522
+ function isNativeBitcoinTransfer(config, chainKey, token) {
4523
+ return isBitcoinChainKeyType(chainKey) && !!token && isNativeBitcoinToken(config.getChainConfig(chainKey), token.address);
4524
+ }
4503
4525
  async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
4504
4526
  do {
4505
4527
  try {
@@ -4516,11 +4538,11 @@ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_R
4516
4538
  throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
4517
4539
  }
4518
4540
  function getRandomBytes(length) {
4519
- const array2 = new Uint8Array(length);
4541
+ const array3 = new Uint8Array(length);
4520
4542
  for (let i = 0; i < length; i++) {
4521
- array2[i] = Math.floor(Math.random() * 256);
4543
+ array3[i] = Math.floor(Math.random() * 256);
4522
4544
  }
4523
- return array2;
4545
+ return array3;
4524
4546
  }
4525
4547
  function randomUint256() {
4526
4548
  const bytes = getRandomBytes(32);
@@ -4682,6 +4704,7 @@ var HttpRelayError = class extends Error {
4682
4704
  }
4683
4705
  };
4684
4706
  var RELAY_REQUEST_TIMEOUT_MS = 15e3;
4707
+ var RELAY_FALLBACK_FLOOR_MS = 5e3;
4685
4708
  function isAbortError(error) {
4686
4709
  return error instanceof Error && error.name === "AbortError";
4687
4710
  }
@@ -13980,6 +14003,13 @@ var ConfigService = class {
13980
14003
  * a client-side option set via `new Sodax({ fee })`. Per-feature overrides live on the feature config.
13981
14004
  */
13982
14005
  fee;
14006
+ /**
14007
+ * RadFi/Bound request signer. Resolved once at construction and kept independent of {@link sodax}
14008
+ * so that {@link initialize}'s dynamic-config swap never clobbers it. Read by `BitcoinSpokeService`
14009
+ * via `config.radfiSigner`; `undefined` unless the consumer passed `radfi.signRequest` to
14010
+ * `new Sodax(...)`. Holds the function reference only — never a credential.
14011
+ */
14012
+ radfiSigner;
13983
14013
  initialized = false;
13984
14014
  // data structures for quick lookup
13985
14015
  supportedHubAssetsSet;
@@ -13993,11 +14023,12 @@ var ConfigService = class {
13993
14023
  hubAssetToXTokenMap;
13994
14024
  // `api` / `userConfig` are accepted but unused while initialize()'s dynamic fetch is disabled
13995
14025
  // (see TODO(config-v2) below); restore their assignments when re-enabling.
13996
- constructor({ api, config, userConfig, logger, analytics, fee }) {
14026
+ constructor({ api, config, userConfig, logger, analytics, fee, radfiSigner }) {
13997
14027
  this.sodax = config;
13998
14028
  this.logger = logger ?? resolveLogger(void 0);
13999
14029
  this.analytics = analytics ?? noopAnalytics;
14000
14030
  this.fee = fee;
14031
+ this.radfiSigner = radfiSigner;
14001
14032
  this.loadSodaxConfigDataStructures(config);
14002
14033
  }
14003
14034
  async initialize() {
@@ -14296,7 +14327,7 @@ function mergeSodaxConfig(base2, override) {
14296
14327
  }
14297
14328
  function encodeContractCalls(calls) {
14298
14329
  return encodeAbiParameters(parseAbiParameters("(address,uint256,bytes)[]"), [
14299
- calls.map((v4) => [v4.address, v4.value, v4.data])
14330
+ calls.map((v9) => [v9.address, v9.value, v9.data])
14300
14331
  ]);
14301
14332
  }
14302
14333
  async function waitForTransactionReceipt(hash, provider) {
@@ -15208,10 +15239,14 @@ var RadfiApiError = class extends Error {
15208
15239
  };
15209
15240
  var RadfiProvider = class {
15210
15241
  config;
15242
+ // Client-side runtime signer (e.g. a backend's HMAC closure). Holds no credential itself — the SDK
15243
+ // only keeps the reference and invokes it per outbound `apiUrl` request. See `RadfiOptions` / gh-831.
15244
+ signer;
15211
15245
  accessToken = "";
15212
15246
  refreshToken = "";
15213
- constructor(config) {
15247
+ constructor(config, options) {
15214
15248
  this.config = config;
15249
+ this.signer = options?.signer;
15215
15250
  this.accessToken = config.accessToken ?? "";
15216
15251
  this.refreshToken = config.refreshToken ?? "";
15217
15252
  if (config.apiUrl.endsWith("/")) {
@@ -15322,6 +15357,9 @@ var RadfiProvider = class {
15322
15357
  }
15323
15358
  return body.data;
15324
15359
  }
15360
+ // UMS call: goes out unsigned even when a signer is configured. Bound scopes the backend
15361
+ // credential to the Sodax endpoints on `apiUrl`, so a signature here is unverified — this
15362
+ // deliberately does not go through `request()`. Same for `getExpiredUtxos` below. See gh-831.
15325
15363
  async getBalance(address) {
15326
15364
  if (!this.config.umsUrl) {
15327
15365
  throw new Error("RadfiConfig.umsUrl is required for getBalance");
@@ -15399,6 +15437,9 @@ var RadfiProvider = class {
15399
15437
  }
15400
15438
  /**
15401
15439
  * Fetch expired (or near-expiry) UTXOs for a trading wallet address from UMS API.
15440
+ *
15441
+ * UMS call — unsigned by design, like `getBalance`: the backend credential is scoped to the
15442
+ * Sodax endpoints on `apiUrl`, so a configured signer intentionally does not reach here.
15402
15443
  */
15403
15444
  async getExpiredUtxos(tradingAddress, params) {
15404
15445
  if (!this.config.umsUrl) {
@@ -15580,11 +15621,13 @@ var RadfiProvider = class {
15580
15621
  }
15581
15622
  }
15582
15623
  async request(endpoint, options) {
15624
+ const signed = this.signer ? await this.signer({ method: options?.method ?? "GET", path: endpoint }) : void 0;
15583
15625
  return fetch(`${this.config.apiUrl}${endpoint}`, {
15584
15626
  ...options,
15585
15627
  headers: {
15586
15628
  "Content-Type": "application/json",
15587
- ...options?.headers || {}
15629
+ ...options?.headers || {},
15630
+ ...signed
15588
15631
  }
15589
15632
  });
15590
15633
  }
@@ -15647,7 +15690,7 @@ function normalizeSignatureToBase64(signature) {
15647
15690
  // src/shared/services/spoke/BitcoinSpokeService.ts
15648
15691
  initEccLib(ecc);
15649
15692
  var BITCOIN_DEFAULT_FEE_RATE = 3;
15650
- var DUST_THRESHOLD = 546;
15693
+ var DUST_THRESHOLD = Number(BITCOIN_DUST_SATS);
15651
15694
  var BitcoinSpokeService = class {
15652
15695
  config;
15653
15696
  rpcUrl;
@@ -15659,7 +15702,7 @@ var BitcoinSpokeService = class {
15659
15702
  this.config = config;
15660
15703
  const chainConfig = config.getChainConfig(ChainKeys.BITCOIN_MAINNET);
15661
15704
  this.rpcUrl = chainConfig.rpcUrl;
15662
- this.radfi = new RadfiProvider(chainConfig.radfi);
15705
+ this.radfi = new RadfiProvider(chainConfig.radfi, { signer: config.radfiSigner });
15663
15706
  this.walletMode = chainConfig.radfi.walletMode ?? "TRADING";
15664
15707
  this.pollingIntervalMs = chainConfig.pollingConfig.pollingIntervalMs;
15665
15708
  this.maxTimeoutMs = chainConfig.pollingConfig.maxTimeoutMs;
@@ -16016,11 +16059,7 @@ var BitcoinSpokeService = class {
16016
16059
  async buildDepositPsbt(walletAddress, walletProvider, srcChainKey, token, amount, data, utxos) {
16017
16060
  const chainConfig = this.config.getChainConfig(srcChainKey);
16018
16061
  const assetManagerAddress = chainConfig.addresses.assetManager;
16019
- const normalizedToken = token.toLocaleLowerCase();
16020
- const nativeBtcTokens = new Set(
16021
- ["btc", chainConfig.nativeToken, chainConfig.supportedTokens.BTC?.address].filter((value) => !!value).map((value) => value.toLocaleLowerCase())
16022
- );
16023
- const isNativeBtc = nativeBtcTokens.has(normalizedToken);
16062
+ const isNativeBtc = isNativeBitcoinToken(chainConfig, token);
16024
16063
  if (isNativeBtc) {
16025
16064
  const OP_RETURN = opcodes.OP_RETURN;
16026
16065
  const OP_12 = opcodes.OP_12;
@@ -16279,7 +16318,7 @@ function hexToBytes2(hex) {
16279
16318
  const al = hl / 2;
16280
16319
  if (hl % 2)
16281
16320
  throw new Error("hex string expected, got unpadded hex of length " + hl);
16282
- const array2 = new Uint8Array(al);
16321
+ const array3 = new Uint8Array(al);
16283
16322
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
16284
16323
  const n1 = asciiToBase16(hex.charCodeAt(hi));
16285
16324
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
@@ -16287,9 +16326,9 @@ function hexToBytes2(hex) {
16287
16326
  const char = hex[hi] + hex[hi + 1];
16288
16327
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
16289
16328
  }
16290
- array2[ai] = n1 * 16 + n2;
16329
+ array3[ai] = n1 * 16 + n2;
16291
16330
  }
16292
- return array2;
16331
+ return array3;
16293
16332
  }
16294
16333
  function concatBytes(...arrays) {
16295
16334
  let sum = 0;
@@ -16919,22 +16958,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16919
16958
  const byte0 = Uint8Array.of(0);
16920
16959
  const byte1 = Uint8Array.of(1);
16921
16960
  const _maxDrbgIters = 1e3;
16922
- let v4 = u8n(hashLen);
16961
+ let v9 = u8n(hashLen);
16923
16962
  let k = u8n(hashLen);
16924
16963
  let i = 0;
16925
16964
  const reset = () => {
16926
- v4.fill(1);
16965
+ v9.fill(1);
16927
16966
  k.fill(0);
16928
16967
  i = 0;
16929
16968
  };
16930
- const h = (...msgs) => hmacFn(k, concatBytes(v4, ...msgs));
16969
+ const h = (...msgs) => hmacFn(k, concatBytes(v9, ...msgs));
16931
16970
  const reseed = (seed = NULL) => {
16932
16971
  k = h(byte0, seed);
16933
- v4 = h();
16972
+ v9 = h();
16934
16973
  if (seed.length === 0)
16935
16974
  return;
16936
16975
  k = h(byte1, seed);
16937
- v4 = h();
16976
+ v9 = h();
16938
16977
  };
16939
16978
  const gen = () => {
16940
16979
  if (i++ >= _maxDrbgIters)
@@ -16942,10 +16981,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16942
16981
  let len = 0;
16943
16982
  const out = [];
16944
16983
  while (len < qByteLen) {
16945
- v4 = h();
16946
- const sl = v4.slice();
16984
+ v9 = h();
16985
+ const sl = v9.slice();
16947
16986
  out.push(sl);
16948
- len += v4.length;
16987
+ len += v9.length;
16949
16988
  }
16950
16989
  return concatBytes(...out);
16951
16990
  };
@@ -16960,18 +16999,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16960
16999
  };
16961
17000
  return genUntil;
16962
17001
  }
16963
- function validateObject(object2, fields = {}, optFields = {}) {
16964
- if (!object2 || typeof object2 !== "object")
17002
+ function validateObject(object5, fields = {}, optFields = {}) {
17003
+ if (!object5 || typeof object5 !== "object")
16965
17004
  throw new Error("expected valid options object");
16966
17005
  function checkField(fieldName, expectedType, isOpt) {
16967
- const val = object2[fieldName];
17006
+ const val = object5[fieldName];
16968
17007
  if (isOpt && val === void 0)
16969
17008
  return;
16970
17009
  const current = typeof val;
16971
17010
  if (current !== expectedType || val === null)
16972
17011
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
16973
17012
  }
16974
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v4]) => checkField(k, v4, isOpt));
17013
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v9]) => checkField(k, v9, isOpt));
16975
17014
  iter(fields, false);
16976
17015
  iter(optFields, true);
16977
17016
  }
@@ -17010,12 +17049,12 @@ function pow2(x, power, modulo) {
17010
17049
  }
17011
17050
  return res;
17012
17051
  }
17013
- function invert(number2, modulo) {
17014
- if (number2 === _0n2)
17052
+ function invert(number5, modulo) {
17053
+ if (number5 === _0n2)
17015
17054
  throw new Error("invert: expected non-zero number");
17016
17055
  if (modulo <= _0n2)
17017
17056
  throw new Error("invert: expected positive modulus, got " + modulo);
17018
- let a = mod(number2, modulo);
17057
+ let a = mod(number5, modulo);
17019
17058
  let b = modulo;
17020
17059
  let x = _0n2, u = _1n2;
17021
17060
  while (a !== _0n2) {
@@ -17042,9 +17081,9 @@ function sqrt3mod4(Fp, n) {
17042
17081
  function sqrt5mod8(Fp, n) {
17043
17082
  const p5div8 = (Fp.ORDER - _5n) / _8n;
17044
17083
  const n2 = Fp.mul(n, _2n);
17045
- const v4 = Fp.pow(n2, p5div8);
17046
- const nv = Fp.mul(n, v4);
17047
- const i = Fp.mul(Fp.mul(nv, _2n), v4);
17084
+ const v9 = Fp.pow(n2, p5div8);
17085
+ const nv = Fp.mul(n, v9);
17086
+ const i = Fp.mul(Fp.mul(nv, _2n), v9);
17048
17087
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
17049
17088
  assertIsSquare(Fp, root, n);
17050
17089
  return root;
@@ -17519,27 +17558,27 @@ var wNAF = class {
17519
17558
  assert0(n);
17520
17559
  return acc;
17521
17560
  }
17522
- getPrecomputes(W, point, transform) {
17561
+ getPrecomputes(W, point, transform2) {
17523
17562
  let comp = pointPrecomputes.get(point);
17524
17563
  if (!comp) {
17525
17564
  comp = this.precomputeWindow(point, W);
17526
17565
  if (W !== 1) {
17527
- if (typeof transform === "function")
17528
- comp = transform(comp);
17566
+ if (typeof transform2 === "function")
17567
+ comp = transform2(comp);
17529
17568
  pointPrecomputes.set(point, comp);
17530
17569
  }
17531
17570
  }
17532
17571
  return comp;
17533
17572
  }
17534
- cached(point, scalar, transform) {
17573
+ cached(point, scalar, transform2) {
17535
17574
  const W = getW(point);
17536
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
17575
+ return this.wNAF(W, this.getPrecomputes(W, point, transform2), scalar);
17537
17576
  }
17538
- unsafe(point, scalar, transform, prev) {
17577
+ unsafe(point, scalar, transform2, prev) {
17539
17578
  const W = getW(point);
17540
17579
  if (W === 1)
17541
17580
  return this._unsafeLadder(point, scalar, prev);
17542
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
17581
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform2), scalar, prev);
17543
17582
  }
17544
17583
  // We calculate precomputes for elliptic curve point multiplication
17545
17584
  // using windowed method. This specifies window size and
@@ -17626,9 +17665,9 @@ function edwards(params, extraOpts = {}) {
17626
17665
  validateObject(extraOpts, {}, { uvRatio: "function" });
17627
17666
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
17628
17667
  const modP = (n) => Fp.create(n);
17629
- const uvRatio2 = extraOpts.uvRatio || ((u, v4) => {
17668
+ const uvRatio2 = extraOpts.uvRatio || ((u, v9) => {
17630
17669
  try {
17631
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v4)) };
17670
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v9)) };
17632
17671
  } catch (e) {
17633
17672
  return { isValid: false, value: _0n4 };
17634
17673
  }
@@ -17724,8 +17763,8 @@ function edwards(params, extraOpts = {}) {
17724
17763
  aInRange("point.y", y, _0n4, max);
17725
17764
  const y2 = modP(y * y);
17726
17765
  const u = modP(y2 - _1n4);
17727
- const v4 = modP(d * y2 - a);
17728
- let { isValid, value: x } = uvRatio2(u, v4);
17766
+ const v9 = modP(d * y2 - a);
17767
+ let { isValid, value: x } = uvRatio2(u, v9);
17729
17768
  if (!isValid)
17730
17769
  throw new Error("bad point: invalid y coordinate");
17731
17770
  const isXOdd = (x & _1n4) === _1n4;
@@ -18065,13 +18104,13 @@ function adjustScalarBytes(bytes) {
18065
18104
  return bytes;
18066
18105
  }
18067
18106
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
18068
- function uvRatio(u, v4) {
18107
+ function uvRatio(u, v9) {
18069
18108
  const P = ed25519_CURVE_p;
18070
- const v32 = mod(v4 * v4 * v4, P);
18071
- const v7 = mod(v32 * v32 * v4, P);
18072
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
18109
+ const v32 = mod(v9 * v9 * v9, P);
18110
+ const v72 = mod(v32 * v32 * v9, P);
18111
+ const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
18073
18112
  let x = mod(u * v32 * pow, P);
18074
- const vx2 = mod(v4 * x * x, P);
18113
+ const vx2 = mod(v9 * x * x, P);
18075
18114
  const root1 = x;
18076
18115
  const root2 = mod(x * ED25519_SQRT_M1, P);
18077
18116
  const useRoot1 = vx2 === u;
@@ -18402,7 +18441,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
18402
18441
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
18403
18442
  }
18404
18443
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
18405
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18444
+ const stakes = validators.map((v9) => BigInt(v9.stake)).sort(sortBigIntAsc);
18406
18445
  const num = BigInt(numSeats);
18407
18446
  const stakesSum = stakes.reduce((a, b) => a + b);
18408
18447
  if (stakesSum < num) {
@@ -18431,7 +18470,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
18431
18470
  if (minimumStakeRatio.length != 2) {
18432
18471
  throw Error("minimumStakeRatio should have 2 elements");
18433
18472
  }
18434
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18473
+ const stakes = validators.map((v9) => BigInt(v9.stake)).sort(sortBigIntAsc);
18435
18474
  const stakesSum = stakes.reduce((a, b) => a + b);
18436
18475
  if (validators.length < maxNumberOfSeats) {
18437
18476
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -18603,10 +18642,10 @@ var DER = {
18603
18642
  if (length < 128)
18604
18643
  throw new E("tlv.decode(long): not minimal encoding");
18605
18644
  }
18606
- const v4 = data.subarray(pos, pos + length);
18607
- if (v4.length !== length)
18645
+ const v9 = data.subarray(pos, pos + length);
18646
+ if (v9.length !== length)
18608
18647
  throw new E("tlv.decode: wrong value length");
18609
- return { v: v4, l: data.subarray(pos + length) };
18648
+ return { v: v9, l: data.subarray(pos + length) };
18610
18649
  }
18611
18650
  },
18612
18651
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -19174,9 +19213,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19174
19213
  extraEntropy: false
19175
19214
  };
19176
19215
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
19177
- function isBiggerThanHalfOrder(number2) {
19216
+ function isBiggerThanHalfOrder(number5) {
19178
19217
  const HALF = CURVE_ORDER >> _1n6;
19179
- return number2 > HALF;
19218
+ return number5 > HALF;
19180
19219
  }
19181
19220
  function validateRS(title, num) {
19182
19221
  if (!Fn.isValidNot0(num))
@@ -19359,8 +19398,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19359
19398
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
19360
19399
  if (R.is0())
19361
19400
  return false;
19362
- const v4 = Fn.create(R.x);
19363
- return v4 === r;
19401
+ const v9 = Fn.create(R.x);
19402
+ return v9 === r;
19364
19403
  } catch (e) {
19365
19404
  return false;
19366
19405
  }
@@ -23498,6 +23537,7 @@ var CustomStellarAccount = class {
23498
23537
  this.sequenceNumber = this.startingSequenceNumber;
23499
23538
  }
23500
23539
  };
23540
+ var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
23501
23541
  var StellarSpokeService = class {
23502
23542
  config;
23503
23543
  chainConfig;
@@ -23735,6 +23775,17 @@ var StellarSpokeService = class {
23735
23775
  throw error;
23736
23776
  }
23737
23777
  }
23778
+ /**
23779
+ * Whether a token requires a trustline. Native XLM and legacy bnUSD are
23780
+ * exempt and therefore need no subentry reserve.
23781
+ */
23782
+ requiresTrustline(token) {
23783
+ const stellarChainConfig = this.chainConfig;
23784
+ const normalized = token.toLowerCase();
23785
+ if (normalized === stellarChainConfig.nativeToken.toLowerCase()) return false;
23786
+ const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23787
+ return legacyBnUSD === void 0 || normalized !== legacyBnUSD.address.toLowerCase();
23788
+ }
23738
23789
  /**
23739
23790
  * Check if the user has sufficient trustline established for the token.
23740
23791
  * @param token - The token address to check the trustline for.
@@ -23744,8 +23795,7 @@ var StellarSpokeService = class {
23744
23795
  */
23745
23796
  async hasSufficientTrustline(token, amount, walletAddress) {
23746
23797
  const stellarChainConfig = this.chainConfig;
23747
- const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23748
- if (token.toLowerCase() === stellarChainConfig.nativeToken.toLowerCase() || legacyBnUSD !== void 0 && token.toLowerCase() === legacyBnUSD.address.toLowerCase()) {
23798
+ if (!this.requiresTrustline(token)) {
23749
23799
  return true;
23750
23800
  }
23751
23801
  const trustlineConfig = stellarChainConfig.trustlineConfigs.find(
@@ -23794,7 +23844,7 @@ var StellarSpokeService = class {
23794
23844
  Operation.changeTrust({
23795
23845
  asset: new Asset(asset?.assetCode, asset?.assetIssuer)
23796
23846
  })
23797
- ).setTimeout(this.maxTimeoutMs).build();
23847
+ ).setTimeout(TRUSTLINE_TX_TIMEOUT_SECONDS).build();
23798
23848
  if (params.raw) {
23799
23849
  const transactionXdr = transaction.toXDR();
23800
23850
  return {
@@ -26643,6 +26693,36 @@ var SolverApiService = class {
26643
26693
  }
26644
26694
  }
26645
26695
  };
26696
+
26697
+ // src/backendApi/pollBackendSubmitTx.ts
26698
+ async function pollBackendSubmitTx({
26699
+ deadline,
26700
+ terminalStatus,
26701
+ getStatus,
26702
+ onExecuted,
26703
+ intervalMs = 1e3,
26704
+ requestTimeoutMs
26705
+ }) {
26706
+ const reserveMs = Math.min(Math.ceil((deadline - Date.now()) / 3), 2e4);
26707
+ const pollDeadline = deadline - reserveMs;
26708
+ const requestOverride = () => requestTimeoutMs === void 0 ? void 0 : { timeout: Math.min(pollDeadline - Date.now(), requestTimeoutMs) };
26709
+ while (Date.now() < pollDeadline) {
26710
+ const statusResult = await getStatus(requestOverride());
26711
+ if (statusResult.ok) {
26712
+ const { status, result, failureReason, abandonedAt } = statusResult.value.data;
26713
+ if (status === terminalStatus) {
26714
+ const value = onExecuted(result);
26715
+ if (value !== void 0) return { ok: true, value };
26716
+ }
26717
+ if (status === "failed" || abandonedAt) {
26718
+ const reason = failureReason ? `: ${failureReason}` : "";
26719
+ return { ok: false, cause: new Error(`backend submit-tx ${status}${reason}`) };
26720
+ }
26721
+ }
26722
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, pollDeadline - Date.now())));
26723
+ }
26724
+ return { ok: false, cause: new Error(`backend submit-tx polling timed out before reaching ${terminalStatus}`) };
26725
+ }
26646
26726
  function decodePacketIntentTarget(payload) {
26647
26727
  try {
26648
26728
  const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
@@ -26965,7 +27045,7 @@ var SwapService = class {
26965
27045
  relayerApiEndpoint: this.relayerApiEndpoint,
26966
27046
  // Remaining shared budget: ≈ full `timeout` on the flag-off path (called immediately), or
26967
27047
  // the reserve `submitTx` left on the backend path. Floor keeps a stalled-backend fallback viable.
26968
- timeout: Math.max(deadline - Date.now(), 5e3)
27048
+ timeout: Math.max(deadline - Date.now(), RELAY_FALLBACK_FLOOR_MS)
26969
27049
  });
26970
27050
  if (!packet.ok) {
26971
27051
  return { ok: false, error: mapRelayFailure(packet.error, { feature: "swap", action: "swap", ...baseCtx }) };
@@ -27027,39 +27107,26 @@ var SwapService = class {
27027
27107
  relayData: relayData.payload
27028
27108
  });
27029
27109
  if (!submitted.ok) return submitTxFailed(submitted.error);
27030
- const reserveMs = Math.min(Math.ceil((deadline - Date.now()) / 3), 2e4);
27031
- const pollDeadline = deadline - reserveMs;
27032
- const pollIntervalMs = 1e3;
27033
- while (Date.now() < pollDeadline) {
27034
- const statusResult = await this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey });
27035
- if (statusResult.ok) {
27036
- const { status, result, failureReason, abandonedAt } = statusResult.value.data;
27037
- if (status === "solved" && result?.dstIntentTxHash && result.intent_hash) {
27038
- return {
27039
- ok: true,
27040
- value: {
27041
- // Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
27042
- solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
27043
- intent,
27044
- intentDeliveryInfo: {
27045
- srcChainKey,
27046
- srcTxHash: spokeTxHash,
27047
- srcAddress: params.srcAddress,
27048
- dstChainKey: params.dstChainKey,
27049
- dstTxHash: result.dstIntentTxHash,
27050
- dstAddress: params.dstAddress
27051
- }
27052
- }
27053
- };
27054
- }
27055
- if (status === "failed" || abandonedAt) {
27056
- const reason = failureReason ? `: ${failureReason}` : "";
27057
- return submitTxFailed(new Error(`backend submit-tx ${status}${reason}`));
27110
+ const polled = await pollBackendSubmitTx({
27111
+ deadline,
27112
+ // Swaps terminal success is `solved` (solver filled) — not the bridge `executed`.
27113
+ terminalStatus: "solved",
27114
+ getStatus: () => this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }),
27115
+ onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
27116
+ // Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
27117
+ solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
27118
+ intent,
27119
+ intentDeliveryInfo: {
27120
+ srcChainKey,
27121
+ srcTxHash: spokeTxHash,
27122
+ srcAddress: params.srcAddress,
27123
+ dstChainKey: params.dstChainKey,
27124
+ dstTxHash: result.dstIntentTxHash,
27125
+ dstAddress: params.dstAddress
27058
27126
  }
27059
- }
27060
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
27061
- }
27062
- return submitTxFailed(new Error("backend submit-tx polling timed out before reaching solved"));
27127
+ } : void 0
27128
+ });
27129
+ return polled.ok ? { ok: true, value: polled.value } : submitTxFailed(polled.cause);
27063
27130
  } catch (error) {
27064
27131
  return { ok: false, error: unknownFailed("swap", error, { ...baseCtx, action: "swap" }) };
27065
27132
  }
@@ -27251,10 +27318,19 @@ var SwapService = class {
27251
27318
  `Invalid spoke chain (params.dstChain): ${params.dstChainKey}`,
27252
27319
  { ...baseCtx, field: "dstChainKey" }
27253
27320
  );
27254
- if (isBitcoinChainKey(params.dstChainKey) && params.outputToken === "BTC") {
27321
+ const inputTokenInfo = this.config.getSpokeTokenFromOriginalAssetAddress(params.srcChainKey, params.inputToken);
27322
+ if (isNativeBitcoinTransfer(this.config, params.srcChainKey, inputTokenInfo)) {
27255
27323
  swapInvariant(
27256
- params.minOutputAmount >= 546n,
27257
- `Invalid minOutputAmount (params.minOutputAmount): ${params.minOutputAmount}`,
27324
+ params.inputAmount >= BITCOIN_DUST_SATS,
27325
+ `Invalid inputAmount (${params.inputAmount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
27326
+ { ...baseCtx, field: "inputAmount" }
27327
+ );
27328
+ }
27329
+ const outputTokenInfo = this.config.getSpokeTokenFromOriginalAssetAddress(params.dstChainKey, params.outputToken);
27330
+ if (isNativeBitcoinTransfer(this.config, params.dstChainKey, outputTokenInfo)) {
27331
+ swapInvariant(
27332
+ params.minOutputAmount >= BITCOIN_DUST_SATS,
27333
+ `Invalid minOutputAmount (${params.minOutputAmount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
27258
27334
  { ...baseCtx, field: "minOutputAmount" }
27259
27335
  );
27260
27336
  }
@@ -29793,10 +29869,41 @@ var MigrationService = class {
29793
29869
  };
29794
29870
 
29795
29871
  // src/backendApi/api-utils.ts
29872
+ var BackendHttpError = class extends Error {
29873
+ status;
29874
+ bodyText;
29875
+ /** Parsed JSON, or `undefined` for empty or malformed bodies. */
29876
+ body;
29877
+ constructor(status, bodyText) {
29878
+ super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
29879
+ this.name = "BackendHttpError";
29880
+ this.status = status;
29881
+ this.bodyText = bodyText;
29882
+ this.body = safeJsonParse(bodyText);
29883
+ }
29884
+ };
29885
+ function isBackendHttpError(error) {
29886
+ if (error instanceof BackendHttpError) return true;
29887
+ return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
29888
+ }
29889
+ function safeJsonParse(text) {
29890
+ if (text.length === 0) return void 0;
29891
+ try {
29892
+ return JSON.parse(text);
29893
+ } catch {
29894
+ return void 0;
29895
+ }
29896
+ }
29897
+ function trimTrailingSlashes(baseURL) {
29898
+ let end = baseURL.length;
29899
+ while (end > 0 && baseURL[end - 1] === "/") end -= 1;
29900
+ return baseURL.slice(0, end);
29901
+ }
29902
+ var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
29796
29903
  async function makeRequest(params) {
29797
29904
  const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
29798
29905
  const baseURL = overrideConfig.baseURL || config.baseURL || "";
29799
- const url = `${baseURL}${endpoint}`;
29906
+ const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
29800
29907
  const headers = { ...config.headers, ...overrideConfig.headers };
29801
29908
  const controller = new AbortController();
29802
29909
  const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
@@ -29811,7 +29918,7 @@ async function makeRequest(params) {
29811
29918
  clearTimeout(timeoutId);
29812
29919
  if (!response.ok) {
29813
29920
  const errorText = await response.text();
29814
- throw new Error("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${response.status}: ${errorText}`) });
29921
+ throw new BackendHttpError(response.status, errorText);
29815
29922
  }
29816
29923
  const data = await response.json();
29817
29924
  return data;
@@ -29828,6 +29935,32 @@ async function makeRequest(params) {
29828
29935
  throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
29829
29936
  }
29830
29937
  }
29938
+ function resolveRequestConfig(config, defaults) {
29939
+ const { baseURL, timeout, headers, ...rest } = config;
29940
+ return {
29941
+ ...rest,
29942
+ baseURL: baseURL || defaults.baseURL,
29943
+ timeout: timeout ?? defaults.timeout,
29944
+ headers: { ...defaults.headers, ...headers }
29945
+ };
29946
+ }
29947
+ function toExternalApiError(params) {
29948
+ const { api, feature, endpoint, error } = params;
29949
+ const context = { api, endpoint };
29950
+ if (isBackendHttpError(error)) context.status = error.status;
29951
+ return new SodaxError(
29952
+ "EXTERNAL_API_ERROR",
29953
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
29954
+ { feature, cause: error, context }
29955
+ );
29956
+ }
29957
+ function toInvalidResponseShapeError(params) {
29958
+ const { api, feature, endpoint, issues } = params;
29959
+ return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
29960
+ feature,
29961
+ context: { api, endpoint, reason: "invalid_response_shape", issues }
29962
+ });
29963
+ }
29831
29964
  var SwapsApiService = class _SwapsApiService {
29832
29965
  // Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
29833
29966
  // `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
@@ -29873,7 +30006,7 @@ var SwapsApiService = class _SwapsApiService {
29873
30006
  if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
29874
30007
  context.reason = "invalid_response_shape";
29875
30008
  const issues = error.context.issues;
29876
- context.issues = issues instanceof v2.ValiError ? v2.flatten(issues.issues) : issues;
30009
+ context.issues = issues instanceof v7.ValiError ? v7.flatten(issues.issues) : issues;
29877
30010
  }
29878
30011
  if (error.context.status !== void 0) context.status = error.context.status;
29879
30012
  }
@@ -30034,10 +30167,503 @@ var SwapsApiService = class _SwapsApiService {
30034
30167
  return this.config.baseURL;
30035
30168
  }
30036
30169
  };
30170
+ var StellarSponsorConfigSchema = v7.object({
30171
+ sponsorAccount: v7.string(),
30172
+ networkPassphrase: v7.string(),
30173
+ minTotalFeeStroops: v7.string(),
30174
+ maxTotalFeeStroops: v7.string(),
30175
+ operationCount: v7.number(),
30176
+ minPerOperationFeeStroops: v7.string(),
30177
+ maxPerOperationFeeStroops: v7.string(),
30178
+ recommendedPerOperationFeeStroops: v7.string(),
30179
+ maxTimeboundSeconds: v7.number(),
30180
+ requiredStartingBalance: v7.string()
30181
+ });
30182
+ var StellarSponsoredAccountResponseSchema = v7.variant("alreadyActive", [
30183
+ v7.object({ hash: v7.string(), alreadyActive: v7.literal(false) }),
30184
+ v7.object({ hash: v7.null(), alreadyActive: v7.literal(true) })
30185
+ ]);
30186
+
30187
+ // src/backendApi/SponsoringApiService.ts
30188
+ var SponsoringApiService = class {
30189
+ config;
30190
+ headers;
30191
+ logger;
30192
+ constructor(config, logger = consoleLogger) {
30193
+ this.config = config;
30194
+ this.headers = {
30195
+ ...config.apiKey !== void 0 ? { "x-api-key": config.apiKey } : {},
30196
+ ...config.headers
30197
+ };
30198
+ this.logger = logger;
30199
+ }
30200
+ /**
30201
+ * Validate a response while preserving HTTP failures on `error.cause` for
30202
+ * sponsor-error classification.
30203
+ */
30204
+ async request(endpoint, config, schema) {
30205
+ try {
30206
+ const raw = await makeRequest({
30207
+ endpoint,
30208
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30209
+ logger: this.logger,
30210
+ serviceLabel: "SponsoringApiService"
30211
+ });
30212
+ const parsed = v7.safeParse(schema, raw);
30213
+ if (!parsed.success) {
30214
+ return {
30215
+ ok: false,
30216
+ error: toInvalidResponseShapeError({
30217
+ api: "sponsoring",
30218
+ feature: "backend",
30219
+ endpoint,
30220
+ issues: v7.flatten(parsed.issues)
30221
+ })
30222
+ };
30223
+ }
30224
+ return { ok: true, value: parsed.output };
30225
+ } catch (error) {
30226
+ return { ok: false, error: toExternalApiError({ api: "sponsoring", feature: "backend", endpoint, error }) };
30227
+ }
30228
+ }
30229
+ /** Fetch build parameters, including the rotatable sponsor account. */
30230
+ async getStellarSponsorConfig(config) {
30231
+ return this.request(
30232
+ `${SPONSORING_API_STELLAR_BASE_PATH}/config`,
30233
+ { ...config, method: "GET" },
30234
+ StellarSponsorConfigSchema
30235
+ );
30236
+ }
30237
+ /**
30238
+ * Submit a client-signed transaction for sponsor co-signing. An
30239
+ * `alreadyActive` response is also successful.
30240
+ */
30241
+ async createStellarSponsoredAccount(body, config) {
30242
+ return this.request(
30243
+ `${SPONSORING_API_STELLAR_BASE_PATH}/accounts`,
30244
+ // The endpoint rejects extra fields.
30245
+ { ...config, method: "POST", body: JSON.stringify({ data: body.data }) },
30246
+ StellarSponsoredAccountResponseSchema
30247
+ );
30248
+ }
30249
+ setHeaders(headers) {
30250
+ Object.entries(headers).forEach(([key, value]) => {
30251
+ this.headers[key] = value;
30252
+ });
30253
+ }
30254
+ getBaseURL() {
30255
+ return this.config.baseURL;
30256
+ }
30257
+ };
30258
+ var RelayExtraDataResponseSchema = v7.object({
30259
+ address: v7.string(),
30260
+ payload: v7.string()
30261
+ });
30262
+ var BridgeTokenSchema = v7.object({
30263
+ symbol: v7.string(),
30264
+ name: v7.string(),
30265
+ decimals: v7.number(),
30266
+ address: v7.string(),
30267
+ chainKey: v7.string(),
30268
+ hubAsset: v7.string(),
30269
+ vault: v7.string()
30270
+ });
30271
+ var BridgeTokensResponseSchema = v7.record(v7.string(), v7.array(BridgeTokenSchema));
30272
+ var BridgeTokensByChainResponseSchema = v7.array(BridgeTokenSchema);
30273
+ var BridgeAllowanceCheckResponseSchema = v7.object({
30274
+ valid: v7.boolean()
30275
+ });
30276
+ var makeBridgeApproveResponseSchema = (txSchema) => v7.object({ tx: txSchema });
30277
+ var makeCreateBridgeIntentResponseSchema = (txSchema) => v7.object({
30278
+ tx: txSchema,
30279
+ relayData: RelayExtraDataResponseSchema
30280
+ });
30281
+ var BridgeSubmitTxResponseSchema = v7.object({
30282
+ success: v7.boolean(),
30283
+ data: v7.object({
30284
+ status: v7.picklist(["inserted", "duplicate"]),
30285
+ message: v7.string()
30286
+ })
30287
+ });
30288
+ var BridgePacketDataSchema = v7.object({
30289
+ src_chain_id: v7.number(),
30290
+ src_tx_hash: v7.string(),
30291
+ src_address: v7.string(),
30292
+ status: v7.picklist(["pending", "validating", "executing", "executed"]),
30293
+ dst_chain_id: v7.number(),
30294
+ conn_sn: v7.number(),
30295
+ dst_address: v7.string(),
30296
+ dst_tx_hash: v7.string(),
30297
+ signatures: v7.array(v7.string()),
30298
+ payload: v7.string()
30299
+ });
30300
+ var BridgeSubmitTxStatusResultSchema = v7.object({
30301
+ dstIntentTxHash: v7.string(),
30302
+ packetData: v7.optional(BridgePacketDataSchema)
30303
+ });
30304
+ var BridgeSubmitTxStatusDataSchema = v7.object({
30305
+ txHash: v7.string(),
30306
+ srcChainKey: v7.string(),
30307
+ status: v7.string(),
30308
+ failedAtStep: v7.optional(v7.string()),
30309
+ failureReason: v7.optional(v7.string()),
30310
+ processingAttempts: v7.number(),
30311
+ abandonedAt: v7.optional(v7.string()),
30312
+ result: v7.optional(BridgeSubmitTxStatusResultSchema),
30313
+ userMessage: v7.optional(v7.string())
30314
+ });
30315
+ var BridgeSubmitTxStatusResponseSchema = v7.object({
30316
+ success: v7.boolean(),
30317
+ data: BridgeSubmitTxStatusDataSchema
30318
+ });
30319
+ var BridgeFeeResponseSchema = v7.object({ fee: v7.string() });
30320
+ var BridgeLimitSchema = v7.object({
30321
+ amount: v7.string(),
30322
+ decimals: v7.number(),
30323
+ type: v7.picklist(["DEPOSIT_LIMIT", "WITHDRAWAL_LIMIT"])
30324
+ });
30325
+ var BridgeableAmountResponseSchema = v7.object({ limit: BridgeLimitSchema });
30326
+ var BridgeableCheckResponseSchema = v7.object({ bridgeable: v7.boolean() });
30327
+ var AddressSchema = v7.custom((input) => typeof input === "string");
30328
+ var HexSchema = v7.custom((input) => typeof input === "string");
30329
+ var BigintFromString = v7.pipe(v7.string(), v7.toBigint());
30330
+ var BytesFromIndexRecord = v7.pipe(
30331
+ v7.record(v7.string(), v7.number()),
30332
+ v7.transform((indexed) => Uint8Array.from(Object.values(indexed)))
30333
+ );
30334
+ var EvmRawTxSchema = v7.object({
30335
+ from: AddressSchema,
30336
+ to: AddressSchema,
30337
+ value: BigintFromString,
30338
+ data: HexSchema
30339
+ });
30340
+ var SolanaRawTxSchema = v7.object({
30341
+ from: v7.string(),
30342
+ to: v7.string(),
30343
+ value: BigintFromString,
30344
+ data: v7.string()
30345
+ });
30346
+ var SuiRawTxSchema = v7.object({
30347
+ from: HexSchema,
30348
+ to: v7.string(),
30349
+ value: BigintFromString,
30350
+ data: v7.string()
30351
+ });
30352
+ var StellarRawTxSchema = v7.object({
30353
+ from: v7.string(),
30354
+ to: v7.string(),
30355
+ value: BigintFromString,
30356
+ data: v7.string()
30357
+ });
30358
+ var BitcoinRawTxSchema = v7.object({
30359
+ from: v7.string(),
30360
+ to: v7.string(),
30361
+ value: BigintFromString,
30362
+ data: v7.string()
30363
+ });
30364
+ var InjectiveRawTxSchema = v7.object({
30365
+ from: HexSchema,
30366
+ to: HexSchema,
30367
+ signedDoc: v7.object({
30368
+ bodyBytes: BytesFromIndexRecord,
30369
+ authInfoBytes: BytesFromIndexRecord,
30370
+ chainId: v7.string(),
30371
+ accountNumber: BigintFromString
30372
+ })
30373
+ });
30374
+ var NearRawTxSchema = v7.object({
30375
+ signerId: v7.string(),
30376
+ params: v7.object({
30377
+ contractId: v7.string(),
30378
+ method: v7.string(),
30379
+ args: v7.custom((input) => typeof input === "object" && input !== null),
30380
+ gas: v7.optional(BigintFromString),
30381
+ deposit: v7.optional(BigintFromString)
30382
+ })
30383
+ });
30384
+ var IconRawTxSchema = v7.record(
30385
+ v7.string(),
30386
+ v7.union([v7.string(), v7.custom((input) => typeof input === "object" && input !== null)])
30387
+ );
30388
+ var StacksRawTxSchema = v7.object({
30389
+ payload: v7.string(),
30390
+ estimatedLength: v7.optional(v7.number())
30391
+ });
30392
+ var AnyRawTxSchema = v7.custom((input) => typeof input === "object" && input !== null);
30393
+ function rawTxSchemaForChainKey(chainKey) {
30394
+ let chainType;
30395
+ try {
30396
+ chainType = getChainType(chainKey);
30397
+ } catch {
30398
+ chainType = void 0;
30399
+ }
30400
+ switch (chainType) {
30401
+ case "EVM":
30402
+ return EvmRawTxSchema;
30403
+ case "SOLANA":
30404
+ return SolanaRawTxSchema;
30405
+ case "SUI":
30406
+ return SuiRawTxSchema;
30407
+ case "STELLAR":
30408
+ return StellarRawTxSchema;
30409
+ case "INJECTIVE":
30410
+ return InjectiveRawTxSchema;
30411
+ case "ICON":
30412
+ return IconRawTxSchema;
30413
+ case "STACKS":
30414
+ return StacksRawTxSchema;
30415
+ case "NEAR":
30416
+ return NearRawTxSchema;
30417
+ case "BITCOIN":
30418
+ return BitcoinRawTxSchema;
30419
+ default:
30420
+ return AnyRawTxSchema;
30421
+ }
30422
+ }
30423
+
30424
+ // src/backendApi/BridgeApiService.ts
30425
+ function toCreateBridgeIntentParamsV2(params, extras) {
30426
+ return {
30427
+ srcChainKey: params.srcChainKey,
30428
+ dstChainKey: params.dstChainKey,
30429
+ inputToken: params.srcToken,
30430
+ outputToken: params.dstToken,
30431
+ inputAmount: params.amount.toString(),
30432
+ srcAddress: params.srcAddress,
30433
+ dstAddress: params.recipient,
30434
+ ...extras?.srcPublicKey !== void 0 ? { srcPublicKey: extras.srcPublicKey } : {},
30435
+ ...extras?.bound !== void 0 ? { bound: extras.bound } : {},
30436
+ ...extras?.partnerFee !== void 0 ? { partnerFee: extras.partnerFee } : {}
30437
+ };
30438
+ }
30439
+ var BridgeApiService = class {
30440
+ // Fully-resolved bridge-API config supplied by the caller (BackendApiService resolves the
30441
+ // `ApiConfig` union via `resolveBridgeApiConfig`); this service does not resolve the union.
30442
+ config;
30443
+ headers;
30444
+ logger;
30445
+ constructor(config, logger = consoleLogger) {
30446
+ this.config = config;
30447
+ this.headers = { ...config.headers };
30448
+ this.logger = logger;
30449
+ }
30450
+ /**
30451
+ * Issues a single HTTP request, validates the JSON body against `schema`, and
30452
+ * wraps the result in `Result<T>`. The service-level `baseURL`/`timeout`/
30453
+ * `headers` are merged with the optional per-call `overrideConfig` (which takes
30454
+ * precedence) inside {@link makeRequest}. Every public method delegates here.
30455
+ */
30456
+ async request(endpoint, config, schema, overrideConfig) {
30457
+ try {
30458
+ const raw = await makeRequest({
30459
+ endpoint,
30460
+ config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
30461
+ overrideConfig,
30462
+ logger: this.logger,
30463
+ serviceLabel: "BridgeApiService"
30464
+ });
30465
+ const parsed = v7.safeParse(schema, raw);
30466
+ if (!parsed.success) {
30467
+ return {
30468
+ ok: false,
30469
+ error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from bridge API for ${endpoint}`, {
30470
+ feature: "backend",
30471
+ context: { api: "bridge", endpoint, reason: "invalid_response_shape", issues: v7.flatten(parsed.issues) }
30472
+ })
30473
+ };
30474
+ }
30475
+ return { ok: true, value: parsed.output };
30476
+ } catch (error) {
30477
+ return {
30478
+ ok: false,
30479
+ error: new SodaxError(
30480
+ "EXTERNAL_API_ERROR",
30481
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
30482
+ {
30483
+ feature: "backend",
30484
+ cause: error,
30485
+ context: { api: "bridge", endpoint }
30486
+ }
30487
+ )
30488
+ };
30489
+ }
30490
+ }
30491
+ // ──────────────────────────────────────────────────────────────────────
30492
+ // Tokens
30493
+ // ──────────────────────────────────────────────────────────────────────
30494
+ /**
30495
+ * Fetch all supported bridge tokens grouped by SpokeChainKey.
30496
+ *
30497
+ * @returns `Result<GetBridgeTokensResponseV2>` — map of chain key → token list.
30498
+ */
30499
+ async getTokens(config) {
30500
+ return this.request("/bridge/tokens", { method: "GET" }, BridgeTokensResponseSchema, config);
30501
+ }
30502
+ /**
30503
+ * Fetch supported bridge tokens for a single SpokeChainKey.
30504
+ *
30505
+ * @param chainKey - SODAX SpokeChainKey (e.g. `0xa4b1.arbitrum`, `solana`).
30506
+ * @returns `Result<GetBridgeTokensByChainResponseV2>` — token list for the chain.
30507
+ */
30508
+ async getTokensByChain(chainKey, config) {
30509
+ return this.request(
30510
+ `/bridge/tokens/${chainKey}`,
30511
+ { method: "GET" },
30512
+ BridgeTokensByChainResponseSchema,
30513
+ config
30514
+ );
30515
+ }
30516
+ // ──────────────────────────────────────────────────────────────────────
30517
+ // Allowance · approve · create intent
30518
+ // ──────────────────────────────────────────────────────────────────────
30519
+ /**
30520
+ * Check whether the source token allowance is already sufficient for the bridge.
30521
+ *
30522
+ * @returns `Result<BridgeAllowanceCheckResponseV2>` — `{ valid }`.
30523
+ */
30524
+ async checkAllowance(body, config) {
30525
+ return this.request(
30526
+ "/bridge/allowance/check",
30527
+ { method: "POST", body: toJsonBody(body) },
30528
+ BridgeAllowanceCheckResponseSchema,
30529
+ config
30530
+ );
30531
+ }
30532
+ /**
30533
+ * Build an unsigned token-approval transaction for the source token.
30534
+ *
30535
+ * @returns `Result<BridgeApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
30536
+ */
30537
+ async approve(body, config) {
30538
+ const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30539
+ return this.request(
30540
+ "/bridge/approve",
30541
+ { method: "POST", body: toJsonBody(body) },
30542
+ makeBridgeApproveResponseSchema(txSchema),
30543
+ config
30544
+ );
30545
+ }
30546
+ /**
30547
+ * Build an unsigned spoke-deposit (create-bridge-intent) transaction.
30548
+ *
30549
+ * @returns `Result<CreateBridgeIntentResponseV2>` — `{ tx, relayData }` (no intent struct).
30550
+ */
30551
+ async createBridgeIntent(body, config) {
30552
+ const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30553
+ return this.request(
30554
+ "/bridge/intents",
30555
+ { method: "POST", body: toJsonBody(body) },
30556
+ makeCreateBridgeIntentResponseSchema(txSchema),
30557
+ config
30558
+ );
30559
+ }
30560
+ // ──────────────────────────────────────────────────────────────────────
30561
+ // Submit-tx state machine
30562
+ // ──────────────────────────────────────────────────────────────────────
30563
+ /**
30564
+ * Submit a broadcast bridge (spoke-deposit) transaction to be processed (relayed).
30565
+ * Carries the FULL `relayData { address, payload }` envelope. Idempotent on `(txHash, srcChainKey)`.
30566
+ *
30567
+ * @returns `Result<BridgeSubmitTxResponseV2>` — `{ success, data: { status, message } }`.
30568
+ */
30569
+ async submitTx(body, config) {
30570
+ return this.request(
30571
+ "/bridge/submit-tx",
30572
+ { method: "POST", body: toJsonBody(body) },
30573
+ BridgeSubmitTxResponseSchema,
30574
+ config
30575
+ );
30576
+ }
30577
+ /**
30578
+ * Get the processing status of a submitted bridge transaction by `(txHash, srcChainKey)`.
30579
+ *
30580
+ * @returns `Result<BridgeSubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
30581
+ */
30582
+ async getSubmitTxStatus(query, config) {
30583
+ const queryParams = new URLSearchParams({ txHash: query.txHash, srcChainKey: query.srcChainKey });
30584
+ return this.request(
30585
+ `/bridge/submit-tx/status?${queryParams.toString()}`,
30586
+ { method: "GET" },
30587
+ BridgeSubmitTxStatusResponseSchema,
30588
+ config
30589
+ );
30590
+ }
30591
+ // ──────────────────────────────────────────────────────────────────────
30592
+ // Fee · bridgeable quote (read-only; mirror the SDK-core client-side methods)
30593
+ // ──────────────────────────────────────────────────────────────────────
30594
+ /**
30595
+ * Bridge partner fee for an input amount (per-request `partnerFee` override, else the configured default).
30596
+ * NOTE: this is a pure client-side computation
30597
+ * in the SDK core (`sodax.bridge.getFee`) — prefer that (no round-trip); this HTTP variant exists for
30598
+ * parity with the backend `/bridge/fee` endpoint (for consumers using only `sodax.api.bridge`).
30599
+ *
30600
+ * @returns `Result<BridgeFeeResponseV2>` — `{ fee }` (decimal string).
30601
+ */
30602
+ async getFee(body, config) {
30603
+ return this.request(
30604
+ "/bridge/fee",
30605
+ { method: "POST", body: toJsonBody(body) },
30606
+ BridgeFeeResponseSchema,
30607
+ config
30608
+ );
30609
+ }
30610
+ /**
30611
+ * Deposit capacity / withdrawal liquidity for a (from, to) token pair. Computable client-side in the
30612
+ * SDK core (`sodax.bridge.getBridgeableAmount`); this HTTP variant mirrors `/bridge/bridgeable-amount`.
30613
+ *
30614
+ * @returns `Result<BridgeableAmountResponseV2>` — `{ limit }`.
30615
+ */
30616
+ async getBridgeableAmount(body, config) {
30617
+ return this.request(
30618
+ "/bridge/bridgeable-amount",
30619
+ { method: "POST", body: toJsonBody(body) },
30620
+ BridgeableAmountResponseSchema,
30621
+ config
30622
+ );
30623
+ }
30624
+ /**
30625
+ * Whether a (from, to) token pair is bridgeable. Computable client-side in the SDK core
30626
+ * (`sodax.bridge.isBridgeable`); this HTTP variant mirrors `/bridge/bridgeable/check`.
30627
+ *
30628
+ * @returns `Result<BridgeableCheckResponseV2>` — `{ bridgeable }`.
30629
+ */
30630
+ async isBridgeable(body, config) {
30631
+ return this.request(
30632
+ "/bridge/bridgeable/check",
30633
+ { method: "POST", body: toJsonBody(body) },
30634
+ BridgeableCheckResponseSchema,
30635
+ config
30636
+ );
30637
+ }
30638
+ // ──────────────────────────────────────────────────────────────────────
30639
+ // Utilities (parity with SwapsApiService)
30640
+ // ──────────────────────────────────────────────────────────────────────
30641
+ /**
30642
+ * Merge additional headers into the service's default header set. Existing
30643
+ * keys are overwritten; keys absent from `headers` are preserved.
30644
+ */
30645
+ setHeaders(headers) {
30646
+ Object.entries(headers).forEach(([key, value]) => {
30647
+ this.headers[key] = value;
30648
+ });
30649
+ }
30650
+ /** Return the base URL the service is currently pointing at. */
30651
+ getBaseURL() {
30652
+ return this.config.baseURL;
30653
+ }
30654
+ /**
30655
+ * Return the effective per-request timeout (ms). Callers that bound a request tighter than the
30656
+ * service default (e.g. `pollBackendSubmitTx` clamping to its poll cutoff) need this as the ceiling,
30657
+ * because a `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it.
30658
+ */
30659
+ getTimeout() {
30660
+ return this.config.timeout;
30661
+ }
30662
+ };
30037
30663
 
30038
30664
  // src/backendApi/apiConfig.ts
30039
- function isCustomApiConfig(config) {
30040
- return "baseApiConfig" in config || "swapsApiConfig" in config;
30665
+ function flatLayer({ baseURL, timeout, headers }) {
30666
+ return { baseURL, timeout, headers };
30041
30667
  }
30042
30668
  function layerConfigs(...slices) {
30043
30669
  return slices.reduce(
@@ -30054,154 +30680,172 @@ function layerConfigs(...slices) {
30054
30680
  );
30055
30681
  }
30056
30682
  function resolveBaseApiConfig(config) {
30057
- if (isCustomApiConfig(config)) {
30058
- return layerConfigs(config.baseApiConfig);
30059
- }
30060
- return layerConfigs(config);
30683
+ const layers = config;
30684
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig);
30061
30685
  }
30062
30686
  function resolveSwapsApiConfig(config) {
30063
- if (isCustomApiConfig(config)) {
30064
- return layerConfigs(config.baseApiConfig, config.swapsApiConfig);
30065
- }
30066
- return layerConfigs(config);
30067
- }
30068
- var ChainKeySchema = v2.custom((input) => typeof input === "string");
30069
- var SpokeChainKeySchema = v2.custom((input) => typeof input === "string");
30070
- var AddressSchema = v2.custom((input) => typeof input === "string");
30071
- var XTokenSchema = v2.object({
30072
- symbol: v2.string(),
30073
- name: v2.string(),
30074
- decimals: v2.number(),
30075
- address: v2.string(),
30687
+ const layers = config;
30688
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig, layers.swapsApiConfig);
30689
+ }
30690
+ function isHttpUrl(value) {
30691
+ return value.startsWith("http://") || value.startsWith("https://");
30692
+ }
30693
+ function normalizeBaseURL(baseURL) {
30694
+ const trimmed = trimTrailingSlashes(baseURL);
30695
+ return isHttpUrl(trimmed) ? trimmed : baseURL;
30696
+ }
30697
+ function resolveSponsoringApiConfig(config) {
30698
+ const layers = config;
30699
+ const slice = layers.sponsoringApiConfig;
30700
+ return {
30701
+ baseURL: normalizeBaseURL(slice?.baseURL ?? DEFAULT_SPONSORING_API_ENDPOINT),
30702
+ timeout: slice?.timeout ?? resolveBaseApiConfig(config).timeout,
30703
+ headers: { ...DEFAULT_BACKEND_API_HEADERS, ...slice?.headers },
30704
+ ...slice?.apiKey === void 0 ? {} : { apiKey: slice.apiKey }
30705
+ };
30706
+ }
30707
+ function resolveBridgeApiConfig(config) {
30708
+ return resolveBaseApiConfig(config);
30709
+ }
30710
+ var ChainKeySchema = v7.custom((input) => typeof input === "string");
30711
+ var SpokeChainKeySchema = v7.custom((input) => typeof input === "string");
30712
+ var AddressSchema2 = v7.custom((input) => typeof input === "string");
30713
+ var XTokenSchema = v7.object({
30714
+ symbol: v7.string(),
30715
+ name: v7.string(),
30716
+ decimals: v7.number(),
30717
+ address: v7.string(),
30076
30718
  chainKey: ChainKeySchema,
30077
- hubAsset: AddressSchema,
30078
- vault: AddressSchema,
30079
- access: v2.optional(v2.picklist(["withdrawOnly", "depositOnly"]))
30719
+ hubAsset: AddressSchema2,
30720
+ vault: AddressSchema2,
30721
+ access: v7.optional(v7.picklist(["withdrawOnly", "depositOnly"]))
30080
30722
  });
30081
- var IntentStructSchema = v2.object({
30082
- intentId: v2.string(),
30083
- creator: v2.string(),
30084
- inputToken: v2.string(),
30085
- outputToken: v2.string(),
30086
- inputAmount: v2.string(),
30087
- minOutputAmount: v2.string(),
30088
- deadline: v2.string(),
30089
- allowPartialFill: v2.boolean(),
30090
- srcChain: v2.number(),
30091
- dstChain: v2.number(),
30092
- srcAddress: v2.string(),
30093
- dstAddress: v2.string(),
30094
- solver: v2.string(),
30095
- data: v2.string()
30723
+ var IntentStructSchema = v7.object({
30724
+ intentId: v7.string(),
30725
+ creator: v7.string(),
30726
+ inputToken: v7.string(),
30727
+ outputToken: v7.string(),
30728
+ inputAmount: v7.string(),
30729
+ minOutputAmount: v7.string(),
30730
+ deadline: v7.string(),
30731
+ allowPartialFill: v7.boolean(),
30732
+ srcChain: v7.number(),
30733
+ dstChain: v7.number(),
30734
+ srcAddress: v7.string(),
30735
+ dstAddress: v7.string(),
30736
+ solver: v7.string(),
30737
+ data: v7.string()
30096
30738
  });
30097
- var IntentResponseSchema = v2.object({
30098
- intentHash: v2.string(),
30099
- txHash: v2.string(),
30100
- logIndex: v2.number(),
30101
- chainId: v2.number(),
30102
- blockNumber: v2.number(),
30103
- open: v2.boolean(),
30739
+ var IntentResponseSchema = v7.object({
30740
+ intentHash: v7.string(),
30741
+ txHash: v7.string(),
30742
+ logIndex: v7.number(),
30743
+ chainId: v7.number(),
30744
+ blockNumber: v7.number(),
30745
+ open: v7.boolean(),
30104
30746
  intent: IntentStructSchema,
30105
- events: v2.array(v2.unknown())
30747
+ events: v7.array(v7.unknown())
30106
30748
  });
30107
- var UserIntentsResponseSchema = v2.object({
30108
- total: v2.number(),
30109
- offset: v2.number(),
30110
- limit: v2.number(),
30111
- items: v2.array(IntentResponseSchema)
30749
+ var UserIntentsResponseSchema = v7.object({
30750
+ total: v7.number(),
30751
+ offset: v7.number(),
30752
+ limit: v7.number(),
30753
+ items: v7.array(IntentResponseSchema)
30112
30754
  });
30113
- var OrderbookResponseSchema = v2.object({
30114
- total: v2.number(),
30115
- data: v2.array(
30116
- v2.object({
30117
- intentState: v2.object({
30118
- exists: v2.boolean(),
30119
- remainingInput: v2.string(),
30120
- receivedOutput: v2.string(),
30121
- pendingPayment: v2.boolean()
30755
+ var OrderbookResponseSchema = v7.object({
30756
+ total: v7.number(),
30757
+ data: v7.array(
30758
+ v7.object({
30759
+ intentState: v7.object({
30760
+ exists: v7.boolean(),
30761
+ remainingInput: v7.string(),
30762
+ receivedOutput: v7.string(),
30763
+ pendingPayment: v7.boolean()
30122
30764
  }),
30123
- intentData: v2.object({
30124
- intentId: v2.string(),
30125
- creator: v2.string(),
30126
- inputToken: v2.string(),
30127
- outputToken: v2.string(),
30128
- inputAmount: v2.string(),
30129
- minOutputAmount: v2.string(),
30130
- deadline: v2.string(),
30131
- allowPartialFill: v2.boolean(),
30132
- srcChain: v2.number(),
30133
- dstChain: v2.number(),
30134
- srcAddress: v2.string(),
30135
- dstAddress: v2.string(),
30136
- solver: v2.string(),
30137
- data: v2.string(),
30138
- intentHash: v2.string(),
30139
- txHash: v2.string(),
30140
- blockNumber: v2.number()
30765
+ intentData: v7.object({
30766
+ intentId: v7.string(),
30767
+ creator: v7.string(),
30768
+ inputToken: v7.string(),
30769
+ outputToken: v7.string(),
30770
+ inputAmount: v7.string(),
30771
+ minOutputAmount: v7.string(),
30772
+ deadline: v7.string(),
30773
+ allowPartialFill: v7.boolean(),
30774
+ srcChain: v7.number(),
30775
+ dstChain: v7.number(),
30776
+ srcAddress: v7.string(),
30777
+ dstAddress: v7.string(),
30778
+ solver: v7.string(),
30779
+ data: v7.string(),
30780
+ intentHash: v7.string(),
30781
+ txHash: v7.string(),
30782
+ blockNumber: v7.number()
30141
30783
  })
30142
30784
  })
30143
30785
  )
30144
30786
  });
30145
- var MoneyMarketPositionSchema = v2.object({
30146
- userAddress: v2.string(),
30147
- positions: v2.array(
30148
- v2.object({
30149
- reserveAddress: v2.string(),
30150
- aTokenAddress: v2.string(),
30151
- variableDebtTokenAddress: v2.string(),
30152
- aTokenBalance: v2.string(),
30153
- variableDebtTokenBalance: v2.string(),
30154
- blockNumber: v2.number()
30787
+ var MoneyMarketPositionSchema = v7.object({
30788
+ userAddress: v7.string(),
30789
+ positions: v7.array(
30790
+ v7.object({
30791
+ reserveAddress: v7.string(),
30792
+ aTokenAddress: v7.string(),
30793
+ variableDebtTokenAddress: v7.string(),
30794
+ aTokenBalance: v7.string(),
30795
+ variableDebtTokenBalance: v7.string(),
30796
+ blockNumber: v7.number()
30155
30797
  })
30156
30798
  )
30157
30799
  });
30158
- var MoneyMarketAssetSchema = v2.object({
30159
- reserveAddress: v2.string(),
30160
- aTokenAddress: v2.string(),
30161
- totalATokenBalance: v2.string(),
30162
- variableDebtTokenAddress: v2.string(),
30163
- totalVariableDebtTokenBalance: v2.string(),
30164
- liquidityRate: v2.string(),
30165
- symbol: v2.string(),
30166
- totalSuppliers: v2.number(),
30167
- totalBorrowers: v2.number(),
30168
- variableBorrowRate: v2.string(),
30169
- stableBorrowRate: v2.string(),
30170
- liquidityIndex: v2.string(),
30171
- variableBorrowIndex: v2.string(),
30172
- blockNumber: v2.number()
30800
+ var MoneyMarketAssetSchema = v7.object({
30801
+ reserveAddress: v7.string(),
30802
+ aTokenAddress: v7.string(),
30803
+ totalATokenBalance: v7.string(),
30804
+ variableDebtTokenAddress: v7.string(),
30805
+ totalVariableDebtTokenBalance: v7.string(),
30806
+ liquidityRate: v7.string(),
30807
+ symbol: v7.string(),
30808
+ totalSuppliers: v7.number(),
30809
+ totalBorrowers: v7.number(),
30810
+ variableBorrowRate: v7.string(),
30811
+ stableBorrowRate: v7.string(),
30812
+ liquidityIndex: v7.string(),
30813
+ variableBorrowIndex: v7.string(),
30814
+ blockNumber: v7.number()
30173
30815
  });
30174
- var MoneyMarketAssetsSchema = v2.array(MoneyMarketAssetSchema);
30175
- var MoneyMarketAssetBorrowersSchema = v2.object({
30176
- borrowers: v2.array(v2.string()),
30177
- total: v2.number(),
30178
- offset: v2.number(),
30179
- limit: v2.number()
30816
+ var MoneyMarketAssetsSchema = v7.array(MoneyMarketAssetSchema);
30817
+ var MoneyMarketAssetBorrowersSchema = v7.object({
30818
+ borrowers: v7.array(v7.string()),
30819
+ total: v7.number(),
30820
+ offset: v7.number(),
30821
+ limit: v7.number()
30180
30822
  });
30181
- var MoneyMarketAssetSuppliersSchema = v2.object({
30182
- suppliers: v2.array(v2.string()),
30183
- total: v2.number(),
30184
- offset: v2.number(),
30185
- limit: v2.number()
30823
+ var MoneyMarketAssetSuppliersSchema = v7.object({
30824
+ suppliers: v7.array(v7.string()),
30825
+ total: v7.number(),
30826
+ offset: v7.number(),
30827
+ limit: v7.number()
30186
30828
  });
30187
- var MoneyMarketBorrowersSchema = v2.object({
30188
- borrowers: v2.array(v2.string()),
30189
- total: v2.number(),
30190
- offset: v2.number(),
30191
- limit: v2.number()
30829
+ var MoneyMarketBorrowersSchema = v7.object({
30830
+ borrowers: v7.array(v7.string()),
30831
+ total: v7.number(),
30832
+ offset: v7.number(),
30833
+ limit: v7.number()
30192
30834
  });
30193
- var GetChainsResponseSchema = v2.array(SpokeChainKeySchema);
30194
- var TokensByChainMapSchema = v2.custom(
30195
- (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v2.is(XTokenSchema, t)))
30835
+ var GetChainsResponseSchema = v7.array(SpokeChainKeySchema);
30836
+ var TokensByChainMapSchema = v7.custom(
30837
+ (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v7.is(XTokenSchema, t)))
30196
30838
  );
30197
- var TokensListSchema = v2.array(XTokenSchema);
30198
- var ReserveAssetsSchema = v2.array(AddressSchema);
30839
+ var TokensListSchema = v7.array(XTokenSchema);
30840
+ var ReserveAssetsSchema = v7.array(AddressSchema2);
30199
30841
 
30200
30842
  // src/backendApi/BackendApiService.ts
30201
30843
  var BackendApiService = class {
30202
30844
  // sub-services exposing domain-specific APIs
30203
30845
  swaps;
30204
- // resolved base-API slice of the ApiConfig union (flat config, or its `baseApiConfig`)
30846
+ sponsoring;
30847
+ bridge;
30848
+ // resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on top
30205
30849
  config;
30206
30850
  headers;
30207
30851
  logger;
@@ -30210,37 +30854,8 @@ var BackendApiService = class {
30210
30854
  this.headers = { ...this.config.headers };
30211
30855
  this.logger = logger;
30212
30856
  this.swaps = new SwapsApiService(resolveSwapsApiConfig(config), this.logger);
30213
- }
30214
- /**
30215
- * Wraps {@link makeRequest} in a `Result<T>` so all errors are captured rather
30216
- * than propagated as thrown exceptions. Every public endpoint method delegates
30217
- * here instead of calling `makeRequest` directly.
30218
- */
30219
- /**
30220
- * Fold any per-call override (carried on `config` alongside `method`/`body`) over the service
30221
- * defaults: baseURL truthy-fallback (an empty-string override defers to the default), timeout
30222
- * nullish-fallback, headers merged (override wins per key). Mirrors the original makeRequest merge.
30223
- */
30224
- resolveRequestConfig(config) {
30225
- const { baseURL, timeout, headers, ...rest } = config;
30226
- return {
30227
- ...rest,
30228
- baseURL: baseURL || this.config.baseURL,
30229
- timeout: timeout ?? this.config.timeout,
30230
- headers: { ...this.headers, ...headers }
30231
- };
30232
- }
30233
- /**
30234
- * Wrap a thrown transport failure (HTTP_REQUEST_FAILED / REQUEST_TIMEOUT / network error) as the
30235
- * canonical backend `SodaxError` — identical shape to SwapsApiService; the underlying failure is
30236
- * preserved on `error.cause`.
30237
- */
30238
- toExternalApiError(endpoint, error) {
30239
- return new SodaxError(
30240
- "EXTERNAL_API_ERROR",
30241
- error instanceof Error ? error.message : `Backend API request to ${endpoint} failed`,
30242
- { feature: "backend", cause: error, context: { api: "backend", endpoint } }
30243
- );
30857
+ this.sponsoring = new SponsoringApiService(resolveSponsoringApiConfig(config), this.logger);
30858
+ this.bridge = new BridgeApiService(resolveBridgeApiConfig(config), this.logger);
30244
30859
  }
30245
30860
  /**
30246
30861
  * Issue a request and validate the JSON body against `schema`, wrapping the result in `Result<T>`.
@@ -30253,23 +30868,25 @@ var BackendApiService = class {
30253
30868
  try {
30254
30869
  const raw = await makeRequest({
30255
30870
  endpoint,
30256
- config: this.resolveRequestConfig(config),
30871
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30257
30872
  logger: this.logger,
30258
30873
  serviceLabel: "BackendApiService"
30259
30874
  });
30260
- const parsed = v2.safeParse(schema, raw);
30875
+ const parsed = v7.safeParse(schema, raw);
30261
30876
  if (!parsed.success) {
30262
30877
  return {
30263
30878
  ok: false,
30264
- error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from backend API for ${endpoint}`, {
30879
+ error: toInvalidResponseShapeError({
30880
+ api: "backend",
30265
30881
  feature: "backend",
30266
- context: { api: "backend", endpoint, reason: "invalid_response_shape", issues: v2.flatten(parsed.issues) }
30882
+ endpoint,
30883
+ issues: v7.flatten(parsed.issues)
30267
30884
  })
30268
30885
  };
30269
30886
  }
30270
30887
  return { ok: true, value: parsed.output };
30271
30888
  } catch (error) {
30272
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30889
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30273
30890
  }
30274
30891
  }
30275
30892
  /**
@@ -30283,13 +30900,13 @@ var BackendApiService = class {
30283
30900
  try {
30284
30901
  const value = await makeRequest({
30285
30902
  endpoint,
30286
- config: this.resolveRequestConfig(config),
30903
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30287
30904
  logger: this.logger,
30288
30905
  serviceLabel: "BackendApiService"
30289
30906
  });
30290
30907
  return { ok: true, value };
30291
30908
  } catch (error) {
30292
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30909
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30293
30910
  }
30294
30911
  }
30295
30912
  // Intent endpoints
@@ -30588,9 +31205,8 @@ var BackendApiService = class {
30588
31205
  * without constructing a new service instance. Existing header keys are
30589
31206
  * overwritten; keys absent from `headers` are preserved.
30590
31207
  *
30591
- * The headers are also fanned out to the sub-services (`swaps`), which hold
30592
- * their own header copies — so a token set here applies to every request made
30593
- * through this client, including `swaps.*`.
31208
+ * Headers also reach `swaps`, which shares this origin, but never `sponsoring`,
31209
+ * whose separate origin must not receive base-API credentials.
30594
31210
  *
30595
31211
  * @param headers - Key-value pairs to add or overwrite in the default headers.
30596
31212
  */
@@ -30599,6 +31215,7 @@ var BackendApiService = class {
30599
31215
  this.headers[key] = value;
30600
31216
  });
30601
31217
  this.swaps.setHeaders(headers);
31218
+ this.bridge.setHeaders(headers);
30602
31219
  }
30603
31220
  /**
30604
31221
  * Return the base URL the service is currently pointing at.
@@ -30649,25 +31266,32 @@ var BridgeService = class {
30649
31266
  hubProvider;
30650
31267
  config;
30651
31268
  spoke;
30652
- constructor({ hubProvider, config, spoke }) {
31269
+ // backend bridge-API client + opt-in backend submit-tx flag
31270
+ backendApi;
31271
+ useBackendSubmitTx;
31272
+ constructor({ hubProvider, config, spoke, backendApi, useBackendSubmitTx }) {
30653
31273
  this.config = config;
30654
31274
  this.hubProvider = hubProvider;
30655
31275
  this.spoke = spoke;
31276
+ this.backendApi = backendApi;
31277
+ this.useBackendSubmitTx = useBackendSubmitTx ?? false;
30656
31278
  }
30657
31279
  /**
30658
31280
  * Calculates the partner fee deducted from a given bridge input amount.
30659
31281
  *
30660
- * Returns `0n` when no partner fee is configured. The fee is denominated in the
30661
- * same units as `inputAmount` (vault token decimals, 18 dp).
31282
+ * Returns `0n` when no partner fee is configured. `inputAmount` must be in 18-dp hub/vault
31283
+ * units — the units the hub deducts the fee in (see `buildBridgeData`) — NOT the spoke token's
31284
+ * native base units. This matters for a fixed `PartnerFee.amount`, which is wei-denominated
31285
+ * (18 dp); a percentage fee is unit-agnostic.
30662
31286
  *
30663
- * @param inputAmount - Gross amount being bridged, in vault token base units.
31287
+ * @param inputAmount - Gross amount being bridged, in 18-dp hub/vault units.
30664
31288
  * @returns Fee amount to be deducted, in the same units as `inputAmount`.
30665
31289
  */
30666
- getFee(inputAmount) {
30667
- if (!this.config.bridgePartnerFee) {
31290
+ getFee(inputAmount, partnerFee = this.config.bridgePartnerFee) {
31291
+ if (!partnerFee) {
30668
31292
  return 0n;
30669
31293
  }
30670
- return calculateFeeAmount(inputAmount, this.config.bridgePartnerFee);
31294
+ return calculateFeeAmount(inputAmount, partnerFee);
30671
31295
  }
30672
31296
  /**
30673
31297
  * Checks whether the caller has sufficient token allowance to execute the bridge.
@@ -30852,42 +31476,21 @@ var BridgeService = class {
30852
31476
  "bridge",
30853
31477
  "bridge",
30854
31478
  async () => {
30855
- const { params, timeout } = _params;
31479
+ const { params } = _params;
30856
31480
  const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
30857
31481
  try {
30858
- const txResult = await this.createBridgeIntent(_params);
30859
- if (!txResult.ok) return { ok: false, error: txResult.error };
30860
- const verifyTxHashResult = await this.spoke.verifyTxHash({
30861
- txHash: txResult.value.tx,
30862
- chainKey: params.srcChainKey
30863
- });
30864
- if (!verifyTxHashResult.ok) {
30865
- return {
30866
- ok: false,
30867
- error: verifyFailed("bridge", verifyTxHashResult.error, baseCtx)
30868
- };
31482
+ const created = await this.createBridgeIntent(_params);
31483
+ if (!created.ok) return { ok: false, error: created.error };
31484
+ const deadline = Date.now() + (_params.timeout ?? DEFAULT_RELAY_TX_TIMEOUT);
31485
+ if (this.useBackendSubmitTx) {
31486
+ const submitted = await this.submitTx(_params, created.value, deadline);
31487
+ if (submitted.ok) return submitted;
31488
+ this.config.logger.warn(
31489
+ "[bridge] backend submit-tx did not complete; falling back to the client-side relay",
31490
+ { error: submitted.error }
31491
+ );
30869
31492
  }
30870
- const packetResult = await relayTxAndWaitPacket({
30871
- srcTxHash: txResult.value.tx,
30872
- data: txResult.value.relayData,
30873
- chainKey: params.srcChainKey,
30874
- relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
30875
- timeout
30876
- });
30877
- if (!packetResult.ok)
30878
- return {
30879
- ok: false,
30880
- error: mapRelayFailure(packetResult.error, {
30881
- feature: "bridge",
30882
- action: "bridge",
30883
- srcChainKey: baseCtx.srcChainKey,
30884
- dstChainKey: baseCtx.dstChainKey
30885
- })
30886
- };
30887
- return {
30888
- ok: true,
30889
- value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: packetResult.value.dst_tx_hash }
30890
- };
31493
+ return this.fallbackBridgeSteps(_params, created.value, deadline);
30891
31494
  } catch (error) {
30892
31495
  if (isBridgeOrchestrationError(error)) return { ok: false, error };
30893
31496
  return {
@@ -30914,6 +31517,98 @@ var BridgeService = class {
30914
31517
  }
30915
31518
  );
30916
31519
  }
31520
+ /**
31521
+ * Client-side bridge completion (the default path): verify the broadcast spoke-deposit tx, then
31522
+ * relay it to the hub and wait for the settlement packet. Extracted verbatim from `bridge()` so the
31523
+ * opt-in backend submit-tx path ({@link submitTx}) can fall back to it on any non-success. Bridge
31524
+ * always relays — there is no hub-source short-circuit.
31525
+ */
31526
+ async fallbackBridgeSteps(_params, created, deadline) {
31527
+ const { params } = _params;
31528
+ const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
31529
+ const verifyTxHashResult = await this.spoke.verifyTxHash({
31530
+ txHash: created.tx,
31531
+ chainKey: params.srcChainKey
31532
+ });
31533
+ if (!verifyTxHashResult.ok) {
31534
+ return { ok: false, error: verifyFailed("bridge", verifyTxHashResult.error, baseCtx) };
31535
+ }
31536
+ const packetResult = await relayTxAndWaitPacket({
31537
+ srcTxHash: created.tx,
31538
+ data: created.relayData,
31539
+ chainKey: params.srcChainKey,
31540
+ relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
31541
+ // Remaining shared budget: ≈ full `timeout` on the flag-off path minus the `verifyTxHash` wait,
31542
+ // or the reserve `submitTx` left on the backend path (`pollBackendSubmitTx` holds back up to a
31543
+ // third, capped at 20s). The floor matters because `relayTxAndWaitPacket` SUBMITS the tx to the
31544
+ // relay before `timeout` bounds anything: a budget exhausted by a slow source-chain confirmation
31545
+ // (Stacks polls for up to its full 120s `maxTimeoutMs`) would otherwise strand an already-landed
31546
+ // deposit unrelayed. Re-relay is idempotent, so always spending the floor is safe.
31547
+ timeout: Math.max(deadline - Date.now(), RELAY_FALLBACK_FLOOR_MS)
31548
+ });
31549
+ if (!packetResult.ok) {
31550
+ return {
31551
+ ok: false,
31552
+ error: mapRelayFailure(packetResult.error, {
31553
+ feature: "bridge",
31554
+ action: "bridge",
31555
+ srcChainKey: baseCtx.srcChainKey,
31556
+ dstChainKey: baseCtx.dstChainKey
31557
+ })
31558
+ };
31559
+ }
31560
+ return {
31561
+ ok: true,
31562
+ value: { srcChainTxHash: created.tx, dstChainTxHash: packetResult.value.dst_tx_hash }
31563
+ };
31564
+ }
31565
+ /**
31566
+ * Backend bridge path (opt-in via `bridgeOptions.useBackendSubmitTx`): hand the broadcast
31567
+ * spoke-deposit tx to the bridge API (`POST /bridge/submit-tx`) with the FULL `relayData`
31568
+ * envelope; the backend relays server-side. Polls `getSubmitTxStatus` until `executed`, then
31569
+ * returns the same {@link TxHashPair} the client-side path returns (`result.dstIntentTxHash` →
31570
+ * destination tx hash; bridge has no solver `intent_hash`).
31571
+ *
31572
+ * Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, terminal `failed` /
31573
+ * abandoned, or poll timeout) so `bridge()` falls back to {@link fallbackBridgeSteps}. Falling back
31574
+ * is safe: re-relaying an already-relayed bridge tx is idempotent — the relay dedups and returns the
31575
+ * existing `executed` packet. Polling stops at `deadline - reserve` so the fallback keeps a
31576
+ * guaranteed slice of the shared `bridge` budget.
31577
+ */
31578
+ async submitTx(_params, created, deadline) {
31579
+ const { params } = _params;
31580
+ const srcChainKey = params.srcChainKey;
31581
+ const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
31582
+ const { tx: spokeTxHash, relayData } = created;
31583
+ const submitTxFailed = (cause) => ({
31584
+ ok: false,
31585
+ error: executionFailed("bridge", cause, { ...baseCtx, action: "bridge" })
31586
+ });
31587
+ try {
31588
+ const submitted = await this.backendApi.bridge.submitTx({
31589
+ txHash: spokeTxHash,
31590
+ srcChainKey,
31591
+ walletAddress: params.srcAddress,
31592
+ // Send the FULL { address, payload } envelope — bridge has no intent.creator for the backend
31593
+ // to rebuild the relay address, so dropping it would break split-tx-chain relay.
31594
+ relayData
31595
+ });
31596
+ if (!submitted.ok) return submitTxFailed(submitted.error);
31597
+ const polled = await pollBackendSubmitTx({
31598
+ deadline,
31599
+ // Bridge terminal success is `executed` (hub-settled) — not the swaps `solved`.
31600
+ terminalStatus: "executed",
31601
+ getStatus: (override) => this.backendApi.bridge.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }, override),
31602
+ onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0,
31603
+ // Bound each status request by the poll cutoff, never above the service default — so a stalled
31604
+ // request can neither eat the fallback's reserve nor consume the window in one attempt.
31605
+ requestTimeoutMs: this.backendApi.bridge.getTimeout()
31606
+ });
31607
+ return polled.ok ? { ok: true, value: polled.value } : submitTxFailed(polled.cause);
31608
+ } catch (error) {
31609
+ return { ok: false, error: unknownFailed("bridge", error, { ...baseCtx, action: "bridge" }) };
31610
+ }
31611
+ }
30917
31612
  /**
30918
31613
  * Submits the spoke-side deposit transaction that initiates a bridge transfer,
30919
31614
  * without waiting for the cross-chain relay to complete.
@@ -30937,9 +31632,15 @@ var BridgeService = class {
30937
31632
  * contains the hub wallet address and encoded hub execution payload needed for relay.
30938
31633
  */
30939
31634
  async createBridgeIntent(_params) {
30940
- const { params, skipSimulation } = _params;
31635
+ const { params, skipSimulation, extras } = _params;
31636
+ const partnerFee = extras?.partnerFee ?? this.config.bridgePartnerFee;
30941
31637
  const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
30942
31638
  try {
31639
+ bridgeInvariant(
31640
+ isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
31641
+ `Invalid wallet provider for chain key: ${params.srcChainKey}`,
31642
+ baseCtx
31643
+ );
30943
31644
  bridgeInvariant(params.amount > 0n, "Amount must be greater than 0", { ...baseCtx, field: "amount" });
30944
31645
  const srcToken = this.resolveBridgeEndpointToken(params.srcChainKey, params.srcToken);
30945
31646
  const dstToken = this.resolveBridgeEndpointToken(params.dstChainKey, params.dstToken);
@@ -30951,25 +31652,62 @@ var BridgeService = class {
30951
31652
  ...baseCtx,
30952
31653
  field: "dstToken"
30953
31654
  });
30954
- const personalAddress = params.srcAddress;
30955
- let walletAddress = personalAddress;
30956
- if (isBitcoinChainKeyType(params.srcChainKey) && _params.raw === false) {
31655
+ bridgeInvariant(
31656
+ this.config.isValidSpokeChainKey(params.srcChainKey),
31657
+ `Invalid spoke chain (srcChainKey): ${params.srcChainKey}`,
31658
+ { ...baseCtx, field: "srcChainKey" }
31659
+ );
31660
+ bridgeInvariant(
31661
+ this.config.isValidSpokeChainKey(params.dstChainKey),
31662
+ `Invalid spoke chain (dstChainKey): ${params.dstChainKey}`,
31663
+ { ...baseCtx, field: "dstChainKey" }
31664
+ );
31665
+ if (isNativeBitcoinTransfer(this.config, params.srcChainKey, srcToken)) {
30957
31666
  bridgeInvariant(
30958
- isBitcoinWalletProviderType(_params.walletProvider),
30959
- `Invalid wallet provider for chain key: ${params.srcChainKey}. Expected bitcoin wallet provider.`,
30960
- { ...baseCtx, field: "walletProvider" }
31667
+ params.amount >= BITCOIN_DUST_SATS,
31668
+ `Invalid amount (${params.amount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
31669
+ { ...baseCtx, field: "amount" }
30961
31670
  );
30962
- walletAddress = await this.spoke.bitcoin.getEffectiveWalletAddress(personalAddress);
30963
- if (this.spoke.bitcoin.walletMode === "TRADING") {
30964
- await this.spoke.bitcoin.radfi.ensureRadfiAccessToken(_params.walletProvider);
31671
+ }
31672
+ if (isNativeBitcoinTransfer(this.config, params.dstChainKey, dstToken)) {
31673
+ const { delivered } = this.computeBridgeAmounts(params.amount, srcToken, dstToken, partnerFee);
31674
+ bridgeInvariant(
31675
+ delivered >= BITCOIN_DUST_SATS,
31676
+ `Post-fee BTC delivery (${delivered}) is below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
31677
+ { ...baseCtx, field: "amount" }
31678
+ );
31679
+ }
31680
+ if (isStacksChainKeyType(params.srcChainKey) && _params.raw === true) {
31681
+ bridgeInvariant(
31682
+ extras?.srcPublicKey !== void 0,
31683
+ "srcPublicKey is required for Stacks createBridgeIntent (raw) \u2014 the source tx is built unsigned and needs the signer public key",
31684
+ { ...baseCtx, field: "srcPublicKey" }
31685
+ );
31686
+ }
31687
+ const personalAddress = params.srcAddress;
31688
+ let walletAddress = personalAddress;
31689
+ if (isBitcoinChainKeyType(params.srcChainKey)) {
31690
+ if (_params.raw === false) {
31691
+ bridgeInvariant(
31692
+ isBitcoinWalletProviderType(_params.walletProvider),
31693
+ `Invalid wallet provider for chain key: ${params.srcChainKey}. Expected bitcoin wallet provider.`,
31694
+ { ...baseCtx, field: "walletProvider" }
31695
+ );
31696
+ if (this.spoke.bitcoin.walletMode === "TRADING") {
31697
+ await this.spoke.bitcoin.radfi.ensureRadfiAccessToken(_params.walletProvider);
31698
+ }
30965
31699
  }
31700
+ walletAddress = await this.spoke.bitcoin.getEffectiveWalletAddress(personalAddress);
30966
31701
  }
30967
31702
  const hubWallet = await this.hubProvider.getUserHubWalletAddress(walletAddress, params.srcChainKey);
30968
31703
  const effectiveSkipSimulation = skipSimulation || isBitcoinChainKeyType(params.srcChainKey) && this.spoke.bitcoin.walletMode === "USER";
30969
- const data = this.buildBridgeData(params, srcToken, dstToken, this.config.bridgePartnerFee);
31704
+ const data = this.buildBridgeData(params, srcToken, dstToken, partnerFee);
30970
31705
  const coreParams = {
30971
31706
  srcChainKey: params.srcChainKey,
30972
31707
  srcAddress: walletAddress,
31708
+ srcPublicKey: extras?.srcPublicKey,
31709
+ // Bitcoin Bound token; BitcoinSpokeService.deposit falls back to the RadfiProvider instance token when undefined.
31710
+ accessToken: extras?.bound?.accessToken,
30973
31711
  to: hubWallet,
30974
31712
  token: params.srcToken,
30975
31713
  amount: params.amount,
@@ -31024,6 +31762,26 @@ var BridgeService = class {
31024
31762
  if (spokeToken) return spokeToken;
31025
31763
  return isHubChainKeyType(chainKey) ? this.config.getXTokenFromHubAsset(token) : void 0;
31026
31764
  }
31765
+ /**
31766
+ * Post-fee amounts for a bridge, in the units each hub step operates in. Single source for the fee +
31767
+ * vault-decimal pipeline, so {@link buildBridgeData}'s encoded hub calls and the BTC-destination dust
31768
+ * guard in {@link createBridgeIntent} can never disagree about what actually gets delivered.
31769
+ *
31770
+ * A spoke endpoint's amount is translated INTO 18-dp vault units on the way in (skipped when the
31771
+ * endpoint already IS the vault asset), the partner fee is deducted there — so a fixed
31772
+ * `PartnerFee.amount` is wei-denominated, never spoke-denominated — and the remainder is translated
31773
+ * back OUT into the destination endpoint's own units.
31774
+ *
31775
+ * @returns `feeAmount` and `withdrawAmount` in 18-dp vault units (what the hub fee transfer and vault
31776
+ * withdrawal use), and `delivered` in the destination endpoint's units (what the recipient receives).
31777
+ */
31778
+ computeBridgeAmounts(amount, srcToken, dstToken, partnerFee) {
31779
+ const translatedAmount = this.config.isSodaVaultHubAsset(srcToken.hubAsset) ? amount : EvmVaultTokenService.translateIncomingDecimals(srcToken.decimals, amount);
31780
+ const feeAmount = calculateFeeAmount(translatedAmount, partnerFee);
31781
+ const withdrawAmount = translatedAmount - feeAmount;
31782
+ const delivered = this.config.isSodaVaultHubAsset(dstToken.hubAsset) ? withdrawAmount : EvmVaultTokenService.translateOutgoingDecimals(dstToken.decimals, withdrawAmount);
31783
+ return { feeAmount, withdrawAmount, delivered };
31784
+ }
31027
31785
  /**
31028
31786
  * Encodes the hub-side execution payload for a bridge operation.
31029
31787
  *
@@ -31047,23 +31805,23 @@ var BridgeService = class {
31047
31805
  */
31048
31806
  buildBridgeData(params, srcToken, dstToken, partnerFee) {
31049
31807
  const calls = [];
31050
- let translatedAmount = params.amount;
31051
- let srcVault = params.srcToken;
31808
+ const { feeAmount, withdrawAmount, delivered } = this.computeBridgeAmounts(
31809
+ params.amount,
31810
+ srcToken,
31811
+ dstToken,
31812
+ partnerFee
31813
+ );
31814
+ let srcVault = srcToken.hubAsset;
31052
31815
  if (!this.config.isSodaVaultHubAsset(srcToken.hubAsset)) {
31053
31816
  calls.push(Erc20Service.encodeApprove(srcToken.hubAsset, srcToken.vault, params.amount));
31054
31817
  calls.push(EvmVaultTokenService.encodeDeposit(srcToken.vault, srcToken.hubAsset, params.amount));
31055
- translatedAmount = EvmVaultTokenService.translateIncomingDecimals(srcToken.decimals, params.amount);
31056
31818
  srcVault = srcToken.vault;
31057
31819
  }
31058
- const feeAmount = calculateFeeAmount(translatedAmount, partnerFee);
31059
31820
  if (partnerFee && feeAmount > 0n) {
31060
31821
  calls.push(Erc20Service.encodeTransfer(srcVault, partnerFee.address, feeAmount));
31061
31822
  }
31062
- const withdrawAmount = translatedAmount - feeAmount;
31063
- let translatedWithdrawAmount = withdrawAmount;
31064
31823
  if (!this.config.isSodaVaultHubAsset(dstToken.hubAsset)) {
31065
31824
  calls.push(EvmVaultTokenService.encodeWithdraw(dstToken.vault, dstToken.hubAsset, withdrawAmount));
31066
- translatedWithdrawAmount = EvmVaultTokenService.translateOutgoingDecimals(dstToken.decimals, withdrawAmount);
31067
31825
  }
31068
31826
  const encodedRecipientAddress = encodeAddress(params.dstChainKey, params.recipient);
31069
31827
  if (isHubChainKey(params.dstChainKey)) {
@@ -31074,11 +31832,11 @@ var BridgeService = class {
31074
31832
  data: encodeFunctionData({
31075
31833
  abi: wrappedSonicAbi,
31076
31834
  functionName: "withdrawTo",
31077
- args: [encodedRecipientAddress, translatedWithdrawAmount]
31835
+ args: [encodedRecipientAddress, delivered]
31078
31836
  })
31079
31837
  });
31080
31838
  } else {
31081
- calls.push(Erc20Service.encodeTransfer(dstToken.hubAsset, encodedRecipientAddress, translatedWithdrawAmount));
31839
+ calls.push(Erc20Service.encodeTransfer(dstToken.hubAsset, encodedRecipientAddress, delivered));
31082
31840
  }
31083
31841
  } else {
31084
31842
  bridgeInvariant(dstToken, `Unsupported hub chain (${params.dstChainKey}) token: ${params.dstToken}`, {
@@ -31089,7 +31847,7 @@ var BridgeService = class {
31089
31847
  EvmAssetManagerService.encodeTransfer(
31090
31848
  dstToken.hubAsset,
31091
31849
  encodedRecipientAddress,
31092
- translatedWithdrawAmount,
31850
+ delivered,
31093
31851
  this.hubProvider.chainConfig.addresses.assetManager
31094
31852
  )
31095
31853
  );
@@ -39308,7 +40066,7 @@ var LeverageYieldService = class {
39308
40066
  }
39309
40067
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
39310
40068
  getVault(name) {
39311
- return this.listVaults().find((v4) => v4.name === name);
40069
+ return this.listVaults().find((v9) => v9.name === name);
39312
40070
  }
39313
40071
  /**
39314
40072
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -39316,7 +40074,7 @@ var LeverageYieldService = class {
39316
40074
  */
39317
40075
  getVaultByAddress(address) {
39318
40076
  const normalized = address.toLowerCase();
39319
- return this.listVaults().find((v4) => v4.vault.toLowerCase() === normalized);
40077
+ return this.listVaults().find((v9) => v9.vault.toLowerCase() === normalized);
39320
40078
  }
39321
40079
  /**
39322
40080
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -40098,6 +40856,566 @@ var LeverageYieldService = class {
40098
40856
  }
40099
40857
  };
40100
40858
 
40859
+ // src/sponsoring/errors.ts
40860
+ var sponsoringInvariant = createInvariant("sponsoring");
40861
+ var ORCHESTRATION_CODES3 = /* @__PURE__ */ new Set([
40862
+ "USER_REJECTED",
40863
+ "VALIDATION_FAILED",
40864
+ "INTENT_CREATION_FAILED",
40865
+ "LOOKUP_FAILED",
40866
+ "EXTERNAL_API_ERROR",
40867
+ "EXECUTION_FAILED",
40868
+ "UNKNOWN"
40869
+ ]);
40870
+ var CONFIG_CODES = /* @__PURE__ */ new Set([
40871
+ "EXTERNAL_API_ERROR",
40872
+ "VALIDATION_FAILED",
40873
+ "UNKNOWN"
40874
+ ]);
40875
+ var isSponsoringOrchestrationError = isCodeMember(ORCHESTRATION_CODES3);
40876
+ var isSponsoringConfigError = isCodeMember(CONFIG_CODES);
40877
+ var isSponsoringLookupError = isCodeMember(LOOKUP_CODES);
40878
+ var DOMAIN_CODES = new Set(SPONSORING_API_ERROR_CODES);
40879
+ function toDomainCode(value) {
40880
+ return typeof value === "string" && DOMAIN_CODES.has(value) ? value : void 0;
40881
+ }
40882
+ function readErrorBody(body) {
40883
+ if (typeof body !== "object" || body === null) return {};
40884
+ const record3 = body;
40885
+ const retryAfterSeconds = typeof record3.retryAfterSeconds === "number" && Number.isFinite(record3.retryAfterSeconds) && record3.retryAfterSeconds > 0 ? record3.retryAfterSeconds : void 0;
40886
+ const sponsorSequence = typeof record3.sponsorSequence === "string" && /^\d+$/.test(record3.sponsorSequence) ? record3.sponsorSequence : void 0;
40887
+ return {
40888
+ message: typeof record3.message === "string" ? record3.message : void 0,
40889
+ code: toDomainCode(record3.error),
40890
+ retryAfterSeconds,
40891
+ sponsorSequence
40892
+ };
40893
+ }
40894
+ var ACTION_POLICY = {
40895
+ fixIntegration: { retryable: false, requiresNewSignature: false },
40896
+ checkApiKey: { retryable: false, requiresNewSignature: false },
40897
+ rebuildAndResign: { retryable: true, requiresNewSignature: true },
40898
+ retrySameRequest: { retryable: true, requiresNewSignature: false },
40899
+ backoff: { retryable: true, requiresNewSignature: false },
40900
+ contactOperator: { retryable: false, requiresNewSignature: false },
40901
+ abort: { retryable: false, requiresNewSignature: false }
40902
+ };
40903
+ function policy(action) {
40904
+ return { action, ...ACTION_POLICY[action] };
40905
+ }
40906
+ function classifySponsorError(error) {
40907
+ const cause = error.cause;
40908
+ const http3 = isBackendHttpError(cause) ? cause : void 0;
40909
+ const { message: serverMessage, code, retryAfterSeconds, sponsorSequence } = readErrorBody(http3?.body);
40910
+ const message = serverMessage ?? error.message;
40911
+ const status = http3?.status;
40912
+ if (status === void 0) {
40913
+ return { ...policy("backoff"), message };
40914
+ }
40915
+ const base2 = { status, code, retryAfterSeconds, sponsorSequence, message };
40916
+ switch (status) {
40917
+ case 400:
40918
+ return { ...base2, ...policy("fixIntegration") };
40919
+ case 401:
40920
+ return { ...base2, ...policy("checkApiKey") };
40921
+ case 409:
40922
+ return { ...base2, ...policy("rebuildAndResign") };
40923
+ case 422:
40924
+ return { ...base2, ...policy("abort") };
40925
+ case 429:
40926
+ return { ...base2, ...policy("backoff") };
40927
+ case 500:
40928
+ return { ...base2, ...policy("contactOperator") };
40929
+ case 503:
40930
+ if (code === "SPONSOR_BUDGET_EXHAUSTED") {
40931
+ return { ...base2, ...policy("contactOperator") };
40932
+ }
40933
+ if (code === "HORIZON_UNAVAILABLE") {
40934
+ return { ...base2, ...policy("retrySameRequest") };
40935
+ }
40936
+ return { ...base2, ...policy("backoff") };
40937
+ default:
40938
+ return { ...base2, ...policy("abort") };
40939
+ }
40940
+ }
40941
+ var SPONSORED_CREATE_OP_COUNT = 3n;
40942
+ var SPONSOR_TIMEBOUND_SECONDS = 300;
40943
+ function parseStroops(value, field) {
40944
+ try {
40945
+ return BigInt(value);
40946
+ } catch {
40947
+ sponsoringInvariant(false, `sponsor config ${field} is not a valid integer: "${value}"`, { field });
40948
+ }
40949
+ }
40950
+ function deriveSponsorBaseFee(config) {
40951
+ const min = parseStroops(config.minTotalFeeStroops, "minTotalFeeStroops");
40952
+ const max = parseStroops(config.maxTotalFeeStroops, "maxTotalFeeStroops");
40953
+ sponsoringInvariant(min > 0n, `sponsor config minTotalFeeStroops must be positive, got ${min}`, {
40954
+ field: "minTotalFeeStroops"
40955
+ });
40956
+ sponsoringInvariant(max >= min, `sponsor config fee band is inverted (min ${min} > max ${max})`, {
40957
+ field: "maxTotalFeeStroops"
40958
+ });
40959
+ const minPerOp = parseStroops(config.minPerOperationFeeStroops, "minPerOperationFeeStroops");
40960
+ const maxPerOp = parseStroops(config.maxPerOperationFeeStroops, "maxPerOperationFeeStroops");
40961
+ sponsoringInvariant(minPerOp > 0n, `sponsor config minPerOperationFeeStroops must be positive, got ${minPerOp}`, {
40962
+ field: "minPerOperationFeeStroops"
40963
+ });
40964
+ sponsoringInvariant(
40965
+ maxPerOp >= minPerOp,
40966
+ `sponsor config per-operation fee band is inverted (min ${minPerOp} > max ${maxPerOp})`,
40967
+ { field: "maxPerOperationFeeStroops" }
40968
+ );
40969
+ sponsoringInvariant(
40970
+ Number.isInteger(config.operationCount) && BigInt(config.operationCount) === SPONSORED_CREATE_OP_COUNT,
40971
+ `sponsor config expects ${config.operationCount} operations but this builder emits ${SPONSORED_CREATE_OP_COUNT} \u2014 the sponsored-create shape has changed server-side`,
40972
+ { field: "operationCount" }
40973
+ );
40974
+ const baseFee = parseStroops(config.recommendedPerOperationFeeStroops, "recommendedPerOperationFeeStroops");
40975
+ const totalFee = baseFee * SPONSORED_CREATE_OP_COUNT;
40976
+ sponsoringInvariant(
40977
+ baseFee >= minPerOp && baseFee <= maxPerOp,
40978
+ `per-operation fee ${baseFee} is outside the accepted per-operation band [${minPerOp}, ${maxPerOp}]`,
40979
+ { field: "recommendedPerOperationFeeStroops" }
40980
+ );
40981
+ sponsoringInvariant(
40982
+ totalFee >= min && totalFee <= max,
40983
+ `per-operation fee ${baseFee} yields a total of ${totalFee} stroops, outside the accepted band [${min}, ${max}]`,
40984
+ { field: "recommendedPerOperationFeeStroops" }
40985
+ );
40986
+ return { baseFee: baseFee.toString(), totalFee };
40987
+ }
40988
+ function resolveTimeboundSeconds(config) {
40989
+ const ceiling = Math.floor(config.maxTimeboundSeconds);
40990
+ const seconds = Math.min(SPONSOR_TIMEBOUND_SECONDS, ceiling);
40991
+ sponsoringInvariant(
40992
+ Number.isFinite(seconds) && seconds > 0,
40993
+ `sponsor config maxTimeboundSeconds leaves no usable window, got ${config.maxTimeboundSeconds}`,
40994
+ { field: "maxTimeboundSeconds" }
40995
+ );
40996
+ return seconds;
40997
+ }
40998
+ function assertSponsoredCreateInputs(params) {
40999
+ const { config, address } = params;
41000
+ sponsoringInvariant(
41001
+ config.networkPassphrase === Networks.PUBLIC,
41002
+ `sponsored create must target the Stellar public network, got "${config.networkPassphrase}"`,
41003
+ { field: "networkPassphrase" }
41004
+ );
41005
+ assertValidStellarAccountId(address);
41006
+ assertValidStellarAccountId(config.sponsorAccount);
41007
+ deriveSponsorBaseFee(config);
41008
+ resolveTimeboundSeconds(config);
41009
+ }
41010
+ function buildSponsoredCreate(params) {
41011
+ const { config, sponsorSequence, address } = params;
41012
+ assertSponsoredCreateInputs({ config, address });
41013
+ const { baseFee } = deriveSponsorBaseFee(config);
41014
+ const timeboundSeconds = resolveTimeboundSeconds(config);
41015
+ return new TransactionBuilder(new Account(config.sponsorAccount, sponsorSequence), {
41016
+ fee: baseFee,
41017
+ networkPassphrase: config.networkPassphrase
41018
+ }).addOperation(Operation.beginSponsoringFutureReserves({ sponsoredId: address })).addOperation(Operation.createAccount({ destination: address, startingBalance: config.requiredStartingBalance })).addOperation(Operation.endSponsoringFutureReserves({ source: address })).setTimeout(timeboundSeconds).build();
41019
+ }
41020
+ function assertValidStellarAccountId(address) {
41021
+ let valid = true;
41022
+ try {
41023
+ Keypair.fromPublicKey(address);
41024
+ } catch {
41025
+ valid = false;
41026
+ }
41027
+ sponsoringInvariant(valid, `"${address}" is not a valid Stellar ed25519 public key`, { field: "address" });
41028
+ }
41029
+ function assertSignedByAccount(params) {
41030
+ const { signedXdr, address, unsignedHash } = params;
41031
+ let parsed;
41032
+ try {
41033
+ parsed = TransactionBuilder.fromXDR(signedXdr, Networks.PUBLIC);
41034
+ } catch (error) {
41035
+ sponsoringInvariant(false, `wallet returned an unparseable transaction: ${messageOf(error, String(error))}`, {
41036
+ field: "signature"
41037
+ });
41038
+ }
41039
+ sponsoringInvariant(
41040
+ !(parsed instanceof FeeBumpTransaction),
41041
+ "wallet returned a fee-bump envelope; the sponsoring API rejects fee-bump transactions",
41042
+ { field: "signature" }
41043
+ );
41044
+ const hash = parsed.hash();
41045
+ sponsoringInvariant(
41046
+ hash.equals(unsignedHash),
41047
+ "wallet altered the transaction before signing it (fee, memo, or time bounds changed)",
41048
+ { field: "signature" }
41049
+ );
41050
+ const keypair = Keypair.fromPublicKey(address);
41051
+ const signedByAccount = parsed.signatures.some((signature) => {
41052
+ try {
41053
+ return keypair.verify(hash, signature.signature());
41054
+ } catch {
41055
+ return false;
41056
+ }
41057
+ });
41058
+ sponsoringInvariant(
41059
+ signedByAccount,
41060
+ "signed transaction is not signed by the account being activated \u2014 the wallet may be connected to a different Stellar network, or may have signed with a different account",
41061
+ { field: "signature" }
41062
+ );
41063
+ }
41064
+ function isHorizonNotFound(error) {
41065
+ if (error instanceof NotFoundError) return true;
41066
+ const status = error?.response?.status;
41067
+ return status === 404;
41068
+ }
41069
+ var XLM_DECIMALS = 7;
41070
+ function xlmDecimalToStroops(amount) {
41071
+ if (!/^\d+(\.\d+)?$/.test(amount)) return 0n;
41072
+ const [whole = "0", fraction = ""] = amount.split(".");
41073
+ const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
41074
+ return BigInt(scaled);
41075
+ }
41076
+ var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
41077
+ var BASE_RESERVE_UNITS = 2;
41078
+ function parseBaseReserveStroops(ledger) {
41079
+ const value = ledger?.base_reserve_in_stroops;
41080
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) return void 0;
41081
+ return BigInt(value);
41082
+ }
41083
+ function readReserveInfo(account, baseReserveStroops) {
41084
+ const native = account.balances.find((balance) => balance.asset_type === "native");
41085
+ const nativeBalanceStroops = native ? xlmDecimalToStroops(native.balance) : 0n;
41086
+ const sellingLiabilitiesStroops = native?.selling_liabilities ? xlmDecimalToStroops(native.selling_liabilities) : 0n;
41087
+ const units = Math.max(
41088
+ 0,
41089
+ BASE_RESERVE_UNITS + (account.subentry_count ?? 0) + (account.num_sponsoring ?? 0) - (account.num_sponsored ?? 0)
41090
+ );
41091
+ const lockedStroops = BigInt(units) * baseReserveStroops + sellingLiabilitiesStroops;
41092
+ return {
41093
+ nativeBalanceStroops,
41094
+ availableBalanceStroops: nativeBalanceStroops > lockedStroops ? nativeBalanceStroops - lockedStroops : 0n
41095
+ };
41096
+ }
41097
+
41098
+ // src/sponsoring/SponsoringService.ts
41099
+ var SPONSOR_CONFIG_TTL_MS = 6e4;
41100
+ var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
41101
+ var DEFAULT_MAX_HORIZON_RETRIES = 2;
41102
+ var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
41103
+ var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS + STELLAR_FEE_HEADROOM_STROOPS;
41104
+ var SponsoringService = class {
41105
+ config;
41106
+ spoke;
41107
+ api;
41108
+ /** Keyed by base URL to isolate deployment-specific sponsor config. */
41109
+ configCache = /* @__PURE__ */ new Map();
41110
+ inflightConfig = /* @__PURE__ */ new Map();
41111
+ baseReserveCache;
41112
+ inflightBaseReserve;
41113
+ constructor(deps) {
41114
+ this.config = deps.config;
41115
+ this.spoke = deps.spoke;
41116
+ this.api = deps.api;
41117
+ }
41118
+ get horizon() {
41119
+ return this.spoke.stellar.server;
41120
+ }
41121
+ /**
41122
+ * Whether an account exists. Read failures remain errors rather than being
41123
+ * misreported as inactive.
41124
+ */
41125
+ async isStellarAccountActive(params) {
41126
+ const account = await this.readAccount(params.address, "isStellarAccountActive");
41127
+ return account.ok ? { ok: true, value: account.value !== void 0 } : account;
41128
+ }
41129
+ /**
41130
+ * Return account existence and trustline affordability. Costs one Horizon
41131
+ * account read, plus a base-reserve read on the first call per hour.
41132
+ */
41133
+ async getStellarAccountStatus(params) {
41134
+ const account = await this.readAccount(params.address, "getStellarAccountStatus");
41135
+ if (!account.ok) return account;
41136
+ const baseReserveStroops = await this.resolveBaseReserveStroops();
41137
+ const trustlineMinXlmStroops = baseReserveStroops + STELLAR_FEE_HEADROOM_STROOPS;
41138
+ if (account.value === void 0) {
41139
+ return {
41140
+ ok: true,
41141
+ value: {
41142
+ exists: false,
41143
+ nativeBalanceStroops: 0n,
41144
+ availableBalanceStroops: 0n,
41145
+ canAffordTrustline: false,
41146
+ trustlineMinXlmStroops
41147
+ }
41148
+ };
41149
+ }
41150
+ const { nativeBalanceStroops, availableBalanceStroops } = readReserveInfo(account.value, baseReserveStroops);
41151
+ return {
41152
+ ok: true,
41153
+ value: {
41154
+ exists: true,
41155
+ nativeBalanceStroops,
41156
+ availableBalanceStroops,
41157
+ canAffordTrustline: availableBalanceStroops >= trustlineMinXlmStroops,
41158
+ trustlineMinXlmStroops
41159
+ }
41160
+ };
41161
+ }
41162
+ /**
41163
+ * Shared account read. A 404 resolves to `undefined` because absence is a
41164
+ * legitimate answer; every other failure remains an error.
41165
+ */
41166
+ async readAccount(address, action) {
41167
+ if (address.length === 0) {
41168
+ return {
41169
+ ok: false,
41170
+ error: new SodaxError("VALIDATION_FAILED", "address is required", {
41171
+ feature: "sponsoring",
41172
+ context: { phase: "validate", method: action, field: "address" }
41173
+ })
41174
+ };
41175
+ }
41176
+ try {
41177
+ return { ok: true, value: await this.horizon.loadAccount(address) };
41178
+ } catch (error) {
41179
+ if (isHorizonNotFound(error)) return { ok: true, value: void 0 };
41180
+ return {
41181
+ ok: false,
41182
+ error: lookupFailed("sponsoring", action, error, { srcChainKey: ChainKeys.STELLAR_MAINNET })
41183
+ };
41184
+ }
41185
+ }
41186
+ /**
41187
+ * The base reserve is a validator-controlled network setting, so read it from
41188
+ * the latest ledger rather than assuming the published 0.5 XLM. A failed read
41189
+ * degrades to that value: this drives a UI hint, never a signed transaction.
41190
+ */
41191
+ async resolveBaseReserveStroops() {
41192
+ const cached = this.baseReserveCache;
41193
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
41194
+ const inflight = this.inflightBaseReserve;
41195
+ if (inflight) return inflight;
41196
+ const read = async () => {
41197
+ try {
41198
+ const page = await this.horizon.ledgers().order("desc").limit(1).call();
41199
+ const value = parseBaseReserveStroops(page.records[0]);
41200
+ if (value !== void 0) return value;
41201
+ } catch (error) {
41202
+ this.config.logger.warn("[SponsoringService] Stellar base-reserve read failed; assuming the published value", {
41203
+ reason: messageOf(error, String(error))
41204
+ });
41205
+ }
41206
+ return STELLAR_BASE_RESERVE_STROOPS;
41207
+ };
41208
+ const request = read().then((value) => {
41209
+ this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
41210
+ return value;
41211
+ }).finally(() => {
41212
+ if (this.inflightBaseReserve === request) this.inflightBaseReserve = void 0;
41213
+ });
41214
+ this.inflightBaseReserve = request;
41215
+ return request;
41216
+ }
41217
+ /**
41218
+ * Cache key for a config request: the resolved base URL plus any per-call
41219
+ * headers. Headers can select a different response from the same URL — an API
41220
+ * key scoped to another deployment, or a test harness's scenario header — so
41221
+ * folding them in stops one caller's override from being served to, or
41222
+ * overwriting, the default path. Kept in memory as a Map key only.
41223
+ */
41224
+ configCacheKey(requestConfig) {
41225
+ const baseURL = requestConfig?.baseURL || this.api.sponsoring.getBaseURL();
41226
+ const headers = requestConfig?.headers;
41227
+ if (!headers) return baseURL;
41228
+ const normalized = Object.keys(headers).sort().map((name) => `${name.toLowerCase()}=${headers[name]}`).join("&");
41229
+ return normalized.length === 0 ? baseURL : `${baseURL}|${normalized}`;
41230
+ }
41231
+ /**
41232
+ * Fetch sponsor config with per-endpoint caching and in-flight deduplication.
41233
+ * Failures are never cached.
41234
+ */
41235
+ async getStellarSponsorConfig(params) {
41236
+ const key = this.configCacheKey(params?.requestConfig);
41237
+ if (params?.forceRefresh) {
41238
+ this.configCache.delete(key);
41239
+ this.inflightConfig.delete(key);
41240
+ } else {
41241
+ const cached = this.configCache.get(key);
41242
+ if (cached && cached.expiresAt > Date.now()) return { ok: true, value: cached.value };
41243
+ const inflight = this.inflightConfig.get(key);
41244
+ if (inflight) return inflight;
41245
+ }
41246
+ const request = this.api.sponsoring.getStellarSponsorConfig(params?.requestConfig).then((result) => {
41247
+ if (result.ok && this.inflightConfig.get(key) === request) {
41248
+ const now = Date.now();
41249
+ for (const [cached, entry] of this.configCache) {
41250
+ if (entry.expiresAt <= now) this.configCache.delete(cached);
41251
+ }
41252
+ this.configCache.set(key, { value: result.value, expiresAt: now + SPONSOR_CONFIG_TTL_MS });
41253
+ }
41254
+ return result;
41255
+ }).finally(() => {
41256
+ if (this.inflightConfig.get(key) === request) this.inflightConfig.delete(key);
41257
+ });
41258
+ this.inflightConfig.set(key, request);
41259
+ return request;
41260
+ }
41261
+ /**
41262
+ * Activate an account with a sponsored base reserve. Config and existence are
41263
+ * checked before prompting; sponsor sequence is never cached.
41264
+ */
41265
+ async activateStellarAccount(params) {
41266
+ let attempts = 0;
41267
+ return this.config.analytics.trackResult(
41268
+ "sponsoring",
41269
+ "activateStellarAccount",
41270
+ async () => {
41271
+ try {
41272
+ const { address } = params;
41273
+ const configResult = await this.getStellarSponsorConfig({
41274
+ forceRefresh: params.forceConfigRefresh,
41275
+ requestConfig: params.requestConfig
41276
+ });
41277
+ if (!configResult.ok) return configResult;
41278
+ const sponsorConfig = configResult.value;
41279
+ if (await this.accountExistsBestEffort(address)) {
41280
+ return { ok: true, value: { status: "alreadyActive", hash: null, attempts: 0 } };
41281
+ }
41282
+ attempts = 1;
41283
+ const first = await this.attemptActivation({ params, sponsorConfig, attempt: 1 });
41284
+ if (first.ok || params.allowSequenceRetry === false) return first;
41285
+ if (first.error.context?.nextAction !== "rebuildAndResign") return first;
41286
+ attempts = 2;
41287
+ return this.attemptActivation({
41288
+ params,
41289
+ sponsorConfig,
41290
+ attempt: 2,
41291
+ sponsorSequenceHint: first.error.context?.sponsorSequence
41292
+ });
41293
+ } catch (error) {
41294
+ if (isSodaxError(error)) {
41295
+ return { ok: false, error };
41296
+ }
41297
+ return {
41298
+ ok: false,
41299
+ error: unknownFailed("sponsoring", error, { action: "activateStellarAccount" })
41300
+ };
41301
+ }
41302
+ },
41303
+ {
41304
+ start: () => ({ srcChainKey: ChainKeys.STELLAR_MAINNET, address: params.address }),
41305
+ success: (value) => ({ status: value.status, attempts: value.attempts, hash: value.hash }),
41306
+ failure: (error) => ({
41307
+ code: error.code,
41308
+ // Preserve evidence that a sequence-conflict retry occurred.
41309
+ attempts,
41310
+ // `status` is already the domain outcome in success events.
41311
+ httpStatus: error.context?.status,
41312
+ nextAction: error.context?.nextAction
41313
+ })
41314
+ }
41315
+ );
41316
+ }
41317
+ /** One build, sign, and submit attempt. */
41318
+ async attemptActivation(args) {
41319
+ const { params, sponsorConfig, attempt, sponsorSequenceHint } = args;
41320
+ const { address, walletProvider } = params;
41321
+ assertSponsoredCreateInputs({ config: sponsorConfig, address });
41322
+ let sponsorSequence;
41323
+ if (sponsorSequenceHint !== void 0) {
41324
+ sponsorSequence = sponsorSequenceHint;
41325
+ } else {
41326
+ try {
41327
+ const sponsorAccount = await this.horizon.loadAccount(sponsorConfig.sponsorAccount);
41328
+ sponsorSequence = sponsorAccount.sequenceNumber();
41329
+ } catch (error) {
41330
+ return {
41331
+ ok: false,
41332
+ error: lookupFailed("sponsoring", "loadSponsorAccount", error, {
41333
+ action: "activateStellarAccount",
41334
+ srcChainKey: ChainKeys.STELLAR_MAINNET
41335
+ })
41336
+ };
41337
+ }
41338
+ }
41339
+ const transaction = buildSponsoredCreate({ config: sponsorConfig, sponsorSequence, address });
41340
+ const unsignedHash = transaction.hash();
41341
+ params.onSignatureRequired?.({ attempt, reason: attempt === 1 ? "initial" : "sequenceConflict" });
41342
+ let signedXdr;
41343
+ try {
41344
+ signedXdr = await walletProvider.signTransaction(transaction.toXDR(), { address });
41345
+ } catch (error) {
41346
+ return {
41347
+ ok: false,
41348
+ error: intentCreationFailed("sponsoring", error, {
41349
+ action: "activateStellarAccount",
41350
+ srcChainKey: ChainKeys.STELLAR_MAINNET
41351
+ })
41352
+ };
41353
+ }
41354
+ assertSignedByAccount({ signedXdr, address, unsignedHash });
41355
+ const submitted = await this.submitWithHorizonRetry({
41356
+ signedXdr,
41357
+ maxRetries: params.maxHorizonRetries ?? DEFAULT_MAX_HORIZON_RETRIES,
41358
+ requestConfig: params.requestConfig
41359
+ });
41360
+ if (submitted.ok) {
41361
+ const response = submitted.value;
41362
+ return response.alreadyActive ? { ok: true, value: { status: "alreadyActive", hash: null, attempts: attempt } } : { ok: true, value: { status: "submitted", hash: response.hash, attempts: attempt } };
41363
+ }
41364
+ const classification = classifySponsorError(submitted.error);
41365
+ if (classification.action === "fixIntegration") {
41366
+ this.configCache.delete(this.configCacheKey(params.requestConfig));
41367
+ }
41368
+ return {
41369
+ ok: false,
41370
+ error: new SodaxError("EXTERNAL_API_ERROR", classification.message, {
41371
+ feature: "sponsoring",
41372
+ cause: submitted.error,
41373
+ context: {
41374
+ api: "sponsoring",
41375
+ action: "activateStellarAccount",
41376
+ phase: "submit",
41377
+ srcChainKey: ChainKeys.STELLAR_MAINNET,
41378
+ attempts: attempt,
41379
+ nextAction: classification.action,
41380
+ retryable: classification.retryable,
41381
+ requiresNewSignature: classification.requiresNewSignature,
41382
+ sponsorAccount: sponsorConfig.sponsorAccount,
41383
+ status: classification.status,
41384
+ code: classification.code,
41385
+ retryAfterSeconds: classification.retryAfterSeconds,
41386
+ sponsorSequence: classification.sponsorSequence
41387
+ }
41388
+ })
41389
+ };
41390
+ }
41391
+ /**
41392
+ * Re-submit identical signed bytes only for `retrySameRequest` failures.
41393
+ */
41394
+ async submitWithHorizonRetry(args) {
41395
+ const { signedXdr, maxRetries, requestConfig } = args;
41396
+ let result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
41397
+ for (let retry2 = 0; retry2 < maxRetries && !result.ok; retry2++) {
41398
+ if (classifySponsorError(result.error).action !== "retrySameRequest") break;
41399
+ await sleep(1e3 * (retry2 + 1));
41400
+ result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
41401
+ }
41402
+ return result;
41403
+ }
41404
+ /**
41405
+ * Best-effort existence pre-flight. Read failures continue to activation
41406
+ * because the server performs the authoritative check.
41407
+ */
41408
+ async accountExistsBestEffort(address) {
41409
+ const account = await this.readAccount(address, "isStellarAccountActive");
41410
+ if (account.ok) return account.value !== void 0;
41411
+ this.config.logger.warn(
41412
+ "[SponsoringService] Stellar account existence pre-flight failed; continuing with activation",
41413
+ { address, reason: messageOf(account.error, String(account.error)) }
41414
+ );
41415
+ return false;
41416
+ }
41417
+ };
41418
+
40101
41419
  // src/shared/entities/Sodax.ts
40102
41420
  var Sodax = class {
40103
41421
  instanceConfig;
@@ -40121,6 +41439,7 @@ var Sodax = class {
40121
41439
  // Recovery service for withdrawing stuck hub-wallet assets back to a spoke chain
40122
41440
  dex;
40123
41441
  // Dex service enabling DEX operations
41442
+ sponsoring;
40124
41443
  leverageYield;
40125
41444
  // Leverage-yield service: cross-chain deposits / withdrawals into ERC-4626 leverage vaults on Sonic
40126
41445
  config;
@@ -40133,7 +41452,9 @@ var Sodax = class {
40133
41452
  const logger = resolveLogger(options?.logger);
40134
41453
  const analytics = resolveAnalytics(options?.analytics);
40135
41454
  const fee = options?.fee;
41455
+ const radfiSigner = options?.radfi?.signRequest;
40136
41456
  const useBackendSubmitTx = options?.swapsOptions?.useBackendSubmitTx ?? false;
41457
+ const bridgeUseBackendSubmitTx = options?.bridgeOptions?.useBackendSubmitTx ?? false;
40137
41458
  this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
40138
41459
  this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
40139
41460
  this.api = this.backendApi;
@@ -40143,7 +41464,8 @@ var Sodax = class {
40143
41464
  userConfig: options,
40144
41465
  logger,
40145
41466
  analytics,
40146
- fee
41467
+ fee,
41468
+ radfiSigner
40147
41469
  });
40148
41470
  this.hubProvider = new EvmHubProvider({ config: this.config });
40149
41471
  this.spoke = new SpokeService({ config: this.config, hubProvider: this.hubProvider });
@@ -40169,7 +41491,13 @@ var Sodax = class {
40169
41491
  config: this.config,
40170
41492
  spoke: this.spoke
40171
41493
  });
40172
- this.bridge = new BridgeService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
41494
+ this.bridge = new BridgeService({
41495
+ hubProvider: this.hubProvider,
41496
+ config: this.config,
41497
+ spoke: this.spoke,
41498
+ backendApi: this.backendApi,
41499
+ useBackendSubmitTx: bridgeUseBackendSubmitTx
41500
+ });
40173
41501
  this.staking = new StakingService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
40174
41502
  this.partners = new PartnerService({
40175
41503
  hubProvider: this.hubProvider,
@@ -40186,6 +41514,11 @@ var Sodax = class {
40186
41514
  config: this.config,
40187
41515
  spoke: this.spoke
40188
41516
  });
41517
+ this.sponsoring = new SponsoringService({
41518
+ config: this.config,
41519
+ spoke: this.spoke,
41520
+ api: this.backendApi
41521
+ });
40189
41522
  }
40190
41523
  /**
40191
41524
  * Initializes the Sodax instance with dynamic configuration.
@@ -40227,4 +41560,4 @@ var isPartnerError = isCodeMember(PARTNER_CODES);
40227
41560
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
40228
41561
  */
40229
41562
 
40230
- export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, erc20Abi, erc4626Abi, estimateBitcoinTxSize, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, serializeAddressData, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
41563
+ export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BITCOIN_DUST_SATS, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BackendHttpError, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeApiService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DEFAULT_SPONSORING_API_ENDPOINT, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RELAY_FALLBACK_FLOOR_MS, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, SPONSORING_API_ERROR_CODES, SPONSORING_API_STELLAR_BASE_PATH, SPONSOR_CONFIG_TTL_MS, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_BASE_RESERVE_TTL_MS, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, SponsoringApiService, SponsoringService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, classifySponsorError, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, erc20Abi, erc4626Abi, estimateBitcoinTxSize, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isBackendHttpError, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeBitcoinToken, isNativeBitcoinTransfer, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isSponsoringConfigError, isSponsoringLookupError, isSponsoringOrchestrationError, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, serializeAddressData, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, sponsoringInvariant, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, toCreateBridgeIntentParamsV2, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };