@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.cjs CHANGED
@@ -19,7 +19,7 @@ var IconSdkRaw = require('icon-sdk-js');
19
19
  var sdkTs = require('@injectivelabs/sdk-ts');
20
20
  var tx_js = require('cosmjs-types/cosmos/tx/v1beta1/tx.js');
21
21
  var networks = require('@injectivelabs/networks');
22
- var v2 = require('valibot');
22
+ var v7 = require('valibot');
23
23
  var swapsApi = require('@sodax/swaps-api');
24
24
  var BigNumber5 = require('bignumber.js');
25
25
  var swapSdkCore = require('@pancakeswap/swap-sdk-core');
@@ -49,7 +49,7 @@ var rlp__namespace = /*#__PURE__*/_interopNamespace(rlp);
49
49
  var ecc__namespace = /*#__PURE__*/_interopNamespace(ecc);
50
50
  var BN__default = /*#__PURE__*/_interopDefault(BN);
51
51
  var IconSdkRaw__namespace = /*#__PURE__*/_interopNamespace(IconSdkRaw);
52
- var v2__namespace = /*#__PURE__*/_interopNamespace(v2);
52
+ var v7__namespace = /*#__PURE__*/_interopNamespace(v7);
53
53
  var BigNumber5__default = /*#__PURE__*/_interopDefault(BigNumber5);
54
54
 
55
55
  // src/errors/SodaxError.ts
@@ -122,8 +122,8 @@ function serializeCause(cause, depth) {
122
122
  }
123
123
  function sanitizeContext(value, depth) {
124
124
  const out = {};
125
- for (const [key, v4] of Object.entries(value)) {
126
- out[key] = sanitizeValue(v4, depth + 1);
125
+ for (const [key, v9] of Object.entries(value)) {
126
+ out[key] = sanitizeValue(v9, depth + 1);
127
127
  }
128
128
  return out;
129
129
  }
@@ -134,13 +134,13 @@ function sanitizeValue(value, depth) {
134
134
  if (t === "bigint") return value.toString();
135
135
  if (t === "string" || t === "number" || t === "boolean") return value;
136
136
  if (t === "function" || t === "symbol") return safeString(value);
137
- if (Array.isArray(value)) return value.map((v4) => sanitizeValue(v4, depth + 1));
137
+ if (Array.isArray(value)) return value.map((v9) => sanitizeValue(v9, depth + 1));
138
138
  if (value instanceof Date) return value.toISOString();
139
139
  if (value instanceof Map) {
140
- return Array.from(value.entries()).map(([k, v4]) => [sanitizeValue(k, depth + 1), sanitizeValue(v4, depth + 1)]);
140
+ return Array.from(value.entries()).map(([k, v9]) => [sanitizeValue(k, depth + 1), sanitizeValue(v9, depth + 1)]);
141
141
  }
142
142
  if (value instanceof Set) {
143
- return Array.from(value.values()).map((v4) => sanitizeValue(v4, depth + 1));
143
+ return Array.from(value.values()).map((v9) => sanitizeValue(v9, depth + 1));
144
144
  }
145
145
  if (value instanceof Error) return { name: value.name, message: value.message };
146
146
  if (t === "object") {
@@ -152,9 +152,9 @@ function sanitizeValue(value, depth) {
152
152
  }
153
153
  return safeString(value);
154
154
  }
155
- function safeString(v4) {
155
+ function safeString(v9) {
156
156
  try {
157
- return String(v4);
157
+ return String(v9);
158
158
  } catch {
159
159
  return "[unserializable]";
160
160
  }
@@ -210,6 +210,7 @@ var SODAX_FEATURES = [
210
210
  "partner",
211
211
  "recovery",
212
212
  "backend",
213
+ "sponsoring",
213
214
  "leverageYield"
214
215
  ];
215
216
 
@@ -512,7 +513,7 @@ var SodaTokens = {
512
513
  name: "Soda RBNT",
513
514
  decimals: 18,
514
515
  address: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac",
515
- chainKey: ChainKeys.REDBELLY_MAINNET,
516
+ chainKey: ChainKeys.SONIC_MAINNET,
516
517
  hubAsset: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac",
517
518
  vault: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac"
518
519
  },
@@ -3524,6 +3525,8 @@ var DEFAULT_BACKEND_API_HEADERS = {
3524
3525
  };
3525
3526
  var DEFAULT_RELAYER_API_ENDPOINT = "https://xcall-relay.nw.iconblockchain.xyz";
3526
3527
  var VAULT_TOKEN_DECIMALS = 18;
3528
+ var DEFAULT_SPONSORING_API_ENDPOINT = "https://api.sodax.com/v1";
3529
+ var SPONSORING_API_STELLAR_BASE_PATH = "/sponsorships/stellar";
3527
3530
  var apiConfig = {
3528
3531
  baseURL: DEFAULT_BACKEND_API_ENDPOINT,
3529
3532
  timeout: DEFAULT_BACKEND_API_TIMEOUT,
@@ -4257,7 +4260,23 @@ var sodaxConfig = {
4257
4260
  relay: relayConfig
4258
4261
  };
4259
4262
 
4263
+ // ../types/dist/backend/sponsoringApi.js
4264
+ var SPONSORING_API_ERROR_CODES = [
4265
+ "INVALID_SPONSOR_XDR",
4266
+ "INVALID_RESERVE_DATA",
4267
+ "SPONSOR_SEQUENCE_CONFLICT",
4268
+ "SPONSOR_TRANSACTION_REJECTED",
4269
+ "HORIZON_UNAVAILABLE",
4270
+ "SPONSOR_RATE_LIMITED",
4271
+ "SPONSOR_BUDGET_EXHAUSTED"
4272
+ ];
4273
+
4260
4274
  // ../types/dist/bitcoin/bitcoin.js
4275
+ var BITCOIN_DUST_SATS = 546n;
4276
+ function isNativeBitcoinToken(chainConfig, token) {
4277
+ const nativeBtcTokens = new Set(["btc", chainConfig.nativeToken, chainConfig.supportedTokens.BTC?.address].filter((value) => !!value).map((value) => value.toLowerCase()));
4278
+ return nativeBtcTokens.has(token.toLowerCase());
4279
+ }
4261
4280
  function isSupportedBitcoinAddressType(addressType) {
4262
4281
  return BTC_ADDRESS_TYPES.includes(addressType);
4263
4282
  }
@@ -4417,7 +4436,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4417
4436
  }
4418
4437
 
4419
4438
  // ../types/dist/index.js
4420
- var CONFIG_VERSION = 220;
4439
+ var CONFIG_VERSION = 222;
4421
4440
  function isEvmSpokeChainConfig(value) {
4422
4441
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
4423
4442
  }
@@ -4528,6 +4547,9 @@ function isUndefinedOrValidWalletProviderForChainKey(chainKey, walletProvider) {
4528
4547
  function isOptionalBitcoinWalletProviderType(walletProvider) {
4529
4548
  return walletProvider === void 0 || isBitcoinWalletProviderType(walletProvider);
4530
4549
  }
4550
+ function isNativeBitcoinTransfer(config, chainKey, token) {
4551
+ return isBitcoinChainKeyType(chainKey) && !!token && isNativeBitcoinToken(config.getChainConfig(chainKey), token.address);
4552
+ }
4531
4553
  async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
4532
4554
  do {
4533
4555
  try {
@@ -4544,11 +4566,11 @@ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_R
4544
4566
  throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
4545
4567
  }
4546
4568
  function getRandomBytes(length) {
4547
- const array2 = new Uint8Array(length);
4569
+ const array3 = new Uint8Array(length);
4548
4570
  for (let i = 0; i < length; i++) {
4549
- array2[i] = Math.floor(Math.random() * 256);
4571
+ array3[i] = Math.floor(Math.random() * 256);
4550
4572
  }
4551
- return array2;
4573
+ return array3;
4552
4574
  }
4553
4575
  function randomUint256() {
4554
4576
  const bytes = getRandomBytes(32);
@@ -4710,6 +4732,7 @@ var HttpRelayError = class extends Error {
4710
4732
  }
4711
4733
  };
4712
4734
  var RELAY_REQUEST_TIMEOUT_MS = 15e3;
4735
+ var RELAY_FALLBACK_FLOOR_MS = 5e3;
4713
4736
  function isAbortError(error) {
4714
4737
  return error instanceof Error && error.name === "AbortError";
4715
4738
  }
@@ -14008,6 +14031,13 @@ var ConfigService = class {
14008
14031
  * a client-side option set via `new Sodax({ fee })`. Per-feature overrides live on the feature config.
14009
14032
  */
14010
14033
  fee;
14034
+ /**
14035
+ * RadFi/Bound request signer. Resolved once at construction and kept independent of {@link sodax}
14036
+ * so that {@link initialize}'s dynamic-config swap never clobbers it. Read by `BitcoinSpokeService`
14037
+ * via `config.radfiSigner`; `undefined` unless the consumer passed `radfi.signRequest` to
14038
+ * `new Sodax(...)`. Holds the function reference only — never a credential.
14039
+ */
14040
+ radfiSigner;
14011
14041
  initialized = false;
14012
14042
  // data structures for quick lookup
14013
14043
  supportedHubAssetsSet;
@@ -14021,11 +14051,12 @@ var ConfigService = class {
14021
14051
  hubAssetToXTokenMap;
14022
14052
  // `api` / `userConfig` are accepted but unused while initialize()'s dynamic fetch is disabled
14023
14053
  // (see TODO(config-v2) below); restore their assignments when re-enabling.
14024
- constructor({ api, config, userConfig, logger, analytics, fee }) {
14054
+ constructor({ api, config, userConfig, logger, analytics, fee, radfiSigner }) {
14025
14055
  this.sodax = config;
14026
14056
  this.logger = logger ?? resolveLogger(void 0);
14027
14057
  this.analytics = analytics ?? noopAnalytics;
14028
14058
  this.fee = fee;
14059
+ this.radfiSigner = radfiSigner;
14029
14060
  this.loadSodaxConfigDataStructures(config);
14030
14061
  }
14031
14062
  async initialize() {
@@ -14324,7 +14355,7 @@ function mergeSodaxConfig(base2, override) {
14324
14355
  }
14325
14356
  function encodeContractCalls(calls) {
14326
14357
  return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
14327
- calls.map((v4) => [v4.address, v4.value, v4.data])
14358
+ calls.map((v9) => [v9.address, v9.value, v9.data])
14328
14359
  ]);
14329
14360
  }
14330
14361
  async function waitForTransactionReceipt(hash, provider) {
@@ -15236,10 +15267,14 @@ var RadfiApiError = class extends Error {
15236
15267
  };
15237
15268
  var RadfiProvider = class {
15238
15269
  config;
15270
+ // Client-side runtime signer (e.g. a backend's HMAC closure). Holds no credential itself — the SDK
15271
+ // only keeps the reference and invokes it per outbound `apiUrl` request. See `RadfiOptions` / gh-831.
15272
+ signer;
15239
15273
  accessToken = "";
15240
15274
  refreshToken = "";
15241
- constructor(config) {
15275
+ constructor(config, options) {
15242
15276
  this.config = config;
15277
+ this.signer = options?.signer;
15243
15278
  this.accessToken = config.accessToken ?? "";
15244
15279
  this.refreshToken = config.refreshToken ?? "";
15245
15280
  if (config.apiUrl.endsWith("/")) {
@@ -15350,6 +15385,9 @@ var RadfiProvider = class {
15350
15385
  }
15351
15386
  return body.data;
15352
15387
  }
15388
+ // UMS call: goes out unsigned even when a signer is configured. Bound scopes the backend
15389
+ // credential to the Sodax endpoints on `apiUrl`, so a signature here is unverified — this
15390
+ // deliberately does not go through `request()`. Same for `getExpiredUtxos` below. See gh-831.
15353
15391
  async getBalance(address) {
15354
15392
  if (!this.config.umsUrl) {
15355
15393
  throw new Error("RadfiConfig.umsUrl is required for getBalance");
@@ -15427,6 +15465,9 @@ var RadfiProvider = class {
15427
15465
  }
15428
15466
  /**
15429
15467
  * Fetch expired (or near-expiry) UTXOs for a trading wallet address from UMS API.
15468
+ *
15469
+ * UMS call — unsigned by design, like `getBalance`: the backend credential is scoped to the
15470
+ * Sodax endpoints on `apiUrl`, so a configured signer intentionally does not reach here.
15430
15471
  */
15431
15472
  async getExpiredUtxos(tradingAddress, params) {
15432
15473
  if (!this.config.umsUrl) {
@@ -15608,11 +15649,13 @@ var RadfiProvider = class {
15608
15649
  }
15609
15650
  }
15610
15651
  async request(endpoint, options) {
15652
+ const signed = this.signer ? await this.signer({ method: options?.method ?? "GET", path: endpoint }) : void 0;
15611
15653
  return fetch(`${this.config.apiUrl}${endpoint}`, {
15612
15654
  ...options,
15613
15655
  headers: {
15614
15656
  "Content-Type": "application/json",
15615
- ...options?.headers || {}
15657
+ ...options?.headers || {},
15658
+ ...signed
15616
15659
  }
15617
15660
  });
15618
15661
  }
@@ -15675,7 +15718,7 @@ function normalizeSignatureToBase64(signature) {
15675
15718
  // src/shared/services/spoke/BitcoinSpokeService.ts
15676
15719
  bitcoinjsLib.initEccLib(ecc__namespace);
15677
15720
  var BITCOIN_DEFAULT_FEE_RATE = 3;
15678
- var DUST_THRESHOLD = 546;
15721
+ var DUST_THRESHOLD = Number(BITCOIN_DUST_SATS);
15679
15722
  var BitcoinSpokeService = class {
15680
15723
  config;
15681
15724
  rpcUrl;
@@ -15687,7 +15730,7 @@ var BitcoinSpokeService = class {
15687
15730
  this.config = config;
15688
15731
  const chainConfig = config.getChainConfig(ChainKeys.BITCOIN_MAINNET);
15689
15732
  this.rpcUrl = chainConfig.rpcUrl;
15690
- this.radfi = new RadfiProvider(chainConfig.radfi);
15733
+ this.radfi = new RadfiProvider(chainConfig.radfi, { signer: config.radfiSigner });
15691
15734
  this.walletMode = chainConfig.radfi.walletMode ?? "TRADING";
15692
15735
  this.pollingIntervalMs = chainConfig.pollingConfig.pollingIntervalMs;
15693
15736
  this.maxTimeoutMs = chainConfig.pollingConfig.maxTimeoutMs;
@@ -16044,11 +16087,7 @@ var BitcoinSpokeService = class {
16044
16087
  async buildDepositPsbt(walletAddress, walletProvider, srcChainKey, token, amount, data, utxos) {
16045
16088
  const chainConfig = this.config.getChainConfig(srcChainKey);
16046
16089
  const assetManagerAddress = chainConfig.addresses.assetManager;
16047
- const normalizedToken = token.toLocaleLowerCase();
16048
- const nativeBtcTokens = new Set(
16049
- ["btc", chainConfig.nativeToken, chainConfig.supportedTokens.BTC?.address].filter((value) => !!value).map((value) => value.toLocaleLowerCase())
16050
- );
16051
- const isNativeBtc = nativeBtcTokens.has(normalizedToken);
16090
+ const isNativeBtc = isNativeBitcoinToken(chainConfig, token);
16052
16091
  if (isNativeBtc) {
16053
16092
  const OP_RETURN = bitcoinjsLib.opcodes.OP_RETURN;
16054
16093
  const OP_12 = bitcoinjsLib.opcodes.OP_12;
@@ -16307,7 +16346,7 @@ function hexToBytes2(hex) {
16307
16346
  const al = hl / 2;
16308
16347
  if (hl % 2)
16309
16348
  throw new Error("hex string expected, got unpadded hex of length " + hl);
16310
- const array2 = new Uint8Array(al);
16349
+ const array3 = new Uint8Array(al);
16311
16350
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
16312
16351
  const n1 = asciiToBase16(hex.charCodeAt(hi));
16313
16352
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
@@ -16315,9 +16354,9 @@ function hexToBytes2(hex) {
16315
16354
  const char = hex[hi] + hex[hi + 1];
16316
16355
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
16317
16356
  }
16318
- array2[ai] = n1 * 16 + n2;
16357
+ array3[ai] = n1 * 16 + n2;
16319
16358
  }
16320
- return array2;
16359
+ return array3;
16321
16360
  }
16322
16361
  function concatBytes(...arrays) {
16323
16362
  let sum = 0;
@@ -16947,22 +16986,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16947
16986
  const byte0 = Uint8Array.of(0);
16948
16987
  const byte1 = Uint8Array.of(1);
16949
16988
  const _maxDrbgIters = 1e3;
16950
- let v4 = u8n(hashLen);
16989
+ let v9 = u8n(hashLen);
16951
16990
  let k = u8n(hashLen);
16952
16991
  let i = 0;
16953
16992
  const reset = () => {
16954
- v4.fill(1);
16993
+ v9.fill(1);
16955
16994
  k.fill(0);
16956
16995
  i = 0;
16957
16996
  };
16958
- const h = (...msgs) => hmacFn(k, concatBytes(v4, ...msgs));
16997
+ const h = (...msgs) => hmacFn(k, concatBytes(v9, ...msgs));
16959
16998
  const reseed = (seed = NULL) => {
16960
16999
  k = h(byte0, seed);
16961
- v4 = h();
17000
+ v9 = h();
16962
17001
  if (seed.length === 0)
16963
17002
  return;
16964
17003
  k = h(byte1, seed);
16965
- v4 = h();
17004
+ v9 = h();
16966
17005
  };
16967
17006
  const gen = () => {
16968
17007
  if (i++ >= _maxDrbgIters)
@@ -16970,10 +17009,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16970
17009
  let len = 0;
16971
17010
  const out = [];
16972
17011
  while (len < qByteLen) {
16973
- v4 = h();
16974
- const sl = v4.slice();
17012
+ v9 = h();
17013
+ const sl = v9.slice();
16975
17014
  out.push(sl);
16976
- len += v4.length;
17015
+ len += v9.length;
16977
17016
  }
16978
17017
  return concatBytes(...out);
16979
17018
  };
@@ -16988,18 +17027,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16988
17027
  };
16989
17028
  return genUntil;
16990
17029
  }
16991
- function validateObject(object2, fields = {}, optFields = {}) {
16992
- if (!object2 || typeof object2 !== "object")
17030
+ function validateObject(object5, fields = {}, optFields = {}) {
17031
+ if (!object5 || typeof object5 !== "object")
16993
17032
  throw new Error("expected valid options object");
16994
17033
  function checkField(fieldName, expectedType, isOpt) {
16995
- const val = object2[fieldName];
17034
+ const val = object5[fieldName];
16996
17035
  if (isOpt && val === void 0)
16997
17036
  return;
16998
17037
  const current = typeof val;
16999
17038
  if (current !== expectedType || val === null)
17000
17039
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
17001
17040
  }
17002
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v4]) => checkField(k, v4, isOpt));
17041
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v9]) => checkField(k, v9, isOpt));
17003
17042
  iter(fields, false);
17004
17043
  iter(optFields, true);
17005
17044
  }
@@ -17038,12 +17077,12 @@ function pow2(x, power, modulo) {
17038
17077
  }
17039
17078
  return res;
17040
17079
  }
17041
- function invert(number2, modulo) {
17042
- if (number2 === _0n2)
17080
+ function invert(number5, modulo) {
17081
+ if (number5 === _0n2)
17043
17082
  throw new Error("invert: expected non-zero number");
17044
17083
  if (modulo <= _0n2)
17045
17084
  throw new Error("invert: expected positive modulus, got " + modulo);
17046
- let a = mod(number2, modulo);
17085
+ let a = mod(number5, modulo);
17047
17086
  let b = modulo;
17048
17087
  let x = _0n2, u = _1n2;
17049
17088
  while (a !== _0n2) {
@@ -17070,9 +17109,9 @@ function sqrt3mod4(Fp, n) {
17070
17109
  function sqrt5mod8(Fp, n) {
17071
17110
  const p5div8 = (Fp.ORDER - _5n) / _8n;
17072
17111
  const n2 = Fp.mul(n, _2n);
17073
- const v4 = Fp.pow(n2, p5div8);
17074
- const nv = Fp.mul(n, v4);
17075
- const i = Fp.mul(Fp.mul(nv, _2n), v4);
17112
+ const v9 = Fp.pow(n2, p5div8);
17113
+ const nv = Fp.mul(n, v9);
17114
+ const i = Fp.mul(Fp.mul(nv, _2n), v9);
17076
17115
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
17077
17116
  assertIsSquare(Fp, root, n);
17078
17117
  return root;
@@ -17547,27 +17586,27 @@ var wNAF = class {
17547
17586
  assert0(n);
17548
17587
  return acc;
17549
17588
  }
17550
- getPrecomputes(W, point, transform) {
17589
+ getPrecomputes(W, point, transform2) {
17551
17590
  let comp = pointPrecomputes.get(point);
17552
17591
  if (!comp) {
17553
17592
  comp = this.precomputeWindow(point, W);
17554
17593
  if (W !== 1) {
17555
- if (typeof transform === "function")
17556
- comp = transform(comp);
17594
+ if (typeof transform2 === "function")
17595
+ comp = transform2(comp);
17557
17596
  pointPrecomputes.set(point, comp);
17558
17597
  }
17559
17598
  }
17560
17599
  return comp;
17561
17600
  }
17562
- cached(point, scalar, transform) {
17601
+ cached(point, scalar, transform2) {
17563
17602
  const W = getW(point);
17564
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
17603
+ return this.wNAF(W, this.getPrecomputes(W, point, transform2), scalar);
17565
17604
  }
17566
- unsafe(point, scalar, transform, prev) {
17605
+ unsafe(point, scalar, transform2, prev) {
17567
17606
  const W = getW(point);
17568
17607
  if (W === 1)
17569
17608
  return this._unsafeLadder(point, scalar, prev);
17570
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
17609
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform2), scalar, prev);
17571
17610
  }
17572
17611
  // We calculate precomputes for elliptic curve point multiplication
17573
17612
  // using windowed method. This specifies window size and
@@ -17654,9 +17693,9 @@ function edwards(params, extraOpts = {}) {
17654
17693
  validateObject(extraOpts, {}, { uvRatio: "function" });
17655
17694
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
17656
17695
  const modP = (n) => Fp.create(n);
17657
- const uvRatio2 = extraOpts.uvRatio || ((u, v4) => {
17696
+ const uvRatio2 = extraOpts.uvRatio || ((u, v9) => {
17658
17697
  try {
17659
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v4)) };
17698
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v9)) };
17660
17699
  } catch (e) {
17661
17700
  return { isValid: false, value: _0n4 };
17662
17701
  }
@@ -17752,8 +17791,8 @@ function edwards(params, extraOpts = {}) {
17752
17791
  aInRange("point.y", y, _0n4, max);
17753
17792
  const y2 = modP(y * y);
17754
17793
  const u = modP(y2 - _1n4);
17755
- const v4 = modP(d * y2 - a);
17756
- let { isValid, value: x } = uvRatio2(u, v4);
17794
+ const v9 = modP(d * y2 - a);
17795
+ let { isValid, value: x } = uvRatio2(u, v9);
17757
17796
  if (!isValid)
17758
17797
  throw new Error("bad point: invalid y coordinate");
17759
17798
  const isXOdd = (x & _1n4) === _1n4;
@@ -18093,13 +18132,13 @@ function adjustScalarBytes(bytes) {
18093
18132
  return bytes;
18094
18133
  }
18095
18134
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
18096
- function uvRatio(u, v4) {
18135
+ function uvRatio(u, v9) {
18097
18136
  const P = ed25519_CURVE_p;
18098
- const v32 = mod(v4 * v4 * v4, P);
18099
- const v7 = mod(v32 * v32 * v4, P);
18100
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
18137
+ const v32 = mod(v9 * v9 * v9, P);
18138
+ const v72 = mod(v32 * v32 * v9, P);
18139
+ const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
18101
18140
  let x = mod(u * v32 * pow, P);
18102
- const vx2 = mod(v4 * x * x, P);
18141
+ const vx2 = mod(v9 * x * x, P);
18103
18142
  const root1 = x;
18104
18143
  const root2 = mod(x * ED25519_SQRT_M1, P);
18105
18144
  const useRoot1 = vx2 === u;
@@ -18430,7 +18469,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
18430
18469
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
18431
18470
  }
18432
18471
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
18433
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18472
+ const stakes = validators.map((v9) => BigInt(v9.stake)).sort(sortBigIntAsc);
18434
18473
  const num = BigInt(numSeats);
18435
18474
  const stakesSum = stakes.reduce((a, b) => a + b);
18436
18475
  if (stakesSum < num) {
@@ -18459,7 +18498,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
18459
18498
  if (minimumStakeRatio.length != 2) {
18460
18499
  throw Error("minimumStakeRatio should have 2 elements");
18461
18500
  }
18462
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18501
+ const stakes = validators.map((v9) => BigInt(v9.stake)).sort(sortBigIntAsc);
18463
18502
  const stakesSum = stakes.reduce((a, b) => a + b);
18464
18503
  if (validators.length < maxNumberOfSeats) {
18465
18504
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -18631,10 +18670,10 @@ var DER = {
18631
18670
  if (length < 128)
18632
18671
  throw new E("tlv.decode(long): not minimal encoding");
18633
18672
  }
18634
- const v4 = data.subarray(pos, pos + length);
18635
- if (v4.length !== length)
18673
+ const v9 = data.subarray(pos, pos + length);
18674
+ if (v9.length !== length)
18636
18675
  throw new E("tlv.decode: wrong value length");
18637
- return { v: v4, l: data.subarray(pos + length) };
18676
+ return { v: v9, l: data.subarray(pos + length) };
18638
18677
  }
18639
18678
  },
18640
18679
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -19202,9 +19241,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19202
19241
  extraEntropy: false
19203
19242
  };
19204
19243
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
19205
- function isBiggerThanHalfOrder(number2) {
19244
+ function isBiggerThanHalfOrder(number5) {
19206
19245
  const HALF = CURVE_ORDER >> _1n6;
19207
- return number2 > HALF;
19246
+ return number5 > HALF;
19208
19247
  }
19209
19248
  function validateRS(title, num) {
19210
19249
  if (!Fn.isValidNot0(num))
@@ -19387,8 +19426,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19387
19426
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
19388
19427
  if (R.is0())
19389
19428
  return false;
19390
- const v4 = Fn.create(R.x);
19391
- return v4 === r;
19429
+ const v9 = Fn.create(R.x);
19430
+ return v9 === r;
19392
19431
  } catch (e) {
19393
19432
  return false;
19394
19433
  }
@@ -23526,6 +23565,7 @@ var CustomStellarAccount = class {
23526
23565
  this.sequenceNumber = this.startingSequenceNumber;
23527
23566
  }
23528
23567
  };
23568
+ var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
23529
23569
  var StellarSpokeService = class {
23530
23570
  config;
23531
23571
  chainConfig;
@@ -23763,6 +23803,17 @@ var StellarSpokeService = class {
23763
23803
  throw error;
23764
23804
  }
23765
23805
  }
23806
+ /**
23807
+ * Whether a token requires a trustline. Native XLM and legacy bnUSD are
23808
+ * exempt and therefore need no subentry reserve.
23809
+ */
23810
+ requiresTrustline(token) {
23811
+ const stellarChainConfig = this.chainConfig;
23812
+ const normalized = token.toLowerCase();
23813
+ if (normalized === stellarChainConfig.nativeToken.toLowerCase()) return false;
23814
+ const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23815
+ return legacyBnUSD === void 0 || normalized !== legacyBnUSD.address.toLowerCase();
23816
+ }
23766
23817
  /**
23767
23818
  * Check if the user has sufficient trustline established for the token.
23768
23819
  * @param token - The token address to check the trustline for.
@@ -23772,8 +23823,7 @@ var StellarSpokeService = class {
23772
23823
  */
23773
23824
  async hasSufficientTrustline(token, amount, walletAddress) {
23774
23825
  const stellarChainConfig = this.chainConfig;
23775
- const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23776
- if (token.toLowerCase() === stellarChainConfig.nativeToken.toLowerCase() || legacyBnUSD !== void 0 && token.toLowerCase() === legacyBnUSD.address.toLowerCase()) {
23826
+ if (!this.requiresTrustline(token)) {
23777
23827
  return true;
23778
23828
  }
23779
23829
  const trustlineConfig = stellarChainConfig.trustlineConfigs.find(
@@ -23822,7 +23872,7 @@ var StellarSpokeService = class {
23822
23872
  stellarSdk.Operation.changeTrust({
23823
23873
  asset: new stellarSdk.Asset(asset?.assetCode, asset?.assetIssuer)
23824
23874
  })
23825
- ).setTimeout(this.maxTimeoutMs).build();
23875
+ ).setTimeout(TRUSTLINE_TX_TIMEOUT_SECONDS).build();
23826
23876
  if (params.raw) {
23827
23877
  const transactionXdr = transaction.toXDR();
23828
23878
  return {
@@ -26671,6 +26721,36 @@ var SolverApiService = class {
26671
26721
  }
26672
26722
  }
26673
26723
  };
26724
+
26725
+ // src/backendApi/pollBackendSubmitTx.ts
26726
+ async function pollBackendSubmitTx({
26727
+ deadline,
26728
+ terminalStatus,
26729
+ getStatus,
26730
+ onExecuted,
26731
+ intervalMs = 1e3,
26732
+ requestTimeoutMs
26733
+ }) {
26734
+ const reserveMs = Math.min(Math.ceil((deadline - Date.now()) / 3), 2e4);
26735
+ const pollDeadline = deadline - reserveMs;
26736
+ const requestOverride = () => requestTimeoutMs === void 0 ? void 0 : { timeout: Math.min(pollDeadline - Date.now(), requestTimeoutMs) };
26737
+ while (Date.now() < pollDeadline) {
26738
+ const statusResult = await getStatus(requestOverride());
26739
+ if (statusResult.ok) {
26740
+ const { status, result, failureReason, abandonedAt } = statusResult.value.data;
26741
+ if (status === terminalStatus) {
26742
+ const value = onExecuted(result);
26743
+ if (value !== void 0) return { ok: true, value };
26744
+ }
26745
+ if (status === "failed" || abandonedAt) {
26746
+ const reason = failureReason ? `: ${failureReason}` : "";
26747
+ return { ok: false, cause: new Error(`backend submit-tx ${status}${reason}`) };
26748
+ }
26749
+ }
26750
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, pollDeadline - Date.now())));
26751
+ }
26752
+ return { ok: false, cause: new Error(`backend submit-tx polling timed out before reaching ${terminalStatus}`) };
26753
+ }
26674
26754
  function decodePacketIntentTarget(payload) {
26675
26755
  try {
26676
26756
  const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
@@ -26993,7 +27073,7 @@ var SwapService = class {
26993
27073
  relayerApiEndpoint: this.relayerApiEndpoint,
26994
27074
  // Remaining shared budget: ≈ full `timeout` on the flag-off path (called immediately), or
26995
27075
  // the reserve `submitTx` left on the backend path. Floor keeps a stalled-backend fallback viable.
26996
- timeout: Math.max(deadline - Date.now(), 5e3)
27076
+ timeout: Math.max(deadline - Date.now(), RELAY_FALLBACK_FLOOR_MS)
26997
27077
  });
26998
27078
  if (!packet.ok) {
26999
27079
  return { ok: false, error: mapRelayFailure(packet.error, { feature: "swap", action: "swap", ...baseCtx }) };
@@ -27055,39 +27135,26 @@ var SwapService = class {
27055
27135
  relayData: relayData.payload
27056
27136
  });
27057
27137
  if (!submitted.ok) return submitTxFailed(submitted.error);
27058
- const reserveMs = Math.min(Math.ceil((deadline - Date.now()) / 3), 2e4);
27059
- const pollDeadline = deadline - reserveMs;
27060
- const pollIntervalMs = 1e3;
27061
- while (Date.now() < pollDeadline) {
27062
- const statusResult = await this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey });
27063
- if (statusResult.ok) {
27064
- const { status, result, failureReason, abandonedAt } = statusResult.value.data;
27065
- if (status === "solved" && result?.dstIntentTxHash && result.intent_hash) {
27066
- return {
27067
- ok: true,
27068
- value: {
27069
- // Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
27070
- solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
27071
- intent,
27072
- intentDeliveryInfo: {
27073
- srcChainKey,
27074
- srcTxHash: spokeTxHash,
27075
- srcAddress: params.srcAddress,
27076
- dstChainKey: params.dstChainKey,
27077
- dstTxHash: result.dstIntentTxHash,
27078
- dstAddress: params.dstAddress
27079
- }
27080
- }
27081
- };
27082
- }
27083
- if (status === "failed" || abandonedAt) {
27084
- const reason = failureReason ? `: ${failureReason}` : "";
27085
- return submitTxFailed(new Error(`backend submit-tx ${status}${reason}`));
27138
+ const polled = await pollBackendSubmitTx({
27139
+ deadline,
27140
+ // Swaps terminal success is `solved` (solver filled) — not the bridge `executed`.
27141
+ terminalStatus: "solved",
27142
+ getStatus: () => this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }),
27143
+ onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
27144
+ // Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
27145
+ solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
27146
+ intent,
27147
+ intentDeliveryInfo: {
27148
+ srcChainKey,
27149
+ srcTxHash: spokeTxHash,
27150
+ srcAddress: params.srcAddress,
27151
+ dstChainKey: params.dstChainKey,
27152
+ dstTxHash: result.dstIntentTxHash,
27153
+ dstAddress: params.dstAddress
27086
27154
  }
27087
- }
27088
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
27089
- }
27090
- return submitTxFailed(new Error("backend submit-tx polling timed out before reaching solved"));
27155
+ } : void 0
27156
+ });
27157
+ return polled.ok ? { ok: true, value: polled.value } : submitTxFailed(polled.cause);
27091
27158
  } catch (error) {
27092
27159
  return { ok: false, error: unknownFailed("swap", error, { ...baseCtx, action: "swap" }) };
27093
27160
  }
@@ -27279,10 +27346,19 @@ var SwapService = class {
27279
27346
  `Invalid spoke chain (params.dstChain): ${params.dstChainKey}`,
27280
27347
  { ...baseCtx, field: "dstChainKey" }
27281
27348
  );
27282
- if (isBitcoinChainKey(params.dstChainKey) && params.outputToken === "BTC") {
27349
+ const inputTokenInfo = this.config.getSpokeTokenFromOriginalAssetAddress(params.srcChainKey, params.inputToken);
27350
+ if (isNativeBitcoinTransfer(this.config, params.srcChainKey, inputTokenInfo)) {
27283
27351
  swapInvariant(
27284
- params.minOutputAmount >= 546n,
27285
- `Invalid minOutputAmount (params.minOutputAmount): ${params.minOutputAmount}`,
27352
+ params.inputAmount >= BITCOIN_DUST_SATS,
27353
+ `Invalid inputAmount (${params.inputAmount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
27354
+ { ...baseCtx, field: "inputAmount" }
27355
+ );
27356
+ }
27357
+ const outputTokenInfo = this.config.getSpokeTokenFromOriginalAssetAddress(params.dstChainKey, params.outputToken);
27358
+ if (isNativeBitcoinTransfer(this.config, params.dstChainKey, outputTokenInfo)) {
27359
+ swapInvariant(
27360
+ params.minOutputAmount >= BITCOIN_DUST_SATS,
27361
+ `Invalid minOutputAmount (${params.minOutputAmount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
27286
27362
  { ...baseCtx, field: "minOutputAmount" }
27287
27363
  );
27288
27364
  }
@@ -29821,10 +29897,41 @@ var MigrationService = class {
29821
29897
  };
29822
29898
 
29823
29899
  // src/backendApi/api-utils.ts
29900
+ var BackendHttpError = class extends Error {
29901
+ status;
29902
+ bodyText;
29903
+ /** Parsed JSON, or `undefined` for empty or malformed bodies. */
29904
+ body;
29905
+ constructor(status, bodyText) {
29906
+ super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
29907
+ this.name = "BackendHttpError";
29908
+ this.status = status;
29909
+ this.bodyText = bodyText;
29910
+ this.body = safeJsonParse(bodyText);
29911
+ }
29912
+ };
29913
+ function isBackendHttpError(error) {
29914
+ if (error instanceof BackendHttpError) return true;
29915
+ return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
29916
+ }
29917
+ function safeJsonParse(text) {
29918
+ if (text.length === 0) return void 0;
29919
+ try {
29920
+ return JSON.parse(text);
29921
+ } catch {
29922
+ return void 0;
29923
+ }
29924
+ }
29925
+ function trimTrailingSlashes(baseURL) {
29926
+ let end = baseURL.length;
29927
+ while (end > 0 && baseURL[end - 1] === "/") end -= 1;
29928
+ return baseURL.slice(0, end);
29929
+ }
29930
+ var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
29824
29931
  async function makeRequest(params) {
29825
29932
  const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
29826
29933
  const baseURL = overrideConfig.baseURL || config.baseURL || "";
29827
- const url = `${baseURL}${endpoint}`;
29934
+ const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
29828
29935
  const headers = { ...config.headers, ...overrideConfig.headers };
29829
29936
  const controller = new AbortController();
29830
29937
  const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
@@ -29839,7 +29946,7 @@ async function makeRequest(params) {
29839
29946
  clearTimeout(timeoutId);
29840
29947
  if (!response.ok) {
29841
29948
  const errorText = await response.text();
29842
- throw new Error("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${response.status}: ${errorText}`) });
29949
+ throw new BackendHttpError(response.status, errorText);
29843
29950
  }
29844
29951
  const data = await response.json();
29845
29952
  return data;
@@ -29856,6 +29963,32 @@ async function makeRequest(params) {
29856
29963
  throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
29857
29964
  }
29858
29965
  }
29966
+ function resolveRequestConfig(config, defaults) {
29967
+ const { baseURL, timeout, headers, ...rest } = config;
29968
+ return {
29969
+ ...rest,
29970
+ baseURL: baseURL || defaults.baseURL,
29971
+ timeout: timeout ?? defaults.timeout,
29972
+ headers: { ...defaults.headers, ...headers }
29973
+ };
29974
+ }
29975
+ function toExternalApiError(params) {
29976
+ const { api, feature, endpoint, error } = params;
29977
+ const context = { api, endpoint };
29978
+ if (isBackendHttpError(error)) context.status = error.status;
29979
+ return new SodaxError(
29980
+ "EXTERNAL_API_ERROR",
29981
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
29982
+ { feature, cause: error, context }
29983
+ );
29984
+ }
29985
+ function toInvalidResponseShapeError(params) {
29986
+ const { api, feature, endpoint, issues } = params;
29987
+ return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
29988
+ feature,
29989
+ context: { api, endpoint, reason: "invalid_response_shape", issues }
29990
+ });
29991
+ }
29859
29992
  var SwapsApiService = class _SwapsApiService {
29860
29993
  // Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
29861
29994
  // `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
@@ -29901,7 +30034,7 @@ var SwapsApiService = class _SwapsApiService {
29901
30034
  if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
29902
30035
  context.reason = "invalid_response_shape";
29903
30036
  const issues = error.context.issues;
29904
- context.issues = issues instanceof v2__namespace.ValiError ? v2__namespace.flatten(issues.issues) : issues;
30037
+ context.issues = issues instanceof v7__namespace.ValiError ? v7__namespace.flatten(issues.issues) : issues;
29905
30038
  }
29906
30039
  if (error.context.status !== void 0) context.status = error.context.status;
29907
30040
  }
@@ -30062,10 +30195,503 @@ var SwapsApiService = class _SwapsApiService {
30062
30195
  return this.config.baseURL;
30063
30196
  }
30064
30197
  };
30198
+ var StellarSponsorConfigSchema = v7__namespace.object({
30199
+ sponsorAccount: v7__namespace.string(),
30200
+ networkPassphrase: v7__namespace.string(),
30201
+ minTotalFeeStroops: v7__namespace.string(),
30202
+ maxTotalFeeStroops: v7__namespace.string(),
30203
+ operationCount: v7__namespace.number(),
30204
+ minPerOperationFeeStroops: v7__namespace.string(),
30205
+ maxPerOperationFeeStroops: v7__namespace.string(),
30206
+ recommendedPerOperationFeeStroops: v7__namespace.string(),
30207
+ maxTimeboundSeconds: v7__namespace.number(),
30208
+ requiredStartingBalance: v7__namespace.string()
30209
+ });
30210
+ var StellarSponsoredAccountResponseSchema = v7__namespace.variant("alreadyActive", [
30211
+ v7__namespace.object({ hash: v7__namespace.string(), alreadyActive: v7__namespace.literal(false) }),
30212
+ v7__namespace.object({ hash: v7__namespace.null(), alreadyActive: v7__namespace.literal(true) })
30213
+ ]);
30214
+
30215
+ // src/backendApi/SponsoringApiService.ts
30216
+ var SponsoringApiService = class {
30217
+ config;
30218
+ headers;
30219
+ logger;
30220
+ constructor(config, logger = consoleLogger) {
30221
+ this.config = config;
30222
+ this.headers = {
30223
+ ...config.apiKey !== void 0 ? { "x-api-key": config.apiKey } : {},
30224
+ ...config.headers
30225
+ };
30226
+ this.logger = logger;
30227
+ }
30228
+ /**
30229
+ * Validate a response while preserving HTTP failures on `error.cause` for
30230
+ * sponsor-error classification.
30231
+ */
30232
+ async request(endpoint, config, schema) {
30233
+ try {
30234
+ const raw = await makeRequest({
30235
+ endpoint,
30236
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30237
+ logger: this.logger,
30238
+ serviceLabel: "SponsoringApiService"
30239
+ });
30240
+ const parsed = v7__namespace.safeParse(schema, raw);
30241
+ if (!parsed.success) {
30242
+ return {
30243
+ ok: false,
30244
+ error: toInvalidResponseShapeError({
30245
+ api: "sponsoring",
30246
+ feature: "backend",
30247
+ endpoint,
30248
+ issues: v7__namespace.flatten(parsed.issues)
30249
+ })
30250
+ };
30251
+ }
30252
+ return { ok: true, value: parsed.output };
30253
+ } catch (error) {
30254
+ return { ok: false, error: toExternalApiError({ api: "sponsoring", feature: "backend", endpoint, error }) };
30255
+ }
30256
+ }
30257
+ /** Fetch build parameters, including the rotatable sponsor account. */
30258
+ async getStellarSponsorConfig(config) {
30259
+ return this.request(
30260
+ `${SPONSORING_API_STELLAR_BASE_PATH}/config`,
30261
+ { ...config, method: "GET" },
30262
+ StellarSponsorConfigSchema
30263
+ );
30264
+ }
30265
+ /**
30266
+ * Submit a client-signed transaction for sponsor co-signing. An
30267
+ * `alreadyActive` response is also successful.
30268
+ */
30269
+ async createStellarSponsoredAccount(body, config) {
30270
+ return this.request(
30271
+ `${SPONSORING_API_STELLAR_BASE_PATH}/accounts`,
30272
+ // The endpoint rejects extra fields.
30273
+ { ...config, method: "POST", body: JSON.stringify({ data: body.data }) },
30274
+ StellarSponsoredAccountResponseSchema
30275
+ );
30276
+ }
30277
+ setHeaders(headers) {
30278
+ Object.entries(headers).forEach(([key, value]) => {
30279
+ this.headers[key] = value;
30280
+ });
30281
+ }
30282
+ getBaseURL() {
30283
+ return this.config.baseURL;
30284
+ }
30285
+ };
30286
+ var RelayExtraDataResponseSchema = v7__namespace.object({
30287
+ address: v7__namespace.string(),
30288
+ payload: v7__namespace.string()
30289
+ });
30290
+ var BridgeTokenSchema = v7__namespace.object({
30291
+ symbol: v7__namespace.string(),
30292
+ name: v7__namespace.string(),
30293
+ decimals: v7__namespace.number(),
30294
+ address: v7__namespace.string(),
30295
+ chainKey: v7__namespace.string(),
30296
+ hubAsset: v7__namespace.string(),
30297
+ vault: v7__namespace.string()
30298
+ });
30299
+ var BridgeTokensResponseSchema = v7__namespace.record(v7__namespace.string(), v7__namespace.array(BridgeTokenSchema));
30300
+ var BridgeTokensByChainResponseSchema = v7__namespace.array(BridgeTokenSchema);
30301
+ var BridgeAllowanceCheckResponseSchema = v7__namespace.object({
30302
+ valid: v7__namespace.boolean()
30303
+ });
30304
+ var makeBridgeApproveResponseSchema = (txSchema) => v7__namespace.object({ tx: txSchema });
30305
+ var makeCreateBridgeIntentResponseSchema = (txSchema) => v7__namespace.object({
30306
+ tx: txSchema,
30307
+ relayData: RelayExtraDataResponseSchema
30308
+ });
30309
+ var BridgeSubmitTxResponseSchema = v7__namespace.object({
30310
+ success: v7__namespace.boolean(),
30311
+ data: v7__namespace.object({
30312
+ status: v7__namespace.picklist(["inserted", "duplicate"]),
30313
+ message: v7__namespace.string()
30314
+ })
30315
+ });
30316
+ var BridgePacketDataSchema = v7__namespace.object({
30317
+ src_chain_id: v7__namespace.number(),
30318
+ src_tx_hash: v7__namespace.string(),
30319
+ src_address: v7__namespace.string(),
30320
+ status: v7__namespace.picklist(["pending", "validating", "executing", "executed"]),
30321
+ dst_chain_id: v7__namespace.number(),
30322
+ conn_sn: v7__namespace.number(),
30323
+ dst_address: v7__namespace.string(),
30324
+ dst_tx_hash: v7__namespace.string(),
30325
+ signatures: v7__namespace.array(v7__namespace.string()),
30326
+ payload: v7__namespace.string()
30327
+ });
30328
+ var BridgeSubmitTxStatusResultSchema = v7__namespace.object({
30329
+ dstIntentTxHash: v7__namespace.string(),
30330
+ packetData: v7__namespace.optional(BridgePacketDataSchema)
30331
+ });
30332
+ var BridgeSubmitTxStatusDataSchema = v7__namespace.object({
30333
+ txHash: v7__namespace.string(),
30334
+ srcChainKey: v7__namespace.string(),
30335
+ status: v7__namespace.string(),
30336
+ failedAtStep: v7__namespace.optional(v7__namespace.string()),
30337
+ failureReason: v7__namespace.optional(v7__namespace.string()),
30338
+ processingAttempts: v7__namespace.number(),
30339
+ abandonedAt: v7__namespace.optional(v7__namespace.string()),
30340
+ result: v7__namespace.optional(BridgeSubmitTxStatusResultSchema),
30341
+ userMessage: v7__namespace.optional(v7__namespace.string())
30342
+ });
30343
+ var BridgeSubmitTxStatusResponseSchema = v7__namespace.object({
30344
+ success: v7__namespace.boolean(),
30345
+ data: BridgeSubmitTxStatusDataSchema
30346
+ });
30347
+ var BridgeFeeResponseSchema = v7__namespace.object({ fee: v7__namespace.string() });
30348
+ var BridgeLimitSchema = v7__namespace.object({
30349
+ amount: v7__namespace.string(),
30350
+ decimals: v7__namespace.number(),
30351
+ type: v7__namespace.picklist(["DEPOSIT_LIMIT", "WITHDRAWAL_LIMIT"])
30352
+ });
30353
+ var BridgeableAmountResponseSchema = v7__namespace.object({ limit: BridgeLimitSchema });
30354
+ var BridgeableCheckResponseSchema = v7__namespace.object({ bridgeable: v7__namespace.boolean() });
30355
+ var AddressSchema = v7__namespace.custom((input) => typeof input === "string");
30356
+ var HexSchema = v7__namespace.custom((input) => typeof input === "string");
30357
+ var BigintFromString = v7__namespace.pipe(v7__namespace.string(), v7__namespace.toBigint());
30358
+ var BytesFromIndexRecord = v7__namespace.pipe(
30359
+ v7__namespace.record(v7__namespace.string(), v7__namespace.number()),
30360
+ v7__namespace.transform((indexed) => Uint8Array.from(Object.values(indexed)))
30361
+ );
30362
+ var EvmRawTxSchema = v7__namespace.object({
30363
+ from: AddressSchema,
30364
+ to: AddressSchema,
30365
+ value: BigintFromString,
30366
+ data: HexSchema
30367
+ });
30368
+ var SolanaRawTxSchema = v7__namespace.object({
30369
+ from: v7__namespace.string(),
30370
+ to: v7__namespace.string(),
30371
+ value: BigintFromString,
30372
+ data: v7__namespace.string()
30373
+ });
30374
+ var SuiRawTxSchema = v7__namespace.object({
30375
+ from: HexSchema,
30376
+ to: v7__namespace.string(),
30377
+ value: BigintFromString,
30378
+ data: v7__namespace.string()
30379
+ });
30380
+ var StellarRawTxSchema = v7__namespace.object({
30381
+ from: v7__namespace.string(),
30382
+ to: v7__namespace.string(),
30383
+ value: BigintFromString,
30384
+ data: v7__namespace.string()
30385
+ });
30386
+ var BitcoinRawTxSchema = v7__namespace.object({
30387
+ from: v7__namespace.string(),
30388
+ to: v7__namespace.string(),
30389
+ value: BigintFromString,
30390
+ data: v7__namespace.string()
30391
+ });
30392
+ var InjectiveRawTxSchema = v7__namespace.object({
30393
+ from: HexSchema,
30394
+ to: HexSchema,
30395
+ signedDoc: v7__namespace.object({
30396
+ bodyBytes: BytesFromIndexRecord,
30397
+ authInfoBytes: BytesFromIndexRecord,
30398
+ chainId: v7__namespace.string(),
30399
+ accountNumber: BigintFromString
30400
+ })
30401
+ });
30402
+ var NearRawTxSchema = v7__namespace.object({
30403
+ signerId: v7__namespace.string(),
30404
+ params: v7__namespace.object({
30405
+ contractId: v7__namespace.string(),
30406
+ method: v7__namespace.string(),
30407
+ args: v7__namespace.custom((input) => typeof input === "object" && input !== null),
30408
+ gas: v7__namespace.optional(BigintFromString),
30409
+ deposit: v7__namespace.optional(BigintFromString)
30410
+ })
30411
+ });
30412
+ var IconRawTxSchema = v7__namespace.record(
30413
+ v7__namespace.string(),
30414
+ v7__namespace.union([v7__namespace.string(), v7__namespace.custom((input) => typeof input === "object" && input !== null)])
30415
+ );
30416
+ var StacksRawTxSchema = v7__namespace.object({
30417
+ payload: v7__namespace.string(),
30418
+ estimatedLength: v7__namespace.optional(v7__namespace.number())
30419
+ });
30420
+ var AnyRawTxSchema = v7__namespace.custom((input) => typeof input === "object" && input !== null);
30421
+ function rawTxSchemaForChainKey(chainKey) {
30422
+ let chainType;
30423
+ try {
30424
+ chainType = getChainType(chainKey);
30425
+ } catch {
30426
+ chainType = void 0;
30427
+ }
30428
+ switch (chainType) {
30429
+ case "EVM":
30430
+ return EvmRawTxSchema;
30431
+ case "SOLANA":
30432
+ return SolanaRawTxSchema;
30433
+ case "SUI":
30434
+ return SuiRawTxSchema;
30435
+ case "STELLAR":
30436
+ return StellarRawTxSchema;
30437
+ case "INJECTIVE":
30438
+ return InjectiveRawTxSchema;
30439
+ case "ICON":
30440
+ return IconRawTxSchema;
30441
+ case "STACKS":
30442
+ return StacksRawTxSchema;
30443
+ case "NEAR":
30444
+ return NearRawTxSchema;
30445
+ case "BITCOIN":
30446
+ return BitcoinRawTxSchema;
30447
+ default:
30448
+ return AnyRawTxSchema;
30449
+ }
30450
+ }
30451
+
30452
+ // src/backendApi/BridgeApiService.ts
30453
+ function toCreateBridgeIntentParamsV2(params, extras) {
30454
+ return {
30455
+ srcChainKey: params.srcChainKey,
30456
+ dstChainKey: params.dstChainKey,
30457
+ inputToken: params.srcToken,
30458
+ outputToken: params.dstToken,
30459
+ inputAmount: params.amount.toString(),
30460
+ srcAddress: params.srcAddress,
30461
+ dstAddress: params.recipient,
30462
+ ...extras?.srcPublicKey !== void 0 ? { srcPublicKey: extras.srcPublicKey } : {},
30463
+ ...extras?.bound !== void 0 ? { bound: extras.bound } : {},
30464
+ ...extras?.partnerFee !== void 0 ? { partnerFee: extras.partnerFee } : {}
30465
+ };
30466
+ }
30467
+ var BridgeApiService = class {
30468
+ // Fully-resolved bridge-API config supplied by the caller (BackendApiService resolves the
30469
+ // `ApiConfig` union via `resolveBridgeApiConfig`); this service does not resolve the union.
30470
+ config;
30471
+ headers;
30472
+ logger;
30473
+ constructor(config, logger = consoleLogger) {
30474
+ this.config = config;
30475
+ this.headers = { ...config.headers };
30476
+ this.logger = logger;
30477
+ }
30478
+ /**
30479
+ * Issues a single HTTP request, validates the JSON body against `schema`, and
30480
+ * wraps the result in `Result<T>`. The service-level `baseURL`/`timeout`/
30481
+ * `headers` are merged with the optional per-call `overrideConfig` (which takes
30482
+ * precedence) inside {@link makeRequest}. Every public method delegates here.
30483
+ */
30484
+ async request(endpoint, config, schema, overrideConfig) {
30485
+ try {
30486
+ const raw = await makeRequest({
30487
+ endpoint,
30488
+ config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
30489
+ overrideConfig,
30490
+ logger: this.logger,
30491
+ serviceLabel: "BridgeApiService"
30492
+ });
30493
+ const parsed = v7__namespace.safeParse(schema, raw);
30494
+ if (!parsed.success) {
30495
+ return {
30496
+ ok: false,
30497
+ error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from bridge API for ${endpoint}`, {
30498
+ feature: "backend",
30499
+ context: { api: "bridge", endpoint, reason: "invalid_response_shape", issues: v7__namespace.flatten(parsed.issues) }
30500
+ })
30501
+ };
30502
+ }
30503
+ return { ok: true, value: parsed.output };
30504
+ } catch (error) {
30505
+ return {
30506
+ ok: false,
30507
+ error: new SodaxError(
30508
+ "EXTERNAL_API_ERROR",
30509
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
30510
+ {
30511
+ feature: "backend",
30512
+ cause: error,
30513
+ context: { api: "bridge", endpoint }
30514
+ }
30515
+ )
30516
+ };
30517
+ }
30518
+ }
30519
+ // ──────────────────────────────────────────────────────────────────────
30520
+ // Tokens
30521
+ // ──────────────────────────────────────────────────────────────────────
30522
+ /**
30523
+ * Fetch all supported bridge tokens grouped by SpokeChainKey.
30524
+ *
30525
+ * @returns `Result<GetBridgeTokensResponseV2>` — map of chain key → token list.
30526
+ */
30527
+ async getTokens(config) {
30528
+ return this.request("/bridge/tokens", { method: "GET" }, BridgeTokensResponseSchema, config);
30529
+ }
30530
+ /**
30531
+ * Fetch supported bridge tokens for a single SpokeChainKey.
30532
+ *
30533
+ * @param chainKey - SODAX SpokeChainKey (e.g. `0xa4b1.arbitrum`, `solana`).
30534
+ * @returns `Result<GetBridgeTokensByChainResponseV2>` — token list for the chain.
30535
+ */
30536
+ async getTokensByChain(chainKey, config) {
30537
+ return this.request(
30538
+ `/bridge/tokens/${chainKey}`,
30539
+ { method: "GET" },
30540
+ BridgeTokensByChainResponseSchema,
30541
+ config
30542
+ );
30543
+ }
30544
+ // ──────────────────────────────────────────────────────────────────────
30545
+ // Allowance · approve · create intent
30546
+ // ──────────────────────────────────────────────────────────────────────
30547
+ /**
30548
+ * Check whether the source token allowance is already sufficient for the bridge.
30549
+ *
30550
+ * @returns `Result<BridgeAllowanceCheckResponseV2>` — `{ valid }`.
30551
+ */
30552
+ async checkAllowance(body, config) {
30553
+ return this.request(
30554
+ "/bridge/allowance/check",
30555
+ { method: "POST", body: toJsonBody(body) },
30556
+ BridgeAllowanceCheckResponseSchema,
30557
+ config
30558
+ );
30559
+ }
30560
+ /**
30561
+ * Build an unsigned token-approval transaction for the source token.
30562
+ *
30563
+ * @returns `Result<BridgeApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
30564
+ */
30565
+ async approve(body, config) {
30566
+ const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30567
+ return this.request(
30568
+ "/bridge/approve",
30569
+ { method: "POST", body: toJsonBody(body) },
30570
+ makeBridgeApproveResponseSchema(txSchema),
30571
+ config
30572
+ );
30573
+ }
30574
+ /**
30575
+ * Build an unsigned spoke-deposit (create-bridge-intent) transaction.
30576
+ *
30577
+ * @returns `Result<CreateBridgeIntentResponseV2>` — `{ tx, relayData }` (no intent struct).
30578
+ */
30579
+ async createBridgeIntent(body, config) {
30580
+ const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30581
+ return this.request(
30582
+ "/bridge/intents",
30583
+ { method: "POST", body: toJsonBody(body) },
30584
+ makeCreateBridgeIntentResponseSchema(txSchema),
30585
+ config
30586
+ );
30587
+ }
30588
+ // ──────────────────────────────────────────────────────────────────────
30589
+ // Submit-tx state machine
30590
+ // ──────────────────────────────────────────────────────────────────────
30591
+ /**
30592
+ * Submit a broadcast bridge (spoke-deposit) transaction to be processed (relayed).
30593
+ * Carries the FULL `relayData { address, payload }` envelope. Idempotent on `(txHash, srcChainKey)`.
30594
+ *
30595
+ * @returns `Result<BridgeSubmitTxResponseV2>` — `{ success, data: { status, message } }`.
30596
+ */
30597
+ async submitTx(body, config) {
30598
+ return this.request(
30599
+ "/bridge/submit-tx",
30600
+ { method: "POST", body: toJsonBody(body) },
30601
+ BridgeSubmitTxResponseSchema,
30602
+ config
30603
+ );
30604
+ }
30605
+ /**
30606
+ * Get the processing status of a submitted bridge transaction by `(txHash, srcChainKey)`.
30607
+ *
30608
+ * @returns `Result<BridgeSubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
30609
+ */
30610
+ async getSubmitTxStatus(query, config) {
30611
+ const queryParams = new URLSearchParams({ txHash: query.txHash, srcChainKey: query.srcChainKey });
30612
+ return this.request(
30613
+ `/bridge/submit-tx/status?${queryParams.toString()}`,
30614
+ { method: "GET" },
30615
+ BridgeSubmitTxStatusResponseSchema,
30616
+ config
30617
+ );
30618
+ }
30619
+ // ──────────────────────────────────────────────────────────────────────
30620
+ // Fee · bridgeable quote (read-only; mirror the SDK-core client-side methods)
30621
+ // ──────────────────────────────────────────────────────────────────────
30622
+ /**
30623
+ * Bridge partner fee for an input amount (per-request `partnerFee` override, else the configured default).
30624
+ * NOTE: this is a pure client-side computation
30625
+ * in the SDK core (`sodax.bridge.getFee`) — prefer that (no round-trip); this HTTP variant exists for
30626
+ * parity with the backend `/bridge/fee` endpoint (for consumers using only `sodax.api.bridge`).
30627
+ *
30628
+ * @returns `Result<BridgeFeeResponseV2>` — `{ fee }` (decimal string).
30629
+ */
30630
+ async getFee(body, config) {
30631
+ return this.request(
30632
+ "/bridge/fee",
30633
+ { method: "POST", body: toJsonBody(body) },
30634
+ BridgeFeeResponseSchema,
30635
+ config
30636
+ );
30637
+ }
30638
+ /**
30639
+ * Deposit capacity / withdrawal liquidity for a (from, to) token pair. Computable client-side in the
30640
+ * SDK core (`sodax.bridge.getBridgeableAmount`); this HTTP variant mirrors `/bridge/bridgeable-amount`.
30641
+ *
30642
+ * @returns `Result<BridgeableAmountResponseV2>` — `{ limit }`.
30643
+ */
30644
+ async getBridgeableAmount(body, config) {
30645
+ return this.request(
30646
+ "/bridge/bridgeable-amount",
30647
+ { method: "POST", body: toJsonBody(body) },
30648
+ BridgeableAmountResponseSchema,
30649
+ config
30650
+ );
30651
+ }
30652
+ /**
30653
+ * Whether a (from, to) token pair is bridgeable. Computable client-side in the SDK core
30654
+ * (`sodax.bridge.isBridgeable`); this HTTP variant mirrors `/bridge/bridgeable/check`.
30655
+ *
30656
+ * @returns `Result<BridgeableCheckResponseV2>` — `{ bridgeable }`.
30657
+ */
30658
+ async isBridgeable(body, config) {
30659
+ return this.request(
30660
+ "/bridge/bridgeable/check",
30661
+ { method: "POST", body: toJsonBody(body) },
30662
+ BridgeableCheckResponseSchema,
30663
+ config
30664
+ );
30665
+ }
30666
+ // ──────────────────────────────────────────────────────────────────────
30667
+ // Utilities (parity with SwapsApiService)
30668
+ // ──────────────────────────────────────────────────────────────────────
30669
+ /**
30670
+ * Merge additional headers into the service's default header set. Existing
30671
+ * keys are overwritten; keys absent from `headers` are preserved.
30672
+ */
30673
+ setHeaders(headers) {
30674
+ Object.entries(headers).forEach(([key, value]) => {
30675
+ this.headers[key] = value;
30676
+ });
30677
+ }
30678
+ /** Return the base URL the service is currently pointing at. */
30679
+ getBaseURL() {
30680
+ return this.config.baseURL;
30681
+ }
30682
+ /**
30683
+ * Return the effective per-request timeout (ms). Callers that bound a request tighter than the
30684
+ * service default (e.g. `pollBackendSubmitTx` clamping to its poll cutoff) need this as the ceiling,
30685
+ * because a `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it.
30686
+ */
30687
+ getTimeout() {
30688
+ return this.config.timeout;
30689
+ }
30690
+ };
30065
30691
 
30066
30692
  // src/backendApi/apiConfig.ts
30067
- function isCustomApiConfig(config) {
30068
- return "baseApiConfig" in config || "swapsApiConfig" in config;
30693
+ function flatLayer({ baseURL, timeout, headers }) {
30694
+ return { baseURL, timeout, headers };
30069
30695
  }
30070
30696
  function layerConfigs(...slices) {
30071
30697
  return slices.reduce(
@@ -30082,154 +30708,172 @@ function layerConfigs(...slices) {
30082
30708
  );
30083
30709
  }
30084
30710
  function resolveBaseApiConfig(config) {
30085
- if (isCustomApiConfig(config)) {
30086
- return layerConfigs(config.baseApiConfig);
30087
- }
30088
- return layerConfigs(config);
30711
+ const layers = config;
30712
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig);
30089
30713
  }
30090
30714
  function resolveSwapsApiConfig(config) {
30091
- if (isCustomApiConfig(config)) {
30092
- return layerConfigs(config.baseApiConfig, config.swapsApiConfig);
30093
- }
30094
- return layerConfigs(config);
30095
- }
30096
- var ChainKeySchema = v2__namespace.custom((input) => typeof input === "string");
30097
- var SpokeChainKeySchema = v2__namespace.custom((input) => typeof input === "string");
30098
- var AddressSchema = v2__namespace.custom((input) => typeof input === "string");
30099
- var XTokenSchema = v2__namespace.object({
30100
- symbol: v2__namespace.string(),
30101
- name: v2__namespace.string(),
30102
- decimals: v2__namespace.number(),
30103
- address: v2__namespace.string(),
30715
+ const layers = config;
30716
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig, layers.swapsApiConfig);
30717
+ }
30718
+ function isHttpUrl(value) {
30719
+ return value.startsWith("http://") || value.startsWith("https://");
30720
+ }
30721
+ function normalizeBaseURL(baseURL) {
30722
+ const trimmed = trimTrailingSlashes(baseURL);
30723
+ return isHttpUrl(trimmed) ? trimmed : baseURL;
30724
+ }
30725
+ function resolveSponsoringApiConfig(config) {
30726
+ const layers = config;
30727
+ const slice = layers.sponsoringApiConfig;
30728
+ return {
30729
+ baseURL: normalizeBaseURL(slice?.baseURL ?? DEFAULT_SPONSORING_API_ENDPOINT),
30730
+ timeout: slice?.timeout ?? resolveBaseApiConfig(config).timeout,
30731
+ headers: { ...DEFAULT_BACKEND_API_HEADERS, ...slice?.headers },
30732
+ ...slice?.apiKey === void 0 ? {} : { apiKey: slice.apiKey }
30733
+ };
30734
+ }
30735
+ function resolveBridgeApiConfig(config) {
30736
+ return resolveBaseApiConfig(config);
30737
+ }
30738
+ var ChainKeySchema = v7__namespace.custom((input) => typeof input === "string");
30739
+ var SpokeChainKeySchema = v7__namespace.custom((input) => typeof input === "string");
30740
+ var AddressSchema2 = v7__namespace.custom((input) => typeof input === "string");
30741
+ var XTokenSchema = v7__namespace.object({
30742
+ symbol: v7__namespace.string(),
30743
+ name: v7__namespace.string(),
30744
+ decimals: v7__namespace.number(),
30745
+ address: v7__namespace.string(),
30104
30746
  chainKey: ChainKeySchema,
30105
- hubAsset: AddressSchema,
30106
- vault: AddressSchema,
30107
- access: v2__namespace.optional(v2__namespace.picklist(["withdrawOnly", "depositOnly"]))
30747
+ hubAsset: AddressSchema2,
30748
+ vault: AddressSchema2,
30749
+ access: v7__namespace.optional(v7__namespace.picklist(["withdrawOnly", "depositOnly"]))
30108
30750
  });
30109
- var IntentStructSchema = v2__namespace.object({
30110
- intentId: v2__namespace.string(),
30111
- creator: v2__namespace.string(),
30112
- inputToken: v2__namespace.string(),
30113
- outputToken: v2__namespace.string(),
30114
- inputAmount: v2__namespace.string(),
30115
- minOutputAmount: v2__namespace.string(),
30116
- deadline: v2__namespace.string(),
30117
- allowPartialFill: v2__namespace.boolean(),
30118
- srcChain: v2__namespace.number(),
30119
- dstChain: v2__namespace.number(),
30120
- srcAddress: v2__namespace.string(),
30121
- dstAddress: v2__namespace.string(),
30122
- solver: v2__namespace.string(),
30123
- data: v2__namespace.string()
30751
+ var IntentStructSchema = v7__namespace.object({
30752
+ intentId: v7__namespace.string(),
30753
+ creator: v7__namespace.string(),
30754
+ inputToken: v7__namespace.string(),
30755
+ outputToken: v7__namespace.string(),
30756
+ inputAmount: v7__namespace.string(),
30757
+ minOutputAmount: v7__namespace.string(),
30758
+ deadline: v7__namespace.string(),
30759
+ allowPartialFill: v7__namespace.boolean(),
30760
+ srcChain: v7__namespace.number(),
30761
+ dstChain: v7__namespace.number(),
30762
+ srcAddress: v7__namespace.string(),
30763
+ dstAddress: v7__namespace.string(),
30764
+ solver: v7__namespace.string(),
30765
+ data: v7__namespace.string()
30124
30766
  });
30125
- var IntentResponseSchema = v2__namespace.object({
30126
- intentHash: v2__namespace.string(),
30127
- txHash: v2__namespace.string(),
30128
- logIndex: v2__namespace.number(),
30129
- chainId: v2__namespace.number(),
30130
- blockNumber: v2__namespace.number(),
30131
- open: v2__namespace.boolean(),
30767
+ var IntentResponseSchema = v7__namespace.object({
30768
+ intentHash: v7__namespace.string(),
30769
+ txHash: v7__namespace.string(),
30770
+ logIndex: v7__namespace.number(),
30771
+ chainId: v7__namespace.number(),
30772
+ blockNumber: v7__namespace.number(),
30773
+ open: v7__namespace.boolean(),
30132
30774
  intent: IntentStructSchema,
30133
- events: v2__namespace.array(v2__namespace.unknown())
30775
+ events: v7__namespace.array(v7__namespace.unknown())
30134
30776
  });
30135
- var UserIntentsResponseSchema = v2__namespace.object({
30136
- total: v2__namespace.number(),
30137
- offset: v2__namespace.number(),
30138
- limit: v2__namespace.number(),
30139
- items: v2__namespace.array(IntentResponseSchema)
30777
+ var UserIntentsResponseSchema = v7__namespace.object({
30778
+ total: v7__namespace.number(),
30779
+ offset: v7__namespace.number(),
30780
+ limit: v7__namespace.number(),
30781
+ items: v7__namespace.array(IntentResponseSchema)
30140
30782
  });
30141
- var OrderbookResponseSchema = v2__namespace.object({
30142
- total: v2__namespace.number(),
30143
- data: v2__namespace.array(
30144
- v2__namespace.object({
30145
- intentState: v2__namespace.object({
30146
- exists: v2__namespace.boolean(),
30147
- remainingInput: v2__namespace.string(),
30148
- receivedOutput: v2__namespace.string(),
30149
- pendingPayment: v2__namespace.boolean()
30783
+ var OrderbookResponseSchema = v7__namespace.object({
30784
+ total: v7__namespace.number(),
30785
+ data: v7__namespace.array(
30786
+ v7__namespace.object({
30787
+ intentState: v7__namespace.object({
30788
+ exists: v7__namespace.boolean(),
30789
+ remainingInput: v7__namespace.string(),
30790
+ receivedOutput: v7__namespace.string(),
30791
+ pendingPayment: v7__namespace.boolean()
30150
30792
  }),
30151
- intentData: v2__namespace.object({
30152
- intentId: v2__namespace.string(),
30153
- creator: v2__namespace.string(),
30154
- inputToken: v2__namespace.string(),
30155
- outputToken: v2__namespace.string(),
30156
- inputAmount: v2__namespace.string(),
30157
- minOutputAmount: v2__namespace.string(),
30158
- deadline: v2__namespace.string(),
30159
- allowPartialFill: v2__namespace.boolean(),
30160
- srcChain: v2__namespace.number(),
30161
- dstChain: v2__namespace.number(),
30162
- srcAddress: v2__namespace.string(),
30163
- dstAddress: v2__namespace.string(),
30164
- solver: v2__namespace.string(),
30165
- data: v2__namespace.string(),
30166
- intentHash: v2__namespace.string(),
30167
- txHash: v2__namespace.string(),
30168
- blockNumber: v2__namespace.number()
30793
+ intentData: v7__namespace.object({
30794
+ intentId: v7__namespace.string(),
30795
+ creator: v7__namespace.string(),
30796
+ inputToken: v7__namespace.string(),
30797
+ outputToken: v7__namespace.string(),
30798
+ inputAmount: v7__namespace.string(),
30799
+ minOutputAmount: v7__namespace.string(),
30800
+ deadline: v7__namespace.string(),
30801
+ allowPartialFill: v7__namespace.boolean(),
30802
+ srcChain: v7__namespace.number(),
30803
+ dstChain: v7__namespace.number(),
30804
+ srcAddress: v7__namespace.string(),
30805
+ dstAddress: v7__namespace.string(),
30806
+ solver: v7__namespace.string(),
30807
+ data: v7__namespace.string(),
30808
+ intentHash: v7__namespace.string(),
30809
+ txHash: v7__namespace.string(),
30810
+ blockNumber: v7__namespace.number()
30169
30811
  })
30170
30812
  })
30171
30813
  )
30172
30814
  });
30173
- var MoneyMarketPositionSchema = v2__namespace.object({
30174
- userAddress: v2__namespace.string(),
30175
- positions: v2__namespace.array(
30176
- v2__namespace.object({
30177
- reserveAddress: v2__namespace.string(),
30178
- aTokenAddress: v2__namespace.string(),
30179
- variableDebtTokenAddress: v2__namespace.string(),
30180
- aTokenBalance: v2__namespace.string(),
30181
- variableDebtTokenBalance: v2__namespace.string(),
30182
- blockNumber: v2__namespace.number()
30815
+ var MoneyMarketPositionSchema = v7__namespace.object({
30816
+ userAddress: v7__namespace.string(),
30817
+ positions: v7__namespace.array(
30818
+ v7__namespace.object({
30819
+ reserveAddress: v7__namespace.string(),
30820
+ aTokenAddress: v7__namespace.string(),
30821
+ variableDebtTokenAddress: v7__namespace.string(),
30822
+ aTokenBalance: v7__namespace.string(),
30823
+ variableDebtTokenBalance: v7__namespace.string(),
30824
+ blockNumber: v7__namespace.number()
30183
30825
  })
30184
30826
  )
30185
30827
  });
30186
- var MoneyMarketAssetSchema = v2__namespace.object({
30187
- reserveAddress: v2__namespace.string(),
30188
- aTokenAddress: v2__namespace.string(),
30189
- totalATokenBalance: v2__namespace.string(),
30190
- variableDebtTokenAddress: v2__namespace.string(),
30191
- totalVariableDebtTokenBalance: v2__namespace.string(),
30192
- liquidityRate: v2__namespace.string(),
30193
- symbol: v2__namespace.string(),
30194
- totalSuppliers: v2__namespace.number(),
30195
- totalBorrowers: v2__namespace.number(),
30196
- variableBorrowRate: v2__namespace.string(),
30197
- stableBorrowRate: v2__namespace.string(),
30198
- liquidityIndex: v2__namespace.string(),
30199
- variableBorrowIndex: v2__namespace.string(),
30200
- blockNumber: v2__namespace.number()
30828
+ var MoneyMarketAssetSchema = v7__namespace.object({
30829
+ reserveAddress: v7__namespace.string(),
30830
+ aTokenAddress: v7__namespace.string(),
30831
+ totalATokenBalance: v7__namespace.string(),
30832
+ variableDebtTokenAddress: v7__namespace.string(),
30833
+ totalVariableDebtTokenBalance: v7__namespace.string(),
30834
+ liquidityRate: v7__namespace.string(),
30835
+ symbol: v7__namespace.string(),
30836
+ totalSuppliers: v7__namespace.number(),
30837
+ totalBorrowers: v7__namespace.number(),
30838
+ variableBorrowRate: v7__namespace.string(),
30839
+ stableBorrowRate: v7__namespace.string(),
30840
+ liquidityIndex: v7__namespace.string(),
30841
+ variableBorrowIndex: v7__namespace.string(),
30842
+ blockNumber: v7__namespace.number()
30201
30843
  });
30202
- var MoneyMarketAssetsSchema = v2__namespace.array(MoneyMarketAssetSchema);
30203
- var MoneyMarketAssetBorrowersSchema = v2__namespace.object({
30204
- borrowers: v2__namespace.array(v2__namespace.string()),
30205
- total: v2__namespace.number(),
30206
- offset: v2__namespace.number(),
30207
- limit: v2__namespace.number()
30844
+ var MoneyMarketAssetsSchema = v7__namespace.array(MoneyMarketAssetSchema);
30845
+ var MoneyMarketAssetBorrowersSchema = v7__namespace.object({
30846
+ borrowers: v7__namespace.array(v7__namespace.string()),
30847
+ total: v7__namespace.number(),
30848
+ offset: v7__namespace.number(),
30849
+ limit: v7__namespace.number()
30208
30850
  });
30209
- var MoneyMarketAssetSuppliersSchema = v2__namespace.object({
30210
- suppliers: v2__namespace.array(v2__namespace.string()),
30211
- total: v2__namespace.number(),
30212
- offset: v2__namespace.number(),
30213
- limit: v2__namespace.number()
30851
+ var MoneyMarketAssetSuppliersSchema = v7__namespace.object({
30852
+ suppliers: v7__namespace.array(v7__namespace.string()),
30853
+ total: v7__namespace.number(),
30854
+ offset: v7__namespace.number(),
30855
+ limit: v7__namespace.number()
30214
30856
  });
30215
- var MoneyMarketBorrowersSchema = v2__namespace.object({
30216
- borrowers: v2__namespace.array(v2__namespace.string()),
30217
- total: v2__namespace.number(),
30218
- offset: v2__namespace.number(),
30219
- limit: v2__namespace.number()
30857
+ var MoneyMarketBorrowersSchema = v7__namespace.object({
30858
+ borrowers: v7__namespace.array(v7__namespace.string()),
30859
+ total: v7__namespace.number(),
30860
+ offset: v7__namespace.number(),
30861
+ limit: v7__namespace.number()
30220
30862
  });
30221
- var GetChainsResponseSchema = v2__namespace.array(SpokeChainKeySchema);
30222
- var TokensByChainMapSchema = v2__namespace.custom(
30223
- (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v2__namespace.is(XTokenSchema, t)))
30863
+ var GetChainsResponseSchema = v7__namespace.array(SpokeChainKeySchema);
30864
+ var TokensByChainMapSchema = v7__namespace.custom(
30865
+ (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v7__namespace.is(XTokenSchema, t)))
30224
30866
  );
30225
- var TokensListSchema = v2__namespace.array(XTokenSchema);
30226
- var ReserveAssetsSchema = v2__namespace.array(AddressSchema);
30867
+ var TokensListSchema = v7__namespace.array(XTokenSchema);
30868
+ var ReserveAssetsSchema = v7__namespace.array(AddressSchema2);
30227
30869
 
30228
30870
  // src/backendApi/BackendApiService.ts
30229
30871
  var BackendApiService = class {
30230
30872
  // sub-services exposing domain-specific APIs
30231
30873
  swaps;
30232
- // resolved base-API slice of the ApiConfig union (flat config, or its `baseApiConfig`)
30874
+ sponsoring;
30875
+ bridge;
30876
+ // resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on top
30233
30877
  config;
30234
30878
  headers;
30235
30879
  logger;
@@ -30238,37 +30882,8 @@ var BackendApiService = class {
30238
30882
  this.headers = { ...this.config.headers };
30239
30883
  this.logger = logger;
30240
30884
  this.swaps = new SwapsApiService(resolveSwapsApiConfig(config), this.logger);
30241
- }
30242
- /**
30243
- * Wraps {@link makeRequest} in a `Result<T>` so all errors are captured rather
30244
- * than propagated as thrown exceptions. Every public endpoint method delegates
30245
- * here instead of calling `makeRequest` directly.
30246
- */
30247
- /**
30248
- * Fold any per-call override (carried on `config` alongside `method`/`body`) over the service
30249
- * defaults: baseURL truthy-fallback (an empty-string override defers to the default), timeout
30250
- * nullish-fallback, headers merged (override wins per key). Mirrors the original makeRequest merge.
30251
- */
30252
- resolveRequestConfig(config) {
30253
- const { baseURL, timeout, headers, ...rest } = config;
30254
- return {
30255
- ...rest,
30256
- baseURL: baseURL || this.config.baseURL,
30257
- timeout: timeout ?? this.config.timeout,
30258
- headers: { ...this.headers, ...headers }
30259
- };
30260
- }
30261
- /**
30262
- * Wrap a thrown transport failure (HTTP_REQUEST_FAILED / REQUEST_TIMEOUT / network error) as the
30263
- * canonical backend `SodaxError` — identical shape to SwapsApiService; the underlying failure is
30264
- * preserved on `error.cause`.
30265
- */
30266
- toExternalApiError(endpoint, error) {
30267
- return new SodaxError(
30268
- "EXTERNAL_API_ERROR",
30269
- error instanceof Error ? error.message : `Backend API request to ${endpoint} failed`,
30270
- { feature: "backend", cause: error, context: { api: "backend", endpoint } }
30271
- );
30885
+ this.sponsoring = new SponsoringApiService(resolveSponsoringApiConfig(config), this.logger);
30886
+ this.bridge = new BridgeApiService(resolveBridgeApiConfig(config), this.logger);
30272
30887
  }
30273
30888
  /**
30274
30889
  * Issue a request and validate the JSON body against `schema`, wrapping the result in `Result<T>`.
@@ -30281,23 +30896,25 @@ var BackendApiService = class {
30281
30896
  try {
30282
30897
  const raw = await makeRequest({
30283
30898
  endpoint,
30284
- config: this.resolveRequestConfig(config),
30899
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30285
30900
  logger: this.logger,
30286
30901
  serviceLabel: "BackendApiService"
30287
30902
  });
30288
- const parsed = v2__namespace.safeParse(schema, raw);
30903
+ const parsed = v7__namespace.safeParse(schema, raw);
30289
30904
  if (!parsed.success) {
30290
30905
  return {
30291
30906
  ok: false,
30292
- error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from backend API for ${endpoint}`, {
30907
+ error: toInvalidResponseShapeError({
30908
+ api: "backend",
30293
30909
  feature: "backend",
30294
- context: { api: "backend", endpoint, reason: "invalid_response_shape", issues: v2__namespace.flatten(parsed.issues) }
30910
+ endpoint,
30911
+ issues: v7__namespace.flatten(parsed.issues)
30295
30912
  })
30296
30913
  };
30297
30914
  }
30298
30915
  return { ok: true, value: parsed.output };
30299
30916
  } catch (error) {
30300
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30917
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30301
30918
  }
30302
30919
  }
30303
30920
  /**
@@ -30311,13 +30928,13 @@ var BackendApiService = class {
30311
30928
  try {
30312
30929
  const value = await makeRequest({
30313
30930
  endpoint,
30314
- config: this.resolveRequestConfig(config),
30931
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30315
30932
  logger: this.logger,
30316
30933
  serviceLabel: "BackendApiService"
30317
30934
  });
30318
30935
  return { ok: true, value };
30319
30936
  } catch (error) {
30320
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30937
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30321
30938
  }
30322
30939
  }
30323
30940
  // Intent endpoints
@@ -30616,9 +31233,8 @@ var BackendApiService = class {
30616
31233
  * without constructing a new service instance. Existing header keys are
30617
31234
  * overwritten; keys absent from `headers` are preserved.
30618
31235
  *
30619
- * The headers are also fanned out to the sub-services (`swaps`), which hold
30620
- * their own header copies — so a token set here applies to every request made
30621
- * through this client, including `swaps.*`.
31236
+ * Headers also reach `swaps`, which shares this origin, but never `sponsoring`,
31237
+ * whose separate origin must not receive base-API credentials.
30622
31238
  *
30623
31239
  * @param headers - Key-value pairs to add or overwrite in the default headers.
30624
31240
  */
@@ -30627,6 +31243,7 @@ var BackendApiService = class {
30627
31243
  this.headers[key] = value;
30628
31244
  });
30629
31245
  this.swaps.setHeaders(headers);
31246
+ this.bridge.setHeaders(headers);
30630
31247
  }
30631
31248
  /**
30632
31249
  * Return the base URL the service is currently pointing at.
@@ -30677,25 +31294,32 @@ var BridgeService = class {
30677
31294
  hubProvider;
30678
31295
  config;
30679
31296
  spoke;
30680
- constructor({ hubProvider, config, spoke }) {
31297
+ // backend bridge-API client + opt-in backend submit-tx flag
31298
+ backendApi;
31299
+ useBackendSubmitTx;
31300
+ constructor({ hubProvider, config, spoke, backendApi, useBackendSubmitTx }) {
30681
31301
  this.config = config;
30682
31302
  this.hubProvider = hubProvider;
30683
31303
  this.spoke = spoke;
31304
+ this.backendApi = backendApi;
31305
+ this.useBackendSubmitTx = useBackendSubmitTx ?? false;
30684
31306
  }
30685
31307
  /**
30686
31308
  * Calculates the partner fee deducted from a given bridge input amount.
30687
31309
  *
30688
- * Returns `0n` when no partner fee is configured. The fee is denominated in the
30689
- * same units as `inputAmount` (vault token decimals, 18 dp).
31310
+ * Returns `0n` when no partner fee is configured. `inputAmount` must be in 18-dp hub/vault
31311
+ * units — the units the hub deducts the fee in (see `buildBridgeData`) — NOT the spoke token's
31312
+ * native base units. This matters for a fixed `PartnerFee.amount`, which is wei-denominated
31313
+ * (18 dp); a percentage fee is unit-agnostic.
30690
31314
  *
30691
- * @param inputAmount - Gross amount being bridged, in vault token base units.
31315
+ * @param inputAmount - Gross amount being bridged, in 18-dp hub/vault units.
30692
31316
  * @returns Fee amount to be deducted, in the same units as `inputAmount`.
30693
31317
  */
30694
- getFee(inputAmount) {
30695
- if (!this.config.bridgePartnerFee) {
31318
+ getFee(inputAmount, partnerFee = this.config.bridgePartnerFee) {
31319
+ if (!partnerFee) {
30696
31320
  return 0n;
30697
31321
  }
30698
- return calculateFeeAmount(inputAmount, this.config.bridgePartnerFee);
31322
+ return calculateFeeAmount(inputAmount, partnerFee);
30699
31323
  }
30700
31324
  /**
30701
31325
  * Checks whether the caller has sufficient token allowance to execute the bridge.
@@ -30880,42 +31504,21 @@ var BridgeService = class {
30880
31504
  "bridge",
30881
31505
  "bridge",
30882
31506
  async () => {
30883
- const { params, timeout } = _params;
31507
+ const { params } = _params;
30884
31508
  const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
30885
31509
  try {
30886
- const txResult = await this.createBridgeIntent(_params);
30887
- if (!txResult.ok) return { ok: false, error: txResult.error };
30888
- const verifyTxHashResult = await this.spoke.verifyTxHash({
30889
- txHash: txResult.value.tx,
30890
- chainKey: params.srcChainKey
30891
- });
30892
- if (!verifyTxHashResult.ok) {
30893
- return {
30894
- ok: false,
30895
- error: verifyFailed("bridge", verifyTxHashResult.error, baseCtx)
30896
- };
31510
+ const created = await this.createBridgeIntent(_params);
31511
+ if (!created.ok) return { ok: false, error: created.error };
31512
+ const deadline = Date.now() + (_params.timeout ?? DEFAULT_RELAY_TX_TIMEOUT);
31513
+ if (this.useBackendSubmitTx) {
31514
+ const submitted = await this.submitTx(_params, created.value, deadline);
31515
+ if (submitted.ok) return submitted;
31516
+ this.config.logger.warn(
31517
+ "[bridge] backend submit-tx did not complete; falling back to the client-side relay",
31518
+ { error: submitted.error }
31519
+ );
30897
31520
  }
30898
- const packetResult = await relayTxAndWaitPacket({
30899
- srcTxHash: txResult.value.tx,
30900
- data: txResult.value.relayData,
30901
- chainKey: params.srcChainKey,
30902
- relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
30903
- timeout
30904
- });
30905
- if (!packetResult.ok)
30906
- return {
30907
- ok: false,
30908
- error: mapRelayFailure(packetResult.error, {
30909
- feature: "bridge",
30910
- action: "bridge",
30911
- srcChainKey: baseCtx.srcChainKey,
30912
- dstChainKey: baseCtx.dstChainKey
30913
- })
30914
- };
30915
- return {
30916
- ok: true,
30917
- value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: packetResult.value.dst_tx_hash }
30918
- };
31521
+ return this.fallbackBridgeSteps(_params, created.value, deadline);
30919
31522
  } catch (error) {
30920
31523
  if (isBridgeOrchestrationError(error)) return { ok: false, error };
30921
31524
  return {
@@ -30942,6 +31545,98 @@ var BridgeService = class {
30942
31545
  }
30943
31546
  );
30944
31547
  }
31548
+ /**
31549
+ * Client-side bridge completion (the default path): verify the broadcast spoke-deposit tx, then
31550
+ * relay it to the hub and wait for the settlement packet. Extracted verbatim from `bridge()` so the
31551
+ * opt-in backend submit-tx path ({@link submitTx}) can fall back to it on any non-success. Bridge
31552
+ * always relays — there is no hub-source short-circuit.
31553
+ */
31554
+ async fallbackBridgeSteps(_params, created, deadline) {
31555
+ const { params } = _params;
31556
+ const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
31557
+ const verifyTxHashResult = await this.spoke.verifyTxHash({
31558
+ txHash: created.tx,
31559
+ chainKey: params.srcChainKey
31560
+ });
31561
+ if (!verifyTxHashResult.ok) {
31562
+ return { ok: false, error: verifyFailed("bridge", verifyTxHashResult.error, baseCtx) };
31563
+ }
31564
+ const packetResult = await relayTxAndWaitPacket({
31565
+ srcTxHash: created.tx,
31566
+ data: created.relayData,
31567
+ chainKey: params.srcChainKey,
31568
+ relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
31569
+ // Remaining shared budget: ≈ full `timeout` on the flag-off path minus the `verifyTxHash` wait,
31570
+ // or the reserve `submitTx` left on the backend path (`pollBackendSubmitTx` holds back up to a
31571
+ // third, capped at 20s). The floor matters because `relayTxAndWaitPacket` SUBMITS the tx to the
31572
+ // relay before `timeout` bounds anything: a budget exhausted by a slow source-chain confirmation
31573
+ // (Stacks polls for up to its full 120s `maxTimeoutMs`) would otherwise strand an already-landed
31574
+ // deposit unrelayed. Re-relay is idempotent, so always spending the floor is safe.
31575
+ timeout: Math.max(deadline - Date.now(), RELAY_FALLBACK_FLOOR_MS)
31576
+ });
31577
+ if (!packetResult.ok) {
31578
+ return {
31579
+ ok: false,
31580
+ error: mapRelayFailure(packetResult.error, {
31581
+ feature: "bridge",
31582
+ action: "bridge",
31583
+ srcChainKey: baseCtx.srcChainKey,
31584
+ dstChainKey: baseCtx.dstChainKey
31585
+ })
31586
+ };
31587
+ }
31588
+ return {
31589
+ ok: true,
31590
+ value: { srcChainTxHash: created.tx, dstChainTxHash: packetResult.value.dst_tx_hash }
31591
+ };
31592
+ }
31593
+ /**
31594
+ * Backend bridge path (opt-in via `bridgeOptions.useBackendSubmitTx`): hand the broadcast
31595
+ * spoke-deposit tx to the bridge API (`POST /bridge/submit-tx`) with the FULL `relayData`
31596
+ * envelope; the backend relays server-side. Polls `getSubmitTxStatus` until `executed`, then
31597
+ * returns the same {@link TxHashPair} the client-side path returns (`result.dstIntentTxHash` →
31598
+ * destination tx hash; bridge has no solver `intent_hash`).
31599
+ *
31600
+ * Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, terminal `failed` /
31601
+ * abandoned, or poll timeout) so `bridge()` falls back to {@link fallbackBridgeSteps}. Falling back
31602
+ * is safe: re-relaying an already-relayed bridge tx is idempotent — the relay dedups and returns the
31603
+ * existing `executed` packet. Polling stops at `deadline - reserve` so the fallback keeps a
31604
+ * guaranteed slice of the shared `bridge` budget.
31605
+ */
31606
+ async submitTx(_params, created, deadline) {
31607
+ const { params } = _params;
31608
+ const srcChainKey = params.srcChainKey;
31609
+ const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
31610
+ const { tx: spokeTxHash, relayData } = created;
31611
+ const submitTxFailed = (cause) => ({
31612
+ ok: false,
31613
+ error: executionFailed("bridge", cause, { ...baseCtx, action: "bridge" })
31614
+ });
31615
+ try {
31616
+ const submitted = await this.backendApi.bridge.submitTx({
31617
+ txHash: spokeTxHash,
31618
+ srcChainKey,
31619
+ walletAddress: params.srcAddress,
31620
+ // Send the FULL { address, payload } envelope — bridge has no intent.creator for the backend
31621
+ // to rebuild the relay address, so dropping it would break split-tx-chain relay.
31622
+ relayData
31623
+ });
31624
+ if (!submitted.ok) return submitTxFailed(submitted.error);
31625
+ const polled = await pollBackendSubmitTx({
31626
+ deadline,
31627
+ // Bridge terminal success is `executed` (hub-settled) — not the swaps `solved`.
31628
+ terminalStatus: "executed",
31629
+ getStatus: (override) => this.backendApi.bridge.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }, override),
31630
+ onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0,
31631
+ // Bound each status request by the poll cutoff, never above the service default — so a stalled
31632
+ // request can neither eat the fallback's reserve nor consume the window in one attempt.
31633
+ requestTimeoutMs: this.backendApi.bridge.getTimeout()
31634
+ });
31635
+ return polled.ok ? { ok: true, value: polled.value } : submitTxFailed(polled.cause);
31636
+ } catch (error) {
31637
+ return { ok: false, error: unknownFailed("bridge", error, { ...baseCtx, action: "bridge" }) };
31638
+ }
31639
+ }
30945
31640
  /**
30946
31641
  * Submits the spoke-side deposit transaction that initiates a bridge transfer,
30947
31642
  * without waiting for the cross-chain relay to complete.
@@ -30965,9 +31660,15 @@ var BridgeService = class {
30965
31660
  * contains the hub wallet address and encoded hub execution payload needed for relay.
30966
31661
  */
30967
31662
  async createBridgeIntent(_params) {
30968
- const { params, skipSimulation } = _params;
31663
+ const { params, skipSimulation, extras } = _params;
31664
+ const partnerFee = extras?.partnerFee ?? this.config.bridgePartnerFee;
30969
31665
  const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
30970
31666
  try {
31667
+ bridgeInvariant(
31668
+ isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
31669
+ `Invalid wallet provider for chain key: ${params.srcChainKey}`,
31670
+ baseCtx
31671
+ );
30971
31672
  bridgeInvariant(params.amount > 0n, "Amount must be greater than 0", { ...baseCtx, field: "amount" });
30972
31673
  const srcToken = this.resolveBridgeEndpointToken(params.srcChainKey, params.srcToken);
30973
31674
  const dstToken = this.resolveBridgeEndpointToken(params.dstChainKey, params.dstToken);
@@ -30979,25 +31680,62 @@ var BridgeService = class {
30979
31680
  ...baseCtx,
30980
31681
  field: "dstToken"
30981
31682
  });
30982
- const personalAddress = params.srcAddress;
30983
- let walletAddress = personalAddress;
30984
- if (isBitcoinChainKeyType(params.srcChainKey) && _params.raw === false) {
31683
+ bridgeInvariant(
31684
+ this.config.isValidSpokeChainKey(params.srcChainKey),
31685
+ `Invalid spoke chain (srcChainKey): ${params.srcChainKey}`,
31686
+ { ...baseCtx, field: "srcChainKey" }
31687
+ );
31688
+ bridgeInvariant(
31689
+ this.config.isValidSpokeChainKey(params.dstChainKey),
31690
+ `Invalid spoke chain (dstChainKey): ${params.dstChainKey}`,
31691
+ { ...baseCtx, field: "dstChainKey" }
31692
+ );
31693
+ if (isNativeBitcoinTransfer(this.config, params.srcChainKey, srcToken)) {
30985
31694
  bridgeInvariant(
30986
- isBitcoinWalletProviderType(_params.walletProvider),
30987
- `Invalid wallet provider for chain key: ${params.srcChainKey}. Expected bitcoin wallet provider.`,
30988
- { ...baseCtx, field: "walletProvider" }
31695
+ params.amount >= BITCOIN_DUST_SATS,
31696
+ `Invalid amount (${params.amount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
31697
+ { ...baseCtx, field: "amount" }
30989
31698
  );
30990
- walletAddress = await this.spoke.bitcoin.getEffectiveWalletAddress(personalAddress);
30991
- if (this.spoke.bitcoin.walletMode === "TRADING") {
30992
- await this.spoke.bitcoin.radfi.ensureRadfiAccessToken(_params.walletProvider);
31699
+ }
31700
+ if (isNativeBitcoinTransfer(this.config, params.dstChainKey, dstToken)) {
31701
+ const { delivered } = this.computeBridgeAmounts(params.amount, srcToken, dstToken, partnerFee);
31702
+ bridgeInvariant(
31703
+ delivered >= BITCOIN_DUST_SATS,
31704
+ `Post-fee BTC delivery (${delivered}) is below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
31705
+ { ...baseCtx, field: "amount" }
31706
+ );
31707
+ }
31708
+ if (isStacksChainKeyType(params.srcChainKey) && _params.raw === true) {
31709
+ bridgeInvariant(
31710
+ extras?.srcPublicKey !== void 0,
31711
+ "srcPublicKey is required for Stacks createBridgeIntent (raw) \u2014 the source tx is built unsigned and needs the signer public key",
31712
+ { ...baseCtx, field: "srcPublicKey" }
31713
+ );
31714
+ }
31715
+ const personalAddress = params.srcAddress;
31716
+ let walletAddress = personalAddress;
31717
+ if (isBitcoinChainKeyType(params.srcChainKey)) {
31718
+ if (_params.raw === false) {
31719
+ bridgeInvariant(
31720
+ isBitcoinWalletProviderType(_params.walletProvider),
31721
+ `Invalid wallet provider for chain key: ${params.srcChainKey}. Expected bitcoin wallet provider.`,
31722
+ { ...baseCtx, field: "walletProvider" }
31723
+ );
31724
+ if (this.spoke.bitcoin.walletMode === "TRADING") {
31725
+ await this.spoke.bitcoin.radfi.ensureRadfiAccessToken(_params.walletProvider);
31726
+ }
30993
31727
  }
31728
+ walletAddress = await this.spoke.bitcoin.getEffectiveWalletAddress(personalAddress);
30994
31729
  }
30995
31730
  const hubWallet = await this.hubProvider.getUserHubWalletAddress(walletAddress, params.srcChainKey);
30996
31731
  const effectiveSkipSimulation = skipSimulation || isBitcoinChainKeyType(params.srcChainKey) && this.spoke.bitcoin.walletMode === "USER";
30997
- const data = this.buildBridgeData(params, srcToken, dstToken, this.config.bridgePartnerFee);
31732
+ const data = this.buildBridgeData(params, srcToken, dstToken, partnerFee);
30998
31733
  const coreParams = {
30999
31734
  srcChainKey: params.srcChainKey,
31000
31735
  srcAddress: walletAddress,
31736
+ srcPublicKey: extras?.srcPublicKey,
31737
+ // Bitcoin Bound token; BitcoinSpokeService.deposit falls back to the RadfiProvider instance token when undefined.
31738
+ accessToken: extras?.bound?.accessToken,
31001
31739
  to: hubWallet,
31002
31740
  token: params.srcToken,
31003
31741
  amount: params.amount,
@@ -31052,6 +31790,26 @@ var BridgeService = class {
31052
31790
  if (spokeToken) return spokeToken;
31053
31791
  return isHubChainKeyType(chainKey) ? this.config.getXTokenFromHubAsset(token) : void 0;
31054
31792
  }
31793
+ /**
31794
+ * Post-fee amounts for a bridge, in the units each hub step operates in. Single source for the fee +
31795
+ * vault-decimal pipeline, so {@link buildBridgeData}'s encoded hub calls and the BTC-destination dust
31796
+ * guard in {@link createBridgeIntent} can never disagree about what actually gets delivered.
31797
+ *
31798
+ * A spoke endpoint's amount is translated INTO 18-dp vault units on the way in (skipped when the
31799
+ * endpoint already IS the vault asset), the partner fee is deducted there — so a fixed
31800
+ * `PartnerFee.amount` is wei-denominated, never spoke-denominated — and the remainder is translated
31801
+ * back OUT into the destination endpoint's own units.
31802
+ *
31803
+ * @returns `feeAmount` and `withdrawAmount` in 18-dp vault units (what the hub fee transfer and vault
31804
+ * withdrawal use), and `delivered` in the destination endpoint's units (what the recipient receives).
31805
+ */
31806
+ computeBridgeAmounts(amount, srcToken, dstToken, partnerFee) {
31807
+ const translatedAmount = this.config.isSodaVaultHubAsset(srcToken.hubAsset) ? amount : EvmVaultTokenService.translateIncomingDecimals(srcToken.decimals, amount);
31808
+ const feeAmount = calculateFeeAmount(translatedAmount, partnerFee);
31809
+ const withdrawAmount = translatedAmount - feeAmount;
31810
+ const delivered = this.config.isSodaVaultHubAsset(dstToken.hubAsset) ? withdrawAmount : EvmVaultTokenService.translateOutgoingDecimals(dstToken.decimals, withdrawAmount);
31811
+ return { feeAmount, withdrawAmount, delivered };
31812
+ }
31055
31813
  /**
31056
31814
  * Encodes the hub-side execution payload for a bridge operation.
31057
31815
  *
@@ -31075,23 +31833,23 @@ var BridgeService = class {
31075
31833
  */
31076
31834
  buildBridgeData(params, srcToken, dstToken, partnerFee) {
31077
31835
  const calls = [];
31078
- let translatedAmount = params.amount;
31079
- let srcVault = params.srcToken;
31836
+ const { feeAmount, withdrawAmount, delivered } = this.computeBridgeAmounts(
31837
+ params.amount,
31838
+ srcToken,
31839
+ dstToken,
31840
+ partnerFee
31841
+ );
31842
+ let srcVault = srcToken.hubAsset;
31080
31843
  if (!this.config.isSodaVaultHubAsset(srcToken.hubAsset)) {
31081
31844
  calls.push(Erc20Service.encodeApprove(srcToken.hubAsset, srcToken.vault, params.amount));
31082
31845
  calls.push(EvmVaultTokenService.encodeDeposit(srcToken.vault, srcToken.hubAsset, params.amount));
31083
- translatedAmount = EvmVaultTokenService.translateIncomingDecimals(srcToken.decimals, params.amount);
31084
31846
  srcVault = srcToken.vault;
31085
31847
  }
31086
- const feeAmount = calculateFeeAmount(translatedAmount, partnerFee);
31087
31848
  if (partnerFee && feeAmount > 0n) {
31088
31849
  calls.push(Erc20Service.encodeTransfer(srcVault, partnerFee.address, feeAmount));
31089
31850
  }
31090
- const withdrawAmount = translatedAmount - feeAmount;
31091
- let translatedWithdrawAmount = withdrawAmount;
31092
31851
  if (!this.config.isSodaVaultHubAsset(dstToken.hubAsset)) {
31093
31852
  calls.push(EvmVaultTokenService.encodeWithdraw(dstToken.vault, dstToken.hubAsset, withdrawAmount));
31094
- translatedWithdrawAmount = EvmVaultTokenService.translateOutgoingDecimals(dstToken.decimals, withdrawAmount);
31095
31853
  }
31096
31854
  const encodedRecipientAddress = encodeAddress(params.dstChainKey, params.recipient);
31097
31855
  if (isHubChainKey(params.dstChainKey)) {
@@ -31102,11 +31860,11 @@ var BridgeService = class {
31102
31860
  data: viem.encodeFunctionData({
31103
31861
  abi: wrappedSonicAbi,
31104
31862
  functionName: "withdrawTo",
31105
- args: [encodedRecipientAddress, translatedWithdrawAmount]
31863
+ args: [encodedRecipientAddress, delivered]
31106
31864
  })
31107
31865
  });
31108
31866
  } else {
31109
- calls.push(Erc20Service.encodeTransfer(dstToken.hubAsset, encodedRecipientAddress, translatedWithdrawAmount));
31867
+ calls.push(Erc20Service.encodeTransfer(dstToken.hubAsset, encodedRecipientAddress, delivered));
31110
31868
  }
31111
31869
  } else {
31112
31870
  bridgeInvariant(dstToken, `Unsupported hub chain (${params.dstChainKey}) token: ${params.dstToken}`, {
@@ -31117,7 +31875,7 @@ var BridgeService = class {
31117
31875
  EvmAssetManagerService.encodeTransfer(
31118
31876
  dstToken.hubAsset,
31119
31877
  encodedRecipientAddress,
31120
- translatedWithdrawAmount,
31878
+ delivered,
31121
31879
  this.hubProvider.chainConfig.addresses.assetManager
31122
31880
  )
31123
31881
  );
@@ -39336,7 +40094,7 @@ var LeverageYieldService = class {
39336
40094
  }
39337
40095
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
39338
40096
  getVault(name) {
39339
- return this.listVaults().find((v4) => v4.name === name);
40097
+ return this.listVaults().find((v9) => v9.name === name);
39340
40098
  }
39341
40099
  /**
39342
40100
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -39344,7 +40102,7 @@ var LeverageYieldService = class {
39344
40102
  */
39345
40103
  getVaultByAddress(address) {
39346
40104
  const normalized = address.toLowerCase();
39347
- return this.listVaults().find((v4) => v4.vault.toLowerCase() === normalized);
40105
+ return this.listVaults().find((v9) => v9.vault.toLowerCase() === normalized);
39348
40106
  }
39349
40107
  /**
39350
40108
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -40126,6 +40884,566 @@ var LeverageYieldService = class {
40126
40884
  }
40127
40885
  };
40128
40886
 
40887
+ // src/sponsoring/errors.ts
40888
+ var sponsoringInvariant = createInvariant("sponsoring");
40889
+ var ORCHESTRATION_CODES3 = /* @__PURE__ */ new Set([
40890
+ "USER_REJECTED",
40891
+ "VALIDATION_FAILED",
40892
+ "INTENT_CREATION_FAILED",
40893
+ "LOOKUP_FAILED",
40894
+ "EXTERNAL_API_ERROR",
40895
+ "EXECUTION_FAILED",
40896
+ "UNKNOWN"
40897
+ ]);
40898
+ var CONFIG_CODES = /* @__PURE__ */ new Set([
40899
+ "EXTERNAL_API_ERROR",
40900
+ "VALIDATION_FAILED",
40901
+ "UNKNOWN"
40902
+ ]);
40903
+ var isSponsoringOrchestrationError = isCodeMember(ORCHESTRATION_CODES3);
40904
+ var isSponsoringConfigError = isCodeMember(CONFIG_CODES);
40905
+ var isSponsoringLookupError = isCodeMember(LOOKUP_CODES);
40906
+ var DOMAIN_CODES = new Set(SPONSORING_API_ERROR_CODES);
40907
+ function toDomainCode(value) {
40908
+ return typeof value === "string" && DOMAIN_CODES.has(value) ? value : void 0;
40909
+ }
40910
+ function readErrorBody(body) {
40911
+ if (typeof body !== "object" || body === null) return {};
40912
+ const record3 = body;
40913
+ const retryAfterSeconds = typeof record3.retryAfterSeconds === "number" && Number.isFinite(record3.retryAfterSeconds) && record3.retryAfterSeconds > 0 ? record3.retryAfterSeconds : void 0;
40914
+ const sponsorSequence = typeof record3.sponsorSequence === "string" && /^\d+$/.test(record3.sponsorSequence) ? record3.sponsorSequence : void 0;
40915
+ return {
40916
+ message: typeof record3.message === "string" ? record3.message : void 0,
40917
+ code: toDomainCode(record3.error),
40918
+ retryAfterSeconds,
40919
+ sponsorSequence
40920
+ };
40921
+ }
40922
+ var ACTION_POLICY = {
40923
+ fixIntegration: { retryable: false, requiresNewSignature: false },
40924
+ checkApiKey: { retryable: false, requiresNewSignature: false },
40925
+ rebuildAndResign: { retryable: true, requiresNewSignature: true },
40926
+ retrySameRequest: { retryable: true, requiresNewSignature: false },
40927
+ backoff: { retryable: true, requiresNewSignature: false },
40928
+ contactOperator: { retryable: false, requiresNewSignature: false },
40929
+ abort: { retryable: false, requiresNewSignature: false }
40930
+ };
40931
+ function policy(action) {
40932
+ return { action, ...ACTION_POLICY[action] };
40933
+ }
40934
+ function classifySponsorError(error) {
40935
+ const cause = error.cause;
40936
+ const http3 = isBackendHttpError(cause) ? cause : void 0;
40937
+ const { message: serverMessage, code, retryAfterSeconds, sponsorSequence } = readErrorBody(http3?.body);
40938
+ const message = serverMessage ?? error.message;
40939
+ const status = http3?.status;
40940
+ if (status === void 0) {
40941
+ return { ...policy("backoff"), message };
40942
+ }
40943
+ const base2 = { status, code, retryAfterSeconds, sponsorSequence, message };
40944
+ switch (status) {
40945
+ case 400:
40946
+ return { ...base2, ...policy("fixIntegration") };
40947
+ case 401:
40948
+ return { ...base2, ...policy("checkApiKey") };
40949
+ case 409:
40950
+ return { ...base2, ...policy("rebuildAndResign") };
40951
+ case 422:
40952
+ return { ...base2, ...policy("abort") };
40953
+ case 429:
40954
+ return { ...base2, ...policy("backoff") };
40955
+ case 500:
40956
+ return { ...base2, ...policy("contactOperator") };
40957
+ case 503:
40958
+ if (code === "SPONSOR_BUDGET_EXHAUSTED") {
40959
+ return { ...base2, ...policy("contactOperator") };
40960
+ }
40961
+ if (code === "HORIZON_UNAVAILABLE") {
40962
+ return { ...base2, ...policy("retrySameRequest") };
40963
+ }
40964
+ return { ...base2, ...policy("backoff") };
40965
+ default:
40966
+ return { ...base2, ...policy("abort") };
40967
+ }
40968
+ }
40969
+ var SPONSORED_CREATE_OP_COUNT = 3n;
40970
+ var SPONSOR_TIMEBOUND_SECONDS = 300;
40971
+ function parseStroops(value, field) {
40972
+ try {
40973
+ return BigInt(value);
40974
+ } catch {
40975
+ sponsoringInvariant(false, `sponsor config ${field} is not a valid integer: "${value}"`, { field });
40976
+ }
40977
+ }
40978
+ function deriveSponsorBaseFee(config) {
40979
+ const min = parseStroops(config.minTotalFeeStroops, "minTotalFeeStroops");
40980
+ const max = parseStroops(config.maxTotalFeeStroops, "maxTotalFeeStroops");
40981
+ sponsoringInvariant(min > 0n, `sponsor config minTotalFeeStroops must be positive, got ${min}`, {
40982
+ field: "minTotalFeeStroops"
40983
+ });
40984
+ sponsoringInvariant(max >= min, `sponsor config fee band is inverted (min ${min} > max ${max})`, {
40985
+ field: "maxTotalFeeStroops"
40986
+ });
40987
+ const minPerOp = parseStroops(config.minPerOperationFeeStroops, "minPerOperationFeeStroops");
40988
+ const maxPerOp = parseStroops(config.maxPerOperationFeeStroops, "maxPerOperationFeeStroops");
40989
+ sponsoringInvariant(minPerOp > 0n, `sponsor config minPerOperationFeeStroops must be positive, got ${minPerOp}`, {
40990
+ field: "minPerOperationFeeStroops"
40991
+ });
40992
+ sponsoringInvariant(
40993
+ maxPerOp >= minPerOp,
40994
+ `sponsor config per-operation fee band is inverted (min ${minPerOp} > max ${maxPerOp})`,
40995
+ { field: "maxPerOperationFeeStroops" }
40996
+ );
40997
+ sponsoringInvariant(
40998
+ Number.isInteger(config.operationCount) && BigInt(config.operationCount) === SPONSORED_CREATE_OP_COUNT,
40999
+ `sponsor config expects ${config.operationCount} operations but this builder emits ${SPONSORED_CREATE_OP_COUNT} \u2014 the sponsored-create shape has changed server-side`,
41000
+ { field: "operationCount" }
41001
+ );
41002
+ const baseFee = parseStroops(config.recommendedPerOperationFeeStroops, "recommendedPerOperationFeeStroops");
41003
+ const totalFee = baseFee * SPONSORED_CREATE_OP_COUNT;
41004
+ sponsoringInvariant(
41005
+ baseFee >= minPerOp && baseFee <= maxPerOp,
41006
+ `per-operation fee ${baseFee} is outside the accepted per-operation band [${minPerOp}, ${maxPerOp}]`,
41007
+ { field: "recommendedPerOperationFeeStroops" }
41008
+ );
41009
+ sponsoringInvariant(
41010
+ totalFee >= min && totalFee <= max,
41011
+ `per-operation fee ${baseFee} yields a total of ${totalFee} stroops, outside the accepted band [${min}, ${max}]`,
41012
+ { field: "recommendedPerOperationFeeStroops" }
41013
+ );
41014
+ return { baseFee: baseFee.toString(), totalFee };
41015
+ }
41016
+ function resolveTimeboundSeconds(config) {
41017
+ const ceiling = Math.floor(config.maxTimeboundSeconds);
41018
+ const seconds = Math.min(SPONSOR_TIMEBOUND_SECONDS, ceiling);
41019
+ sponsoringInvariant(
41020
+ Number.isFinite(seconds) && seconds > 0,
41021
+ `sponsor config maxTimeboundSeconds leaves no usable window, got ${config.maxTimeboundSeconds}`,
41022
+ { field: "maxTimeboundSeconds" }
41023
+ );
41024
+ return seconds;
41025
+ }
41026
+ function assertSponsoredCreateInputs(params) {
41027
+ const { config, address } = params;
41028
+ sponsoringInvariant(
41029
+ config.networkPassphrase === stellarSdk.Networks.PUBLIC,
41030
+ `sponsored create must target the Stellar public network, got "${config.networkPassphrase}"`,
41031
+ { field: "networkPassphrase" }
41032
+ );
41033
+ assertValidStellarAccountId(address);
41034
+ assertValidStellarAccountId(config.sponsorAccount);
41035
+ deriveSponsorBaseFee(config);
41036
+ resolveTimeboundSeconds(config);
41037
+ }
41038
+ function buildSponsoredCreate(params) {
41039
+ const { config, sponsorSequence, address } = params;
41040
+ assertSponsoredCreateInputs({ config, address });
41041
+ const { baseFee } = deriveSponsorBaseFee(config);
41042
+ const timeboundSeconds = resolveTimeboundSeconds(config);
41043
+ return new stellarSdk.TransactionBuilder(new stellarSdk.Account(config.sponsorAccount, sponsorSequence), {
41044
+ fee: baseFee,
41045
+ networkPassphrase: config.networkPassphrase
41046
+ }).addOperation(stellarSdk.Operation.beginSponsoringFutureReserves({ sponsoredId: address })).addOperation(stellarSdk.Operation.createAccount({ destination: address, startingBalance: config.requiredStartingBalance })).addOperation(stellarSdk.Operation.endSponsoringFutureReserves({ source: address })).setTimeout(timeboundSeconds).build();
41047
+ }
41048
+ function assertValidStellarAccountId(address) {
41049
+ let valid = true;
41050
+ try {
41051
+ stellarSdk.Keypair.fromPublicKey(address);
41052
+ } catch {
41053
+ valid = false;
41054
+ }
41055
+ sponsoringInvariant(valid, `"${address}" is not a valid Stellar ed25519 public key`, { field: "address" });
41056
+ }
41057
+ function assertSignedByAccount(params) {
41058
+ const { signedXdr, address, unsignedHash } = params;
41059
+ let parsed;
41060
+ try {
41061
+ parsed = stellarSdk.TransactionBuilder.fromXDR(signedXdr, stellarSdk.Networks.PUBLIC);
41062
+ } catch (error) {
41063
+ sponsoringInvariant(false, `wallet returned an unparseable transaction: ${messageOf(error, String(error))}`, {
41064
+ field: "signature"
41065
+ });
41066
+ }
41067
+ sponsoringInvariant(
41068
+ !(parsed instanceof stellarSdk.FeeBumpTransaction),
41069
+ "wallet returned a fee-bump envelope; the sponsoring API rejects fee-bump transactions",
41070
+ { field: "signature" }
41071
+ );
41072
+ const hash = parsed.hash();
41073
+ sponsoringInvariant(
41074
+ hash.equals(unsignedHash),
41075
+ "wallet altered the transaction before signing it (fee, memo, or time bounds changed)",
41076
+ { field: "signature" }
41077
+ );
41078
+ const keypair = stellarSdk.Keypair.fromPublicKey(address);
41079
+ const signedByAccount = parsed.signatures.some((signature) => {
41080
+ try {
41081
+ return keypair.verify(hash, signature.signature());
41082
+ } catch {
41083
+ return false;
41084
+ }
41085
+ });
41086
+ sponsoringInvariant(
41087
+ signedByAccount,
41088
+ "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",
41089
+ { field: "signature" }
41090
+ );
41091
+ }
41092
+ function isHorizonNotFound(error) {
41093
+ if (error instanceof stellarSdk.NotFoundError) return true;
41094
+ const status = error?.response?.status;
41095
+ return status === 404;
41096
+ }
41097
+ var XLM_DECIMALS = 7;
41098
+ function xlmDecimalToStroops(amount) {
41099
+ if (!/^\d+(\.\d+)?$/.test(amount)) return 0n;
41100
+ const [whole = "0", fraction = ""] = amount.split(".");
41101
+ const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
41102
+ return BigInt(scaled);
41103
+ }
41104
+ var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
41105
+ var BASE_RESERVE_UNITS = 2;
41106
+ function parseBaseReserveStroops(ledger) {
41107
+ const value = ledger?.base_reserve_in_stroops;
41108
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) return void 0;
41109
+ return BigInt(value);
41110
+ }
41111
+ function readReserveInfo(account, baseReserveStroops) {
41112
+ const native = account.balances.find((balance) => balance.asset_type === "native");
41113
+ const nativeBalanceStroops = native ? xlmDecimalToStroops(native.balance) : 0n;
41114
+ const sellingLiabilitiesStroops = native?.selling_liabilities ? xlmDecimalToStroops(native.selling_liabilities) : 0n;
41115
+ const units = Math.max(
41116
+ 0,
41117
+ BASE_RESERVE_UNITS + (account.subentry_count ?? 0) + (account.num_sponsoring ?? 0) - (account.num_sponsored ?? 0)
41118
+ );
41119
+ const lockedStroops = BigInt(units) * baseReserveStroops + sellingLiabilitiesStroops;
41120
+ return {
41121
+ nativeBalanceStroops,
41122
+ availableBalanceStroops: nativeBalanceStroops > lockedStroops ? nativeBalanceStroops - lockedStroops : 0n
41123
+ };
41124
+ }
41125
+
41126
+ // src/sponsoring/SponsoringService.ts
41127
+ var SPONSOR_CONFIG_TTL_MS = 6e4;
41128
+ var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
41129
+ var DEFAULT_MAX_HORIZON_RETRIES = 2;
41130
+ var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
41131
+ var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS + STELLAR_FEE_HEADROOM_STROOPS;
41132
+ var SponsoringService = class {
41133
+ config;
41134
+ spoke;
41135
+ api;
41136
+ /** Keyed by base URL to isolate deployment-specific sponsor config. */
41137
+ configCache = /* @__PURE__ */ new Map();
41138
+ inflightConfig = /* @__PURE__ */ new Map();
41139
+ baseReserveCache;
41140
+ inflightBaseReserve;
41141
+ constructor(deps) {
41142
+ this.config = deps.config;
41143
+ this.spoke = deps.spoke;
41144
+ this.api = deps.api;
41145
+ }
41146
+ get horizon() {
41147
+ return this.spoke.stellar.server;
41148
+ }
41149
+ /**
41150
+ * Whether an account exists. Read failures remain errors rather than being
41151
+ * misreported as inactive.
41152
+ */
41153
+ async isStellarAccountActive(params) {
41154
+ const account = await this.readAccount(params.address, "isStellarAccountActive");
41155
+ return account.ok ? { ok: true, value: account.value !== void 0 } : account;
41156
+ }
41157
+ /**
41158
+ * Return account existence and trustline affordability. Costs one Horizon
41159
+ * account read, plus a base-reserve read on the first call per hour.
41160
+ */
41161
+ async getStellarAccountStatus(params) {
41162
+ const account = await this.readAccount(params.address, "getStellarAccountStatus");
41163
+ if (!account.ok) return account;
41164
+ const baseReserveStroops = await this.resolveBaseReserveStroops();
41165
+ const trustlineMinXlmStroops = baseReserveStroops + STELLAR_FEE_HEADROOM_STROOPS;
41166
+ if (account.value === void 0) {
41167
+ return {
41168
+ ok: true,
41169
+ value: {
41170
+ exists: false,
41171
+ nativeBalanceStroops: 0n,
41172
+ availableBalanceStroops: 0n,
41173
+ canAffordTrustline: false,
41174
+ trustlineMinXlmStroops
41175
+ }
41176
+ };
41177
+ }
41178
+ const { nativeBalanceStroops, availableBalanceStroops } = readReserveInfo(account.value, baseReserveStroops);
41179
+ return {
41180
+ ok: true,
41181
+ value: {
41182
+ exists: true,
41183
+ nativeBalanceStroops,
41184
+ availableBalanceStroops,
41185
+ canAffordTrustline: availableBalanceStroops >= trustlineMinXlmStroops,
41186
+ trustlineMinXlmStroops
41187
+ }
41188
+ };
41189
+ }
41190
+ /**
41191
+ * Shared account read. A 404 resolves to `undefined` because absence is a
41192
+ * legitimate answer; every other failure remains an error.
41193
+ */
41194
+ async readAccount(address, action) {
41195
+ if (address.length === 0) {
41196
+ return {
41197
+ ok: false,
41198
+ error: new SodaxError("VALIDATION_FAILED", "address is required", {
41199
+ feature: "sponsoring",
41200
+ context: { phase: "validate", method: action, field: "address" }
41201
+ })
41202
+ };
41203
+ }
41204
+ try {
41205
+ return { ok: true, value: await this.horizon.loadAccount(address) };
41206
+ } catch (error) {
41207
+ if (isHorizonNotFound(error)) return { ok: true, value: void 0 };
41208
+ return {
41209
+ ok: false,
41210
+ error: lookupFailed("sponsoring", action, error, { srcChainKey: ChainKeys.STELLAR_MAINNET })
41211
+ };
41212
+ }
41213
+ }
41214
+ /**
41215
+ * The base reserve is a validator-controlled network setting, so read it from
41216
+ * the latest ledger rather than assuming the published 0.5 XLM. A failed read
41217
+ * degrades to that value: this drives a UI hint, never a signed transaction.
41218
+ */
41219
+ async resolveBaseReserveStroops() {
41220
+ const cached = this.baseReserveCache;
41221
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
41222
+ const inflight = this.inflightBaseReserve;
41223
+ if (inflight) return inflight;
41224
+ const read = async () => {
41225
+ try {
41226
+ const page = await this.horizon.ledgers().order("desc").limit(1).call();
41227
+ const value = parseBaseReserveStroops(page.records[0]);
41228
+ if (value !== void 0) return value;
41229
+ } catch (error) {
41230
+ this.config.logger.warn("[SponsoringService] Stellar base-reserve read failed; assuming the published value", {
41231
+ reason: messageOf(error, String(error))
41232
+ });
41233
+ }
41234
+ return STELLAR_BASE_RESERVE_STROOPS;
41235
+ };
41236
+ const request = read().then((value) => {
41237
+ this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
41238
+ return value;
41239
+ }).finally(() => {
41240
+ if (this.inflightBaseReserve === request) this.inflightBaseReserve = void 0;
41241
+ });
41242
+ this.inflightBaseReserve = request;
41243
+ return request;
41244
+ }
41245
+ /**
41246
+ * Cache key for a config request: the resolved base URL plus any per-call
41247
+ * headers. Headers can select a different response from the same URL — an API
41248
+ * key scoped to another deployment, or a test harness's scenario header — so
41249
+ * folding them in stops one caller's override from being served to, or
41250
+ * overwriting, the default path. Kept in memory as a Map key only.
41251
+ */
41252
+ configCacheKey(requestConfig) {
41253
+ const baseURL = requestConfig?.baseURL || this.api.sponsoring.getBaseURL();
41254
+ const headers = requestConfig?.headers;
41255
+ if (!headers) return baseURL;
41256
+ const normalized = Object.keys(headers).sort().map((name) => `${name.toLowerCase()}=${headers[name]}`).join("&");
41257
+ return normalized.length === 0 ? baseURL : `${baseURL}|${normalized}`;
41258
+ }
41259
+ /**
41260
+ * Fetch sponsor config with per-endpoint caching and in-flight deduplication.
41261
+ * Failures are never cached.
41262
+ */
41263
+ async getStellarSponsorConfig(params) {
41264
+ const key = this.configCacheKey(params?.requestConfig);
41265
+ if (params?.forceRefresh) {
41266
+ this.configCache.delete(key);
41267
+ this.inflightConfig.delete(key);
41268
+ } else {
41269
+ const cached = this.configCache.get(key);
41270
+ if (cached && cached.expiresAt > Date.now()) return { ok: true, value: cached.value };
41271
+ const inflight = this.inflightConfig.get(key);
41272
+ if (inflight) return inflight;
41273
+ }
41274
+ const request = this.api.sponsoring.getStellarSponsorConfig(params?.requestConfig).then((result) => {
41275
+ if (result.ok && this.inflightConfig.get(key) === request) {
41276
+ const now = Date.now();
41277
+ for (const [cached, entry] of this.configCache) {
41278
+ if (entry.expiresAt <= now) this.configCache.delete(cached);
41279
+ }
41280
+ this.configCache.set(key, { value: result.value, expiresAt: now + SPONSOR_CONFIG_TTL_MS });
41281
+ }
41282
+ return result;
41283
+ }).finally(() => {
41284
+ if (this.inflightConfig.get(key) === request) this.inflightConfig.delete(key);
41285
+ });
41286
+ this.inflightConfig.set(key, request);
41287
+ return request;
41288
+ }
41289
+ /**
41290
+ * Activate an account with a sponsored base reserve. Config and existence are
41291
+ * checked before prompting; sponsor sequence is never cached.
41292
+ */
41293
+ async activateStellarAccount(params) {
41294
+ let attempts = 0;
41295
+ return this.config.analytics.trackResult(
41296
+ "sponsoring",
41297
+ "activateStellarAccount",
41298
+ async () => {
41299
+ try {
41300
+ const { address } = params;
41301
+ const configResult = await this.getStellarSponsorConfig({
41302
+ forceRefresh: params.forceConfigRefresh,
41303
+ requestConfig: params.requestConfig
41304
+ });
41305
+ if (!configResult.ok) return configResult;
41306
+ const sponsorConfig = configResult.value;
41307
+ if (await this.accountExistsBestEffort(address)) {
41308
+ return { ok: true, value: { status: "alreadyActive", hash: null, attempts: 0 } };
41309
+ }
41310
+ attempts = 1;
41311
+ const first = await this.attemptActivation({ params, sponsorConfig, attempt: 1 });
41312
+ if (first.ok || params.allowSequenceRetry === false) return first;
41313
+ if (first.error.context?.nextAction !== "rebuildAndResign") return first;
41314
+ attempts = 2;
41315
+ return this.attemptActivation({
41316
+ params,
41317
+ sponsorConfig,
41318
+ attempt: 2,
41319
+ sponsorSequenceHint: first.error.context?.sponsorSequence
41320
+ });
41321
+ } catch (error) {
41322
+ if (isSodaxError(error)) {
41323
+ return { ok: false, error };
41324
+ }
41325
+ return {
41326
+ ok: false,
41327
+ error: unknownFailed("sponsoring", error, { action: "activateStellarAccount" })
41328
+ };
41329
+ }
41330
+ },
41331
+ {
41332
+ start: () => ({ srcChainKey: ChainKeys.STELLAR_MAINNET, address: params.address }),
41333
+ success: (value) => ({ status: value.status, attempts: value.attempts, hash: value.hash }),
41334
+ failure: (error) => ({
41335
+ code: error.code,
41336
+ // Preserve evidence that a sequence-conflict retry occurred.
41337
+ attempts,
41338
+ // `status` is already the domain outcome in success events.
41339
+ httpStatus: error.context?.status,
41340
+ nextAction: error.context?.nextAction
41341
+ })
41342
+ }
41343
+ );
41344
+ }
41345
+ /** One build, sign, and submit attempt. */
41346
+ async attemptActivation(args) {
41347
+ const { params, sponsorConfig, attempt, sponsorSequenceHint } = args;
41348
+ const { address, walletProvider } = params;
41349
+ assertSponsoredCreateInputs({ config: sponsorConfig, address });
41350
+ let sponsorSequence;
41351
+ if (sponsorSequenceHint !== void 0) {
41352
+ sponsorSequence = sponsorSequenceHint;
41353
+ } else {
41354
+ try {
41355
+ const sponsorAccount = await this.horizon.loadAccount(sponsorConfig.sponsorAccount);
41356
+ sponsorSequence = sponsorAccount.sequenceNumber();
41357
+ } catch (error) {
41358
+ return {
41359
+ ok: false,
41360
+ error: lookupFailed("sponsoring", "loadSponsorAccount", error, {
41361
+ action: "activateStellarAccount",
41362
+ srcChainKey: ChainKeys.STELLAR_MAINNET
41363
+ })
41364
+ };
41365
+ }
41366
+ }
41367
+ const transaction = buildSponsoredCreate({ config: sponsorConfig, sponsorSequence, address });
41368
+ const unsignedHash = transaction.hash();
41369
+ params.onSignatureRequired?.({ attempt, reason: attempt === 1 ? "initial" : "sequenceConflict" });
41370
+ let signedXdr;
41371
+ try {
41372
+ signedXdr = await walletProvider.signTransaction(transaction.toXDR(), { address });
41373
+ } catch (error) {
41374
+ return {
41375
+ ok: false,
41376
+ error: intentCreationFailed("sponsoring", error, {
41377
+ action: "activateStellarAccount",
41378
+ srcChainKey: ChainKeys.STELLAR_MAINNET
41379
+ })
41380
+ };
41381
+ }
41382
+ assertSignedByAccount({ signedXdr, address, unsignedHash });
41383
+ const submitted = await this.submitWithHorizonRetry({
41384
+ signedXdr,
41385
+ maxRetries: params.maxHorizonRetries ?? DEFAULT_MAX_HORIZON_RETRIES,
41386
+ requestConfig: params.requestConfig
41387
+ });
41388
+ if (submitted.ok) {
41389
+ const response = submitted.value;
41390
+ return response.alreadyActive ? { ok: true, value: { status: "alreadyActive", hash: null, attempts: attempt } } : { ok: true, value: { status: "submitted", hash: response.hash, attempts: attempt } };
41391
+ }
41392
+ const classification = classifySponsorError(submitted.error);
41393
+ if (classification.action === "fixIntegration") {
41394
+ this.configCache.delete(this.configCacheKey(params.requestConfig));
41395
+ }
41396
+ return {
41397
+ ok: false,
41398
+ error: new SodaxError("EXTERNAL_API_ERROR", classification.message, {
41399
+ feature: "sponsoring",
41400
+ cause: submitted.error,
41401
+ context: {
41402
+ api: "sponsoring",
41403
+ action: "activateStellarAccount",
41404
+ phase: "submit",
41405
+ srcChainKey: ChainKeys.STELLAR_MAINNET,
41406
+ attempts: attempt,
41407
+ nextAction: classification.action,
41408
+ retryable: classification.retryable,
41409
+ requiresNewSignature: classification.requiresNewSignature,
41410
+ sponsorAccount: sponsorConfig.sponsorAccount,
41411
+ status: classification.status,
41412
+ code: classification.code,
41413
+ retryAfterSeconds: classification.retryAfterSeconds,
41414
+ sponsorSequence: classification.sponsorSequence
41415
+ }
41416
+ })
41417
+ };
41418
+ }
41419
+ /**
41420
+ * Re-submit identical signed bytes only for `retrySameRequest` failures.
41421
+ */
41422
+ async submitWithHorizonRetry(args) {
41423
+ const { signedXdr, maxRetries, requestConfig } = args;
41424
+ let result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
41425
+ for (let retry2 = 0; retry2 < maxRetries && !result.ok; retry2++) {
41426
+ if (classifySponsorError(result.error).action !== "retrySameRequest") break;
41427
+ await sleep(1e3 * (retry2 + 1));
41428
+ result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
41429
+ }
41430
+ return result;
41431
+ }
41432
+ /**
41433
+ * Best-effort existence pre-flight. Read failures continue to activation
41434
+ * because the server performs the authoritative check.
41435
+ */
41436
+ async accountExistsBestEffort(address) {
41437
+ const account = await this.readAccount(address, "isStellarAccountActive");
41438
+ if (account.ok) return account.value !== void 0;
41439
+ this.config.logger.warn(
41440
+ "[SponsoringService] Stellar account existence pre-flight failed; continuing with activation",
41441
+ { address, reason: messageOf(account.error, String(account.error)) }
41442
+ );
41443
+ return false;
41444
+ }
41445
+ };
41446
+
40129
41447
  // src/shared/entities/Sodax.ts
40130
41448
  var Sodax = class {
40131
41449
  instanceConfig;
@@ -40149,6 +41467,7 @@ var Sodax = class {
40149
41467
  // Recovery service for withdrawing stuck hub-wallet assets back to a spoke chain
40150
41468
  dex;
40151
41469
  // Dex service enabling DEX operations
41470
+ sponsoring;
40152
41471
  leverageYield;
40153
41472
  // Leverage-yield service: cross-chain deposits / withdrawals into ERC-4626 leverage vaults on Sonic
40154
41473
  config;
@@ -40161,7 +41480,9 @@ var Sodax = class {
40161
41480
  const logger = resolveLogger(options?.logger);
40162
41481
  const analytics = resolveAnalytics(options?.analytics);
40163
41482
  const fee = options?.fee;
41483
+ const radfiSigner = options?.radfi?.signRequest;
40164
41484
  const useBackendSubmitTx = options?.swapsOptions?.useBackendSubmitTx ?? false;
41485
+ const bridgeUseBackendSubmitTx = options?.bridgeOptions?.useBackendSubmitTx ?? false;
40165
41486
  this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
40166
41487
  this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
40167
41488
  this.api = this.backendApi;
@@ -40171,7 +41492,8 @@ var Sodax = class {
40171
41492
  userConfig: options,
40172
41493
  logger,
40173
41494
  analytics,
40174
- fee
41495
+ fee,
41496
+ radfiSigner
40175
41497
  });
40176
41498
  this.hubProvider = new EvmHubProvider({ config: this.config });
40177
41499
  this.spoke = new SpokeService({ config: this.config, hubProvider: this.hubProvider });
@@ -40197,7 +41519,13 @@ var Sodax = class {
40197
41519
  config: this.config,
40198
41520
  spoke: this.spoke
40199
41521
  });
40200
- this.bridge = new BridgeService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
41522
+ this.bridge = new BridgeService({
41523
+ hubProvider: this.hubProvider,
41524
+ config: this.config,
41525
+ spoke: this.spoke,
41526
+ backendApi: this.backendApi,
41527
+ useBackendSubmitTx: bridgeUseBackendSubmitTx
41528
+ });
40201
41529
  this.staking = new StakingService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
40202
41530
  this.partners = new PartnerService({
40203
41531
  hubProvider: this.hubProvider,
@@ -40214,6 +41542,11 @@ var Sodax = class {
40214
41542
  config: this.config,
40215
41543
  spoke: this.spoke
40216
41544
  });
41545
+ this.sponsoring = new SponsoringService({
41546
+ config: this.config,
41547
+ spoke: this.spoke,
41548
+ api: this.backendApi
41549
+ });
40217
41550
  }
40218
41551
  /**
40219
41552
  * Initializes the Sodax instance with dynamic configuration.
@@ -40264,13 +41597,16 @@ exports.APPROVE_CODES = APPROVE_CODES;
40264
41597
  exports.AssetService = AssetService;
40265
41598
  exports.BITCOIN_CHAIN_KEYS = BITCOIN_CHAIN_KEYS;
40266
41599
  exports.BITCOIN_CHAIN_KEYS_SET = BITCOIN_CHAIN_KEYS_SET;
41600
+ exports.BITCOIN_DUST_SATS = BITCOIN_DUST_SATS;
40267
41601
  exports.BTC_WALLET_ADDRESS_TYPES = BTC_WALLET_ADDRESS_TYPES;
40268
41602
  exports.BackendApiService = BackendApiService;
41603
+ exports.BackendHttpError = BackendHttpError;
40269
41604
  exports.BalnSwapService = BalnSwapService;
40270
41605
  exports.BigIntToHex = BigIntToHex;
40271
41606
  exports.BigNumberZeroDecimal = BigNumberZeroDecimal;
40272
41607
  exports.BitcoinSpokeService = BitcoinSpokeService;
40273
41608
  exports.BnUSDMigrationService = BnUSDMigrationService;
41609
+ exports.BridgeApiService = BridgeApiService;
40274
41610
  exports.BridgeService = BridgeService;
40275
41611
  exports.CHAIN_KEYS = CHAIN_KEYS;
40276
41612
  exports.CHAIN_LOGO_BASE_URL = CHAIN_LOGO_BASE_URL;
@@ -40290,6 +41626,7 @@ exports.DEFAULT_MAX_RETRY = DEFAULT_MAX_RETRY;
40290
41626
  exports.DEFAULT_RELAYER_API_ENDPOINT = DEFAULT_RELAYER_API_ENDPOINT;
40291
41627
  exports.DEFAULT_RELAY_TX_TIMEOUT = DEFAULT_RELAY_TX_TIMEOUT;
40292
41628
  exports.DEFAULT_RETRY_DELAY_MS = DEFAULT_RETRY_DELAY_MS;
41629
+ exports.DEFAULT_SPONSORING_API_ENDPOINT = DEFAULT_SPONSORING_API_ENDPOINT;
40293
41630
  exports.DexService = DexService;
40294
41631
  exports.EVM_CHAIN_ID_TO_KEY = EVM_CHAIN_ID_TO_KEY;
40295
41632
  exports.EVM_CHAIN_KEYS = EVM_CHAIN_KEYS;
@@ -40353,6 +41690,7 @@ exports.ProtocolIntentsAbi = ProtocolIntentsAbi;
40353
41690
  exports.RAY = RAY;
40354
41691
  exports.RAY_DECIMALS = RAY_DECIMALS;
40355
41692
  exports.RELAY_ERROR_CODES = RELAY_ERROR_CODES;
41693
+ exports.RELAY_FALLBACK_FLOOR_MS = RELAY_FALLBACK_FLOOR_MS;
40356
41694
  exports.RadfiApiError = RadfiApiError;
40357
41695
  exports.RadfiProvider = RadfiProvider;
40358
41696
  exports.RecoveryService = RecoveryService;
@@ -40364,10 +41702,15 @@ exports.SOLANA_CHAIN_KEYS = SOLANA_CHAIN_KEYS;
40364
41702
  exports.SOLANA_CHAIN_KEYS_SET = SOLANA_CHAIN_KEYS_SET;
40365
41703
  exports.SONIC_CHAIN_KEYS = SONIC_CHAIN_KEYS;
40366
41704
  exports.SONIC_CHAIN_KEYS_SET = SONIC_CHAIN_KEYS_SET;
41705
+ exports.SPONSORING_API_ERROR_CODES = SPONSORING_API_ERROR_CODES;
41706
+ exports.SPONSORING_API_STELLAR_BASE_PATH = SPONSORING_API_STELLAR_BASE_PATH;
41707
+ exports.SPONSOR_CONFIG_TTL_MS = SPONSOR_CONFIG_TTL_MS;
40367
41708
  exports.STACKS_CHAIN_KEYS = STACKS_CHAIN_KEYS;
40368
41709
  exports.STACKS_CHAIN_KEYS_SET = STACKS_CHAIN_KEYS_SET;
41710
+ exports.STELLAR_BASE_RESERVE_TTL_MS = STELLAR_BASE_RESERVE_TTL_MS;
40369
41711
  exports.STELLAR_CHAIN_KEYS = STELLAR_CHAIN_KEYS;
40370
41712
  exports.STELLAR_CHAIN_KEYS_SET = STELLAR_CHAIN_KEYS_SET;
41713
+ exports.STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_TRUSTLINE_MIN_XLM_STROOPS;
40371
41714
  exports.SUI_CHAIN_KEYS = SUI_CHAIN_KEYS;
40372
41715
  exports.SUI_CHAIN_KEYS_SET = SUI_CHAIN_KEYS_SET;
40373
41716
  exports.SodaTokens = SodaTokens;
@@ -40377,6 +41720,8 @@ exports.SolanaSpokeService = SolanaSpokeService;
40377
41720
  exports.SolverApiService = SolverApiService;
40378
41721
  exports.SonicSpokeService = SonicSpokeService;
40379
41722
  exports.SpokeService = SpokeService;
41723
+ exports.SponsoringApiService = SponsoringApiService;
41724
+ exports.SponsoringService = SponsoringService;
40380
41725
  exports.StacksSpokeService = StacksSpokeService;
40381
41726
  exports.StakingLogic = StakingLogic;
40382
41727
  exports.StakingService = StakingService;
@@ -40427,6 +41772,7 @@ exports.clPositionManagerAbi = clPositionManagerAbi;
40427
41772
  exports.clQuoterAbi = clQuoterAbi;
40428
41773
  exports.clRouterAbi = clRouterAbi;
40429
41774
  exports.clTickLensAbi = clTickLensAbi;
41775
+ exports.classifySponsorError = classifySponsorError;
40430
41776
  exports.concentratedLiquidityConfig = concentratedLiquidityConfig;
40431
41777
  exports.connectionAbi = connectionAbi;
40432
41778
  exports.consoleLogger = consoleLogger;
@@ -40495,6 +41841,7 @@ exports.hyperevmSupportedTokens = hyperevmSupportedTokens;
40495
41841
  exports.iconSupportedTokens = iconSupportedTokens;
40496
41842
  exports.injectiveSupportedTokens = injectiveSupportedTokens;
40497
41843
  exports.intentCreationFailed = intentCreationFailed;
41844
+ exports.isBackendHttpError = isBackendHttpError;
40498
41845
  exports.isBalnMigrateParams = isBalnMigrateParams;
40499
41846
  exports.isBitcoinChainKey = isBitcoinChainKey;
40500
41847
  exports.isBitcoinChainKeyType = isBitcoinChainKeyType;
@@ -40548,6 +41895,8 @@ exports.isMoneyMarketCreateIntentError = isMoneyMarketCreateIntentError;
40548
41895
  exports.isMoneyMarketError = isMoneyMarketError;
40549
41896
  exports.isMoneyMarketGasEstimationError = isMoneyMarketGasEstimationError;
40550
41897
  exports.isMoneyMarketOrchestrationError = isMoneyMarketOrchestrationError;
41898
+ exports.isNativeBitcoinToken = isNativeBitcoinToken;
41899
+ exports.isNativeBitcoinTransfer = isNativeBitcoinTransfer;
40551
41900
  exports.isNativeToken = isNativeToken;
40552
41901
  exports.isNearChainKey = isNearChainKey;
40553
41902
  exports.isNearChainKeyType = isNearChainKeyType;
@@ -40578,6 +41927,9 @@ exports.isSpokeChainKey = isSpokeChainKey;
40578
41927
  exports.isSpokeIsAllowanceValidParamsEvmSpoke = isSpokeIsAllowanceValidParamsEvmSpoke;
40579
41928
  exports.isSpokeIsAllowanceValidParamsHub = isSpokeIsAllowanceValidParamsHub;
40580
41929
  exports.isSpokeIsAllowanceValidParamsStellar = isSpokeIsAllowanceValidParamsStellar;
41930
+ exports.isSponsoringConfigError = isSponsoringConfigError;
41931
+ exports.isSponsoringLookupError = isSponsoringLookupError;
41932
+ exports.isSponsoringOrchestrationError = isSponsoringOrchestrationError;
40581
41933
  exports.isStacksChainKey = isStacksChainKey;
40582
41934
  exports.isStacksChainKeyType = isStacksChainKeyType;
40583
41935
  exports.isStakeOrchestrationError = isStakeOrchestrationError;
@@ -40664,6 +42016,7 @@ exports.spokeAssetManagerAbi = spokeAssetManagerAbi;
40664
42016
  exports.spokeChainConfig = spokeChainConfig;
40665
42017
  exports.spokeChainKeysSet = spokeChainKeysSet;
40666
42018
  exports.spokeHooks = spokeHooks;
42019
+ exports.sponsoringInvariant = sponsoringInvariant;
40667
42020
  exports.stacksSupportedTokens = stacksSupportedTokens;
40668
42021
  exports.stagingSwapSupportedTokens = stagingSwapSupportedTokens;
40669
42022
  exports.stakedSodaAbi = stakedSodaAbi;
@@ -40679,6 +42032,7 @@ exports.swapExactInSingleParamsAbi = swapExactInSingleParamsAbi;
40679
42032
  exports.swapInvariant = swapInvariant;
40680
42033
  exports.swapSupportedTokens = swapSupportedTokens;
40681
42034
  exports.swapsConfig = swapsConfig;
42035
+ exports.toCreateBridgeIntentParamsV2 = toCreateBridgeIntentParamsV2;
40682
42036
  exports.tokenLogo = tokenLogo;
40683
42037
  exports.tokenLogoSlug = tokenLogoSlug;
40684
42038
  exports.uiPoolDataAbi = uiPoolDataAbi;