@sodax/sdk 2.0.0 → 2.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getAbiItem, parseAbi, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, defineChain, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, stringToBytes, fromHex, encodePacked, decodeAbiParameters, parseEventLogs, maxUint160, maxUint48, fallback } from 'viem';
2
2
  import { bcs } from '@mysten/sui/bcs';
3
3
  import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram, TransactionMessage, TransactionInstruction } from '@solana/web3.js';
4
- import { rpc, Address, xdr, Account, Horizon, Contract, TransactionBuilder, nativeToScVal, TimeoutInfinite, scValToBigInt, Operation, Asset, FeeBumpTransaction } from '@stellar/stellar-sdk';
4
+ import { rpc, Address, xdr, Account, Horizon, Contract, TransactionBuilder, nativeToScVal, TimeoutInfinite, scValToBigInt, Operation, Asset, FeeBumpTransaction, NotFoundError, Networks, Keypair } from '@stellar/stellar-sdk';
5
5
  import { serializeCV, Cl, deserializeCV, cvToString, createNetwork, fetchFeeEstimateTransaction, fetchCallReadOnlyFunction, parseContractId, PostConditionMode, noneCV, someCV, uintCV, getAddressFromPublicKey, makeUnsignedContractCall, serializePayloadBytes } from '@sodax/libs/stacks/core';
6
6
  import { hedera, kaia, redbellyMainnet, mainnet, lightlinkPhoenix, polygon, bsc, optimism, base, arbitrum, avalanche, sonic } from 'viem/chains';
7
7
  import * as rlp from 'rlp';
@@ -17,7 +17,7 @@ import * as IconSdkRaw from 'icon-sdk-js';
17
17
  import { ChainGrpcWasmApi, TxGrpcApi, toBase64, fromBase64, MsgExecuteContract, ChainRestAuthApi, BaseAccount, createTransaction } from '@injectivelabs/sdk-ts';
18
18
  import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
19
19
  import { getNetworkEndpoints, Network } from '@injectivelabs/networks';
20
- import * as v2 from 'valibot';
20
+ import * as v4 from 'valibot';
21
21
  import { SwapsApi, SwapsApiError } from '@sodax/swaps-api';
22
22
  export { SwapsApiError } from '@sodax/swaps-api';
23
23
  import BigNumber5, { BigNumber } from 'bignumber.js';
@@ -94,8 +94,8 @@ function serializeCause(cause, depth) {
94
94
  }
95
95
  function sanitizeContext(value, depth) {
96
96
  const out = {};
97
- for (const [key, v4] of Object.entries(value)) {
98
- out[key] = sanitizeValue(v4, depth + 1);
97
+ for (const [key, v6] of Object.entries(value)) {
98
+ out[key] = sanitizeValue(v6, depth + 1);
99
99
  }
100
100
  return out;
101
101
  }
@@ -106,13 +106,13 @@ function sanitizeValue(value, depth) {
106
106
  if (t === "bigint") return value.toString();
107
107
  if (t === "string" || t === "number" || t === "boolean") return value;
108
108
  if (t === "function" || t === "symbol") return safeString(value);
109
- if (Array.isArray(value)) return value.map((v4) => sanitizeValue(v4, depth + 1));
109
+ if (Array.isArray(value)) return value.map((v6) => sanitizeValue(v6, depth + 1));
110
110
  if (value instanceof Date) return value.toISOString();
111
111
  if (value instanceof Map) {
112
- return Array.from(value.entries()).map(([k, v4]) => [sanitizeValue(k, depth + 1), sanitizeValue(v4, depth + 1)]);
112
+ return Array.from(value.entries()).map(([k, v6]) => [sanitizeValue(k, depth + 1), sanitizeValue(v6, depth + 1)]);
113
113
  }
114
114
  if (value instanceof Set) {
115
- return Array.from(value.values()).map((v4) => sanitizeValue(v4, depth + 1));
115
+ return Array.from(value.values()).map((v6) => sanitizeValue(v6, depth + 1));
116
116
  }
117
117
  if (value instanceof Error) return { name: value.name, message: value.message };
118
118
  if (t === "object") {
@@ -124,9 +124,9 @@ function sanitizeValue(value, depth) {
124
124
  }
125
125
  return safeString(value);
126
126
  }
127
- function safeString(v4) {
127
+ function safeString(v6) {
128
128
  try {
129
- return String(v4);
129
+ return String(v6);
130
130
  } catch {
131
131
  return "[unserializable]";
132
132
  }
@@ -182,6 +182,7 @@ var SODAX_FEATURES = [
182
182
  "partner",
183
183
  "recovery",
184
184
  "backend",
185
+ "sponsoring",
185
186
  "leverageYield"
186
187
  ];
187
188
 
@@ -3496,6 +3497,8 @@ var DEFAULT_BACKEND_API_HEADERS = {
3496
3497
  };
3497
3498
  var DEFAULT_RELAYER_API_ENDPOINT = "https://xcall-relay.nw.iconblockchain.xyz";
3498
3499
  var VAULT_TOKEN_DECIMALS = 18;
3500
+ var DEFAULT_SPONSORING_API_ENDPOINT = "https://api.sodax.com/v1";
3501
+ var SPONSORING_API_STELLAR_BASE_PATH = "/sponsorships/stellar";
3499
3502
  var apiConfig = {
3500
3503
  baseURL: DEFAULT_BACKEND_API_ENDPOINT,
3501
3504
  timeout: DEFAULT_BACKEND_API_TIMEOUT,
@@ -4229,6 +4232,17 @@ var sodaxConfig = {
4229
4232
  relay: relayConfig
4230
4233
  };
4231
4234
 
4235
+ // ../types/dist/backend/sponsoringApi.js
4236
+ var SPONSORING_API_ERROR_CODES = [
4237
+ "INVALID_SPONSOR_XDR",
4238
+ "INVALID_RESERVE_DATA",
4239
+ "SPONSOR_SEQUENCE_CONFLICT",
4240
+ "SPONSOR_TRANSACTION_REJECTED",
4241
+ "HORIZON_UNAVAILABLE",
4242
+ "SPONSOR_RATE_LIMITED",
4243
+ "SPONSOR_BUDGET_EXHAUSTED"
4244
+ ];
4245
+
4232
4246
  // ../types/dist/bitcoin/bitcoin.js
4233
4247
  function isSupportedBitcoinAddressType(addressType) {
4234
4248
  return BTC_ADDRESS_TYPES.includes(addressType);
@@ -4389,7 +4403,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4389
4403
  }
4390
4404
 
4391
4405
  // ../types/dist/index.js
4392
- var CONFIG_VERSION = 220;
4406
+ var CONFIG_VERSION = 221;
4393
4407
  function isEvmSpokeChainConfig(value) {
4394
4408
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
4395
4409
  }
@@ -14296,7 +14310,7 @@ function mergeSodaxConfig(base2, override) {
14296
14310
  }
14297
14311
  function encodeContractCalls(calls) {
14298
14312
  return encodeAbiParameters(parseAbiParameters("(address,uint256,bytes)[]"), [
14299
- calls.map((v4) => [v4.address, v4.value, v4.data])
14313
+ calls.map((v6) => [v6.address, v6.value, v6.data])
14300
14314
  ]);
14301
14315
  }
14302
14316
  async function waitForTransactionReceipt(hash, provider) {
@@ -16919,22 +16933,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16919
16933
  const byte0 = Uint8Array.of(0);
16920
16934
  const byte1 = Uint8Array.of(1);
16921
16935
  const _maxDrbgIters = 1e3;
16922
- let v4 = u8n(hashLen);
16936
+ let v6 = u8n(hashLen);
16923
16937
  let k = u8n(hashLen);
16924
16938
  let i = 0;
16925
16939
  const reset = () => {
16926
- v4.fill(1);
16940
+ v6.fill(1);
16927
16941
  k.fill(0);
16928
16942
  i = 0;
16929
16943
  };
16930
- const h = (...msgs) => hmacFn(k, concatBytes(v4, ...msgs));
16944
+ const h = (...msgs) => hmacFn(k, concatBytes(v6, ...msgs));
16931
16945
  const reseed = (seed = NULL) => {
16932
16946
  k = h(byte0, seed);
16933
- v4 = h();
16947
+ v6 = h();
16934
16948
  if (seed.length === 0)
16935
16949
  return;
16936
16950
  k = h(byte1, seed);
16937
- v4 = h();
16951
+ v6 = h();
16938
16952
  };
16939
16953
  const gen = () => {
16940
16954
  if (i++ >= _maxDrbgIters)
@@ -16942,10 +16956,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16942
16956
  let len = 0;
16943
16957
  const out = [];
16944
16958
  while (len < qByteLen) {
16945
- v4 = h();
16946
- const sl = v4.slice();
16959
+ v6 = h();
16960
+ const sl = v6.slice();
16947
16961
  out.push(sl);
16948
- len += v4.length;
16962
+ len += v6.length;
16949
16963
  }
16950
16964
  return concatBytes(...out);
16951
16965
  };
@@ -16960,18 +16974,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16960
16974
  };
16961
16975
  return genUntil;
16962
16976
  }
16963
- function validateObject(object2, fields = {}, optFields = {}) {
16964
- if (!object2 || typeof object2 !== "object")
16977
+ function validateObject(object3, fields = {}, optFields = {}) {
16978
+ if (!object3 || typeof object3 !== "object")
16965
16979
  throw new Error("expected valid options object");
16966
16980
  function checkField(fieldName, expectedType, isOpt) {
16967
- const val = object2[fieldName];
16981
+ const val = object3[fieldName];
16968
16982
  if (isOpt && val === void 0)
16969
16983
  return;
16970
16984
  const current = typeof val;
16971
16985
  if (current !== expectedType || val === null)
16972
16986
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
16973
16987
  }
16974
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v4]) => checkField(k, v4, isOpt));
16988
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v6]) => checkField(k, v6, isOpt));
16975
16989
  iter(fields, false);
16976
16990
  iter(optFields, true);
16977
16991
  }
@@ -17010,12 +17024,12 @@ function pow2(x, power, modulo) {
17010
17024
  }
17011
17025
  return res;
17012
17026
  }
17013
- function invert(number2, modulo) {
17014
- if (number2 === _0n2)
17027
+ function invert(number3, modulo) {
17028
+ if (number3 === _0n2)
17015
17029
  throw new Error("invert: expected non-zero number");
17016
17030
  if (modulo <= _0n2)
17017
17031
  throw new Error("invert: expected positive modulus, got " + modulo);
17018
- let a = mod(number2, modulo);
17032
+ let a = mod(number3, modulo);
17019
17033
  let b = modulo;
17020
17034
  let x = _0n2, u = _1n2;
17021
17035
  while (a !== _0n2) {
@@ -17042,9 +17056,9 @@ function sqrt3mod4(Fp, n) {
17042
17056
  function sqrt5mod8(Fp, n) {
17043
17057
  const p5div8 = (Fp.ORDER - _5n) / _8n;
17044
17058
  const n2 = Fp.mul(n, _2n);
17045
- const v4 = Fp.pow(n2, p5div8);
17046
- const nv = Fp.mul(n, v4);
17047
- const i = Fp.mul(Fp.mul(nv, _2n), v4);
17059
+ const v6 = Fp.pow(n2, p5div8);
17060
+ const nv = Fp.mul(n, v6);
17061
+ const i = Fp.mul(Fp.mul(nv, _2n), v6);
17048
17062
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
17049
17063
  assertIsSquare(Fp, root, n);
17050
17064
  return root;
@@ -17626,9 +17640,9 @@ function edwards(params, extraOpts = {}) {
17626
17640
  validateObject(extraOpts, {}, { uvRatio: "function" });
17627
17641
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
17628
17642
  const modP = (n) => Fp.create(n);
17629
- const uvRatio2 = extraOpts.uvRatio || ((u, v4) => {
17643
+ const uvRatio2 = extraOpts.uvRatio || ((u, v6) => {
17630
17644
  try {
17631
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v4)) };
17645
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v6)) };
17632
17646
  } catch (e) {
17633
17647
  return { isValid: false, value: _0n4 };
17634
17648
  }
@@ -17724,8 +17738,8 @@ function edwards(params, extraOpts = {}) {
17724
17738
  aInRange("point.y", y, _0n4, max);
17725
17739
  const y2 = modP(y * y);
17726
17740
  const u = modP(y2 - _1n4);
17727
- const v4 = modP(d * y2 - a);
17728
- let { isValid, value: x } = uvRatio2(u, v4);
17741
+ const v6 = modP(d * y2 - a);
17742
+ let { isValid, value: x } = uvRatio2(u, v6);
17729
17743
  if (!isValid)
17730
17744
  throw new Error("bad point: invalid y coordinate");
17731
17745
  const isXOdd = (x & _1n4) === _1n4;
@@ -18065,13 +18079,13 @@ function adjustScalarBytes(bytes) {
18065
18079
  return bytes;
18066
18080
  }
18067
18081
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
18068
- function uvRatio(u, v4) {
18082
+ function uvRatio(u, v6) {
18069
18083
  const P = ed25519_CURVE_p;
18070
- const v32 = mod(v4 * v4 * v4, P);
18071
- const v7 = mod(v32 * v32 * v4, P);
18084
+ const v32 = mod(v6 * v6 * v6, P);
18085
+ const v7 = mod(v32 * v32 * v6, P);
18072
18086
  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
18073
18087
  let x = mod(u * v32 * pow, P);
18074
- const vx2 = mod(v4 * x * x, P);
18088
+ const vx2 = mod(v6 * x * x, P);
18075
18089
  const root1 = x;
18076
18090
  const root2 = mod(x * ED25519_SQRT_M1, P);
18077
18091
  const useRoot1 = vx2 === u;
@@ -18402,7 +18416,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
18402
18416
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
18403
18417
  }
18404
18418
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
18405
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18419
+ const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18406
18420
  const num = BigInt(numSeats);
18407
18421
  const stakesSum = stakes.reduce((a, b) => a + b);
18408
18422
  if (stakesSum < num) {
@@ -18431,7 +18445,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
18431
18445
  if (minimumStakeRatio.length != 2) {
18432
18446
  throw Error("minimumStakeRatio should have 2 elements");
18433
18447
  }
18434
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18448
+ const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18435
18449
  const stakesSum = stakes.reduce((a, b) => a + b);
18436
18450
  if (validators.length < maxNumberOfSeats) {
18437
18451
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -18603,10 +18617,10 @@ var DER = {
18603
18617
  if (length < 128)
18604
18618
  throw new E("tlv.decode(long): not minimal encoding");
18605
18619
  }
18606
- const v4 = data.subarray(pos, pos + length);
18607
- if (v4.length !== length)
18620
+ const v6 = data.subarray(pos, pos + length);
18621
+ if (v6.length !== length)
18608
18622
  throw new E("tlv.decode: wrong value length");
18609
- return { v: v4, l: data.subarray(pos + length) };
18623
+ return { v: v6, l: data.subarray(pos + length) };
18610
18624
  }
18611
18625
  },
18612
18626
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -19174,9 +19188,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19174
19188
  extraEntropy: false
19175
19189
  };
19176
19190
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
19177
- function isBiggerThanHalfOrder(number2) {
19191
+ function isBiggerThanHalfOrder(number3) {
19178
19192
  const HALF = CURVE_ORDER >> _1n6;
19179
- return number2 > HALF;
19193
+ return number3 > HALF;
19180
19194
  }
19181
19195
  function validateRS(title, num) {
19182
19196
  if (!Fn.isValidNot0(num))
@@ -19359,8 +19373,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19359
19373
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
19360
19374
  if (R.is0())
19361
19375
  return false;
19362
- const v4 = Fn.create(R.x);
19363
- return v4 === r;
19376
+ const v6 = Fn.create(R.x);
19377
+ return v6 === r;
19364
19378
  } catch (e) {
19365
19379
  return false;
19366
19380
  }
@@ -23498,6 +23512,7 @@ var CustomStellarAccount = class {
23498
23512
  this.sequenceNumber = this.startingSequenceNumber;
23499
23513
  }
23500
23514
  };
23515
+ var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
23501
23516
  var StellarSpokeService = class {
23502
23517
  config;
23503
23518
  chainConfig;
@@ -23735,6 +23750,17 @@ var StellarSpokeService = class {
23735
23750
  throw error;
23736
23751
  }
23737
23752
  }
23753
+ /**
23754
+ * Whether a token requires a trustline. Native XLM and legacy bnUSD are
23755
+ * exempt and therefore need no subentry reserve.
23756
+ */
23757
+ requiresTrustline(token) {
23758
+ const stellarChainConfig = this.chainConfig;
23759
+ const normalized = token.toLowerCase();
23760
+ if (normalized === stellarChainConfig.nativeToken.toLowerCase()) return false;
23761
+ const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23762
+ return legacyBnUSD === void 0 || normalized !== legacyBnUSD.address.toLowerCase();
23763
+ }
23738
23764
  /**
23739
23765
  * Check if the user has sufficient trustline established for the token.
23740
23766
  * @param token - The token address to check the trustline for.
@@ -23744,8 +23770,7 @@ var StellarSpokeService = class {
23744
23770
  */
23745
23771
  async hasSufficientTrustline(token, amount, walletAddress) {
23746
23772
  const stellarChainConfig = this.chainConfig;
23747
- const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23748
- if (token.toLowerCase() === stellarChainConfig.nativeToken.toLowerCase() || legacyBnUSD !== void 0 && token.toLowerCase() === legacyBnUSD.address.toLowerCase()) {
23773
+ if (!this.requiresTrustline(token)) {
23749
23774
  return true;
23750
23775
  }
23751
23776
  const trustlineConfig = stellarChainConfig.trustlineConfigs.find(
@@ -23794,7 +23819,7 @@ var StellarSpokeService = class {
23794
23819
  Operation.changeTrust({
23795
23820
  asset: new Asset(asset?.assetCode, asset?.assetIssuer)
23796
23821
  })
23797
- ).setTimeout(this.maxTimeoutMs).build();
23822
+ ).setTimeout(TRUSTLINE_TX_TIMEOUT_SECONDS).build();
23798
23823
  if (params.raw) {
23799
23824
  const transactionXdr = transaction.toXDR();
23800
23825
  return {
@@ -29793,10 +29818,40 @@ var MigrationService = class {
29793
29818
  };
29794
29819
 
29795
29820
  // src/backendApi/api-utils.ts
29821
+ var BackendHttpError = class extends Error {
29822
+ status;
29823
+ bodyText;
29824
+ /** Parsed JSON, or `undefined` for empty or malformed bodies. */
29825
+ body;
29826
+ constructor(status, bodyText) {
29827
+ super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
29828
+ this.name = "BackendHttpError";
29829
+ this.status = status;
29830
+ this.bodyText = bodyText;
29831
+ this.body = safeJsonParse(bodyText);
29832
+ }
29833
+ };
29834
+ function isBackendHttpError(error) {
29835
+ if (error instanceof BackendHttpError) return true;
29836
+ return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
29837
+ }
29838
+ function safeJsonParse(text) {
29839
+ if (text.length === 0) return void 0;
29840
+ try {
29841
+ return JSON.parse(text);
29842
+ } catch {
29843
+ return void 0;
29844
+ }
29845
+ }
29846
+ function trimTrailingSlashes(baseURL) {
29847
+ let end = baseURL.length;
29848
+ while (end > 0 && baseURL[end - 1] === "/") end -= 1;
29849
+ return baseURL.slice(0, end);
29850
+ }
29796
29851
  async function makeRequest(params) {
29797
29852
  const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
29798
29853
  const baseURL = overrideConfig.baseURL || config.baseURL || "";
29799
- const url = `${baseURL}${endpoint}`;
29854
+ const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
29800
29855
  const headers = { ...config.headers, ...overrideConfig.headers };
29801
29856
  const controller = new AbortController();
29802
29857
  const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
@@ -29811,7 +29866,7 @@ async function makeRequest(params) {
29811
29866
  clearTimeout(timeoutId);
29812
29867
  if (!response.ok) {
29813
29868
  const errorText = await response.text();
29814
- throw new Error("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${response.status}: ${errorText}`) });
29869
+ throw new BackendHttpError(response.status, errorText);
29815
29870
  }
29816
29871
  const data = await response.json();
29817
29872
  return data;
@@ -29828,6 +29883,32 @@ async function makeRequest(params) {
29828
29883
  throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
29829
29884
  }
29830
29885
  }
29886
+ function resolveRequestConfig(config, defaults) {
29887
+ const { baseURL, timeout, headers, ...rest } = config;
29888
+ return {
29889
+ ...rest,
29890
+ baseURL: baseURL || defaults.baseURL,
29891
+ timeout: timeout ?? defaults.timeout,
29892
+ headers: { ...defaults.headers, ...headers }
29893
+ };
29894
+ }
29895
+ function toExternalApiError(params) {
29896
+ const { api, feature, endpoint, error } = params;
29897
+ const context = { api, endpoint };
29898
+ if (isBackendHttpError(error)) context.status = error.status;
29899
+ return new SodaxError(
29900
+ "EXTERNAL_API_ERROR",
29901
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
29902
+ { feature, cause: error, context }
29903
+ );
29904
+ }
29905
+ function toInvalidResponseShapeError(params) {
29906
+ const { api, feature, endpoint, issues } = params;
29907
+ return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
29908
+ feature,
29909
+ context: { api, endpoint, reason: "invalid_response_shape", issues }
29910
+ });
29911
+ }
29831
29912
  var SwapsApiService = class _SwapsApiService {
29832
29913
  // Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
29833
29914
  // `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
@@ -29873,7 +29954,7 @@ var SwapsApiService = class _SwapsApiService {
29873
29954
  if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
29874
29955
  context.reason = "invalid_response_shape";
29875
29956
  const issues = error.context.issues;
29876
- context.issues = issues instanceof v2.ValiError ? v2.flatten(issues.issues) : issues;
29957
+ context.issues = issues instanceof v4.ValiError ? v4.flatten(issues.issues) : issues;
29877
29958
  }
29878
29959
  if (error.context.status !== void 0) context.status = error.context.status;
29879
29960
  }
@@ -30034,10 +30115,98 @@ var SwapsApiService = class _SwapsApiService {
30034
30115
  return this.config.baseURL;
30035
30116
  }
30036
30117
  };
30118
+ var StellarSponsorConfigSchema = v4.object({
30119
+ sponsorAccount: v4.string(),
30120
+ networkPassphrase: v4.string(),
30121
+ minTotalFeeStroops: v4.string(),
30122
+ maxTotalFeeStroops: v4.string(),
30123
+ operationCount: v4.number(),
30124
+ minPerOperationFeeStroops: v4.string(),
30125
+ maxPerOperationFeeStroops: v4.string(),
30126
+ recommendedPerOperationFeeStroops: v4.string(),
30127
+ maxTimeboundSeconds: v4.number(),
30128
+ requiredStartingBalance: v4.string()
30129
+ });
30130
+ var StellarSponsoredAccountResponseSchema = v4.variant("alreadyActive", [
30131
+ v4.object({ hash: v4.string(), alreadyActive: v4.literal(false) }),
30132
+ v4.object({ hash: v4.null(), alreadyActive: v4.literal(true) })
30133
+ ]);
30134
+
30135
+ // src/backendApi/SponsoringApiService.ts
30136
+ var SponsoringApiService = class {
30137
+ config;
30138
+ headers;
30139
+ logger;
30140
+ constructor(config, logger = consoleLogger) {
30141
+ this.config = config;
30142
+ this.headers = {
30143
+ ...config.apiKey !== void 0 ? { "x-api-key": config.apiKey } : {},
30144
+ ...config.headers
30145
+ };
30146
+ this.logger = logger;
30147
+ }
30148
+ /**
30149
+ * Validate a response while preserving HTTP failures on `error.cause` for
30150
+ * sponsor-error classification.
30151
+ */
30152
+ async request(endpoint, config, schema) {
30153
+ try {
30154
+ const raw = await makeRequest({
30155
+ endpoint,
30156
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30157
+ logger: this.logger,
30158
+ serviceLabel: "SponsoringApiService"
30159
+ });
30160
+ const parsed = v4.safeParse(schema, raw);
30161
+ if (!parsed.success) {
30162
+ return {
30163
+ ok: false,
30164
+ error: toInvalidResponseShapeError({
30165
+ api: "sponsoring",
30166
+ feature: "backend",
30167
+ endpoint,
30168
+ issues: v4.flatten(parsed.issues)
30169
+ })
30170
+ };
30171
+ }
30172
+ return { ok: true, value: parsed.output };
30173
+ } catch (error) {
30174
+ return { ok: false, error: toExternalApiError({ api: "sponsoring", feature: "backend", endpoint, error }) };
30175
+ }
30176
+ }
30177
+ /** Fetch build parameters, including the rotatable sponsor account. */
30178
+ async getStellarSponsorConfig(config) {
30179
+ return this.request(
30180
+ `${SPONSORING_API_STELLAR_BASE_PATH}/config`,
30181
+ { ...config, method: "GET" },
30182
+ StellarSponsorConfigSchema
30183
+ );
30184
+ }
30185
+ /**
30186
+ * Submit a client-signed transaction for sponsor co-signing. An
30187
+ * `alreadyActive` response is also successful.
30188
+ */
30189
+ async createStellarSponsoredAccount(body, config) {
30190
+ return this.request(
30191
+ `${SPONSORING_API_STELLAR_BASE_PATH}/accounts`,
30192
+ // The endpoint rejects extra fields.
30193
+ { ...config, method: "POST", body: JSON.stringify({ data: body.data }) },
30194
+ StellarSponsoredAccountResponseSchema
30195
+ );
30196
+ }
30197
+ setHeaders(headers) {
30198
+ Object.entries(headers).forEach(([key, value]) => {
30199
+ this.headers[key] = value;
30200
+ });
30201
+ }
30202
+ getBaseURL() {
30203
+ return this.config.baseURL;
30204
+ }
30205
+ };
30037
30206
 
30038
30207
  // src/backendApi/apiConfig.ts
30039
- function isCustomApiConfig(config) {
30040
- return "baseApiConfig" in config || "swapsApiConfig" in config;
30208
+ function flatLayer({ baseURL, timeout, headers }) {
30209
+ return { baseURL, timeout, headers };
30041
30210
  }
30042
30211
  function layerConfigs(...slices) {
30043
30212
  return slices.reduce(
@@ -30054,154 +30223,168 @@ function layerConfigs(...slices) {
30054
30223
  );
30055
30224
  }
30056
30225
  function resolveBaseApiConfig(config) {
30057
- if (isCustomApiConfig(config)) {
30058
- return layerConfigs(config.baseApiConfig);
30059
- }
30060
- return layerConfigs(config);
30226
+ const layers = config;
30227
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig);
30061
30228
  }
30062
30229
  function resolveSwapsApiConfig(config) {
30063
- if (isCustomApiConfig(config)) {
30064
- return layerConfigs(config.baseApiConfig, config.swapsApiConfig);
30065
- }
30066
- return layerConfigs(config);
30067
- }
30068
- var ChainKeySchema = v2.custom((input) => typeof input === "string");
30069
- var SpokeChainKeySchema = v2.custom((input) => typeof input === "string");
30070
- var AddressSchema = v2.custom((input) => typeof input === "string");
30071
- var XTokenSchema = v2.object({
30072
- symbol: v2.string(),
30073
- name: v2.string(),
30074
- decimals: v2.number(),
30075
- address: v2.string(),
30230
+ const layers = config;
30231
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig, layers.swapsApiConfig);
30232
+ }
30233
+ function isHttpUrl(value) {
30234
+ return value.startsWith("http://") || value.startsWith("https://");
30235
+ }
30236
+ function normalizeBaseURL(baseURL) {
30237
+ const trimmed = trimTrailingSlashes(baseURL);
30238
+ return isHttpUrl(trimmed) ? trimmed : baseURL;
30239
+ }
30240
+ function resolveSponsoringApiConfig(config) {
30241
+ const layers = config;
30242
+ const slice = layers.sponsoringApiConfig;
30243
+ return {
30244
+ baseURL: normalizeBaseURL(slice?.baseURL ?? DEFAULT_SPONSORING_API_ENDPOINT),
30245
+ timeout: slice?.timeout ?? resolveBaseApiConfig(config).timeout,
30246
+ headers: { ...DEFAULT_BACKEND_API_HEADERS, ...slice?.headers },
30247
+ ...slice?.apiKey === void 0 ? {} : { apiKey: slice.apiKey }
30248
+ };
30249
+ }
30250
+ var ChainKeySchema = v4.custom((input) => typeof input === "string");
30251
+ var SpokeChainKeySchema = v4.custom((input) => typeof input === "string");
30252
+ var AddressSchema = v4.custom((input) => typeof input === "string");
30253
+ var XTokenSchema = v4.object({
30254
+ symbol: v4.string(),
30255
+ name: v4.string(),
30256
+ decimals: v4.number(),
30257
+ address: v4.string(),
30076
30258
  chainKey: ChainKeySchema,
30077
30259
  hubAsset: AddressSchema,
30078
30260
  vault: AddressSchema,
30079
- access: v2.optional(v2.picklist(["withdrawOnly", "depositOnly"]))
30261
+ access: v4.optional(v4.picklist(["withdrawOnly", "depositOnly"]))
30080
30262
  });
30081
- var IntentStructSchema = v2.object({
30082
- intentId: v2.string(),
30083
- creator: v2.string(),
30084
- inputToken: v2.string(),
30085
- outputToken: v2.string(),
30086
- inputAmount: v2.string(),
30087
- minOutputAmount: v2.string(),
30088
- deadline: v2.string(),
30089
- allowPartialFill: v2.boolean(),
30090
- srcChain: v2.number(),
30091
- dstChain: v2.number(),
30092
- srcAddress: v2.string(),
30093
- dstAddress: v2.string(),
30094
- solver: v2.string(),
30095
- data: v2.string()
30263
+ var IntentStructSchema = v4.object({
30264
+ intentId: v4.string(),
30265
+ creator: v4.string(),
30266
+ inputToken: v4.string(),
30267
+ outputToken: v4.string(),
30268
+ inputAmount: v4.string(),
30269
+ minOutputAmount: v4.string(),
30270
+ deadline: v4.string(),
30271
+ allowPartialFill: v4.boolean(),
30272
+ srcChain: v4.number(),
30273
+ dstChain: v4.number(),
30274
+ srcAddress: v4.string(),
30275
+ dstAddress: v4.string(),
30276
+ solver: v4.string(),
30277
+ data: v4.string()
30096
30278
  });
30097
- var IntentResponseSchema = v2.object({
30098
- intentHash: v2.string(),
30099
- txHash: v2.string(),
30100
- logIndex: v2.number(),
30101
- chainId: v2.number(),
30102
- blockNumber: v2.number(),
30103
- open: v2.boolean(),
30279
+ var IntentResponseSchema = v4.object({
30280
+ intentHash: v4.string(),
30281
+ txHash: v4.string(),
30282
+ logIndex: v4.number(),
30283
+ chainId: v4.number(),
30284
+ blockNumber: v4.number(),
30285
+ open: v4.boolean(),
30104
30286
  intent: IntentStructSchema,
30105
- events: v2.array(v2.unknown())
30287
+ events: v4.array(v4.unknown())
30106
30288
  });
30107
- var UserIntentsResponseSchema = v2.object({
30108
- total: v2.number(),
30109
- offset: v2.number(),
30110
- limit: v2.number(),
30111
- items: v2.array(IntentResponseSchema)
30289
+ var UserIntentsResponseSchema = v4.object({
30290
+ total: v4.number(),
30291
+ offset: v4.number(),
30292
+ limit: v4.number(),
30293
+ items: v4.array(IntentResponseSchema)
30112
30294
  });
30113
- var OrderbookResponseSchema = v2.object({
30114
- total: v2.number(),
30115
- data: v2.array(
30116
- v2.object({
30117
- intentState: v2.object({
30118
- exists: v2.boolean(),
30119
- remainingInput: v2.string(),
30120
- receivedOutput: v2.string(),
30121
- pendingPayment: v2.boolean()
30295
+ var OrderbookResponseSchema = v4.object({
30296
+ total: v4.number(),
30297
+ data: v4.array(
30298
+ v4.object({
30299
+ intentState: v4.object({
30300
+ exists: v4.boolean(),
30301
+ remainingInput: v4.string(),
30302
+ receivedOutput: v4.string(),
30303
+ pendingPayment: v4.boolean()
30122
30304
  }),
30123
- intentData: v2.object({
30124
- intentId: v2.string(),
30125
- creator: v2.string(),
30126
- inputToken: v2.string(),
30127
- outputToken: v2.string(),
30128
- inputAmount: v2.string(),
30129
- minOutputAmount: v2.string(),
30130
- deadline: v2.string(),
30131
- allowPartialFill: v2.boolean(),
30132
- srcChain: v2.number(),
30133
- dstChain: v2.number(),
30134
- srcAddress: v2.string(),
30135
- dstAddress: v2.string(),
30136
- solver: v2.string(),
30137
- data: v2.string(),
30138
- intentHash: v2.string(),
30139
- txHash: v2.string(),
30140
- blockNumber: v2.number()
30305
+ intentData: v4.object({
30306
+ intentId: v4.string(),
30307
+ creator: v4.string(),
30308
+ inputToken: v4.string(),
30309
+ outputToken: v4.string(),
30310
+ inputAmount: v4.string(),
30311
+ minOutputAmount: v4.string(),
30312
+ deadline: v4.string(),
30313
+ allowPartialFill: v4.boolean(),
30314
+ srcChain: v4.number(),
30315
+ dstChain: v4.number(),
30316
+ srcAddress: v4.string(),
30317
+ dstAddress: v4.string(),
30318
+ solver: v4.string(),
30319
+ data: v4.string(),
30320
+ intentHash: v4.string(),
30321
+ txHash: v4.string(),
30322
+ blockNumber: v4.number()
30141
30323
  })
30142
30324
  })
30143
30325
  )
30144
30326
  });
30145
- var MoneyMarketPositionSchema = v2.object({
30146
- userAddress: v2.string(),
30147
- positions: v2.array(
30148
- v2.object({
30149
- reserveAddress: v2.string(),
30150
- aTokenAddress: v2.string(),
30151
- variableDebtTokenAddress: v2.string(),
30152
- aTokenBalance: v2.string(),
30153
- variableDebtTokenBalance: v2.string(),
30154
- blockNumber: v2.number()
30327
+ var MoneyMarketPositionSchema = v4.object({
30328
+ userAddress: v4.string(),
30329
+ positions: v4.array(
30330
+ v4.object({
30331
+ reserveAddress: v4.string(),
30332
+ aTokenAddress: v4.string(),
30333
+ variableDebtTokenAddress: v4.string(),
30334
+ aTokenBalance: v4.string(),
30335
+ variableDebtTokenBalance: v4.string(),
30336
+ blockNumber: v4.number()
30155
30337
  })
30156
30338
  )
30157
30339
  });
30158
- var MoneyMarketAssetSchema = v2.object({
30159
- reserveAddress: v2.string(),
30160
- aTokenAddress: v2.string(),
30161
- totalATokenBalance: v2.string(),
30162
- variableDebtTokenAddress: v2.string(),
30163
- totalVariableDebtTokenBalance: v2.string(),
30164
- liquidityRate: v2.string(),
30165
- symbol: v2.string(),
30166
- totalSuppliers: v2.number(),
30167
- totalBorrowers: v2.number(),
30168
- variableBorrowRate: v2.string(),
30169
- stableBorrowRate: v2.string(),
30170
- liquidityIndex: v2.string(),
30171
- variableBorrowIndex: v2.string(),
30172
- blockNumber: v2.number()
30340
+ var MoneyMarketAssetSchema = v4.object({
30341
+ reserveAddress: v4.string(),
30342
+ aTokenAddress: v4.string(),
30343
+ totalATokenBalance: v4.string(),
30344
+ variableDebtTokenAddress: v4.string(),
30345
+ totalVariableDebtTokenBalance: v4.string(),
30346
+ liquidityRate: v4.string(),
30347
+ symbol: v4.string(),
30348
+ totalSuppliers: v4.number(),
30349
+ totalBorrowers: v4.number(),
30350
+ variableBorrowRate: v4.string(),
30351
+ stableBorrowRate: v4.string(),
30352
+ liquidityIndex: v4.string(),
30353
+ variableBorrowIndex: v4.string(),
30354
+ blockNumber: v4.number()
30173
30355
  });
30174
- var MoneyMarketAssetsSchema = v2.array(MoneyMarketAssetSchema);
30175
- var MoneyMarketAssetBorrowersSchema = v2.object({
30176
- borrowers: v2.array(v2.string()),
30177
- total: v2.number(),
30178
- offset: v2.number(),
30179
- limit: v2.number()
30356
+ var MoneyMarketAssetsSchema = v4.array(MoneyMarketAssetSchema);
30357
+ var MoneyMarketAssetBorrowersSchema = v4.object({
30358
+ borrowers: v4.array(v4.string()),
30359
+ total: v4.number(),
30360
+ offset: v4.number(),
30361
+ limit: v4.number()
30180
30362
  });
30181
- var MoneyMarketAssetSuppliersSchema = v2.object({
30182
- suppliers: v2.array(v2.string()),
30183
- total: v2.number(),
30184
- offset: v2.number(),
30185
- limit: v2.number()
30363
+ var MoneyMarketAssetSuppliersSchema = v4.object({
30364
+ suppliers: v4.array(v4.string()),
30365
+ total: v4.number(),
30366
+ offset: v4.number(),
30367
+ limit: v4.number()
30186
30368
  });
30187
- var MoneyMarketBorrowersSchema = v2.object({
30188
- borrowers: v2.array(v2.string()),
30189
- total: v2.number(),
30190
- offset: v2.number(),
30191
- limit: v2.number()
30369
+ var MoneyMarketBorrowersSchema = v4.object({
30370
+ borrowers: v4.array(v4.string()),
30371
+ total: v4.number(),
30372
+ offset: v4.number(),
30373
+ limit: v4.number()
30192
30374
  });
30193
- var GetChainsResponseSchema = v2.array(SpokeChainKeySchema);
30194
- var TokensByChainMapSchema = v2.custom(
30195
- (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v2.is(XTokenSchema, t)))
30375
+ var GetChainsResponseSchema = v4.array(SpokeChainKeySchema);
30376
+ var TokensByChainMapSchema = v4.custom(
30377
+ (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v4.is(XTokenSchema, t)))
30196
30378
  );
30197
- var TokensListSchema = v2.array(XTokenSchema);
30198
- var ReserveAssetsSchema = v2.array(AddressSchema);
30379
+ var TokensListSchema = v4.array(XTokenSchema);
30380
+ var ReserveAssetsSchema = v4.array(AddressSchema);
30199
30381
 
30200
30382
  // src/backendApi/BackendApiService.ts
30201
30383
  var BackendApiService = class {
30202
30384
  // sub-services exposing domain-specific APIs
30203
30385
  swaps;
30204
- // resolved base-API slice of the ApiConfig union (flat config, or its `baseApiConfig`)
30386
+ sponsoring;
30387
+ // resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on top
30205
30388
  config;
30206
30389
  headers;
30207
30390
  logger;
@@ -30210,37 +30393,7 @@ var BackendApiService = class {
30210
30393
  this.headers = { ...this.config.headers };
30211
30394
  this.logger = logger;
30212
30395
  this.swaps = new SwapsApiService(resolveSwapsApiConfig(config), this.logger);
30213
- }
30214
- /**
30215
- * Wraps {@link makeRequest} in a `Result<T>` so all errors are captured rather
30216
- * than propagated as thrown exceptions. Every public endpoint method delegates
30217
- * here instead of calling `makeRequest` directly.
30218
- */
30219
- /**
30220
- * Fold any per-call override (carried on `config` alongside `method`/`body`) over the service
30221
- * defaults: baseURL truthy-fallback (an empty-string override defers to the default), timeout
30222
- * nullish-fallback, headers merged (override wins per key). Mirrors the original makeRequest merge.
30223
- */
30224
- resolveRequestConfig(config) {
30225
- const { baseURL, timeout, headers, ...rest } = config;
30226
- return {
30227
- ...rest,
30228
- baseURL: baseURL || this.config.baseURL,
30229
- timeout: timeout ?? this.config.timeout,
30230
- headers: { ...this.headers, ...headers }
30231
- };
30232
- }
30233
- /**
30234
- * Wrap a thrown transport failure (HTTP_REQUEST_FAILED / REQUEST_TIMEOUT / network error) as the
30235
- * canonical backend `SodaxError` — identical shape to SwapsApiService; the underlying failure is
30236
- * preserved on `error.cause`.
30237
- */
30238
- toExternalApiError(endpoint, error) {
30239
- return new SodaxError(
30240
- "EXTERNAL_API_ERROR",
30241
- error instanceof Error ? error.message : `Backend API request to ${endpoint} failed`,
30242
- { feature: "backend", cause: error, context: { api: "backend", endpoint } }
30243
- );
30396
+ this.sponsoring = new SponsoringApiService(resolveSponsoringApiConfig(config), this.logger);
30244
30397
  }
30245
30398
  /**
30246
30399
  * Issue a request and validate the JSON body against `schema`, wrapping the result in `Result<T>`.
@@ -30253,23 +30406,25 @@ var BackendApiService = class {
30253
30406
  try {
30254
30407
  const raw = await makeRequest({
30255
30408
  endpoint,
30256
- config: this.resolveRequestConfig(config),
30409
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30257
30410
  logger: this.logger,
30258
30411
  serviceLabel: "BackendApiService"
30259
30412
  });
30260
- const parsed = v2.safeParse(schema, raw);
30413
+ const parsed = v4.safeParse(schema, raw);
30261
30414
  if (!parsed.success) {
30262
30415
  return {
30263
30416
  ok: false,
30264
- error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from backend API for ${endpoint}`, {
30417
+ error: toInvalidResponseShapeError({
30418
+ api: "backend",
30265
30419
  feature: "backend",
30266
- context: { api: "backend", endpoint, reason: "invalid_response_shape", issues: v2.flatten(parsed.issues) }
30420
+ endpoint,
30421
+ issues: v4.flatten(parsed.issues)
30267
30422
  })
30268
30423
  };
30269
30424
  }
30270
30425
  return { ok: true, value: parsed.output };
30271
30426
  } catch (error) {
30272
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30427
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30273
30428
  }
30274
30429
  }
30275
30430
  /**
@@ -30283,13 +30438,13 @@ var BackendApiService = class {
30283
30438
  try {
30284
30439
  const value = await makeRequest({
30285
30440
  endpoint,
30286
- config: this.resolveRequestConfig(config),
30441
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30287
30442
  logger: this.logger,
30288
30443
  serviceLabel: "BackendApiService"
30289
30444
  });
30290
30445
  return { ok: true, value };
30291
30446
  } catch (error) {
30292
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30447
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30293
30448
  }
30294
30449
  }
30295
30450
  // Intent endpoints
@@ -30588,9 +30743,8 @@ var BackendApiService = class {
30588
30743
  * without constructing a new service instance. Existing header keys are
30589
30744
  * overwritten; keys absent from `headers` are preserved.
30590
30745
  *
30591
- * The headers are also fanned out to the sub-services (`swaps`), which hold
30592
- * their own header copies — so a token set here applies to every request made
30593
- * through this client, including `swaps.*`.
30746
+ * Headers also reach `swaps`, which shares this origin, but never `sponsoring`,
30747
+ * whose separate origin must not receive base-API credentials.
30594
30748
  *
30595
30749
  * @param headers - Key-value pairs to add or overwrite in the default headers.
30596
30750
  */
@@ -39308,7 +39462,7 @@ var LeverageYieldService = class {
39308
39462
  }
39309
39463
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
39310
39464
  getVault(name) {
39311
- return this.listVaults().find((v4) => v4.name === name);
39465
+ return this.listVaults().find((v6) => v6.name === name);
39312
39466
  }
39313
39467
  /**
39314
39468
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -39316,7 +39470,7 @@ var LeverageYieldService = class {
39316
39470
  */
39317
39471
  getVaultByAddress(address) {
39318
39472
  const normalized = address.toLowerCase();
39319
- return this.listVaults().find((v4) => v4.vault.toLowerCase() === normalized);
39473
+ return this.listVaults().find((v6) => v6.vault.toLowerCase() === normalized);
39320
39474
  }
39321
39475
  /**
39322
39476
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -40098,6 +40252,566 @@ var LeverageYieldService = class {
40098
40252
  }
40099
40253
  };
40100
40254
 
40255
+ // src/sponsoring/errors.ts
40256
+ var sponsoringInvariant = createInvariant("sponsoring");
40257
+ var ORCHESTRATION_CODES3 = /* @__PURE__ */ new Set([
40258
+ "USER_REJECTED",
40259
+ "VALIDATION_FAILED",
40260
+ "INTENT_CREATION_FAILED",
40261
+ "LOOKUP_FAILED",
40262
+ "EXTERNAL_API_ERROR",
40263
+ "EXECUTION_FAILED",
40264
+ "UNKNOWN"
40265
+ ]);
40266
+ var CONFIG_CODES = /* @__PURE__ */ new Set([
40267
+ "EXTERNAL_API_ERROR",
40268
+ "VALIDATION_FAILED",
40269
+ "UNKNOWN"
40270
+ ]);
40271
+ var isSponsoringOrchestrationError = isCodeMember(ORCHESTRATION_CODES3);
40272
+ var isSponsoringConfigError = isCodeMember(CONFIG_CODES);
40273
+ var isSponsoringLookupError = isCodeMember(LOOKUP_CODES);
40274
+ var DOMAIN_CODES = new Set(SPONSORING_API_ERROR_CODES);
40275
+ function toDomainCode(value) {
40276
+ return typeof value === "string" && DOMAIN_CODES.has(value) ? value : void 0;
40277
+ }
40278
+ function readErrorBody(body) {
40279
+ if (typeof body !== "object" || body === null) return {};
40280
+ const record = body;
40281
+ const retryAfterSeconds = typeof record.retryAfterSeconds === "number" && Number.isFinite(record.retryAfterSeconds) && record.retryAfterSeconds > 0 ? record.retryAfterSeconds : void 0;
40282
+ const sponsorSequence = typeof record.sponsorSequence === "string" && /^\d+$/.test(record.sponsorSequence) ? record.sponsorSequence : void 0;
40283
+ return {
40284
+ message: typeof record.message === "string" ? record.message : void 0,
40285
+ code: toDomainCode(record.error),
40286
+ retryAfterSeconds,
40287
+ sponsorSequence
40288
+ };
40289
+ }
40290
+ var ACTION_POLICY = {
40291
+ fixIntegration: { retryable: false, requiresNewSignature: false },
40292
+ checkApiKey: { retryable: false, requiresNewSignature: false },
40293
+ rebuildAndResign: { retryable: true, requiresNewSignature: true },
40294
+ retrySameRequest: { retryable: true, requiresNewSignature: false },
40295
+ backoff: { retryable: true, requiresNewSignature: false },
40296
+ contactOperator: { retryable: false, requiresNewSignature: false },
40297
+ abort: { retryable: false, requiresNewSignature: false }
40298
+ };
40299
+ function policy(action) {
40300
+ return { action, ...ACTION_POLICY[action] };
40301
+ }
40302
+ function classifySponsorError(error) {
40303
+ const cause = error.cause;
40304
+ const http3 = isBackendHttpError(cause) ? cause : void 0;
40305
+ const { message: serverMessage, code, retryAfterSeconds, sponsorSequence } = readErrorBody(http3?.body);
40306
+ const message = serverMessage ?? error.message;
40307
+ const status = http3?.status;
40308
+ if (status === void 0) {
40309
+ return { ...policy("backoff"), message };
40310
+ }
40311
+ const base2 = { status, code, retryAfterSeconds, sponsorSequence, message };
40312
+ switch (status) {
40313
+ case 400:
40314
+ return { ...base2, ...policy("fixIntegration") };
40315
+ case 401:
40316
+ return { ...base2, ...policy("checkApiKey") };
40317
+ case 409:
40318
+ return { ...base2, ...policy("rebuildAndResign") };
40319
+ case 422:
40320
+ return { ...base2, ...policy("abort") };
40321
+ case 429:
40322
+ return { ...base2, ...policy("backoff") };
40323
+ case 500:
40324
+ return { ...base2, ...policy("contactOperator") };
40325
+ case 503:
40326
+ if (code === "SPONSOR_BUDGET_EXHAUSTED") {
40327
+ return { ...base2, ...policy("contactOperator") };
40328
+ }
40329
+ if (code === "HORIZON_UNAVAILABLE") {
40330
+ return { ...base2, ...policy("retrySameRequest") };
40331
+ }
40332
+ return { ...base2, ...policy("backoff") };
40333
+ default:
40334
+ return { ...base2, ...policy("abort") };
40335
+ }
40336
+ }
40337
+ var SPONSORED_CREATE_OP_COUNT = 3n;
40338
+ var SPONSOR_TIMEBOUND_SECONDS = 300;
40339
+ function parseStroops(value, field) {
40340
+ try {
40341
+ return BigInt(value);
40342
+ } catch {
40343
+ sponsoringInvariant(false, `sponsor config ${field} is not a valid integer: "${value}"`, { field });
40344
+ }
40345
+ }
40346
+ function deriveSponsorBaseFee(config) {
40347
+ const min = parseStroops(config.minTotalFeeStroops, "minTotalFeeStroops");
40348
+ const max = parseStroops(config.maxTotalFeeStroops, "maxTotalFeeStroops");
40349
+ sponsoringInvariant(min > 0n, `sponsor config minTotalFeeStroops must be positive, got ${min}`, {
40350
+ field: "minTotalFeeStroops"
40351
+ });
40352
+ sponsoringInvariant(max >= min, `sponsor config fee band is inverted (min ${min} > max ${max})`, {
40353
+ field: "maxTotalFeeStroops"
40354
+ });
40355
+ const minPerOp = parseStroops(config.minPerOperationFeeStroops, "minPerOperationFeeStroops");
40356
+ const maxPerOp = parseStroops(config.maxPerOperationFeeStroops, "maxPerOperationFeeStroops");
40357
+ sponsoringInvariant(minPerOp > 0n, `sponsor config minPerOperationFeeStroops must be positive, got ${minPerOp}`, {
40358
+ field: "minPerOperationFeeStroops"
40359
+ });
40360
+ sponsoringInvariant(
40361
+ maxPerOp >= minPerOp,
40362
+ `sponsor config per-operation fee band is inverted (min ${minPerOp} > max ${maxPerOp})`,
40363
+ { field: "maxPerOperationFeeStroops" }
40364
+ );
40365
+ sponsoringInvariant(
40366
+ Number.isInteger(config.operationCount) && BigInt(config.operationCount) === SPONSORED_CREATE_OP_COUNT,
40367
+ `sponsor config expects ${config.operationCount} operations but this builder emits ${SPONSORED_CREATE_OP_COUNT} \u2014 the sponsored-create shape has changed server-side`,
40368
+ { field: "operationCount" }
40369
+ );
40370
+ const baseFee = parseStroops(config.recommendedPerOperationFeeStroops, "recommendedPerOperationFeeStroops");
40371
+ const totalFee = baseFee * SPONSORED_CREATE_OP_COUNT;
40372
+ sponsoringInvariant(
40373
+ baseFee >= minPerOp && baseFee <= maxPerOp,
40374
+ `per-operation fee ${baseFee} is outside the accepted per-operation band [${minPerOp}, ${maxPerOp}]`,
40375
+ { field: "recommendedPerOperationFeeStroops" }
40376
+ );
40377
+ sponsoringInvariant(
40378
+ totalFee >= min && totalFee <= max,
40379
+ `per-operation fee ${baseFee} yields a total of ${totalFee} stroops, outside the accepted band [${min}, ${max}]`,
40380
+ { field: "recommendedPerOperationFeeStroops" }
40381
+ );
40382
+ return { baseFee: baseFee.toString(), totalFee };
40383
+ }
40384
+ function resolveTimeboundSeconds(config) {
40385
+ const ceiling = Math.floor(config.maxTimeboundSeconds);
40386
+ const seconds = Math.min(SPONSOR_TIMEBOUND_SECONDS, ceiling);
40387
+ sponsoringInvariant(
40388
+ Number.isFinite(seconds) && seconds > 0,
40389
+ `sponsor config maxTimeboundSeconds leaves no usable window, got ${config.maxTimeboundSeconds}`,
40390
+ { field: "maxTimeboundSeconds" }
40391
+ );
40392
+ return seconds;
40393
+ }
40394
+ function assertSponsoredCreateInputs(params) {
40395
+ const { config, address } = params;
40396
+ sponsoringInvariant(
40397
+ config.networkPassphrase === Networks.PUBLIC,
40398
+ `sponsored create must target the Stellar public network, got "${config.networkPassphrase}"`,
40399
+ { field: "networkPassphrase" }
40400
+ );
40401
+ assertValidStellarAccountId(address);
40402
+ assertValidStellarAccountId(config.sponsorAccount);
40403
+ deriveSponsorBaseFee(config);
40404
+ resolveTimeboundSeconds(config);
40405
+ }
40406
+ function buildSponsoredCreate(params) {
40407
+ const { config, sponsorSequence, address } = params;
40408
+ assertSponsoredCreateInputs({ config, address });
40409
+ const { baseFee } = deriveSponsorBaseFee(config);
40410
+ const timeboundSeconds = resolveTimeboundSeconds(config);
40411
+ return new TransactionBuilder(new Account(config.sponsorAccount, sponsorSequence), {
40412
+ fee: baseFee,
40413
+ networkPassphrase: config.networkPassphrase
40414
+ }).addOperation(Operation.beginSponsoringFutureReserves({ sponsoredId: address })).addOperation(Operation.createAccount({ destination: address, startingBalance: config.requiredStartingBalance })).addOperation(Operation.endSponsoringFutureReserves({ source: address })).setTimeout(timeboundSeconds).build();
40415
+ }
40416
+ function assertValidStellarAccountId(address) {
40417
+ let valid = true;
40418
+ try {
40419
+ Keypair.fromPublicKey(address);
40420
+ } catch {
40421
+ valid = false;
40422
+ }
40423
+ sponsoringInvariant(valid, `"${address}" is not a valid Stellar ed25519 public key`, { field: "address" });
40424
+ }
40425
+ function assertSignedByAccount(params) {
40426
+ const { signedXdr, address, unsignedHash } = params;
40427
+ let parsed;
40428
+ try {
40429
+ parsed = TransactionBuilder.fromXDR(signedXdr, Networks.PUBLIC);
40430
+ } catch (error) {
40431
+ sponsoringInvariant(false, `wallet returned an unparseable transaction: ${messageOf(error, String(error))}`, {
40432
+ field: "signature"
40433
+ });
40434
+ }
40435
+ sponsoringInvariant(
40436
+ !(parsed instanceof FeeBumpTransaction),
40437
+ "wallet returned a fee-bump envelope; the sponsoring API rejects fee-bump transactions",
40438
+ { field: "signature" }
40439
+ );
40440
+ const hash = parsed.hash();
40441
+ sponsoringInvariant(
40442
+ hash.equals(unsignedHash),
40443
+ "wallet altered the transaction before signing it (fee, memo, or time bounds changed)",
40444
+ { field: "signature" }
40445
+ );
40446
+ const keypair = Keypair.fromPublicKey(address);
40447
+ const signedByAccount = parsed.signatures.some((signature) => {
40448
+ try {
40449
+ return keypair.verify(hash, signature.signature());
40450
+ } catch {
40451
+ return false;
40452
+ }
40453
+ });
40454
+ sponsoringInvariant(
40455
+ signedByAccount,
40456
+ "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",
40457
+ { field: "signature" }
40458
+ );
40459
+ }
40460
+ function isHorizonNotFound(error) {
40461
+ if (error instanceof NotFoundError) return true;
40462
+ const status = error?.response?.status;
40463
+ return status === 404;
40464
+ }
40465
+ var XLM_DECIMALS = 7;
40466
+ function xlmDecimalToStroops(amount) {
40467
+ if (!/^\d+(\.\d+)?$/.test(amount)) return 0n;
40468
+ const [whole = "0", fraction = ""] = amount.split(".");
40469
+ const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
40470
+ return BigInt(scaled);
40471
+ }
40472
+ var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
40473
+ var BASE_RESERVE_UNITS = 2;
40474
+ function parseBaseReserveStroops(ledger) {
40475
+ const value = ledger?.base_reserve_in_stroops;
40476
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) return void 0;
40477
+ return BigInt(value);
40478
+ }
40479
+ function readReserveInfo(account, baseReserveStroops) {
40480
+ const native = account.balances.find((balance) => balance.asset_type === "native");
40481
+ const nativeBalanceStroops = native ? xlmDecimalToStroops(native.balance) : 0n;
40482
+ const sellingLiabilitiesStroops = native?.selling_liabilities ? xlmDecimalToStroops(native.selling_liabilities) : 0n;
40483
+ const units = Math.max(
40484
+ 0,
40485
+ BASE_RESERVE_UNITS + (account.subentry_count ?? 0) + (account.num_sponsoring ?? 0) - (account.num_sponsored ?? 0)
40486
+ );
40487
+ const lockedStroops = BigInt(units) * baseReserveStroops + sellingLiabilitiesStroops;
40488
+ return {
40489
+ nativeBalanceStroops,
40490
+ availableBalanceStroops: nativeBalanceStroops > lockedStroops ? nativeBalanceStroops - lockedStroops : 0n
40491
+ };
40492
+ }
40493
+
40494
+ // src/sponsoring/SponsoringService.ts
40495
+ var SPONSOR_CONFIG_TTL_MS = 6e4;
40496
+ var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
40497
+ var DEFAULT_MAX_HORIZON_RETRIES = 2;
40498
+ var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
40499
+ var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS + STELLAR_FEE_HEADROOM_STROOPS;
40500
+ var SponsoringService = class {
40501
+ config;
40502
+ spoke;
40503
+ api;
40504
+ /** Keyed by base URL to isolate deployment-specific sponsor config. */
40505
+ configCache = /* @__PURE__ */ new Map();
40506
+ inflightConfig = /* @__PURE__ */ new Map();
40507
+ baseReserveCache;
40508
+ inflightBaseReserve;
40509
+ constructor(deps) {
40510
+ this.config = deps.config;
40511
+ this.spoke = deps.spoke;
40512
+ this.api = deps.api;
40513
+ }
40514
+ get horizon() {
40515
+ return this.spoke.stellar.server;
40516
+ }
40517
+ /**
40518
+ * Whether an account exists. Read failures remain errors rather than being
40519
+ * misreported as inactive.
40520
+ */
40521
+ async isStellarAccountActive(params) {
40522
+ const account = await this.readAccount(params.address, "isStellarAccountActive");
40523
+ return account.ok ? { ok: true, value: account.value !== void 0 } : account;
40524
+ }
40525
+ /**
40526
+ * Return account existence and trustline affordability. Costs one Horizon
40527
+ * account read, plus a base-reserve read on the first call per hour.
40528
+ */
40529
+ async getStellarAccountStatus(params) {
40530
+ const account = await this.readAccount(params.address, "getStellarAccountStatus");
40531
+ if (!account.ok) return account;
40532
+ const baseReserveStroops = await this.resolveBaseReserveStroops();
40533
+ const trustlineMinXlmStroops = baseReserveStroops + STELLAR_FEE_HEADROOM_STROOPS;
40534
+ if (account.value === void 0) {
40535
+ return {
40536
+ ok: true,
40537
+ value: {
40538
+ exists: false,
40539
+ nativeBalanceStroops: 0n,
40540
+ availableBalanceStroops: 0n,
40541
+ canAffordTrustline: false,
40542
+ trustlineMinXlmStroops
40543
+ }
40544
+ };
40545
+ }
40546
+ const { nativeBalanceStroops, availableBalanceStroops } = readReserveInfo(account.value, baseReserveStroops);
40547
+ return {
40548
+ ok: true,
40549
+ value: {
40550
+ exists: true,
40551
+ nativeBalanceStroops,
40552
+ availableBalanceStroops,
40553
+ canAffordTrustline: availableBalanceStroops >= trustlineMinXlmStroops,
40554
+ trustlineMinXlmStroops
40555
+ }
40556
+ };
40557
+ }
40558
+ /**
40559
+ * Shared account read. A 404 resolves to `undefined` because absence is a
40560
+ * legitimate answer; every other failure remains an error.
40561
+ */
40562
+ async readAccount(address, action) {
40563
+ if (address.length === 0) {
40564
+ return {
40565
+ ok: false,
40566
+ error: new SodaxError("VALIDATION_FAILED", "address is required", {
40567
+ feature: "sponsoring",
40568
+ context: { phase: "validate", method: action, field: "address" }
40569
+ })
40570
+ };
40571
+ }
40572
+ try {
40573
+ return { ok: true, value: await this.horizon.loadAccount(address) };
40574
+ } catch (error) {
40575
+ if (isHorizonNotFound(error)) return { ok: true, value: void 0 };
40576
+ return {
40577
+ ok: false,
40578
+ error: lookupFailed("sponsoring", action, error, { srcChainKey: ChainKeys.STELLAR_MAINNET })
40579
+ };
40580
+ }
40581
+ }
40582
+ /**
40583
+ * The base reserve is a validator-controlled network setting, so read it from
40584
+ * the latest ledger rather than assuming the published 0.5 XLM. A failed read
40585
+ * degrades to that value: this drives a UI hint, never a signed transaction.
40586
+ */
40587
+ async resolveBaseReserveStroops() {
40588
+ const cached = this.baseReserveCache;
40589
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
40590
+ const inflight = this.inflightBaseReserve;
40591
+ if (inflight) return inflight;
40592
+ const read = async () => {
40593
+ try {
40594
+ const page = await this.horizon.ledgers().order("desc").limit(1).call();
40595
+ const value = parseBaseReserveStroops(page.records[0]);
40596
+ if (value !== void 0) return value;
40597
+ } catch (error) {
40598
+ this.config.logger.warn("[SponsoringService] Stellar base-reserve read failed; assuming the published value", {
40599
+ reason: messageOf(error, String(error))
40600
+ });
40601
+ }
40602
+ return STELLAR_BASE_RESERVE_STROOPS;
40603
+ };
40604
+ const request = read().then((value) => {
40605
+ this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
40606
+ return value;
40607
+ }).finally(() => {
40608
+ if (this.inflightBaseReserve === request) this.inflightBaseReserve = void 0;
40609
+ });
40610
+ this.inflightBaseReserve = request;
40611
+ return request;
40612
+ }
40613
+ /**
40614
+ * Cache key for a config request: the resolved base URL plus any per-call
40615
+ * headers. Headers can select a different response from the same URL — an API
40616
+ * key scoped to another deployment, or a test harness's scenario header — so
40617
+ * folding them in stops one caller's override from being served to, or
40618
+ * overwriting, the default path. Kept in memory as a Map key only.
40619
+ */
40620
+ configCacheKey(requestConfig) {
40621
+ const baseURL = requestConfig?.baseURL || this.api.sponsoring.getBaseURL();
40622
+ const headers = requestConfig?.headers;
40623
+ if (!headers) return baseURL;
40624
+ const normalized = Object.keys(headers).sort().map((name) => `${name.toLowerCase()}=${headers[name]}`).join("&");
40625
+ return normalized.length === 0 ? baseURL : `${baseURL}|${normalized}`;
40626
+ }
40627
+ /**
40628
+ * Fetch sponsor config with per-endpoint caching and in-flight deduplication.
40629
+ * Failures are never cached.
40630
+ */
40631
+ async getStellarSponsorConfig(params) {
40632
+ const key = this.configCacheKey(params?.requestConfig);
40633
+ if (params?.forceRefresh) {
40634
+ this.configCache.delete(key);
40635
+ this.inflightConfig.delete(key);
40636
+ } else {
40637
+ const cached = this.configCache.get(key);
40638
+ if (cached && cached.expiresAt > Date.now()) return { ok: true, value: cached.value };
40639
+ const inflight = this.inflightConfig.get(key);
40640
+ if (inflight) return inflight;
40641
+ }
40642
+ const request = this.api.sponsoring.getStellarSponsorConfig(params?.requestConfig).then((result) => {
40643
+ if (result.ok && this.inflightConfig.get(key) === request) {
40644
+ const now = Date.now();
40645
+ for (const [cached, entry] of this.configCache) {
40646
+ if (entry.expiresAt <= now) this.configCache.delete(cached);
40647
+ }
40648
+ this.configCache.set(key, { value: result.value, expiresAt: now + SPONSOR_CONFIG_TTL_MS });
40649
+ }
40650
+ return result;
40651
+ }).finally(() => {
40652
+ if (this.inflightConfig.get(key) === request) this.inflightConfig.delete(key);
40653
+ });
40654
+ this.inflightConfig.set(key, request);
40655
+ return request;
40656
+ }
40657
+ /**
40658
+ * Activate an account with a sponsored base reserve. Config and existence are
40659
+ * checked before prompting; sponsor sequence is never cached.
40660
+ */
40661
+ async activateStellarAccount(params) {
40662
+ let attempts = 0;
40663
+ return this.config.analytics.trackResult(
40664
+ "sponsoring",
40665
+ "activateStellarAccount",
40666
+ async () => {
40667
+ try {
40668
+ const { address } = params;
40669
+ const configResult = await this.getStellarSponsorConfig({
40670
+ forceRefresh: params.forceConfigRefresh,
40671
+ requestConfig: params.requestConfig
40672
+ });
40673
+ if (!configResult.ok) return configResult;
40674
+ const sponsorConfig = configResult.value;
40675
+ if (await this.accountExistsBestEffort(address)) {
40676
+ return { ok: true, value: { status: "alreadyActive", hash: null, attempts: 0 } };
40677
+ }
40678
+ attempts = 1;
40679
+ const first = await this.attemptActivation({ params, sponsorConfig, attempt: 1 });
40680
+ if (first.ok || params.allowSequenceRetry === false) return first;
40681
+ if (first.error.context?.nextAction !== "rebuildAndResign") return first;
40682
+ attempts = 2;
40683
+ return this.attemptActivation({
40684
+ params,
40685
+ sponsorConfig,
40686
+ attempt: 2,
40687
+ sponsorSequenceHint: first.error.context?.sponsorSequence
40688
+ });
40689
+ } catch (error) {
40690
+ if (isSodaxError(error)) {
40691
+ return { ok: false, error };
40692
+ }
40693
+ return {
40694
+ ok: false,
40695
+ error: unknownFailed("sponsoring", error, { action: "activateStellarAccount" })
40696
+ };
40697
+ }
40698
+ },
40699
+ {
40700
+ start: () => ({ srcChainKey: ChainKeys.STELLAR_MAINNET, address: params.address }),
40701
+ success: (value) => ({ status: value.status, attempts: value.attempts, hash: value.hash }),
40702
+ failure: (error) => ({
40703
+ code: error.code,
40704
+ // Preserve evidence that a sequence-conflict retry occurred.
40705
+ attempts,
40706
+ // `status` is already the domain outcome in success events.
40707
+ httpStatus: error.context?.status,
40708
+ nextAction: error.context?.nextAction
40709
+ })
40710
+ }
40711
+ );
40712
+ }
40713
+ /** One build, sign, and submit attempt. */
40714
+ async attemptActivation(args) {
40715
+ const { params, sponsorConfig, attempt, sponsorSequenceHint } = args;
40716
+ const { address, walletProvider } = params;
40717
+ assertSponsoredCreateInputs({ config: sponsorConfig, address });
40718
+ let sponsorSequence;
40719
+ if (sponsorSequenceHint !== void 0) {
40720
+ sponsorSequence = sponsorSequenceHint;
40721
+ } else {
40722
+ try {
40723
+ const sponsorAccount = await this.horizon.loadAccount(sponsorConfig.sponsorAccount);
40724
+ sponsorSequence = sponsorAccount.sequenceNumber();
40725
+ } catch (error) {
40726
+ return {
40727
+ ok: false,
40728
+ error: lookupFailed("sponsoring", "loadSponsorAccount", error, {
40729
+ action: "activateStellarAccount",
40730
+ srcChainKey: ChainKeys.STELLAR_MAINNET
40731
+ })
40732
+ };
40733
+ }
40734
+ }
40735
+ const transaction = buildSponsoredCreate({ config: sponsorConfig, sponsorSequence, address });
40736
+ const unsignedHash = transaction.hash();
40737
+ params.onSignatureRequired?.({ attempt, reason: attempt === 1 ? "initial" : "sequenceConflict" });
40738
+ let signedXdr;
40739
+ try {
40740
+ signedXdr = await walletProvider.signTransaction(transaction.toXDR(), { address });
40741
+ } catch (error) {
40742
+ return {
40743
+ ok: false,
40744
+ error: intentCreationFailed("sponsoring", error, {
40745
+ action: "activateStellarAccount",
40746
+ srcChainKey: ChainKeys.STELLAR_MAINNET
40747
+ })
40748
+ };
40749
+ }
40750
+ assertSignedByAccount({ signedXdr, address, unsignedHash });
40751
+ const submitted = await this.submitWithHorizonRetry({
40752
+ signedXdr,
40753
+ maxRetries: params.maxHorizonRetries ?? DEFAULT_MAX_HORIZON_RETRIES,
40754
+ requestConfig: params.requestConfig
40755
+ });
40756
+ if (submitted.ok) {
40757
+ const response = submitted.value;
40758
+ return response.alreadyActive ? { ok: true, value: { status: "alreadyActive", hash: null, attempts: attempt } } : { ok: true, value: { status: "submitted", hash: response.hash, attempts: attempt } };
40759
+ }
40760
+ const classification = classifySponsorError(submitted.error);
40761
+ if (classification.action === "fixIntegration") {
40762
+ this.configCache.delete(this.configCacheKey(params.requestConfig));
40763
+ }
40764
+ return {
40765
+ ok: false,
40766
+ error: new SodaxError("EXTERNAL_API_ERROR", classification.message, {
40767
+ feature: "sponsoring",
40768
+ cause: submitted.error,
40769
+ context: {
40770
+ api: "sponsoring",
40771
+ action: "activateStellarAccount",
40772
+ phase: "submit",
40773
+ srcChainKey: ChainKeys.STELLAR_MAINNET,
40774
+ attempts: attempt,
40775
+ nextAction: classification.action,
40776
+ retryable: classification.retryable,
40777
+ requiresNewSignature: classification.requiresNewSignature,
40778
+ sponsorAccount: sponsorConfig.sponsorAccount,
40779
+ status: classification.status,
40780
+ code: classification.code,
40781
+ retryAfterSeconds: classification.retryAfterSeconds,
40782
+ sponsorSequence: classification.sponsorSequence
40783
+ }
40784
+ })
40785
+ };
40786
+ }
40787
+ /**
40788
+ * Re-submit identical signed bytes only for `retrySameRequest` failures.
40789
+ */
40790
+ async submitWithHorizonRetry(args) {
40791
+ const { signedXdr, maxRetries, requestConfig } = args;
40792
+ let result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
40793
+ for (let retry2 = 0; retry2 < maxRetries && !result.ok; retry2++) {
40794
+ if (classifySponsorError(result.error).action !== "retrySameRequest") break;
40795
+ await sleep(1e3 * (retry2 + 1));
40796
+ result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
40797
+ }
40798
+ return result;
40799
+ }
40800
+ /**
40801
+ * Best-effort existence pre-flight. Read failures continue to activation
40802
+ * because the server performs the authoritative check.
40803
+ */
40804
+ async accountExistsBestEffort(address) {
40805
+ const account = await this.readAccount(address, "isStellarAccountActive");
40806
+ if (account.ok) return account.value !== void 0;
40807
+ this.config.logger.warn(
40808
+ "[SponsoringService] Stellar account existence pre-flight failed; continuing with activation",
40809
+ { address, reason: messageOf(account.error, String(account.error)) }
40810
+ );
40811
+ return false;
40812
+ }
40813
+ };
40814
+
40101
40815
  // src/shared/entities/Sodax.ts
40102
40816
  var Sodax = class {
40103
40817
  instanceConfig;
@@ -40121,6 +40835,7 @@ var Sodax = class {
40121
40835
  // Recovery service for withdrawing stuck hub-wallet assets back to a spoke chain
40122
40836
  dex;
40123
40837
  // Dex service enabling DEX operations
40838
+ sponsoring;
40124
40839
  leverageYield;
40125
40840
  // Leverage-yield service: cross-chain deposits / withdrawals into ERC-4626 leverage vaults on Sonic
40126
40841
  config;
@@ -40186,6 +40901,11 @@ var Sodax = class {
40186
40901
  config: this.config,
40187
40902
  spoke: this.spoke
40188
40903
  });
40904
+ this.sponsoring = new SponsoringService({
40905
+ config: this.config,
40906
+ spoke: this.spoke,
40907
+ api: this.backendApi
40908
+ });
40189
40909
  }
40190
40910
  /**
40191
40911
  * Initializes the Sodax instance with dynamic configuration.
@@ -40227,4 +40947,4 @@ var isPartnerError = isCodeMember(PARTNER_CODES);
40227
40947
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
40228
40948
  */
40229
40949
 
40230
- export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, erc20Abi, erc4626Abi, estimateBitcoinTxSize, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, serializeAddressData, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
40950
+ export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BackendHttpError, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeService, CHAIN_KEYS, CHAIN_LOGO_BASE_URL, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DEFAULT_SPONSORING_API_ENDPOINT, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HookKind, HookService, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataService, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LeverageYieldService, LockupMultiplier, LockupPeriod, LsodaSymbols, LsodaTokens, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NEAR_STORAGE_DEPOSIT, NearSpokeService, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, SPONSORING_API_ERROR_CODES, SPONSORING_API_STELLAR_BASE_PATH, SPONSOR_CONFIG_TTL_MS, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_BASE_RESERVE_TTL_MS, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, SponsoringApiService, SponsoringService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiSpokeService, SupportedMigrationTokens, SwapService, SwapsApiService, TOKEN_LOGO_BASE_URL, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calcOpReturnOutputVbytes, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, classifySponsorError, concentratedLiquidityConfig, connectionAbi, consoleLogger, convertTransactionInstructionToRaw, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, erc20Abi, erc4626Abi, estimateBitcoinTxSize, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSpokeHook, getSpokeHooks, getStagingSolverTokens, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hederaSupportedTokens, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isBackendHttpError, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexApproveError, isDexCreateIntentError, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isHookSupportedToken, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isLeverageYieldAllowanceCheckError, isLeverageYieldApproveError, isLeverageYieldCreateIntentError, isLeverageYieldError, isLeverageYieldLookupError, isLeverageYieldPostExecutionError, isLeverageYieldSwapError, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isSponsoringConfigError, isSponsoringLookupError, isSponsoringOrchestrationError, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidWalletProviderForChainKey, kaiaSupportedTokens, leverageYieldConfig, leverageYieldInvariant, leverageYieldVaults, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, mergeSodaxConfig, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, noopAnalytics, normalize, normalizeBN, normalizePsbtToBase64, normalizeSignatureToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, resolveAnalytics, resolveLogger, retry, reverseEncodeAddress, serializeAddressData, silentLogger, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, spokeHooks, sponsoringInvariant, stacksSupportedTokens, stagingSwapSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, tokenLogo, tokenLogoSlug, uiPoolDataAbi, universalRouterAbi, unknownFailed, usesBip322MessageSigning, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };