@sodax/skills 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/AGENTS.md CHANGED
@@ -175,6 +175,8 @@ Chains six sub-scripts. Each catches a distinct bug class — green guards toget
175
175
 
176
176
  Run individually for faster feedback: `pnpm run check:ai-imports`, `pnpm run check:ai-keys`, etc.
177
177
 
178
+ **Prose accuracy is gated separately.** An `AI Files Drift Check` workflow runs per pull request: it works out which knowledge files the changed source could invalidate, has a read-only agent compare the claims in them against that source, then re-reads each cited quote before letting any finding count. It flags a claim the current source disproves and warns when new public surface reaches no knowledge file. It is advisory until the `AI_DRIFT_ENFORCE` repository variable is set, and is not runnable locally — the guards above are what you run before pushing.
179
+
178
180
  ### Distribution
179
181
 
180
182
  Two paths:
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "2.1.0",
7
+ "version": "2.2.0-rc.1",
8
8
  "license": "MIT",
9
9
  "description": "AI-agent skills and knowledge for consumers of @sodax/* SDKs (Claude Code, Codex, Cursor, …)",
10
10
  "keywords": [
@@ -87,6 +87,43 @@ await createIntent({ body: { ...intentBody, partnerFee } });
87
87
 
88
88
  See the `sodax-sdk` skill (integration mode), `swaps-api.md` § `partnerFee`.
89
89
 
90
+ ### API key (`x-api-key`)
91
+
92
+ The backend guards `POST /swaps/*` with an API-key check. There is ONE instance-wide key: configure it
93
+ once on the provider config — `<SodaxProvider config={{ apiKey }}>` — and every `sodax.api.*` call these
94
+ hooks make carries it. Override per request via the hooks' existing `apiConfig` param
95
+ (`RequestOverrideConfig`), which also accepts `apiKey`:
96
+
97
+ ```ts
98
+ // @ai-snippets-skip
99
+ const { data: quote } = useSwapsApiQuote({
100
+ params: { body: quoteBody, apiConfig: { apiKey: 'partner-api-key' } },
101
+ });
102
+ ```
103
+
104
+ Never put the key in a `queryKey` (the hooks already exclude `apiConfig` from their keys). Auth failures
105
+ surface with `context.status` `401`/`403` — nothing but a corrected key fixes them, so treat them as
106
+ terminal in your UI; the transient verification `503` is retried by the wire client. See the
107
+ `sodax-sdk` skill (integration mode), `swaps-api.md` § API key, for the precedence order.
108
+
109
+ Every retrying `useSwapsApi*` hook already handles this: its default `retry` is `retryUnlessAuthFailure`
110
+ (exported from `@sodax/dapp-kit`), which retries transport blips up to 3 times but never replays a
111
+ 401/403. `useSwapsApiStatus` and `useSwapsApiSubmitTxStatus` additionally stop their 1s poll on a
112
+ rejected key, instead of re-requesting forever. So an invalid key surfaces once, fast, on `error`.
113
+
114
+ Override or compose it through `queryOptions` / `mutationOptions` when you want different behaviour:
115
+
116
+ ```ts
117
+ // @ai-snippets-skip
118
+ const { data: quote } = useSwapsApiQuote({
119
+ params: { body: quoteBody },
120
+ queryOptions: { retry: (count, error) => !isAuthFailure(error) && count < 5 },
121
+ });
122
+ ```
123
+
124
+ `isAuthFailure` (re-exported from `@sodax/sdk`) is the same guard the default uses — prefer it over
125
+ re-deriving `context.status`, so your UI and the hooks agree on what counts as terminal.
126
+
90
127
  `useSwapsApiSubmitTx` is a mutation hook — per-call config (e.g. backend base URL) flows through `mutate(vars)`. The `request` is a `SubmitTxRequestV2` (`{ txHash, srcChainKey, walletAddress, intent, relayData }`):
91
128
 
92
129
  ```ts
@@ -321,7 +358,10 @@ rather than on the HTTP status.
321
358
  When the server rate-limits a key it also supplies `error.context.retryAfterSeconds`; render "try again
322
359
  in Ns" instead of a generic "try later". The SDK never auto-retries a rate limit.
323
360
 
324
- Requires `api.sponsoringApiConfig` (at minimum `apiKey`) on the `SodaxProvider` config. An api key
361
+ On the packaged gateway no sponsoring-specific credential is needed: the instance-wide key from
362
+ `<SodaxProvider config={{ apiKey }}>` (`new Sodax({ apiKey })`) is inherited by sponsoring.
363
+ `api.sponsoringApiConfig.apiKey` is the credential for an independently hosted sponsoring service, and
364
+ wins wherever the slice points. An api key
325
365
  in a browser bundle is public by nature; the service's per-key quotas, fleet cap, per-IP throttle,
326
366
  and origin gating are the real controls. Proxy through your own backend if that is not acceptable.
327
367
 
@@ -38,11 +38,17 @@ const { mutateAsyncSafe: swap } = useSwap();
38
38
 
39
39
  // vars shape (TVars):
40
40
  type UseSwapVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SwapActionParams<K, false>, 'raw'>;
41
- // = { params: CreateIntentParams; walletProvider: GetWalletProviderType<K> }
41
+ // = { params: CreateIntentParams; walletProvider: GetWalletProviderType<K>;
42
+ // extras?; timeout?; skipSimulation? } // extras: per-action partnerFee / apiKey overrides
42
43
 
43
44
  const result = await swap({ params: intentParams, walletProvider });
44
45
  ```
45
46
 
47
+ `vars` also carries the SDK's optional exec fields: `timeout` (per-attempt relay budget),
48
+ `skipSimulation`, and `extras` — per-action overrides of the configured swap `partnerFee` and the
49
+ backend API key (`extras.apiKey`, sent as `x-api-key` on the backend submit-tx leg). Both fall back to
50
+ the `SodaxProvider` config when omitted.
51
+
46
52
  `useSwapApprove` follows the same `{ params, walletProvider }` shape via `mutate(vars)`, where `params` is `CreateIntentParams<K> | CreateLimitOrderParams<K>` (the union — limit-order params also flow through `useSwapApprove`).
47
53
 
48
54
  `useCreateLimitOrder` takes `{ params: CreateLimitOrderParams; walletProvider }` (no deadline; the order persists until cancelled).
@@ -136,7 +136,7 @@ import type { SubmitTxRequestV2 } from '@sodax/sdk';
136
136
 
137
137
  function SubmitButton({ request, baseURL }: { request: SubmitTxRequestV2; baseURL: string }) {
138
138
  const { mutateAsync: submitSwapTx, isPending } = useSwapsApiSubmitTx({
139
- mutationOptions: { retry: 5 }, // overrides default retry: 3
139
+ mutationOptions: { retry: 5 }, // overrides the default `retryUnlessAuthFailure` (3 retries, never on 401/403)
140
140
  });
141
141
 
142
142
  const handleSubmit = async () => {
@@ -59,12 +59,14 @@ type BridgeExtras<K extends SpokeChainKey> = (GetChainType<K> extends 'STACKS'
59
59
  : { srcPublicKey?: never }) &
60
60
  (GetChainType<K> extends 'BITCOIN' ? { bound?: { accessToken?: string } } : { bound?: never }) & {
61
61
  partnerFee?: PartnerFee;
62
+ apiKey?: string;
62
63
  };
63
64
  ```
64
65
 
65
66
  | Slot | When | Notes |
66
67
  |---|---|---|
67
68
  | `partnerFee` | any chain, optional | Takes precedence over the config-level `bridge.partnerFee` for this call. Omit to use the configured fee. |
69
+ | `apiKey` | any chain, optional | Overrides the configured backend API key (`x-api-key`) for this action's backend submit-tx leg. Omit to use `new Sodax({ apiKey })`. |
68
70
  | `srcPublicKey` | Stacks source + `raw: true` — **required** | A Stacks address can't yield the signer public key at raw-tx build time. Omitting it fails `VALIDATION_FAILED` (`field: 'srcPublicKey'`). |
69
71
  | `bound` | raw Bitcoin TRADING source, optional | Bound Exchange (Radfi) access token; falls back to the `RadfiProvider` instance token. |
70
72
 
@@ -154,6 +154,12 @@ routes at its bare origin is reached with `baseURL: 'http://localhost:3011'`.
154
154
  per-key quotas, fleet-wide daily cap, per-IP throttle, and origin gating are the real controls. Proxy
155
155
  through your own backend if that is not acceptable.
156
156
 
157
+ The instance-wide `new Sodax({ apiKey })` is **gated** here, unlike every other backend service: it is
158
+ inherited only when the call targets a SODAX gateway (the packaged sponsoring default or the resolved
159
+ shared root), and the check runs per request against the effective target, so a per-call `baseURL`
160
+ override cannot carry it off-gateway. A custom sponsoring origin never receives it. The slice `apiKey`
161
+ above is the credential for independently hosted sponsoring and wins wherever the slice points.
162
+
157
163
  ## Cross-references
158
164
 
159
165
  - React hooks wrapping this service — `useStellarAccountActive`, `useSponsorConfig`,
@@ -46,6 +46,12 @@ sodax.swaps.cancelLimitOrder<K>(/* … */): Promise<Result<TxHashPair, SodaxErro
46
46
  sodax.swaps.approve<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
47
47
  sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxError>>;
48
48
 
49
+ sodax.swaps.getSwapSpeedTier(params: { srcToken: XToken; dstToken: XToken }): SwapSpeedTierResult;
50
+ // Synchronous, offline, no Result wrapper — estimates settlement speed from SDK config alone
51
+ // (no network / on-chain / backend call). SwapSpeedTierResult = { tier: 'fast'|'normal'|'slow', estimatedSeconds }.
52
+ // A token tied to a money-market-reserve (sodaAsset) settles faster; an Ethereum leg adds a fixed penalty.
53
+ // Safe to call synchronously while rendering a quote (e.g. an ETA badge next to the output amount).
54
+
49
55
  sodax.swaps.getStatus(
50
56
  request: SolverIntentStatusRequest, // { intent_tx_hash } — the HUB (Sonic) tx hash
51
57
  ): Promise<Result<SolverIntentStatusResponse, SolverErrorResponse>>; // legacy error shape, NOT SodaxError
@@ -91,11 +97,12 @@ type SwapActionParams<K extends SpokeChainKey, Raw extends boolean> = {
91
97
  } & WalletProviderSlot<K, Raw>;
92
98
  ```
93
99
 
94
- `extras` and every field on it are optional. `partnerFee` overrides the configured swap fee for this single action (the same override `getQuote` accepts, below); `srcPublicKey` is chain-key-gated — only typeable when `K` is a Stacks chain (`never` elsewhere) and only needed for raw (`raw: true`) Stacks `createIntent`; `bound` is chain-key-gated to Bitcoin and groups the Bound Exchange (Radfi) inputs — its `accessToken` is only needed for raw Bitcoin TRADING-mode `createIntent`, overriding the RadfiProvider's configured token and falling back to that instance token when omitted. (Grouping keeps future Bound inputs — trading mode, refresh token — under one slot rather than spreading a new `extras` field per item.) `LimitOrderActionParams<K, Raw>` carries the same `SwapExtras<K>`.
100
+ `extras` and every field on it are optional. `partnerFee` overrides the configured swap fee for this single action (the same override `getQuote` accepts, below); `apiKey` overrides the configured backend API key (`new Sodax({ apiKey })`) for this action's backend submit-tx leg, sent as the `x-api-key` header; `srcPublicKey` is chain-key-gated — only typeable when `K` is a Stacks chain (`never` elsewhere) and only needed for raw (`raw: true`) Stacks `createIntent`; `bound` is chain-key-gated to Bitcoin and groups the Bound Exchange (Radfi) inputs — its `accessToken` is only needed for raw Bitcoin TRADING-mode `createIntent`, overriding the RadfiProvider's configured token and falling back to that instance token when omitted. (Grouping keeps future Bound inputs — trading mode, refresh token — under one slot rather than spreading a new `extras` field per item.) `LimitOrderActionParams<K, Raw>` carries the same `SwapExtras<K>`.
95
101
 
96
102
  ```ts
97
103
  type SwapExtras<K extends SpokeChainKey> = {
98
104
  partnerFee?: PartnerFee; // overrides the configured swap fee for this action; falls back to config
105
+ apiKey?: string; // overrides the configured backend API key (x-api-key) for this action's backend submit-tx leg
99
106
  srcPublicKey?: string; // Stacks only (raw createIntent): signer public key. Chain-key-gated — `never` on non-Stacks K.
100
107
  bound?: BitcoinBoundExtras; // Bitcoin only: grouped Bound Exchange (Radfi) inputs. Chain-key-gated — `never` on non-Bitcoin K.
101
108
  };
@@ -321,6 +328,7 @@ await sodax.swaps.cancelIntent({
321
328
  | `cancelIntent` / `cancelLimitOrder` | `TxHashPair` = `{ srcChainTxHash, dstChainTxHash }` (not generic over `Raw`) |
322
329
  | `approve` | `TxReturnType<K, Raw>` |
323
330
  | `isAllowanceValid` | `boolean` |
331
+ | `getSwapSpeedTier` | `SwapSpeedTierResult` = `{ tier: 'fast' \| 'normal' \| 'slow', estimatedSeconds: number }` (synchronous, not a `Result`) |
324
332
 
325
333
  `RelayExtraData`:
326
334
 
@@ -54,7 +54,7 @@ sodax.api.swaps.submitTx(body: SubmitTxRequestV2, config?): Promise<Result<Submi
54
54
  sodax.api.swaps.getSubmitTxStatus(query: SubmitTxStatusQueryV2, config?): Promise<Result<SubmitTxStatusResponseV2>>;
55
55
  ```
56
56
 
57
- The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers? }`) on every method
57
+ The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers?, apiKey? }`) on every method
58
58
  applies per-call overrides that take precedence over the service config (see "Per-call overrides" below).
59
59
 
60
60
  ## `approve` can return two transactions
@@ -97,6 +97,31 @@ Optional on the type, but no default: the backend does not fill it in, and
97
97
  create-intent. `checkAllowance` / `approve` inherit the field but ignore it.
98
98
  Bridge API v2 is different: omitted `partnerFee` falls back to `bridgePartnerFee`.
99
99
 
100
+ ## API key
101
+
102
+ The backend guards `POST /swaps/*` routes with an `x-api-key` header check (keys come from the partner
103
+ portal). Unlike `partnerFee`, the config-level key DOES reach this wire path: there is ONE
104
+ instance-wide key, `new Sodax({ apiKey })`, sent on every backend request — this client,
105
+ `sodax.backendApi`, `sodax.api.bridge`, the solver API, and the backend submit-tx legs of `swap()` /
106
+ `bridge()`. There is no per-feature or per-slice swaps key. Override per call via the trailing
107
+ `RequestOverrideConfig`:
108
+
109
+ ```ts
110
+ await sodax.api.swaps.createIntent(body, { apiKey: 'per-request-key' });
111
+ ```
112
+
113
+ Precedence, highest first: per-call `headers['x-api-key']` (any casing) → per-call `apiKey` → a
114
+ configured explicit `x-api-key` header (`api.headers` / `setHeaders`) → the configured `apiKey`. That
115
+ full order is what the data, swaps, and bridge transports resolve; sponsoring's tier 3 is its own
116
+ slice/runtime headers (shared `api.headers` / `backendApi.setHeaders` never reach it — rotate via
117
+ `sodax.api.sponsoring.setHeaders`), and the solver API has no per-call override surface and no
118
+ configured-header slot, so it carries the configured `apiKey` alone. An empty `apiKey` counts as unset
119
+ and falls back. Read the configured value back on `sodax.config.apiKey`.
120
+ Auth failures surface as `EXTERNAL_API_ERROR` with `context.status` `401` (missing/invalid key) or `403`
121
+ (suspended org / missing scope) — terminal until the consumer fixes the key. The transient verification
122
+ `503` is retried automatically by the wire client (all calls, mutations included — the guard rejects
123
+ before the handler runs).
124
+
100
125
  ## Common call shapes
101
126
 
102
127
  ### Quote
@@ -180,7 +205,7 @@ if (status.ok && status.value.data.status === 'solved') { /* settled */ }
180
205
  ## Per-call overrides
181
206
 
182
207
  Every method accepts a trailing `RequestOverrideConfig` to redirect a single call to a different host or
183
- attach request-specific headers (auth, tracing), overriding the service config:
208
+ attach request-specific headers (auth, tracing) or a per-call `apiKey`, overriding the service config:
184
209
 
185
210
  ```ts
186
211
  // `baseURL` is the gateway ROOT — the SDK appends `/swaps/*` itself. Never include a service segment.
@@ -18,7 +18,7 @@ const result = sodax.config.isValidSpokeChainKey(ChainKeys.ARBITRUM_MAINNET);
18
18
  import { Sodax, ChainKeys, type SodaxOptions } from '@sodax/sdk';
19
19
 
20
20
  // `SodaxOptions` = `DeepPartial<SodaxDefaultConfig>` (the data override) plus the client-side options:
21
- // `logger`, the global `fee`, and per-feature options on `swaps` / `bridge` (e.g. `{ useBackendSubmitTx: false }` — opt out of the default-on backend 2-step flow).
21
+ // `logger`, the global `fee`, the global `apiKey` (one instance-wide key, sent as `x-api-key` on every backend request; override per request via `RequestOverrideConfig.apiKey`), and per-feature options on `swaps` / `bridge` (e.g. `{ useBackendSubmitTx: false }` — opt out of the default-on backend 2-step flow).
22
22
  const config: SodaxOptions = {
23
23
  // Per-chain overrides — merged with packaged defaults at the field level.
24
24
  chains: {
@@ -10,7 +10,7 @@ Import everything from `@sodax/sdk`. The barrel re-exports the entire `@sodax/ty
10
10
  import {
11
11
  // Main entry
12
12
  Sodax,
13
- type SodaxOptions, // constructor param: DeepPartial<SodaxDefaultConfig> & client options (logger + global fee)
13
+ type SodaxOptions, // constructor param: DeepPartial<SodaxDefaultConfig> & client options (logger + global fee + the instance-wide backend apiKey)
14
14
  type SodaxConfig, // merged result: SodaxDefaultConfig & client options (e.g. sodax.instanceConfig)
15
15
  type SodaxDefaultConfig, // static data contract the backend serves / defaults are built from
16
16
  type DeepPartial,
@@ -147,7 +147,7 @@ import {
147
147
  type BaseApiConfig, // { baseURL, timeout, headers } — baseURL is the GATEWAY ROOT
148
148
  type BackendApiConfig, // BaseApiConfig & { basePath? } — the data API's mount, default '/be'
149
149
  type CustomApiConfig, // point the swaps / sponsoring API at its own endpoint
150
- type SwapsApiConfig,
150
+ type SwapsApiConfig, // = BaseApiConfig — the swaps client uses the instance-wide apiKey
151
151
  type SponsoringApiConfig, // BaseApiConfig & { apiKey? } — own host, own x-api-key
152
152
  DEFAULT_API_BASE_URL, // 'https://api.sodax.com/v1' — the root every service resolves
153
153
  BACKEND_API_BASE_PATH, // '/be'
@@ -180,6 +180,7 @@ import {
180
180
  // Structured non-2xx backend failure (on error.cause) — status + parsed body
181
181
  BackendHttpError,
182
182
  isBackendHttpError, // bundle-safe guard; prefer over instanceof
183
+ isAuthFailure, // terminal API-key rejection (context.status 401/403); a 503 is transient
183
184
 
184
185
  // Backend intent events — `IntentResponse.events` is `unknown[]`
185
186
  isFillEvent, // narrows an events entry to a recorded `intent-filled`
@@ -74,7 +74,7 @@ narrowing, wallet providers passed per call) are covered in:
74
74
  4. Failure handling branches on `error.context.nextAction` — not on `message`, not on `status` alone.
75
75
  5. The sponsor account is read from `getStellarSponsorConfig()` (or left to `activateStellarAccount`), never hardcoded.
76
76
  6. `onSignatureRequired` is wired in any interactive UI.
77
- 7. The api key comes from an env var via `sponsoringApiConfig.apiKey` (or an `x-api-key` header) — not a literal.
77
+ 7. The api key comes from an env var — not a literal. On the packaged SODAX gateway the instance-wide `new Sodax({ apiKey })` is inherited; for an independently hosted sponsoring service set `sponsoringApiConfig.apiKey` (or an `x-api-key` header), which wins.
78
78
 
79
79
  ## Related granular skills (same family)
80
80