@sodax/sdk 2.1.0 → 2.2.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
@@ -3724,7 +3724,7 @@ var spokeChainConfig = {
3724
3724
  }
3725
3725
  },
3726
3726
  [ChainKeys.NEAR_MAINNET]: {
3727
- rpcUrl: "https://1rpc.io/near",
3727
+ rpcUrl: "https://free.rpc.fastnear.com",
3728
3728
  chain: baseChainInfo[ChainKeys.NEAR_MAINNET],
3729
3729
  nativeToken: "NEAR",
3730
3730
  addresses: {
@@ -4886,7 +4886,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4886
4886
  }
4887
4887
 
4888
4888
  // ../types/dist/index.js
4889
- var CONFIG_VERSION = 230;
4889
+ var CONFIG_VERSION = 231;
4890
4890
 
4891
4891
  // src/shared/utils/resolveTimeoutMs.ts
4892
4892
  function resolveTimeoutMs(timeout, fallbackMs) {
@@ -5435,6 +5435,12 @@ function isFeatureError(feature) {
5435
5435
  function isCodeMember(codes) {
5436
5436
  return (e) => isSodaxError(e) && codes.has(e.code);
5437
5437
  }
5438
+ function isAuthStatus(status) {
5439
+ return status === 401 || status === 403;
5440
+ }
5441
+ function isAuthFailure(error) {
5442
+ return isSodaxError(error) && isAuthStatus(error.context?.status);
5443
+ }
5438
5444
 
5439
5445
  // src/errors/wrappers.ts
5440
5446
  function messageOf(error, fallback2) {
@@ -14492,6 +14498,13 @@ var ConfigService = class {
14492
14498
  * a client-side option set via `new Sodax({ fee })`. Per-feature overrides live on the feature config.
14493
14499
  */
14494
14500
  fee;
14501
+ /**
14502
+ * Global backend API key. Resolved once at construction and kept independent of {@link sodax} so
14503
+ * that {@link initialize}'s dynamic-config swap never clobbers it. The backend never supplies it —
14504
+ * it is a client-side option set via `new Sodax({ apiKey })`. Never logged; read here by the swap,
14505
+ * leverage-yield, and partner solver flows, whose transport does not go through `BackendApiService`.
14506
+ */
14507
+ apiKey;
14495
14508
  /**
14496
14509
  * RadFi/Bound request signer. Resolved once at construction and kept independent of {@link sodax}
14497
14510
  * so that {@link initialize}'s dynamic-config swap never clobbers it. Read by `BitcoinSpokeService`
@@ -14512,11 +14525,21 @@ var ConfigService = class {
14512
14525
  hubAssetToXTokenMap;
14513
14526
  // `api` / `userConfig` are accepted but unused while initialize()'s dynamic fetch is disabled
14514
14527
  // (see TODO(config-v2) below); restore their assignments when re-enabling.
14515
- constructor({ api, config, userConfig, logger, analytics, fee, radfiSigner }) {
14528
+ constructor({
14529
+ api,
14530
+ config,
14531
+ userConfig,
14532
+ logger,
14533
+ analytics,
14534
+ fee,
14535
+ apiKey,
14536
+ radfiSigner
14537
+ }) {
14516
14538
  this.sodax = config;
14517
14539
  this.logger = logger ?? resolveLogger(void 0);
14518
14540
  this.analytics = analytics ?? noopAnalytics;
14519
14541
  this.fee = fee;
14542
+ this.apiKey = apiKey;
14520
14543
  this.radfiSigner = radfiSigner;
14521
14544
  this.loadSodaxConfigDataStructures(config);
14522
14545
  }
@@ -14710,7 +14733,9 @@ var ConfigService = class {
14710
14733
  ])
14711
14734
  );
14712
14735
  this.loadSpokeChainConfigDataStructures(sodaxConfig2);
14713
- this.moneyMarketReserveAssetsSet = new Set(sodaxConfig2.moneyMarket.supportedReserveAssets);
14736
+ this.moneyMarketReserveAssetsSet = new Set(
14737
+ sodaxConfig2.moneyMarket.supportedReserveAssets.map((address) => address.toLowerCase())
14738
+ );
14714
14739
  this.stakedATokenAddressesSet = new Set(
14715
14740
  Object.keys(sodaxConfig2.dex.statATokenAddresses).map((address) => address.toLowerCase())
14716
14741
  );
@@ -27324,6 +27349,119 @@ var EvmHubProvider = class {
27324
27349
  }
27325
27350
  };
27326
27351
 
27352
+ // src/backendApi/api-utils.ts
27353
+ var API_KEY_HEADER = "x-api-key";
27354
+ function apiKeyHeader(apiKey) {
27355
+ return apiKey ? { [API_KEY_HEADER]: apiKey } : {};
27356
+ }
27357
+ function mergeHeaders(...sources) {
27358
+ const byName = /* @__PURE__ */ new Map();
27359
+ for (const source of sources) {
27360
+ for (const entry of Object.entries(source ?? {})) byName.set(entry[0].toLowerCase(), entry);
27361
+ }
27362
+ return Object.fromEntries(byName.values());
27363
+ }
27364
+ function withApiKey(config, apiKey) {
27365
+ return { ...config, headers: mergeHeaders(apiKeyHeader(apiKey), config.headers) };
27366
+ }
27367
+ function assignHeaders(target, source) {
27368
+ const merged = mergeHeaders(target, source);
27369
+ for (const name of Object.keys(target)) delete target[name];
27370
+ Object.assign(target, merged);
27371
+ }
27372
+ var BackendHttpError = class extends Error {
27373
+ status;
27374
+ bodyText;
27375
+ /** Parsed JSON, or `undefined` for empty or malformed bodies. */
27376
+ body;
27377
+ constructor(status, bodyText) {
27378
+ super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
27379
+ this.name = "BackendHttpError";
27380
+ this.status = status;
27381
+ this.bodyText = bodyText;
27382
+ this.body = safeJsonParse(bodyText);
27383
+ }
27384
+ };
27385
+ function isBackendHttpError(error) {
27386
+ if (error instanceof BackendHttpError) return true;
27387
+ return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
27388
+ }
27389
+ function safeJsonParse(text) {
27390
+ if (text.length === 0) return void 0;
27391
+ try {
27392
+ return JSON.parse(text);
27393
+ } catch {
27394
+ return void 0;
27395
+ }
27396
+ }
27397
+ function trimTrailingSlashes(baseURL) {
27398
+ let end = baseURL.length;
27399
+ while (end > 0 && baseURL[end - 1] === "/") end -= 1;
27400
+ return baseURL.slice(0, end);
27401
+ }
27402
+ var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
27403
+ async function makeRequest(params) {
27404
+ const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
27405
+ const baseURL = overrideConfig.baseURL || config.baseURL || "";
27406
+ const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
27407
+ const headers = mergeHeaders(config.headers, apiKeyHeader(overrideConfig.apiKey), overrideConfig.headers);
27408
+ const controller = new AbortController();
27409
+ const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
27410
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
27411
+ try {
27412
+ const response = await fetch(url, {
27413
+ method: config.method,
27414
+ headers,
27415
+ body: config.body,
27416
+ signal: controller.signal
27417
+ });
27418
+ if (!response.ok) {
27419
+ const errorText = await response.text();
27420
+ throw new BackendHttpError(response.status, errorText);
27421
+ }
27422
+ const data = await response.json();
27423
+ return data;
27424
+ } catch (error) {
27425
+ if (error instanceof Error) {
27426
+ if (error.name === "AbortError") {
27427
+ throw new Error("REQUEST_TIMEOUT", { cause: new Error(`Request timeout after ${timeout}ms`) });
27428
+ }
27429
+ logger.error(`[${serviceLabel}] Request error`, error);
27430
+ throw error;
27431
+ }
27432
+ logger.error(`[${serviceLabel}] Unknown error`, error);
27433
+ throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
27434
+ } finally {
27435
+ clearTimeout(timeoutId);
27436
+ }
27437
+ }
27438
+ function resolveRequestConfig(config, defaults) {
27439
+ const { baseURL, timeout, headers, apiKey, ...rest } = config;
27440
+ return {
27441
+ ...rest,
27442
+ baseURL: baseURL || defaults.baseURL,
27443
+ timeout: timeout ?? defaults.timeout,
27444
+ headers: mergeHeaders(defaults.headers, apiKeyHeader(apiKey), headers)
27445
+ };
27446
+ }
27447
+ function toExternalApiError(params) {
27448
+ const { api, feature, endpoint, error } = params;
27449
+ const context = { api, endpoint };
27450
+ if (isBackendHttpError(error)) context.status = error.status;
27451
+ return new SodaxError(
27452
+ "EXTERNAL_API_ERROR",
27453
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
27454
+ { feature, cause: error, context }
27455
+ );
27456
+ }
27457
+ function toInvalidResponseShapeError(params) {
27458
+ const { api, feature, endpoint, issues } = params;
27459
+ return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
27460
+ feature,
27461
+ context: { api, endpoint, reason: "invalid_response_shape", issues }
27462
+ });
27463
+ }
27464
+
27327
27465
  // src/swap/SolverApiService.ts
27328
27466
  var bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
27329
27467
  var SolverApiService = class {
@@ -27370,9 +27508,7 @@ var SolverApiService = class {
27370
27508
  try {
27371
27509
  const response = await fetch(`${config.solverApiEndpoint}/quote`, {
27372
27510
  method: "POST",
27373
- headers: {
27374
- "Content-Type": "application/json"
27375
- },
27511
+ headers: mergeHeaders({ "Content-Type": "application/json" }, apiKeyHeader(configService.apiKey)),
27376
27512
  body: JSON.stringify({
27377
27513
  token_src: tokenSrc,
27378
27514
  token_dst: tokenDst,
@@ -27418,16 +27554,16 @@ var SolverApiService = class {
27418
27554
  *
27419
27555
  * @param request - Object containing `intent_tx_hash` (the hub-chain tx hash of the created intent).
27420
27556
  * @param config - Solver endpoint configuration.
27557
+ * @param logger - Diagnostics sink; defaults to the silent logger.
27558
+ * @param apiKey - Configured backend API key (`config.apiKey`), sent as the `x-api-key` header.
27421
27559
  * @returns A `Result` containing `{ answer: 'OK', intent_hash: Hex }` on success.
27422
27560
  */
27423
- static async postExecution(request, config, logger = silentLogger) {
27561
+ static async postExecution(request, config, logger = silentLogger, apiKey) {
27424
27562
  try {
27425
27563
  const response = await retry(
27426
27564
  () => fetch(`${config.solverApiEndpoint}/execute`, {
27427
27565
  method: "POST",
27428
- headers: {
27429
- "Content-Type": "application/json"
27430
- },
27566
+ headers: mergeHeaders({ "Content-Type": "application/json" }, apiKeyHeader(apiKey)),
27431
27567
  body: JSON.stringify(request)
27432
27568
  })
27433
27569
  );
@@ -27471,11 +27607,12 @@ var SolverApiService = class {
27471
27607
  * request instantly. A non-positive one is a real budget of zero: the request aborts at once.
27472
27608
  * The relay's `getTransactionPackets` takes the same parameter but degrades a non-finite value
27473
27609
  * to its own per-request budget instead; the divergence is deliberate, and explained inline.
27610
+ * @param apiKey - Configured backend API key (`config.apiKey`), sent as the `x-api-key` header.
27474
27611
  * @returns A `Result` containing `{ status: SolverIntentStatusCode, fill_tx_hash?: string }`.
27475
27612
  * `fill_tx_hash` is set only when `status === SolverIntentStatusCode.SOLVED (3)`.
27476
27613
  * @throws Invariant error if `intent_tx_hash` is empty (thrown before the async request).
27477
27614
  */
27478
- static async getStatus(request, config, logger = silentLogger, timeoutMs) {
27615
+ static async getStatus(request, config, logger = silentLogger, timeoutMs, apiKey) {
27479
27616
  invariant(request.intent_tx_hash.length > 0, "Empty intent_tx_hash");
27480
27617
  const budgetMs = timeoutMs !== void 0 && Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : void 0;
27481
27618
  const controller = budgetMs === void 0 ? void 0 : new AbortController();
@@ -27483,9 +27620,7 @@ var SolverApiService = class {
27483
27620
  try {
27484
27621
  const response = await fetch(`${config.solverApiEndpoint}/status`, {
27485
27622
  method: "POST",
27486
- headers: {
27487
- "Content-Type": "application/json"
27488
- },
27623
+ headers: mergeHeaders({ "Content-Type": "application/json" }, apiKeyHeader(apiKey)),
27489
27624
  body: JSON.stringify(request),
27490
27625
  signal: controller?.signal
27491
27626
  });
@@ -27546,6 +27681,12 @@ async function pollBackendSubmitTx({
27546
27681
  }
27547
27682
  } else {
27548
27683
  lastStatusError = statusResult.error;
27684
+ if (isAuthFailure(statusResult.error)) {
27685
+ return {
27686
+ ok: false,
27687
+ cause: new Error("backend submit-tx status rejected the API key", { cause: statusResult.error })
27688
+ };
27689
+ }
27549
27690
  }
27550
27691
  if (attempt.remaining() <= intervalMs) break;
27551
27692
  await sleep(intervalMs);
@@ -27587,12 +27728,13 @@ async function runBackendSubmitTx({
27587
27728
  body,
27588
27729
  statusQuery,
27589
27730
  terminalStatus,
27590
- onExecuted
27731
+ onExecuted,
27732
+ overrideConfig
27591
27733
  }) {
27592
27734
  const serviceTimeoutMs = api.getTimeout();
27593
27735
  const requestTimeout = attempt.requestTimeout(serviceTimeoutMs);
27594
27736
  if (requestTimeout === null) return { ok: false, cause: noRequestBudgetCause(serviceTimeoutMs) };
27595
- const submitted = await api.submitTx(body, { timeout: requestTimeout });
27737
+ const submitted = await api.submitTx(body, { ...overrideConfig, timeout: requestTimeout });
27596
27738
  if (!submitted.ok) return { ok: false, cause: submitted.error };
27597
27739
  if (!submitted.value.success) {
27598
27740
  return { ok: false, cause: new Error(`backend submit-tx not accepted: ${submitted.value.data.message}`) };
@@ -27600,7 +27742,8 @@ async function runBackendSubmitTx({
27600
27742
  const polled = await pollBackendSubmitTx({
27601
27743
  attempt,
27602
27744
  terminalStatus,
27603
- getStatus: (override) => api.getSubmitTxStatus(statusQuery, override),
27745
+ // The poll's own override (its per-request timeout) wins over the per-action fields.
27746
+ getStatus: (override) => api.getSubmitTxStatus(statusQuery, { ...overrideConfig, ...override }),
27604
27747
  onExecuted,
27605
27748
  // While this ceiling is the smaller bound the poll retries within the attempt; once the attempt's
27606
27749
  // remainder falls below it, one stalled request can spend the rest.
@@ -27773,6 +27916,34 @@ function selectSolvedIntentPacket(packets, intentsContract) {
27773
27916
  return packets.reduce((highest, packet) => packet.conn_sn > highest.conn_sn ? packet : highest);
27774
27917
  }
27775
27918
 
27919
+ // src/swap/speed-tier.ts
27920
+ var SPEED_TIER_SECONDS = {
27921
+ /** Either token maps to a money-market-reserve (sodaAsset) hub asset. */
27922
+ sodaAsset: 15,
27923
+ /** Anything else / default. */
27924
+ default: 35,
27925
+ /** Added once when either src or dst is an Ethereum asset. */
27926
+ ethereumPenalty: 10
27927
+ };
27928
+ var SPEED_TIER_THRESHOLDS = {
27929
+ fast: 20,
27930
+ normal: 30
27931
+ };
27932
+ var isEthereumToken = (token) => token.chainKey === ChainKeys.ETHEREUM_MAINNET;
27933
+ var secondsToTier = (seconds) => {
27934
+ if (seconds <= SPEED_TIER_THRESHOLDS.fast) return "fast";
27935
+ if (seconds <= SPEED_TIER_THRESHOLDS.normal) return "normal";
27936
+ return "slow";
27937
+ };
27938
+ function estimateSwapSpeedTier({ srcToken, dstToken }, isSodaAssetRelated) {
27939
+ const eitherSodaAsset = isSodaAssetRelated(srcToken.hubAsset) || isSodaAssetRelated(dstToken.hubAsset);
27940
+ let estimatedSeconds = eitherSodaAsset ? SPEED_TIER_SECONDS.sodaAsset : SPEED_TIER_SECONDS.default;
27941
+ if (isEthereumToken(srcToken) || isEthereumToken(dstToken)) {
27942
+ estimatedSeconds += SPEED_TIER_SECONDS.ethereumPenalty;
27943
+ }
27944
+ return { tier: secondsToTier(estimatedSeconds), estimatedSeconds };
27945
+ }
27946
+
27776
27947
  // src/swap/detailedStatus.ts
27777
27948
  var DETAILED_STATUS_NOT_DELIVERED = "relay_not_delivered";
27778
27949
  function isBackendSubmitTxAbandoned(data) {
@@ -27929,7 +28100,13 @@ var SwapService = class {
27929
28100
  * falls through to carries its own {@link RECONCILE_TIMEOUT_MS}, so a bounded call can cost both.
27930
28101
  */
27931
28102
  async resolveSolverStatus(request, timeoutMs) {
27932
- const solverResult = await SolverApiService.getStatus(request, this.solver, this.config.logger, timeoutMs);
28103
+ const solverResult = await SolverApiService.getStatus(
28104
+ request,
28105
+ this.solver,
28106
+ this.config.logger,
28107
+ timeoutMs,
28108
+ this.config.apiKey
28109
+ );
27933
28110
  const forgotten = !solverResult.ok || solverResult.value.status === exports.SolverIntentStatusCode.NOT_FOUND;
27934
28111
  if (!forgotten) return solverResult;
27935
28112
  const timeout = Math.min(RECONCILE_TIMEOUT_MS, this.backendApi.requestTimeoutMs);
@@ -28078,7 +28255,7 @@ var SwapService = class {
28078
28255
  */
28079
28256
  async postExecution(request) {
28080
28257
  try {
28081
- const result = await SolverApiService.postExecution(request, this.solver, this.config.logger);
28258
+ const result = await SolverApiService.postExecution(request, this.solver, this.config.logger, this.config.apiKey);
28082
28259
  if (result.ok) return result;
28083
28260
  const detail = result.error?.detail ?? {
28084
28261
  code: -999,
@@ -28309,6 +28486,9 @@ var SwapService = class {
28309
28486
  const outcome = await runBackendSubmitTx({
28310
28487
  attempt,
28311
28488
  api: this.backendApi.swaps,
28489
+ // The configured key is already baked into the SwapsApiService headers, so only this
28490
+ // per-action override (mirroring `extras.partnerFee`) travels per call.
28491
+ overrideConfig: { apiKey: _params.extras?.apiKey },
28312
28492
  body: {
28313
28493
  txHash: spokeTxHash,
28314
28494
  srcChainKey,
@@ -29057,6 +29237,19 @@ var SwapService = class {
29057
29237
  getSupportedSwapTokens() {
29058
29238
  return this.config.getSupportedSwapTokens();
29059
29239
  }
29240
+ /**
29241
+ * Offline, rule-based estimate of how fast a `srcToken`→`dstToken` swap will settle.
29242
+ *
29243
+ * Derived purely from SDK config (no network / on-chain / backend call): tokens tied to a
29244
+ * money-market-reserve sodaAsset settle faster, and an Ethereum leg adds a fixed penalty. See
29245
+ * {@link estimateSwapSpeedTier} for the rules.
29246
+ *
29247
+ * @param params `{ srcToken, dstToken }` spoke token pair to estimate
29248
+ * @returns the estimated `tier` bucket and `estimatedSeconds`
29249
+ */
29250
+ getSwapSpeedTier(params) {
29251
+ return estimateSwapSpeedTier(params, (hubAsset) => this.config.isMoneyMarketReserveHubAsset(hubAsset));
29252
+ }
29060
29253
  };
29061
29254
 
29062
29255
  // src/migration/errors.ts
@@ -31135,100 +31328,6 @@ var MigrationService = class {
31135
31328
  }
31136
31329
  };
31137
31330
 
31138
- // src/backendApi/api-utils.ts
31139
- var BackendHttpError = class extends Error {
31140
- status;
31141
- bodyText;
31142
- /** Parsed JSON, or `undefined` for empty or malformed bodies. */
31143
- body;
31144
- constructor(status, bodyText) {
31145
- super("HTTP_REQUEST_FAILED", { cause: new Error(`HTTP ${status}: ${bodyText}`) });
31146
- this.name = "BackendHttpError";
31147
- this.status = status;
31148
- this.bodyText = bodyText;
31149
- this.body = safeJsonParse(bodyText);
31150
- }
31151
- };
31152
- function isBackendHttpError(error) {
31153
- if (error instanceof BackendHttpError) return true;
31154
- return error instanceof Error && error.name === "BackendHttpError" && typeof error.status === "number";
31155
- }
31156
- function safeJsonParse(text) {
31157
- if (text.length === 0) return void 0;
31158
- try {
31159
- return JSON.parse(text);
31160
- } catch {
31161
- return void 0;
31162
- }
31163
- }
31164
- function trimTrailingSlashes(baseURL) {
31165
- let end = baseURL.length;
31166
- while (end > 0 && baseURL[end - 1] === "/") end -= 1;
31167
- return baseURL.slice(0, end);
31168
- }
31169
- var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
31170
- async function makeRequest(params) {
31171
- const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
31172
- const baseURL = overrideConfig.baseURL || config.baseURL || "";
31173
- const url = `${trimTrailingSlashes(baseURL)}${endpoint}`;
31174
- const headers = { ...config.headers, ...overrideConfig.headers };
31175
- const controller = new AbortController();
31176
- const timeout = overrideConfig.timeout ?? config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
31177
- const timeoutId = setTimeout(() => controller.abort(), timeout);
31178
- try {
31179
- const response = await fetch(url, {
31180
- method: config.method,
31181
- headers,
31182
- body: config.body,
31183
- signal: controller.signal
31184
- });
31185
- if (!response.ok) {
31186
- const errorText = await response.text();
31187
- throw new BackendHttpError(response.status, errorText);
31188
- }
31189
- const data = await response.json();
31190
- return data;
31191
- } catch (error) {
31192
- if (error instanceof Error) {
31193
- if (error.name === "AbortError") {
31194
- throw new Error("REQUEST_TIMEOUT", { cause: new Error(`Request timeout after ${timeout}ms`) });
31195
- }
31196
- logger.error(`[${serviceLabel}] Request error`, error);
31197
- throw error;
31198
- }
31199
- logger.error(`[${serviceLabel}] Unknown error`, error);
31200
- throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
31201
- } finally {
31202
- clearTimeout(timeoutId);
31203
- }
31204
- }
31205
- function resolveRequestConfig(config, defaults) {
31206
- const { baseURL, timeout, headers, ...rest } = config;
31207
- return {
31208
- ...rest,
31209
- baseURL: baseURL || defaults.baseURL,
31210
- timeout: timeout ?? defaults.timeout,
31211
- headers: { ...defaults.headers, ...headers }
31212
- };
31213
- }
31214
- function toExternalApiError(params) {
31215
- const { api, feature, endpoint, error } = params;
31216
- const context = { api, endpoint };
31217
- if (isBackendHttpError(error)) context.status = error.status;
31218
- return new SodaxError(
31219
- "EXTERNAL_API_ERROR",
31220
- error instanceof Error ? error.message : `Request to ${endpoint} failed`,
31221
- { feature, cause: error, context }
31222
- );
31223
- }
31224
- function toInvalidResponseShapeError(params) {
31225
- const { api, feature, endpoint, issues } = params;
31226
- return new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from ${api} API for ${endpoint}`, {
31227
- feature,
31228
- context: { api, endpoint, reason: "invalid_response_shape", issues }
31229
- });
31230
- }
31231
-
31232
31331
  // src/backendApi/apiConfig.ts
31233
31332
  function flatLayer({ baseURL, timeout, headers }) {
31234
31333
  return { baseURL, timeout, headers };
@@ -31331,7 +31430,7 @@ var SwapsApiService = class _SwapsApiService {
31331
31430
  trimsLegacyOverrides;
31332
31431
  constructor(config, logger = consoleLogger, options = {}) {
31333
31432
  this.config = config;
31334
- this.headers = { ...config.headers };
31433
+ this.headers = mergeHeaders(config.headers);
31335
31434
  this.logger = logger;
31336
31435
  this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
31337
31436
  }
@@ -31347,7 +31446,7 @@ var SwapsApiService = class _SwapsApiService {
31347
31446
  const override = overrideConfig?.baseURL;
31348
31447
  const baseUrl = override ? this.trimsLegacyOverrides ? stripLegacyBackendMount(override) : override : this.config.baseURL;
31349
31448
  const timeout = overrideConfig?.timeout ?? this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
31350
- const headers = { ...this.headers, ...overrideConfig?.headers };
31449
+ const headers = mergeHeaders(this.headers, apiKeyHeader(overrideConfig?.apiKey), overrideConfig?.headers);
31351
31450
  return new swapsApi.SwapsApi({ baseUrl, headers, timeout });
31352
31451
  }
31353
31452
  /**
@@ -31373,6 +31472,11 @@ var SwapsApiService = class _SwapsApiService {
31373
31472
  context.issues = issues instanceof v__namespace.ValiError ? v__namespace.flatten(issues.issues) : issues;
31374
31473
  }
31375
31474
  if (error.context.status !== void 0) context.status = error.context.status;
31475
+ if (isAuthStatus(error.context.status)) {
31476
+ this.logger.warn(
31477
+ `[SwapsApiService] ${endpoint} was rejected by the swaps API key guard (${error.context.status}). Configure a valid partner API key \u2014 new Sodax({ apiKey }) \u2014 see docs/CONFIGURE_SDK.md.`
31478
+ );
31479
+ }
31376
31480
  }
31377
31481
  this.logger.error(`[SwapsApiService] Request to ${endpoint} failed`, error);
31378
31482
  return {
@@ -31524,9 +31628,7 @@ var SwapsApiService = class _SwapsApiService {
31524
31628
  * every subsequent call (the delegated client is rebuilt per call).
31525
31629
  */
31526
31630
  setHeaders(headers) {
31527
- Object.entries(headers).forEach(([key, value]) => {
31528
- this.headers[key] = value;
31529
- });
31631
+ assignHeaders(this.headers, headers);
31530
31632
  }
31531
31633
  /** Return the base URL the service is currently pointing at. */
31532
31634
  getBaseURL() {
@@ -31567,13 +31669,22 @@ var SponsoringApiService = class {
31567
31669
  config;
31568
31670
  headers;
31569
31671
  logger;
31570
- constructor(config, logger = consoleLogger) {
31672
+ inheritedApiKey;
31673
+ inheritedApiKeyBaseURLs;
31674
+ constructor(config, logger = consoleLogger, options = {}) {
31571
31675
  this.config = config;
31572
- this.headers = {
31573
- ...config.apiKey !== void 0 ? { "x-api-key": config.apiKey } : {},
31574
- ...config.headers
31575
- };
31676
+ this.headers = mergeHeaders(apiKeyHeader(config.apiKey), config.headers);
31576
31677
  this.logger = logger;
31678
+ this.inheritedApiKey = options.inheritedApiKey;
31679
+ this.inheritedApiKeyBaseURLs = (options.inheritedApiKeyBaseURLs ?? []).map(trimTrailingSlashes);
31680
+ }
31681
+ /**
31682
+ * The inherited instance key, but only for a request whose effective target is an allowed root.
31683
+ * Evaluated per call because a `RequestOverrideConfig.baseURL` retargets the request.
31684
+ */
31685
+ inheritedKeyFor(baseURL) {
31686
+ if (!this.inheritedApiKey) return void 0;
31687
+ return this.inheritedApiKeyBaseURLs.includes(trimTrailingSlashes(baseURL)) ? this.inheritedApiKey : void 0;
31577
31688
  }
31578
31689
  /**
31579
31690
  * Validate a response while preserving HTTP failures on `error.cause` for
@@ -31581,9 +31692,10 @@ var SponsoringApiService = class {
31581
31692
  */
31582
31693
  async request(endpoint, config, schema) {
31583
31694
  try {
31695
+ const inherited = apiKeyHeader(this.inheritedKeyFor(config.baseURL || this.config.baseURL));
31584
31696
  const raw = await makeRequest({
31585
31697
  endpoint,
31586
- config: resolveRequestConfig(config, { ...this.config, headers: this.headers }),
31698
+ config: resolveRequestConfig(config, { ...this.config, headers: mergeHeaders(inherited, this.headers) }),
31587
31699
  logger: this.logger,
31588
31700
  serviceLabel: "SponsoringApiService"
31589
31701
  });
@@ -31625,9 +31737,7 @@ var SponsoringApiService = class {
31625
31737
  );
31626
31738
  }
31627
31739
  setHeaders(headers) {
31628
- Object.entries(headers).forEach(([key, value]) => {
31629
- this.headers[key] = value;
31630
- });
31740
+ assignHeaders(this.headers, headers);
31631
31741
  }
31632
31742
  getBaseURL() {
31633
31743
  return this.config.baseURL;
@@ -31858,18 +31968,7 @@ var BridgeApiService = class {
31858
31968
  }
31859
31969
  return { ok: true, value: parsed.output };
31860
31970
  } catch (error) {
31861
- return {
31862
- ok: false,
31863
- error: new SodaxError(
31864
- "EXTERNAL_API_ERROR",
31865
- error instanceof Error ? error.message : `Request to ${endpoint} failed`,
31866
- {
31867
- feature: "backend",
31868
- cause: error,
31869
- context: { api: "bridge", endpoint }
31870
- }
31871
- )
31872
- };
31971
+ return { ok: false, error: toExternalApiError({ api: "bridge", feature: "backend", endpoint, error }) };
31873
31972
  }
31874
31973
  }
31875
31974
  // ──────────────────────────────────────────────────────────────────────
@@ -32028,9 +32127,7 @@ var BridgeApiService = class {
32028
32127
  * keys are overwritten; keys absent from `headers` are preserved.
32029
32128
  */
32030
32129
  setHeaders(headers) {
32031
- Object.entries(headers).forEach(([key, value]) => {
32032
- this.headers[key] = value;
32033
- });
32130
+ assignHeaders(this.headers, headers);
32034
32131
  }
32035
32132
  /** Return the base URL the service is currently pointing at. */
32036
32133
  getBaseURL() {
@@ -32075,8 +32172,8 @@ var BackendApiService = class {
32075
32172
  * left exactly as given rather than having a real path segment eaten.
32076
32173
  */
32077
32174
  trimsLegacyOverrides;
32078
- constructor(config, logger = consoleLogger) {
32079
- this.config = resolveBaseApiConfig(config);
32175
+ constructor(config, logger = consoleLogger, options = {}) {
32176
+ this.config = withApiKey(resolveBaseApiConfig(config), options.apiKey);
32080
32177
  this.headers = { ...this.config.headers };
32081
32178
  this.logger = logger;
32082
32179
  this.trimsLegacyOverrides = !hasExplicitBasePath(config);
@@ -32101,9 +32198,12 @@ var BackendApiService = class {
32101
32198
  );
32102
32199
  }
32103
32200
  const overrideOptions = { trimLegacyOverrides: this.trimsLegacyOverrides };
32104
- this.swaps = new SwapsApiService(swapsConfig2, this.logger, overrideOptions);
32105
- this.sponsoring = new SponsoringApiService(sponsoringConfig, this.logger);
32106
- this.bridge = new BridgeApiService(bridgeConfig2, this.logger, overrideOptions);
32201
+ this.swaps = new SwapsApiService(withApiKey(swapsConfig2, options.apiKey), this.logger, overrideOptions);
32202
+ this.sponsoring = new SponsoringApiService(sponsoringConfig, this.logger, {
32203
+ inheritedApiKey: options.apiKey,
32204
+ inheritedApiKeyBaseURLs: [DEFAULT_SPONSORING_API_ENDPOINT, this.config.baseURL]
32205
+ });
32206
+ this.bridge = new BridgeApiService(withApiKey(bridgeConfig2, options.apiKey), this.logger, overrideOptions);
32107
32207
  }
32108
32208
  /**
32109
32209
  * Issue the HTTP call for a route.
@@ -32474,9 +32574,7 @@ var BackendApiService = class {
32474
32574
  * @param headers - Key-value pairs to add or overwrite in the default headers.
32475
32575
  */
32476
32576
  setHeaders(headers) {
32477
- Object.entries(headers).forEach(([key, value]) => {
32478
- this.headers[key] = value;
32479
- });
32577
+ assignHeaders(this.headers, headers);
32480
32578
  this.swaps.setHeaders(headers);
32481
32579
  this.bridge.setHeaders(headers);
32482
32580
  }
@@ -32945,6 +33043,9 @@ var BridgeService = class {
32945
33043
  const outcome = await runBackendSubmitTx({
32946
33044
  attempt,
32947
33045
  api: this.backendApi.bridge,
33046
+ // The configured key is already baked into the BridgeApiService headers, so only this
33047
+ // per-action override (mirroring `extras.partnerFee`) travels per call.
33048
+ overrideConfig: { apiKey: _params.extras?.apiKey },
32948
33049
  body: {
32949
33050
  txHash: spokeTxHash,
32950
33051
  srcChainKey,
@@ -40957,7 +41058,8 @@ var PartnerFeeClaimService = class {
40957
41058
  const solverExecutionResponse = await SolverApiService.postExecution(
40958
41059
  { intent_tx_hash: intentTxHash },
40959
41060
  this.config.solver,
40960
- this.config.logger
41061
+ this.config.logger,
41062
+ this.config.apiKey
40961
41063
  );
40962
41064
  if (!solverExecutionResponse.ok) {
40963
41065
  return solverExecutionResponse;
@@ -41961,7 +42063,12 @@ var LeverageYieldService = class {
41961
42063
  */
41962
42064
  async notifySolver(request) {
41963
42065
  try {
41964
- const result = await SolverApiService.postExecution(request, this.config.solver, this.config.logger);
42066
+ const result = await SolverApiService.postExecution(
42067
+ request,
42068
+ this.config.solver,
42069
+ this.config.logger,
42070
+ this.config.apiKey
42071
+ );
41965
42072
  if (result.ok) return result;
41966
42073
  const detail = result.error?.detail ?? {
41967
42074
  code: -999,
@@ -42654,18 +42761,18 @@ var SponsoringService = class {
42654
42761
  return request;
42655
42762
  }
42656
42763
  /**
42657
- * Cache key for a config request: the resolved base URL plus any per-call
42658
- * headers. Headers can select a different response from the same URL — an API
42659
- * key scoped to another deployment, or a test harness's scenario header — so
42660
- * folding them in stops one caller's override from being served to, or
42661
- * overwriting, the default path. Kept in memory as a Map key only.
42764
+ * Cache key for a config request: the resolved base URL plus the per-call headers the request will
42765
+ * actually carry, `apiKey` included. Headers can select a different response from the same URL — an
42766
+ * API key scoped to another deployment, or a test harness's scenario header — so folding them in
42767
+ * stops one caller's override from being served to, or overwriting, the default path. Names are
42768
+ * lower-cased before sorting and serialized as JSON so casing and delimiters cannot collide two
42769
+ * distinct header sets onto one key. Kept in memory as a Map key only.
42662
42770
  */
42663
42771
  configCacheKey(requestConfig) {
42664
42772
  const baseURL = requestConfig?.baseURL || this.api.sponsoring.getBaseURL();
42665
- const headers = requestConfig?.headers;
42666
- if (!headers) return baseURL;
42667
- const normalized = Object.keys(headers).sort().map((name) => `${name.toLowerCase()}=${headers[name]}`).join("&");
42668
- return normalized.length === 0 ? baseURL : `${baseURL}|${normalized}`;
42773
+ const headers = mergeHeaders(apiKeyHeader(requestConfig?.apiKey), requestConfig?.headers);
42774
+ const entries = Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
42775
+ return entries.length === 0 ? baseURL : `${baseURL}|${JSON.stringify(entries)}`;
42669
42776
  }
42670
42777
  /**
42671
42778
  * Fetch sponsor config with per-endpoint caching and in-flight deduplication.
@@ -42891,17 +42998,20 @@ var Sodax = class {
42891
42998
  const logger = resolveLogger(options?.logger);
42892
42999
  const analytics = resolveAnalytics(options?.analytics);
42893
43000
  const fee = options?.fee;
43001
+ const apiKey = options?.apiKey || void 0;
42894
43002
  const radfiSigner = options?.radfi?.signRequest;
42895
- this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
42896
- this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
43003
+ const mergeOptions = options ? { ...options, apiKey: void 0 } : void 0;
43004
+ this.instanceConfig = mergeOptions ? mergeSodaxConfig(sodaxConfig, mergeOptions) : sodaxConfig;
43005
+ this.backendApi = new BackendApiService(this.instanceConfig.api, logger, { apiKey });
42897
43006
  this.api = this.backendApi;
42898
43007
  this.config = new ConfigService({
42899
43008
  api: this.backendApi,
42900
43009
  config: this.instanceConfig,
42901
- userConfig: options,
43010
+ userConfig: mergeOptions,
42902
43011
  logger,
42903
43012
  analytics,
42904
43013
  fee,
43014
+ apiKey,
42905
43015
  radfiSigner
42906
43016
  });
42907
43017
  this.hubProvider = new EvmHubProvider({ config: this.config });
@@ -43113,6 +43223,8 @@ exports.SOLANA_CHAIN_KEYS = SOLANA_CHAIN_KEYS;
43113
43223
  exports.SOLANA_CHAIN_KEYS_SET = SOLANA_CHAIN_KEYS_SET;
43114
43224
  exports.SONIC_CHAIN_KEYS = SONIC_CHAIN_KEYS;
43115
43225
  exports.SONIC_CHAIN_KEYS_SET = SONIC_CHAIN_KEYS_SET;
43226
+ exports.SPEED_TIER_SECONDS = SPEED_TIER_SECONDS;
43227
+ exports.SPEED_TIER_THRESHOLDS = SPEED_TIER_THRESHOLDS;
43116
43228
  exports.SPONSORING_API_ERROR_CODES = SPONSORING_API_ERROR_CODES;
43117
43229
  exports.SPONSORING_API_STELLAR_BASE_PATH = SPONSORING_API_STELLAR_BASE_PATH;
43118
43230
  exports.SPONSOR_CONFIG_TTL_MS = SPONSOR_CONFIG_TTL_MS;
@@ -43202,6 +43314,7 @@ exports.encodeContractCalls = encodeContractCalls;
43202
43314
  exports.erc20Abi = erc20Abi;
43203
43315
  exports.erc4626Abi = erc4626Abi;
43204
43316
  exports.estimateBitcoinTxSize = estimateBitcoinTxSize;
43317
+ exports.estimateSwapSpeedTier = estimateSwapSpeedTier;
43205
43318
  exports.ethereumSupportedTokens = ethereumSupportedTokens;
43206
43319
  exports.executionFailed = executionFailed;
43207
43320
  exports.formatBasisPoints = formatBasisPoints;
@@ -43254,6 +43367,8 @@ exports.iconSupportedTokens = iconSupportedTokens;
43254
43367
  exports.injectiveSupportedTokens = injectiveSupportedTokens;
43255
43368
  exports.intentCreationFailed = intentCreationFailed;
43256
43369
  exports.isApprovalSupportedChainKeyType = isApprovalSupportedChainKeyType;
43370
+ exports.isAuthFailure = isAuthFailure;
43371
+ exports.isAuthStatus = isAuthStatus;
43257
43372
  exports.isBackendHttpError = isBackendHttpError;
43258
43373
  exports.isBalnMigrateParams = isBalnMigrateParams;
43259
43374
  exports.isBitcoinChainKey = isBitcoinChainKey;