@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.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 v4 = 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 v4__namespace = /*#__PURE__*/_interopNamespace(v4);
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, v6] of Object.entries(value)) {
126
+ out[key] = sanitizeValue(v6, 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((v6) => sanitizeValue(v6, 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, v6]) => [sanitizeValue(k, depth + 1), sanitizeValue(v6, 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((v6) => sanitizeValue(v6, 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(v6) {
156
156
  try {
157
- return String(v4);
157
+ return String(v6);
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
 
@@ -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,6 +4260,17 @@ 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
4261
4275
  function isSupportedBitcoinAddressType(addressType) {
4262
4276
  return BTC_ADDRESS_TYPES.includes(addressType);
@@ -4417,7 +4431,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4417
4431
  }
4418
4432
 
4419
4433
  // ../types/dist/index.js
4420
- var CONFIG_VERSION = 220;
4434
+ var CONFIG_VERSION = 221;
4421
4435
  function isEvmSpokeChainConfig(value) {
4422
4436
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
4423
4437
  }
@@ -14324,7 +14338,7 @@ function mergeSodaxConfig(base2, override) {
14324
14338
  }
14325
14339
  function encodeContractCalls(calls) {
14326
14340
  return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
14327
- calls.map((v4) => [v4.address, v4.value, v4.data])
14341
+ calls.map((v6) => [v6.address, v6.value, v6.data])
14328
14342
  ]);
14329
14343
  }
14330
14344
  async function waitForTransactionReceipt(hash, provider) {
@@ -16947,22 +16961,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16947
16961
  const byte0 = Uint8Array.of(0);
16948
16962
  const byte1 = Uint8Array.of(1);
16949
16963
  const _maxDrbgIters = 1e3;
16950
- let v4 = u8n(hashLen);
16964
+ let v6 = u8n(hashLen);
16951
16965
  let k = u8n(hashLen);
16952
16966
  let i = 0;
16953
16967
  const reset = () => {
16954
- v4.fill(1);
16968
+ v6.fill(1);
16955
16969
  k.fill(0);
16956
16970
  i = 0;
16957
16971
  };
16958
- const h = (...msgs) => hmacFn(k, concatBytes(v4, ...msgs));
16972
+ const h = (...msgs) => hmacFn(k, concatBytes(v6, ...msgs));
16959
16973
  const reseed = (seed = NULL) => {
16960
16974
  k = h(byte0, seed);
16961
- v4 = h();
16975
+ v6 = h();
16962
16976
  if (seed.length === 0)
16963
16977
  return;
16964
16978
  k = h(byte1, seed);
16965
- v4 = h();
16979
+ v6 = h();
16966
16980
  };
16967
16981
  const gen = () => {
16968
16982
  if (i++ >= _maxDrbgIters)
@@ -16970,10 +16984,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16970
16984
  let len = 0;
16971
16985
  const out = [];
16972
16986
  while (len < qByteLen) {
16973
- v4 = h();
16974
- const sl = v4.slice();
16987
+ v6 = h();
16988
+ const sl = v6.slice();
16975
16989
  out.push(sl);
16976
- len += v4.length;
16990
+ len += v6.length;
16977
16991
  }
16978
16992
  return concatBytes(...out);
16979
16993
  };
@@ -16988,18 +17002,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16988
17002
  };
16989
17003
  return genUntil;
16990
17004
  }
16991
- function validateObject(object2, fields = {}, optFields = {}) {
16992
- if (!object2 || typeof object2 !== "object")
17005
+ function validateObject(object3, fields = {}, optFields = {}) {
17006
+ if (!object3 || typeof object3 !== "object")
16993
17007
  throw new Error("expected valid options object");
16994
17008
  function checkField(fieldName, expectedType, isOpt) {
16995
- const val = object2[fieldName];
17009
+ const val = object3[fieldName];
16996
17010
  if (isOpt && val === void 0)
16997
17011
  return;
16998
17012
  const current = typeof val;
16999
17013
  if (current !== expectedType || val === null)
17000
17014
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
17001
17015
  }
17002
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v4]) => checkField(k, v4, isOpt));
17016
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v6]) => checkField(k, v6, isOpt));
17003
17017
  iter(fields, false);
17004
17018
  iter(optFields, true);
17005
17019
  }
@@ -17038,12 +17052,12 @@ function pow2(x, power, modulo) {
17038
17052
  }
17039
17053
  return res;
17040
17054
  }
17041
- function invert(number2, modulo) {
17042
- if (number2 === _0n2)
17055
+ function invert(number3, modulo) {
17056
+ if (number3 === _0n2)
17043
17057
  throw new Error("invert: expected non-zero number");
17044
17058
  if (modulo <= _0n2)
17045
17059
  throw new Error("invert: expected positive modulus, got " + modulo);
17046
- let a = mod(number2, modulo);
17060
+ let a = mod(number3, modulo);
17047
17061
  let b = modulo;
17048
17062
  let x = _0n2, u = _1n2;
17049
17063
  while (a !== _0n2) {
@@ -17070,9 +17084,9 @@ function sqrt3mod4(Fp, n) {
17070
17084
  function sqrt5mod8(Fp, n) {
17071
17085
  const p5div8 = (Fp.ORDER - _5n) / _8n;
17072
17086
  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);
17087
+ const v6 = Fp.pow(n2, p5div8);
17088
+ const nv = Fp.mul(n, v6);
17089
+ const i = Fp.mul(Fp.mul(nv, _2n), v6);
17076
17090
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
17077
17091
  assertIsSquare(Fp, root, n);
17078
17092
  return root;
@@ -17654,9 +17668,9 @@ function edwards(params, extraOpts = {}) {
17654
17668
  validateObject(extraOpts, {}, { uvRatio: "function" });
17655
17669
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
17656
17670
  const modP = (n) => Fp.create(n);
17657
- const uvRatio2 = extraOpts.uvRatio || ((u, v4) => {
17671
+ const uvRatio2 = extraOpts.uvRatio || ((u, v6) => {
17658
17672
  try {
17659
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v4)) };
17673
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v6)) };
17660
17674
  } catch (e) {
17661
17675
  return { isValid: false, value: _0n4 };
17662
17676
  }
@@ -17752,8 +17766,8 @@ function edwards(params, extraOpts = {}) {
17752
17766
  aInRange("point.y", y, _0n4, max);
17753
17767
  const y2 = modP(y * y);
17754
17768
  const u = modP(y2 - _1n4);
17755
- const v4 = modP(d * y2 - a);
17756
- let { isValid, value: x } = uvRatio2(u, v4);
17769
+ const v6 = modP(d * y2 - a);
17770
+ let { isValid, value: x } = uvRatio2(u, v6);
17757
17771
  if (!isValid)
17758
17772
  throw new Error("bad point: invalid y coordinate");
17759
17773
  const isXOdd = (x & _1n4) === _1n4;
@@ -18093,13 +18107,13 @@ function adjustScalarBytes(bytes) {
18093
18107
  return bytes;
18094
18108
  }
18095
18109
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
18096
- function uvRatio(u, v4) {
18110
+ function uvRatio(u, v6) {
18097
18111
  const P = ed25519_CURVE_p;
18098
- const v32 = mod(v4 * v4 * v4, P);
18099
- const v7 = mod(v32 * v32 * v4, P);
18112
+ const v32 = mod(v6 * v6 * v6, P);
18113
+ const v7 = mod(v32 * v32 * v6, P);
18100
18114
  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
18101
18115
  let x = mod(u * v32 * pow, P);
18102
- const vx2 = mod(v4 * x * x, P);
18116
+ const vx2 = mod(v6 * x * x, P);
18103
18117
  const root1 = x;
18104
18118
  const root2 = mod(x * ED25519_SQRT_M1, P);
18105
18119
  const useRoot1 = vx2 === u;
@@ -18430,7 +18444,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
18430
18444
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
18431
18445
  }
18432
18446
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
18433
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18447
+ const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18434
18448
  const num = BigInt(numSeats);
18435
18449
  const stakesSum = stakes.reduce((a, b) => a + b);
18436
18450
  if (stakesSum < num) {
@@ -18459,7 +18473,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
18459
18473
  if (minimumStakeRatio.length != 2) {
18460
18474
  throw Error("minimumStakeRatio should have 2 elements");
18461
18475
  }
18462
- const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18476
+ const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18463
18477
  const stakesSum = stakes.reduce((a, b) => a + b);
18464
18478
  if (validators.length < maxNumberOfSeats) {
18465
18479
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -18631,10 +18645,10 @@ var DER = {
18631
18645
  if (length < 128)
18632
18646
  throw new E("tlv.decode(long): not minimal encoding");
18633
18647
  }
18634
- const v4 = data.subarray(pos, pos + length);
18635
- if (v4.length !== length)
18648
+ const v6 = data.subarray(pos, pos + length);
18649
+ if (v6.length !== length)
18636
18650
  throw new E("tlv.decode: wrong value length");
18637
- return { v: v4, l: data.subarray(pos + length) };
18651
+ return { v: v6, l: data.subarray(pos + length) };
18638
18652
  }
18639
18653
  },
18640
18654
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -19202,9 +19216,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19202
19216
  extraEntropy: false
19203
19217
  };
19204
19218
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
19205
- function isBiggerThanHalfOrder(number2) {
19219
+ function isBiggerThanHalfOrder(number3) {
19206
19220
  const HALF = CURVE_ORDER >> _1n6;
19207
- return number2 > HALF;
19221
+ return number3 > HALF;
19208
19222
  }
19209
19223
  function validateRS(title, num) {
19210
19224
  if (!Fn.isValidNot0(num))
@@ -19387,8 +19401,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19387
19401
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
19388
19402
  if (R.is0())
19389
19403
  return false;
19390
- const v4 = Fn.create(R.x);
19391
- return v4 === r;
19404
+ const v6 = Fn.create(R.x);
19405
+ return v6 === r;
19392
19406
  } catch (e) {
19393
19407
  return false;
19394
19408
  }
@@ -23526,6 +23540,7 @@ var CustomStellarAccount = class {
23526
23540
  this.sequenceNumber = this.startingSequenceNumber;
23527
23541
  }
23528
23542
  };
23543
+ var TRUSTLINE_TX_TIMEOUT_SECONDS = 300;
23529
23544
  var StellarSpokeService = class {
23530
23545
  config;
23531
23546
  chainConfig;
@@ -23763,6 +23778,17 @@ var StellarSpokeService = class {
23763
23778
  throw error;
23764
23779
  }
23765
23780
  }
23781
+ /**
23782
+ * Whether a token requires a trustline. Native XLM and legacy bnUSD are
23783
+ * exempt and therefore need no subentry reserve.
23784
+ */
23785
+ requiresTrustline(token) {
23786
+ const stellarChainConfig = this.chainConfig;
23787
+ const normalized = token.toLowerCase();
23788
+ if (normalized === stellarChainConfig.nativeToken.toLowerCase()) return false;
23789
+ const legacyBnUSD = stellarChainConfig.supportedTokens.legacybnUSD;
23790
+ return legacyBnUSD === void 0 || normalized !== legacyBnUSD.address.toLowerCase();
23791
+ }
23766
23792
  /**
23767
23793
  * Check if the user has sufficient trustline established for the token.
23768
23794
  * @param token - The token address to check the trustline for.
@@ -23772,8 +23798,7 @@ var StellarSpokeService = class {
23772
23798
  */
23773
23799
  async hasSufficientTrustline(token, amount, walletAddress) {
23774
23800
  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()) {
23801
+ if (!this.requiresTrustline(token)) {
23777
23802
  return true;
23778
23803
  }
23779
23804
  const trustlineConfig = stellarChainConfig.trustlineConfigs.find(
@@ -23822,7 +23847,7 @@ var StellarSpokeService = class {
23822
23847
  stellarSdk.Operation.changeTrust({
23823
23848
  asset: new stellarSdk.Asset(asset?.assetCode, asset?.assetIssuer)
23824
23849
  })
23825
- ).setTimeout(this.maxTimeoutMs).build();
23850
+ ).setTimeout(TRUSTLINE_TX_TIMEOUT_SECONDS).build();
23826
23851
  if (params.raw) {
23827
23852
  const transactionXdr = transaction.toXDR();
23828
23853
  return {
@@ -29821,10 +29846,40 @@ var MigrationService = class {
29821
29846
  };
29822
29847
 
29823
29848
  // src/backendApi/api-utils.ts
29849
+ var BackendHttpError = class extends Error {
29850
+ status;
29851
+ bodyText;
29852
+ /** Parsed JSON, or `undefined` for empty or malformed bodies. */
29853
+ body;
29854
+ constructor(status, bodyText) {
29855
+ super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
29856
+ this.name = "BackendHttpError";
29857
+ this.status = status;
29858
+ this.bodyText = bodyText;
29859
+ this.body = safeJsonParse(bodyText);
29860
+ }
29861
+ };
29862
+ function isBackendHttpError(error) {
29863
+ if (error instanceof BackendHttpError) return true;
29864
+ return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
29865
+ }
29866
+ function safeJsonParse(text) {
29867
+ if (text.length === 0) return void 0;
29868
+ try {
29869
+ return JSON.parse(text);
29870
+ } catch {
29871
+ return void 0;
29872
+ }
29873
+ }
29874
+ function trimTrailingSlashes(baseURL) {
29875
+ let end = baseURL.length;
29876
+ while (end > 0 && baseURL[end - 1] === "/") end -= 1;
29877
+ return baseURL.slice(0, end);
29878
+ }
29824
29879
  async function makeRequest(params) {
29825
29880
  const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
29826
29881
  const baseURL = overrideConfig.baseURL || config.baseURL || "";
29827
- const url = `${baseURL}${endpoint}`;
29882
+ const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
29828
29883
  const headers = { ...config.headers, ...overrideConfig.headers };
29829
29884
  const controller = new AbortController();
29830
29885
  const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
@@ -29839,7 +29894,7 @@ async function makeRequest(params) {
29839
29894
  clearTimeout(timeoutId);
29840
29895
  if (!response.ok) {
29841
29896
  const errorText = await response.text();
29842
- throw new Error("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${response.status}: ${errorText}`) });
29897
+ throw new BackendHttpError(response.status, errorText);
29843
29898
  }
29844
29899
  const data = await response.json();
29845
29900
  return data;
@@ -29856,6 +29911,32 @@ async function makeRequest(params) {
29856
29911
  throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
29857
29912
  }
29858
29913
  }
29914
+ function resolveRequestConfig(config, defaults) {
29915
+ const { baseURL, timeout, headers, ...rest } = config;
29916
+ return {
29917
+ ...rest,
29918
+ baseURL: baseURL || defaults.baseURL,
29919
+ timeout: timeout ?? defaults.timeout,
29920
+ headers: { ...defaults.headers, ...headers }
29921
+ };
29922
+ }
29923
+ function toExternalApiError(params) {
29924
+ const { api, feature, endpoint, error } = params;
29925
+ const context = { api, endpoint };
29926
+ if (isBackendHttpError(error)) context.status = error.status;
29927
+ return new SodaxError(
29928
+ "EXTERNAL_API_ERROR",
29929
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
29930
+ { feature, cause: error, context }
29931
+ );
29932
+ }
29933
+ function toInvalidResponseShapeError(params) {
29934
+ const { api, feature, endpoint, issues } = params;
29935
+ return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
29936
+ feature,
29937
+ context: { api, endpoint, reason: "invalid_response_shape", issues }
29938
+ });
29939
+ }
29859
29940
  var SwapsApiService = class _SwapsApiService {
29860
29941
  // Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
29861
29942
  // `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
@@ -29901,7 +29982,7 @@ var SwapsApiService = class _SwapsApiService {
29901
29982
  if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
29902
29983
  context.reason = "invalid_response_shape";
29903
29984
  const issues = error.context.issues;
29904
- context.issues = issues instanceof v2__namespace.ValiError ? v2__namespace.flatten(issues.issues) : issues;
29985
+ context.issues = issues instanceof v4__namespace.ValiError ? v4__namespace.flatten(issues.issues) : issues;
29905
29986
  }
29906
29987
  if (error.context.status !== void 0) context.status = error.context.status;
29907
29988
  }
@@ -30062,10 +30143,98 @@ var SwapsApiService = class _SwapsApiService {
30062
30143
  return this.config.baseURL;
30063
30144
  }
30064
30145
  };
30146
+ var StellarSponsorConfigSchema = v4__namespace.object({
30147
+ sponsorAccount: v4__namespace.string(),
30148
+ networkPassphrase: v4__namespace.string(),
30149
+ minTotalFeeStroops: v4__namespace.string(),
30150
+ maxTotalFeeStroops: v4__namespace.string(),
30151
+ operationCount: v4__namespace.number(),
30152
+ minPerOperationFeeStroops: v4__namespace.string(),
30153
+ maxPerOperationFeeStroops: v4__namespace.string(),
30154
+ recommendedPerOperationFeeStroops: v4__namespace.string(),
30155
+ maxTimeboundSeconds: v4__namespace.number(),
30156
+ requiredStartingBalance: v4__namespace.string()
30157
+ });
30158
+ var StellarSponsoredAccountResponseSchema = v4__namespace.variant("alreadyActive", [
30159
+ v4__namespace.object({ hash: v4__namespace.string(), alreadyActive: v4__namespace.literal(false) }),
30160
+ v4__namespace.object({ hash: v4__namespace.null(), alreadyActive: v4__namespace.literal(true) })
30161
+ ]);
30162
+
30163
+ // src/backendApi/SponsoringApiService.ts
30164
+ var SponsoringApiService = class {
30165
+ config;
30166
+ headers;
30167
+ logger;
30168
+ constructor(config, logger = consoleLogger) {
30169
+ this.config = config;
30170
+ this.headers = {
30171
+ ...config.apiKey !== void 0 ? { "x-api-key": config.apiKey } : {},
30172
+ ...config.headers
30173
+ };
30174
+ this.logger = logger;
30175
+ }
30176
+ /**
30177
+ * Validate a response while preserving HTTP failures on `error.cause` for
30178
+ * sponsor-error classification.
30179
+ */
30180
+ async request(endpoint, config, schema) {
30181
+ try {
30182
+ const raw = await makeRequest({
30183
+ endpoint,
30184
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30185
+ logger: this.logger,
30186
+ serviceLabel: "SponsoringApiService"
30187
+ });
30188
+ const parsed = v4__namespace.safeParse(schema, raw);
30189
+ if (!parsed.success) {
30190
+ return {
30191
+ ok: false,
30192
+ error: toInvalidResponseShapeError({
30193
+ api: "sponsoring",
30194
+ feature: "backend",
30195
+ endpoint,
30196
+ issues: v4__namespace.flatten(parsed.issues)
30197
+ })
30198
+ };
30199
+ }
30200
+ return { ok: true, value: parsed.output };
30201
+ } catch (error) {
30202
+ return { ok: false, error: toExternalApiError({ api: "sponsoring", feature: "backend", endpoint, error }) };
30203
+ }
30204
+ }
30205
+ /** Fetch build parameters, including the rotatable sponsor account. */
30206
+ async getStellarSponsorConfig(config) {
30207
+ return this.request(
30208
+ `${SPONSORING_API_STELLAR_BASE_PATH}/config`,
30209
+ { ...config, method: "GET" },
30210
+ StellarSponsorConfigSchema
30211
+ );
30212
+ }
30213
+ /**
30214
+ * Submit a client-signed transaction for sponsor co-signing. An
30215
+ * `alreadyActive` response is also successful.
30216
+ */
30217
+ async createStellarSponsoredAccount(body, config) {
30218
+ return this.request(
30219
+ `${SPONSORING_API_STELLAR_BASE_PATH}/accounts`,
30220
+ // The endpoint rejects extra fields.
30221
+ { ...config, method: "POST", body: JSON.stringify({ data: body.data }) },
30222
+ StellarSponsoredAccountResponseSchema
30223
+ );
30224
+ }
30225
+ setHeaders(headers) {
30226
+ Object.entries(headers).forEach(([key, value]) => {
30227
+ this.headers[key] = value;
30228
+ });
30229
+ }
30230
+ getBaseURL() {
30231
+ return this.config.baseURL;
30232
+ }
30233
+ };
30065
30234
 
30066
30235
  // src/backendApi/apiConfig.ts
30067
- function isCustomApiConfig(config) {
30068
- return "baseApiConfig" in config || "swapsApiConfig" in config;
30236
+ function flatLayer({ baseURL, timeout, headers }) {
30237
+ return { baseURL, timeout, headers };
30069
30238
  }
30070
30239
  function layerConfigs(...slices) {
30071
30240
  return slices.reduce(
@@ -30082,154 +30251,168 @@ function layerConfigs(...slices) {
30082
30251
  );
30083
30252
  }
30084
30253
  function resolveBaseApiConfig(config) {
30085
- if (isCustomApiConfig(config)) {
30086
- return layerConfigs(config.baseApiConfig);
30087
- }
30088
- return layerConfigs(config);
30254
+ const layers = config;
30255
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig);
30089
30256
  }
30090
30257
  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(),
30258
+ const layers = config;
30259
+ return layerConfigs(flatLayer(layers), layers.baseApiConfig, layers.swapsApiConfig);
30260
+ }
30261
+ function isHttpUrl(value) {
30262
+ return value.startsWith("http://") || value.startsWith("https://");
30263
+ }
30264
+ function normalizeBaseURL(baseURL) {
30265
+ const trimmed = trimTrailingSlashes(baseURL);
30266
+ return isHttpUrl(trimmed) ? trimmed : baseURL;
30267
+ }
30268
+ function resolveSponsoringApiConfig(config) {
30269
+ const layers = config;
30270
+ const slice = layers.sponsoringApiConfig;
30271
+ return {
30272
+ baseURL: normalizeBaseURL(slice?.baseURL ?? DEFAULT_SPONSORING_API_ENDPOINT),
30273
+ timeout: slice?.timeout ?? resolveBaseApiConfig(config).timeout,
30274
+ headers: { ...DEFAULT_BACKEND_API_HEADERS, ...slice?.headers },
30275
+ ...slice?.apiKey === void 0 ? {} : { apiKey: slice.apiKey }
30276
+ };
30277
+ }
30278
+ var ChainKeySchema = v4__namespace.custom((input) => typeof input === "string");
30279
+ var SpokeChainKeySchema = v4__namespace.custom((input) => typeof input === "string");
30280
+ var AddressSchema = v4__namespace.custom((input) => typeof input === "string");
30281
+ var XTokenSchema = v4__namespace.object({
30282
+ symbol: v4__namespace.string(),
30283
+ name: v4__namespace.string(),
30284
+ decimals: v4__namespace.number(),
30285
+ address: v4__namespace.string(),
30104
30286
  chainKey: ChainKeySchema,
30105
30287
  hubAsset: AddressSchema,
30106
30288
  vault: AddressSchema,
30107
- access: v2__namespace.optional(v2__namespace.picklist(["withdrawOnly", "depositOnly"]))
30289
+ access: v4__namespace.optional(v4__namespace.picklist(["withdrawOnly", "depositOnly"]))
30108
30290
  });
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()
30291
+ var IntentStructSchema = v4__namespace.object({
30292
+ intentId: v4__namespace.string(),
30293
+ creator: v4__namespace.string(),
30294
+ inputToken: v4__namespace.string(),
30295
+ outputToken: v4__namespace.string(),
30296
+ inputAmount: v4__namespace.string(),
30297
+ minOutputAmount: v4__namespace.string(),
30298
+ deadline: v4__namespace.string(),
30299
+ allowPartialFill: v4__namespace.boolean(),
30300
+ srcChain: v4__namespace.number(),
30301
+ dstChain: v4__namespace.number(),
30302
+ srcAddress: v4__namespace.string(),
30303
+ dstAddress: v4__namespace.string(),
30304
+ solver: v4__namespace.string(),
30305
+ data: v4__namespace.string()
30124
30306
  });
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(),
30307
+ var IntentResponseSchema = v4__namespace.object({
30308
+ intentHash: v4__namespace.string(),
30309
+ txHash: v4__namespace.string(),
30310
+ logIndex: v4__namespace.number(),
30311
+ chainId: v4__namespace.number(),
30312
+ blockNumber: v4__namespace.number(),
30313
+ open: v4__namespace.boolean(),
30132
30314
  intent: IntentStructSchema,
30133
- events: v2__namespace.array(v2__namespace.unknown())
30315
+ events: v4__namespace.array(v4__namespace.unknown())
30134
30316
  });
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)
30317
+ var UserIntentsResponseSchema = v4__namespace.object({
30318
+ total: v4__namespace.number(),
30319
+ offset: v4__namespace.number(),
30320
+ limit: v4__namespace.number(),
30321
+ items: v4__namespace.array(IntentResponseSchema)
30140
30322
  });
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()
30323
+ var OrderbookResponseSchema = v4__namespace.object({
30324
+ total: v4__namespace.number(),
30325
+ data: v4__namespace.array(
30326
+ v4__namespace.object({
30327
+ intentState: v4__namespace.object({
30328
+ exists: v4__namespace.boolean(),
30329
+ remainingInput: v4__namespace.string(),
30330
+ receivedOutput: v4__namespace.string(),
30331
+ pendingPayment: v4__namespace.boolean()
30150
30332
  }),
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()
30333
+ intentData: v4__namespace.object({
30334
+ intentId: v4__namespace.string(),
30335
+ creator: v4__namespace.string(),
30336
+ inputToken: v4__namespace.string(),
30337
+ outputToken: v4__namespace.string(),
30338
+ inputAmount: v4__namespace.string(),
30339
+ minOutputAmount: v4__namespace.string(),
30340
+ deadline: v4__namespace.string(),
30341
+ allowPartialFill: v4__namespace.boolean(),
30342
+ srcChain: v4__namespace.number(),
30343
+ dstChain: v4__namespace.number(),
30344
+ srcAddress: v4__namespace.string(),
30345
+ dstAddress: v4__namespace.string(),
30346
+ solver: v4__namespace.string(),
30347
+ data: v4__namespace.string(),
30348
+ intentHash: v4__namespace.string(),
30349
+ txHash: v4__namespace.string(),
30350
+ blockNumber: v4__namespace.number()
30169
30351
  })
30170
30352
  })
30171
30353
  )
30172
30354
  });
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()
30355
+ var MoneyMarketPositionSchema = v4__namespace.object({
30356
+ userAddress: v4__namespace.string(),
30357
+ positions: v4__namespace.array(
30358
+ v4__namespace.object({
30359
+ reserveAddress: v4__namespace.string(),
30360
+ aTokenAddress: v4__namespace.string(),
30361
+ variableDebtTokenAddress: v4__namespace.string(),
30362
+ aTokenBalance: v4__namespace.string(),
30363
+ variableDebtTokenBalance: v4__namespace.string(),
30364
+ blockNumber: v4__namespace.number()
30183
30365
  })
30184
30366
  )
30185
30367
  });
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()
30368
+ var MoneyMarketAssetSchema = v4__namespace.object({
30369
+ reserveAddress: v4__namespace.string(),
30370
+ aTokenAddress: v4__namespace.string(),
30371
+ totalATokenBalance: v4__namespace.string(),
30372
+ variableDebtTokenAddress: v4__namespace.string(),
30373
+ totalVariableDebtTokenBalance: v4__namespace.string(),
30374
+ liquidityRate: v4__namespace.string(),
30375
+ symbol: v4__namespace.string(),
30376
+ totalSuppliers: v4__namespace.number(),
30377
+ totalBorrowers: v4__namespace.number(),
30378
+ variableBorrowRate: v4__namespace.string(),
30379
+ stableBorrowRate: v4__namespace.string(),
30380
+ liquidityIndex: v4__namespace.string(),
30381
+ variableBorrowIndex: v4__namespace.string(),
30382
+ blockNumber: v4__namespace.number()
30201
30383
  });
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()
30384
+ var MoneyMarketAssetsSchema = v4__namespace.array(MoneyMarketAssetSchema);
30385
+ var MoneyMarketAssetBorrowersSchema = v4__namespace.object({
30386
+ borrowers: v4__namespace.array(v4__namespace.string()),
30387
+ total: v4__namespace.number(),
30388
+ offset: v4__namespace.number(),
30389
+ limit: v4__namespace.number()
30208
30390
  });
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()
30391
+ var MoneyMarketAssetSuppliersSchema = v4__namespace.object({
30392
+ suppliers: v4__namespace.array(v4__namespace.string()),
30393
+ total: v4__namespace.number(),
30394
+ offset: v4__namespace.number(),
30395
+ limit: v4__namespace.number()
30214
30396
  });
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()
30397
+ var MoneyMarketBorrowersSchema = v4__namespace.object({
30398
+ borrowers: v4__namespace.array(v4__namespace.string()),
30399
+ total: v4__namespace.number(),
30400
+ offset: v4__namespace.number(),
30401
+ limit: v4__namespace.number()
30220
30402
  });
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)))
30403
+ var GetChainsResponseSchema = v4__namespace.array(SpokeChainKeySchema);
30404
+ var TokensByChainMapSchema = v4__namespace.custom(
30405
+ (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v4__namespace.is(XTokenSchema, t)))
30224
30406
  );
30225
- var TokensListSchema = v2__namespace.array(XTokenSchema);
30226
- var ReserveAssetsSchema = v2__namespace.array(AddressSchema);
30407
+ var TokensListSchema = v4__namespace.array(XTokenSchema);
30408
+ var ReserveAssetsSchema = v4__namespace.array(AddressSchema);
30227
30409
 
30228
30410
  // src/backendApi/BackendApiService.ts
30229
30411
  var BackendApiService = class {
30230
30412
  // sub-services exposing domain-specific APIs
30231
30413
  swaps;
30232
- // resolved base-API slice of the ApiConfig union (flat config, or its `baseApiConfig`)
30414
+ sponsoring;
30415
+ // resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on top
30233
30416
  config;
30234
30417
  headers;
30235
30418
  logger;
@@ -30238,37 +30421,7 @@ var BackendApiService = class {
30238
30421
  this.headers = { ...this.config.headers };
30239
30422
  this.logger = logger;
30240
30423
  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
- );
30424
+ this.sponsoring = new SponsoringApiService(resolveSponsoringApiConfig(config), this.logger);
30272
30425
  }
30273
30426
  /**
30274
30427
  * Issue a request and validate the JSON body against `schema`, wrapping the result in `Result<T>`.
@@ -30281,23 +30434,25 @@ var BackendApiService = class {
30281
30434
  try {
30282
30435
  const raw = await makeRequest({
30283
30436
  endpoint,
30284
- config: this.resolveRequestConfig(config),
30437
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30285
30438
  logger: this.logger,
30286
30439
  serviceLabel: "BackendApiService"
30287
30440
  });
30288
- const parsed = v2__namespace.safeParse(schema, raw);
30441
+ const parsed = v4__namespace.safeParse(schema, raw);
30289
30442
  if (!parsed.success) {
30290
30443
  return {
30291
30444
  ok: false,
30292
- error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from backend API for ${endpoint}`, {
30445
+ error: toInvalidResponseShapeError({
30446
+ api: "backend",
30293
30447
  feature: "backend",
30294
- context: { api: "backend", endpoint, reason: "invalid_response_shape", issues: v2__namespace.flatten(parsed.issues) }
30448
+ endpoint,
30449
+ issues: v4__namespace.flatten(parsed.issues)
30295
30450
  })
30296
30451
  };
30297
30452
  }
30298
30453
  return { ok: true, value: parsed.output };
30299
30454
  } catch (error) {
30300
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30455
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30301
30456
  }
30302
30457
  }
30303
30458
  /**
@@ -30311,13 +30466,13 @@ var BackendApiService = class {
30311
30466
  try {
30312
30467
  const value = await makeRequest({
30313
30468
  endpoint,
30314
- config: this.resolveRequestConfig(config),
30469
+ config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
30315
30470
  logger: this.logger,
30316
30471
  serviceLabel: "BackendApiService"
30317
30472
  });
30318
30473
  return { ok: true, value };
30319
30474
  } catch (error) {
30320
- return { ok: false, error: this.toExternalApiError(endpoint, error) };
30475
+ return { ok: false, error: toExternalApiError({ api: "backend", feature: "backend", endpoint, error }) };
30321
30476
  }
30322
30477
  }
30323
30478
  // Intent endpoints
@@ -30616,9 +30771,8 @@ var BackendApiService = class {
30616
30771
  * without constructing a new service instance. Existing header keys are
30617
30772
  * overwritten; keys absent from `headers` are preserved.
30618
30773
  *
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.*`.
30774
+ * Headers also reach `swaps`, which shares this origin, but never `sponsoring`,
30775
+ * whose separate origin must not receive base-API credentials.
30622
30776
  *
30623
30777
  * @param headers - Key-value pairs to add or overwrite in the default headers.
30624
30778
  */
@@ -39336,7 +39490,7 @@ var LeverageYieldService = class {
39336
39490
  }
39337
39491
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
39338
39492
  getVault(name) {
39339
- return this.listVaults().find((v4) => v4.name === name);
39493
+ return this.listVaults().find((v6) => v6.name === name);
39340
39494
  }
39341
39495
  /**
39342
39496
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -39344,7 +39498,7 @@ var LeverageYieldService = class {
39344
39498
  */
39345
39499
  getVaultByAddress(address) {
39346
39500
  const normalized = address.toLowerCase();
39347
- return this.listVaults().find((v4) => v4.vault.toLowerCase() === normalized);
39501
+ return this.listVaults().find((v6) => v6.vault.toLowerCase() === normalized);
39348
39502
  }
39349
39503
  /**
39350
39504
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -40126,6 +40280,566 @@ var LeverageYieldService = class {
40126
40280
  }
40127
40281
  };
40128
40282
 
40283
+ // src/sponsoring/errors.ts
40284
+ var sponsoringInvariant = createInvariant("sponsoring");
40285
+ var ORCHESTRATION_CODES3 = /* @__PURE__ */ new Set([
40286
+ "USER_REJECTED",
40287
+ "VALIDATION_FAILED",
40288
+ "INTENT_CREATION_FAILED",
40289
+ "LOOKUP_FAILED",
40290
+ "EXTERNAL_API_ERROR",
40291
+ "EXECUTION_FAILED",
40292
+ "UNKNOWN"
40293
+ ]);
40294
+ var CONFIG_CODES = /* @__PURE__ */ new Set([
40295
+ "EXTERNAL_API_ERROR",
40296
+ "VALIDATION_FAILED",
40297
+ "UNKNOWN"
40298
+ ]);
40299
+ var isSponsoringOrchestrationError = isCodeMember(ORCHESTRATION_CODES3);
40300
+ var isSponsoringConfigError = isCodeMember(CONFIG_CODES);
40301
+ var isSponsoringLookupError = isCodeMember(LOOKUP_CODES);
40302
+ var DOMAIN_CODES = new Set(SPONSORING_API_ERROR_CODES);
40303
+ function toDomainCode(value) {
40304
+ return typeof value === "string" && DOMAIN_CODES.has(value) ? value : void 0;
40305
+ }
40306
+ function readErrorBody(body) {
40307
+ if (typeof body !== "object" || body === null) return {};
40308
+ const record = body;
40309
+ const retryAfterSeconds = typeof record.retryAfterSeconds === "number" && Number.isFinite(record.retryAfterSeconds) && record.retryAfterSeconds > 0 ? record.retryAfterSeconds : void 0;
40310
+ const sponsorSequence = typeof record.sponsorSequence === "string" && /^\d+$/.test(record.sponsorSequence) ? record.sponsorSequence : void 0;
40311
+ return {
40312
+ message: typeof record.message === "string" ? record.message : void 0,
40313
+ code: toDomainCode(record.error),
40314
+ retryAfterSeconds,
40315
+ sponsorSequence
40316
+ };
40317
+ }
40318
+ var ACTION_POLICY = {
40319
+ fixIntegration: { retryable: false, requiresNewSignature: false },
40320
+ checkApiKey: { retryable: false, requiresNewSignature: false },
40321
+ rebuildAndResign: { retryable: true, requiresNewSignature: true },
40322
+ retrySameRequest: { retryable: true, requiresNewSignature: false },
40323
+ backoff: { retryable: true, requiresNewSignature: false },
40324
+ contactOperator: { retryable: false, requiresNewSignature: false },
40325
+ abort: { retryable: false, requiresNewSignature: false }
40326
+ };
40327
+ function policy(action) {
40328
+ return { action, ...ACTION_POLICY[action] };
40329
+ }
40330
+ function classifySponsorError(error) {
40331
+ const cause = error.cause;
40332
+ const http3 = isBackendHttpError(cause) ? cause : void 0;
40333
+ const { message: serverMessage, code, retryAfterSeconds, sponsorSequence } = readErrorBody(http3?.body);
40334
+ const message = serverMessage ?? error.message;
40335
+ const status = http3?.status;
40336
+ if (status === void 0) {
40337
+ return { ...policy("backoff"), message };
40338
+ }
40339
+ const base2 = { status, code, retryAfterSeconds, sponsorSequence, message };
40340
+ switch (status) {
40341
+ case 400:
40342
+ return { ...base2, ...policy("fixIntegration") };
40343
+ case 401:
40344
+ return { ...base2, ...policy("checkApiKey") };
40345
+ case 409:
40346
+ return { ...base2, ...policy("rebuildAndResign") };
40347
+ case 422:
40348
+ return { ...base2, ...policy("abort") };
40349
+ case 429:
40350
+ return { ...base2, ...policy("backoff") };
40351
+ case 500:
40352
+ return { ...base2, ...policy("contactOperator") };
40353
+ case 503:
40354
+ if (code === "SPONSOR_BUDGET_EXHAUSTED") {
40355
+ return { ...base2, ...policy("contactOperator") };
40356
+ }
40357
+ if (code === "HORIZON_UNAVAILABLE") {
40358
+ return { ...base2, ...policy("retrySameRequest") };
40359
+ }
40360
+ return { ...base2, ...policy("backoff") };
40361
+ default:
40362
+ return { ...base2, ...policy("abort") };
40363
+ }
40364
+ }
40365
+ var SPONSORED_CREATE_OP_COUNT = 3n;
40366
+ var SPONSOR_TIMEBOUND_SECONDS = 300;
40367
+ function parseStroops(value, field) {
40368
+ try {
40369
+ return BigInt(value);
40370
+ } catch {
40371
+ sponsoringInvariant(false, `sponsor config ${field} is not a valid integer: "${value}"`, { field });
40372
+ }
40373
+ }
40374
+ function deriveSponsorBaseFee(config) {
40375
+ const min = parseStroops(config.minTotalFeeStroops, "minTotalFeeStroops");
40376
+ const max = parseStroops(config.maxTotalFeeStroops, "maxTotalFeeStroops");
40377
+ sponsoringInvariant(min > 0n, `sponsor config minTotalFeeStroops must be positive, got ${min}`, {
40378
+ field: "minTotalFeeStroops"
40379
+ });
40380
+ sponsoringInvariant(max >= min, `sponsor config fee band is inverted (min ${min} > max ${max})`, {
40381
+ field: "maxTotalFeeStroops"
40382
+ });
40383
+ const minPerOp = parseStroops(config.minPerOperationFeeStroops, "minPerOperationFeeStroops");
40384
+ const maxPerOp = parseStroops(config.maxPerOperationFeeStroops, "maxPerOperationFeeStroops");
40385
+ sponsoringInvariant(minPerOp > 0n, `sponsor config minPerOperationFeeStroops must be positive, got ${minPerOp}`, {
40386
+ field: "minPerOperationFeeStroops"
40387
+ });
40388
+ sponsoringInvariant(
40389
+ maxPerOp >= minPerOp,
40390
+ `sponsor config per-operation fee band is inverted (min ${minPerOp} > max ${maxPerOp})`,
40391
+ { field: "maxPerOperationFeeStroops" }
40392
+ );
40393
+ sponsoringInvariant(
40394
+ Number.isInteger(config.operationCount) && BigInt(config.operationCount) === SPONSORED_CREATE_OP_COUNT,
40395
+ `sponsor config expects ${config.operationCount} operations but this builder emits ${SPONSORED_CREATE_OP_COUNT} \u2014 the sponsored-create shape has changed server-side`,
40396
+ { field: "operationCount" }
40397
+ );
40398
+ const baseFee = parseStroops(config.recommendedPerOperationFeeStroops, "recommendedPerOperationFeeStroops");
40399
+ const totalFee = baseFee * SPONSORED_CREATE_OP_COUNT;
40400
+ sponsoringInvariant(
40401
+ baseFee >= minPerOp && baseFee <= maxPerOp,
40402
+ `per-operation fee ${baseFee} is outside the accepted per-operation band [${minPerOp}, ${maxPerOp}]`,
40403
+ { field: "recommendedPerOperationFeeStroops" }
40404
+ );
40405
+ sponsoringInvariant(
40406
+ totalFee >= min && totalFee <= max,
40407
+ `per-operation fee ${baseFee} yields a total of ${totalFee} stroops, outside the accepted band [${min}, ${max}]`,
40408
+ { field: "recommendedPerOperationFeeStroops" }
40409
+ );
40410
+ return { baseFee: baseFee.toString(), totalFee };
40411
+ }
40412
+ function resolveTimeboundSeconds(config) {
40413
+ const ceiling = Math.floor(config.maxTimeboundSeconds);
40414
+ const seconds = Math.min(SPONSOR_TIMEBOUND_SECONDS, ceiling);
40415
+ sponsoringInvariant(
40416
+ Number.isFinite(seconds) && seconds > 0,
40417
+ `sponsor config maxTimeboundSeconds leaves no usable window, got ${config.maxTimeboundSeconds}`,
40418
+ { field: "maxTimeboundSeconds" }
40419
+ );
40420
+ return seconds;
40421
+ }
40422
+ function assertSponsoredCreateInputs(params) {
40423
+ const { config, address } = params;
40424
+ sponsoringInvariant(
40425
+ config.networkPassphrase === stellarSdk.Networks.PUBLIC,
40426
+ `sponsored create must target the Stellar public network, got "${config.networkPassphrase}"`,
40427
+ { field: "networkPassphrase" }
40428
+ );
40429
+ assertValidStellarAccountId(address);
40430
+ assertValidStellarAccountId(config.sponsorAccount);
40431
+ deriveSponsorBaseFee(config);
40432
+ resolveTimeboundSeconds(config);
40433
+ }
40434
+ function buildSponsoredCreate(params) {
40435
+ const { config, sponsorSequence, address } = params;
40436
+ assertSponsoredCreateInputs({ config, address });
40437
+ const { baseFee } = deriveSponsorBaseFee(config);
40438
+ const timeboundSeconds = resolveTimeboundSeconds(config);
40439
+ return new stellarSdk.TransactionBuilder(new stellarSdk.Account(config.sponsorAccount, sponsorSequence), {
40440
+ fee: baseFee,
40441
+ networkPassphrase: config.networkPassphrase
40442
+ }).addOperation(stellarSdk.Operation.beginSponsoringFutureReserves({ sponsoredId: address })).addOperation(stellarSdk.Operation.createAccount({ destination: address, startingBalance: config.requiredStartingBalance })).addOperation(stellarSdk.Operation.endSponsoringFutureReserves({ source: address })).setTimeout(timeboundSeconds).build();
40443
+ }
40444
+ function assertValidStellarAccountId(address) {
40445
+ let valid = true;
40446
+ try {
40447
+ stellarSdk.Keypair.fromPublicKey(address);
40448
+ } catch {
40449
+ valid = false;
40450
+ }
40451
+ sponsoringInvariant(valid, `"${address}" is not a valid Stellar ed25519 public key`, { field: "address" });
40452
+ }
40453
+ function assertSignedByAccount(params) {
40454
+ const { signedXdr, address, unsignedHash } = params;
40455
+ let parsed;
40456
+ try {
40457
+ parsed = stellarSdk.TransactionBuilder.fromXDR(signedXdr, stellarSdk.Networks.PUBLIC);
40458
+ } catch (error) {
40459
+ sponsoringInvariant(false, `wallet returned an unparseable transaction: ${messageOf(error, String(error))}`, {
40460
+ field: "signature"
40461
+ });
40462
+ }
40463
+ sponsoringInvariant(
40464
+ !(parsed instanceof stellarSdk.FeeBumpTransaction),
40465
+ "wallet returned a fee-bump envelope; the sponsoring API rejects fee-bump transactions",
40466
+ { field: "signature" }
40467
+ );
40468
+ const hash = parsed.hash();
40469
+ sponsoringInvariant(
40470
+ hash.equals(unsignedHash),
40471
+ "wallet altered the transaction before signing it (fee, memo, or time bounds changed)",
40472
+ { field: "signature" }
40473
+ );
40474
+ const keypair = stellarSdk.Keypair.fromPublicKey(address);
40475
+ const signedByAccount = parsed.signatures.some((signature) => {
40476
+ try {
40477
+ return keypair.verify(hash, signature.signature());
40478
+ } catch {
40479
+ return false;
40480
+ }
40481
+ });
40482
+ sponsoringInvariant(
40483
+ signedByAccount,
40484
+ "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",
40485
+ { field: "signature" }
40486
+ );
40487
+ }
40488
+ function isHorizonNotFound(error) {
40489
+ if (error instanceof stellarSdk.NotFoundError) return true;
40490
+ const status = error?.response?.status;
40491
+ return status === 404;
40492
+ }
40493
+ var XLM_DECIMALS = 7;
40494
+ function xlmDecimalToStroops(amount) {
40495
+ if (!/^\d+(\.\d+)?$/.test(amount)) return 0n;
40496
+ const [whole = "0", fraction = ""] = amount.split(".");
40497
+ const scaled = `${whole}${fraction.padEnd(XLM_DECIMALS, "0").slice(0, XLM_DECIMALS)}`;
40498
+ return BigInt(scaled);
40499
+ }
40500
+ var STELLAR_BASE_RESERVE_STROOPS = 5000000n;
40501
+ var BASE_RESERVE_UNITS = 2;
40502
+ function parseBaseReserveStroops(ledger) {
40503
+ const value = ledger?.base_reserve_in_stroops;
40504
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) return void 0;
40505
+ return BigInt(value);
40506
+ }
40507
+ function readReserveInfo(account, baseReserveStroops) {
40508
+ const native = account.balances.find((balance) => balance.asset_type === "native");
40509
+ const nativeBalanceStroops = native ? xlmDecimalToStroops(native.balance) : 0n;
40510
+ const sellingLiabilitiesStroops = native?.selling_liabilities ? xlmDecimalToStroops(native.selling_liabilities) : 0n;
40511
+ const units = Math.max(
40512
+ 0,
40513
+ BASE_RESERVE_UNITS + (account.subentry_count ?? 0) + (account.num_sponsoring ?? 0) - (account.num_sponsored ?? 0)
40514
+ );
40515
+ const lockedStroops = BigInt(units) * baseReserveStroops + sellingLiabilitiesStroops;
40516
+ return {
40517
+ nativeBalanceStroops,
40518
+ availableBalanceStroops: nativeBalanceStroops > lockedStroops ? nativeBalanceStroops - lockedStroops : 0n
40519
+ };
40520
+ }
40521
+
40522
+ // src/sponsoring/SponsoringService.ts
40523
+ var SPONSOR_CONFIG_TTL_MS = 6e4;
40524
+ var STELLAR_BASE_RESERVE_TTL_MS = 36e5;
40525
+ var DEFAULT_MAX_HORIZON_RETRIES = 2;
40526
+ var STELLAR_FEE_HEADROOM_STROOPS = 100000n;
40527
+ var STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_BASE_RESERVE_STROOPS + STELLAR_FEE_HEADROOM_STROOPS;
40528
+ var SponsoringService = class {
40529
+ config;
40530
+ spoke;
40531
+ api;
40532
+ /** Keyed by base URL to isolate deployment-specific sponsor config. */
40533
+ configCache = /* @__PURE__ */ new Map();
40534
+ inflightConfig = /* @__PURE__ */ new Map();
40535
+ baseReserveCache;
40536
+ inflightBaseReserve;
40537
+ constructor(deps) {
40538
+ this.config = deps.config;
40539
+ this.spoke = deps.spoke;
40540
+ this.api = deps.api;
40541
+ }
40542
+ get horizon() {
40543
+ return this.spoke.stellar.server;
40544
+ }
40545
+ /**
40546
+ * Whether an account exists. Read failures remain errors rather than being
40547
+ * misreported as inactive.
40548
+ */
40549
+ async isStellarAccountActive(params) {
40550
+ const account = await this.readAccount(params.address, "isStellarAccountActive");
40551
+ return account.ok ? { ok: true, value: account.value !== void 0 } : account;
40552
+ }
40553
+ /**
40554
+ * Return account existence and trustline affordability. Costs one Horizon
40555
+ * account read, plus a base-reserve read on the first call per hour.
40556
+ */
40557
+ async getStellarAccountStatus(params) {
40558
+ const account = await this.readAccount(params.address, "getStellarAccountStatus");
40559
+ if (!account.ok) return account;
40560
+ const baseReserveStroops = await this.resolveBaseReserveStroops();
40561
+ const trustlineMinXlmStroops = baseReserveStroops + STELLAR_FEE_HEADROOM_STROOPS;
40562
+ if (account.value === void 0) {
40563
+ return {
40564
+ ok: true,
40565
+ value: {
40566
+ exists: false,
40567
+ nativeBalanceStroops: 0n,
40568
+ availableBalanceStroops: 0n,
40569
+ canAffordTrustline: false,
40570
+ trustlineMinXlmStroops
40571
+ }
40572
+ };
40573
+ }
40574
+ const { nativeBalanceStroops, availableBalanceStroops } = readReserveInfo(account.value, baseReserveStroops);
40575
+ return {
40576
+ ok: true,
40577
+ value: {
40578
+ exists: true,
40579
+ nativeBalanceStroops,
40580
+ availableBalanceStroops,
40581
+ canAffordTrustline: availableBalanceStroops >= trustlineMinXlmStroops,
40582
+ trustlineMinXlmStroops
40583
+ }
40584
+ };
40585
+ }
40586
+ /**
40587
+ * Shared account read. A 404 resolves to `undefined` because absence is a
40588
+ * legitimate answer; every other failure remains an error.
40589
+ */
40590
+ async readAccount(address, action) {
40591
+ if (address.length === 0) {
40592
+ return {
40593
+ ok: false,
40594
+ error: new SodaxError("VALIDATION_FAILED", "address is required", {
40595
+ feature: "sponsoring",
40596
+ context: { phase: "validate", method: action, field: "address" }
40597
+ })
40598
+ };
40599
+ }
40600
+ try {
40601
+ return { ok: true, value: await this.horizon.loadAccount(address) };
40602
+ } catch (error) {
40603
+ if (isHorizonNotFound(error)) return { ok: true, value: void 0 };
40604
+ return {
40605
+ ok: false,
40606
+ error: lookupFailed("sponsoring", action, error, { srcChainKey: ChainKeys.STELLAR_MAINNET })
40607
+ };
40608
+ }
40609
+ }
40610
+ /**
40611
+ * The base reserve is a validator-controlled network setting, so read it from
40612
+ * the latest ledger rather than assuming the published 0.5 XLM. A failed read
40613
+ * degrades to that value: this drives a UI hint, never a signed transaction.
40614
+ */
40615
+ async resolveBaseReserveStroops() {
40616
+ const cached = this.baseReserveCache;
40617
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
40618
+ const inflight = this.inflightBaseReserve;
40619
+ if (inflight) return inflight;
40620
+ const read = async () => {
40621
+ try {
40622
+ const page = await this.horizon.ledgers().order("desc").limit(1).call();
40623
+ const value = parseBaseReserveStroops(page.records[0]);
40624
+ if (value !== void 0) return value;
40625
+ } catch (error) {
40626
+ this.config.logger.warn("[SponsoringService] Stellar base-reserve read failed; assuming the published value", {
40627
+ reason: messageOf(error, String(error))
40628
+ });
40629
+ }
40630
+ return STELLAR_BASE_RESERVE_STROOPS;
40631
+ };
40632
+ const request = read().then((value) => {
40633
+ this.baseReserveCache = { value, expiresAt: Date.now() + STELLAR_BASE_RESERVE_TTL_MS };
40634
+ return value;
40635
+ }).finally(() => {
40636
+ if (this.inflightBaseReserve === request) this.inflightBaseReserve = void 0;
40637
+ });
40638
+ this.inflightBaseReserve = request;
40639
+ return request;
40640
+ }
40641
+ /**
40642
+ * Cache key for a config request: the resolved base URL plus any per-call
40643
+ * headers. Headers can select a different response from the same URL — an API
40644
+ * key scoped to another deployment, or a test harness's scenario header — so
40645
+ * folding them in stops one caller's override from being served to, or
40646
+ * overwriting, the default path. Kept in memory as a Map key only.
40647
+ */
40648
+ configCacheKey(requestConfig) {
40649
+ const baseURL = requestConfig?.baseURL || this.api.sponsoring.getBaseURL();
40650
+ const headers = requestConfig?.headers;
40651
+ if (!headers) return baseURL;
40652
+ const normalized = Object.keys(headers).sort().map((name) => `${name.toLowerCase()}=${headers[name]}`).join("&");
40653
+ return normalized.length === 0 ? baseURL : `${baseURL}|${normalized}`;
40654
+ }
40655
+ /**
40656
+ * Fetch sponsor config with per-endpoint caching and in-flight deduplication.
40657
+ * Failures are never cached.
40658
+ */
40659
+ async getStellarSponsorConfig(params) {
40660
+ const key = this.configCacheKey(params?.requestConfig);
40661
+ if (params?.forceRefresh) {
40662
+ this.configCache.delete(key);
40663
+ this.inflightConfig.delete(key);
40664
+ } else {
40665
+ const cached = this.configCache.get(key);
40666
+ if (cached && cached.expiresAt > Date.now()) return { ok: true, value: cached.value };
40667
+ const inflight = this.inflightConfig.get(key);
40668
+ if (inflight) return inflight;
40669
+ }
40670
+ const request = this.api.sponsoring.getStellarSponsorConfig(params?.requestConfig).then((result) => {
40671
+ if (result.ok && this.inflightConfig.get(key) === request) {
40672
+ const now = Date.now();
40673
+ for (const [cached, entry] of this.configCache) {
40674
+ if (entry.expiresAt <= now) this.configCache.delete(cached);
40675
+ }
40676
+ this.configCache.set(key, { value: result.value, expiresAt: now + SPONSOR_CONFIG_TTL_MS });
40677
+ }
40678
+ return result;
40679
+ }).finally(() => {
40680
+ if (this.inflightConfig.get(key) === request) this.inflightConfig.delete(key);
40681
+ });
40682
+ this.inflightConfig.set(key, request);
40683
+ return request;
40684
+ }
40685
+ /**
40686
+ * Activate an account with a sponsored base reserve. Config and existence are
40687
+ * checked before prompting; sponsor sequence is never cached.
40688
+ */
40689
+ async activateStellarAccount(params) {
40690
+ let attempts = 0;
40691
+ return this.config.analytics.trackResult(
40692
+ "sponsoring",
40693
+ "activateStellarAccount",
40694
+ async () => {
40695
+ try {
40696
+ const { address } = params;
40697
+ const configResult = await this.getStellarSponsorConfig({
40698
+ forceRefresh: params.forceConfigRefresh,
40699
+ requestConfig: params.requestConfig
40700
+ });
40701
+ if (!configResult.ok) return configResult;
40702
+ const sponsorConfig = configResult.value;
40703
+ if (await this.accountExistsBestEffort(address)) {
40704
+ return { ok: true, value: { status: "alreadyActive", hash: null, attempts: 0 } };
40705
+ }
40706
+ attempts = 1;
40707
+ const first = await this.attemptActivation({ params, sponsorConfig, attempt: 1 });
40708
+ if (first.ok || params.allowSequenceRetry === false) return first;
40709
+ if (first.error.context?.nextAction !== "rebuildAndResign") return first;
40710
+ attempts = 2;
40711
+ return this.attemptActivation({
40712
+ params,
40713
+ sponsorConfig,
40714
+ attempt: 2,
40715
+ sponsorSequenceHint: first.error.context?.sponsorSequence
40716
+ });
40717
+ } catch (error) {
40718
+ if (isSodaxError(error)) {
40719
+ return { ok: false, error };
40720
+ }
40721
+ return {
40722
+ ok: false,
40723
+ error: unknownFailed("sponsoring", error, { action: "activateStellarAccount" })
40724
+ };
40725
+ }
40726
+ },
40727
+ {
40728
+ start: () => ({ srcChainKey: ChainKeys.STELLAR_MAINNET, address: params.address }),
40729
+ success: (value) => ({ status: value.status, attempts: value.attempts, hash: value.hash }),
40730
+ failure: (error) => ({
40731
+ code: error.code,
40732
+ // Preserve evidence that a sequence-conflict retry occurred.
40733
+ attempts,
40734
+ // `status` is already the domain outcome in success events.
40735
+ httpStatus: error.context?.status,
40736
+ nextAction: error.context?.nextAction
40737
+ })
40738
+ }
40739
+ );
40740
+ }
40741
+ /** One build, sign, and submit attempt. */
40742
+ async attemptActivation(args) {
40743
+ const { params, sponsorConfig, attempt, sponsorSequenceHint } = args;
40744
+ const { address, walletProvider } = params;
40745
+ assertSponsoredCreateInputs({ config: sponsorConfig, address });
40746
+ let sponsorSequence;
40747
+ if (sponsorSequenceHint !== void 0) {
40748
+ sponsorSequence = sponsorSequenceHint;
40749
+ } else {
40750
+ try {
40751
+ const sponsorAccount = await this.horizon.loadAccount(sponsorConfig.sponsorAccount);
40752
+ sponsorSequence = sponsorAccount.sequenceNumber();
40753
+ } catch (error) {
40754
+ return {
40755
+ ok: false,
40756
+ error: lookupFailed("sponsoring", "loadSponsorAccount", error, {
40757
+ action: "activateStellarAccount",
40758
+ srcChainKey: ChainKeys.STELLAR_MAINNET
40759
+ })
40760
+ };
40761
+ }
40762
+ }
40763
+ const transaction = buildSponsoredCreate({ config: sponsorConfig, sponsorSequence, address });
40764
+ const unsignedHash = transaction.hash();
40765
+ params.onSignatureRequired?.({ attempt, reason: attempt === 1 ? "initial" : "sequenceConflict" });
40766
+ let signedXdr;
40767
+ try {
40768
+ signedXdr = await walletProvider.signTransaction(transaction.toXDR(), { address });
40769
+ } catch (error) {
40770
+ return {
40771
+ ok: false,
40772
+ error: intentCreationFailed("sponsoring", error, {
40773
+ action: "activateStellarAccount",
40774
+ srcChainKey: ChainKeys.STELLAR_MAINNET
40775
+ })
40776
+ };
40777
+ }
40778
+ assertSignedByAccount({ signedXdr, address, unsignedHash });
40779
+ const submitted = await this.submitWithHorizonRetry({
40780
+ signedXdr,
40781
+ maxRetries: params.maxHorizonRetries ?? DEFAULT_MAX_HORIZON_RETRIES,
40782
+ requestConfig: params.requestConfig
40783
+ });
40784
+ if (submitted.ok) {
40785
+ const response = submitted.value;
40786
+ return response.alreadyActive ? { ok: true, value: { status: "alreadyActive", hash: null, attempts: attempt } } : { ok: true, value: { status: "submitted", hash: response.hash, attempts: attempt } };
40787
+ }
40788
+ const classification = classifySponsorError(submitted.error);
40789
+ if (classification.action === "fixIntegration") {
40790
+ this.configCache.delete(this.configCacheKey(params.requestConfig));
40791
+ }
40792
+ return {
40793
+ ok: false,
40794
+ error: new SodaxError("EXTERNAL_API_ERROR", classification.message, {
40795
+ feature: "sponsoring",
40796
+ cause: submitted.error,
40797
+ context: {
40798
+ api: "sponsoring",
40799
+ action: "activateStellarAccount",
40800
+ phase: "submit",
40801
+ srcChainKey: ChainKeys.STELLAR_MAINNET,
40802
+ attempts: attempt,
40803
+ nextAction: classification.action,
40804
+ retryable: classification.retryable,
40805
+ requiresNewSignature: classification.requiresNewSignature,
40806
+ sponsorAccount: sponsorConfig.sponsorAccount,
40807
+ status: classification.status,
40808
+ code: classification.code,
40809
+ retryAfterSeconds: classification.retryAfterSeconds,
40810
+ sponsorSequence: classification.sponsorSequence
40811
+ }
40812
+ })
40813
+ };
40814
+ }
40815
+ /**
40816
+ * Re-submit identical signed bytes only for `retrySameRequest` failures.
40817
+ */
40818
+ async submitWithHorizonRetry(args) {
40819
+ const { signedXdr, maxRetries, requestConfig } = args;
40820
+ let result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
40821
+ for (let retry2 = 0; retry2 < maxRetries && !result.ok; retry2++) {
40822
+ if (classifySponsorError(result.error).action !== "retrySameRequest") break;
40823
+ await sleep(1e3 * (retry2 + 1));
40824
+ result = await this.api.sponsoring.createStellarSponsoredAccount({ data: signedXdr }, requestConfig);
40825
+ }
40826
+ return result;
40827
+ }
40828
+ /**
40829
+ * Best-effort existence pre-flight. Read failures continue to activation
40830
+ * because the server performs the authoritative check.
40831
+ */
40832
+ async accountExistsBestEffort(address) {
40833
+ const account = await this.readAccount(address, "isStellarAccountActive");
40834
+ if (account.ok) return account.value !== void 0;
40835
+ this.config.logger.warn(
40836
+ "[SponsoringService] Stellar account existence pre-flight failed; continuing with activation",
40837
+ { address, reason: messageOf(account.error, String(account.error)) }
40838
+ );
40839
+ return false;
40840
+ }
40841
+ };
40842
+
40129
40843
  // src/shared/entities/Sodax.ts
40130
40844
  var Sodax = class {
40131
40845
  instanceConfig;
@@ -40149,6 +40863,7 @@ var Sodax = class {
40149
40863
  // Recovery service for withdrawing stuck hub-wallet assets back to a spoke chain
40150
40864
  dex;
40151
40865
  // Dex service enabling DEX operations
40866
+ sponsoring;
40152
40867
  leverageYield;
40153
40868
  // Leverage-yield service: cross-chain deposits / withdrawals into ERC-4626 leverage vaults on Sonic
40154
40869
  config;
@@ -40214,6 +40929,11 @@ var Sodax = class {
40214
40929
  config: this.config,
40215
40930
  spoke: this.spoke
40216
40931
  });
40932
+ this.sponsoring = new SponsoringService({
40933
+ config: this.config,
40934
+ spoke: this.spoke,
40935
+ api: this.backendApi
40936
+ });
40217
40937
  }
40218
40938
  /**
40219
40939
  * Initializes the Sodax instance with dynamic configuration.
@@ -40266,6 +40986,7 @@ exports.BITCOIN_CHAIN_KEYS = BITCOIN_CHAIN_KEYS;
40266
40986
  exports.BITCOIN_CHAIN_KEYS_SET = BITCOIN_CHAIN_KEYS_SET;
40267
40987
  exports.BTC_WALLET_ADDRESS_TYPES = BTC_WALLET_ADDRESS_TYPES;
40268
40988
  exports.BackendApiService = BackendApiService;
40989
+ exports.BackendHttpError = BackendHttpError;
40269
40990
  exports.BalnSwapService = BalnSwapService;
40270
40991
  exports.BigIntToHex = BigIntToHex;
40271
40992
  exports.BigNumberZeroDecimal = BigNumberZeroDecimal;
@@ -40290,6 +41011,7 @@ exports.DEFAULT_MAX_RETRY = DEFAULT_MAX_RETRY;
40290
41011
  exports.DEFAULT_RELAYER_API_ENDPOINT = DEFAULT_RELAYER_API_ENDPOINT;
40291
41012
  exports.DEFAULT_RELAY_TX_TIMEOUT = DEFAULT_RELAY_TX_TIMEOUT;
40292
41013
  exports.DEFAULT_RETRY_DELAY_MS = DEFAULT_RETRY_DELAY_MS;
41014
+ exports.DEFAULT_SPONSORING_API_ENDPOINT = DEFAULT_SPONSORING_API_ENDPOINT;
40293
41015
  exports.DexService = DexService;
40294
41016
  exports.EVM_CHAIN_ID_TO_KEY = EVM_CHAIN_ID_TO_KEY;
40295
41017
  exports.EVM_CHAIN_KEYS = EVM_CHAIN_KEYS;
@@ -40364,10 +41086,15 @@ exports.SOLANA_CHAIN_KEYS = SOLANA_CHAIN_KEYS;
40364
41086
  exports.SOLANA_CHAIN_KEYS_SET = SOLANA_CHAIN_KEYS_SET;
40365
41087
  exports.SONIC_CHAIN_KEYS = SONIC_CHAIN_KEYS;
40366
41088
  exports.SONIC_CHAIN_KEYS_SET = SONIC_CHAIN_KEYS_SET;
41089
+ exports.SPONSORING_API_ERROR_CODES = SPONSORING_API_ERROR_CODES;
41090
+ exports.SPONSORING_API_STELLAR_BASE_PATH = SPONSORING_API_STELLAR_BASE_PATH;
41091
+ exports.SPONSOR_CONFIG_TTL_MS = SPONSOR_CONFIG_TTL_MS;
40367
41092
  exports.STACKS_CHAIN_KEYS = STACKS_CHAIN_KEYS;
40368
41093
  exports.STACKS_CHAIN_KEYS_SET = STACKS_CHAIN_KEYS_SET;
41094
+ exports.STELLAR_BASE_RESERVE_TTL_MS = STELLAR_BASE_RESERVE_TTL_MS;
40369
41095
  exports.STELLAR_CHAIN_KEYS = STELLAR_CHAIN_KEYS;
40370
41096
  exports.STELLAR_CHAIN_KEYS_SET = STELLAR_CHAIN_KEYS_SET;
41097
+ exports.STELLAR_TRUSTLINE_MIN_XLM_STROOPS = STELLAR_TRUSTLINE_MIN_XLM_STROOPS;
40371
41098
  exports.SUI_CHAIN_KEYS = SUI_CHAIN_KEYS;
40372
41099
  exports.SUI_CHAIN_KEYS_SET = SUI_CHAIN_KEYS_SET;
40373
41100
  exports.SodaTokens = SodaTokens;
@@ -40377,6 +41104,8 @@ exports.SolanaSpokeService = SolanaSpokeService;
40377
41104
  exports.SolverApiService = SolverApiService;
40378
41105
  exports.SonicSpokeService = SonicSpokeService;
40379
41106
  exports.SpokeService = SpokeService;
41107
+ exports.SponsoringApiService = SponsoringApiService;
41108
+ exports.SponsoringService = SponsoringService;
40380
41109
  exports.StacksSpokeService = StacksSpokeService;
40381
41110
  exports.StakingLogic = StakingLogic;
40382
41111
  exports.StakingService = StakingService;
@@ -40427,6 +41156,7 @@ exports.clPositionManagerAbi = clPositionManagerAbi;
40427
41156
  exports.clQuoterAbi = clQuoterAbi;
40428
41157
  exports.clRouterAbi = clRouterAbi;
40429
41158
  exports.clTickLensAbi = clTickLensAbi;
41159
+ exports.classifySponsorError = classifySponsorError;
40430
41160
  exports.concentratedLiquidityConfig = concentratedLiquidityConfig;
40431
41161
  exports.connectionAbi = connectionAbi;
40432
41162
  exports.consoleLogger = consoleLogger;
@@ -40495,6 +41225,7 @@ exports.hyperevmSupportedTokens = hyperevmSupportedTokens;
40495
41225
  exports.iconSupportedTokens = iconSupportedTokens;
40496
41226
  exports.injectiveSupportedTokens = injectiveSupportedTokens;
40497
41227
  exports.intentCreationFailed = intentCreationFailed;
41228
+ exports.isBackendHttpError = isBackendHttpError;
40498
41229
  exports.isBalnMigrateParams = isBalnMigrateParams;
40499
41230
  exports.isBitcoinChainKey = isBitcoinChainKey;
40500
41231
  exports.isBitcoinChainKeyType = isBitcoinChainKeyType;
@@ -40578,6 +41309,9 @@ exports.isSpokeChainKey = isSpokeChainKey;
40578
41309
  exports.isSpokeIsAllowanceValidParamsEvmSpoke = isSpokeIsAllowanceValidParamsEvmSpoke;
40579
41310
  exports.isSpokeIsAllowanceValidParamsHub = isSpokeIsAllowanceValidParamsHub;
40580
41311
  exports.isSpokeIsAllowanceValidParamsStellar = isSpokeIsAllowanceValidParamsStellar;
41312
+ exports.isSponsoringConfigError = isSponsoringConfigError;
41313
+ exports.isSponsoringLookupError = isSponsoringLookupError;
41314
+ exports.isSponsoringOrchestrationError = isSponsoringOrchestrationError;
40581
41315
  exports.isStacksChainKey = isStacksChainKey;
40582
41316
  exports.isStacksChainKeyType = isStacksChainKeyType;
40583
41317
  exports.isStakeOrchestrationError = isStakeOrchestrationError;
@@ -40664,6 +41398,7 @@ exports.spokeAssetManagerAbi = spokeAssetManagerAbi;
40664
41398
  exports.spokeChainConfig = spokeChainConfig;
40665
41399
  exports.spokeChainKeysSet = spokeChainKeysSet;
40666
41400
  exports.spokeHooks = spokeHooks;
41401
+ exports.sponsoringInvariant = sponsoringInvariant;
40667
41402
  exports.stacksSupportedTokens = stacksSupportedTokens;
40668
41403
  exports.stagingSwapSupportedTokens = stagingSwapSupportedTokens;
40669
41404
  exports.stakedSodaAbi = stakedSodaAbi;