@sodax/skills 2.1.0 → 2.2.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/AGENTS.md +3 -1
  2. package/package.json +1 -1
  3. package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +2 -2
  4. package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +7 -4
  5. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +87 -3
  6. package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +7 -1
  7. package/skills/sodax-dapp-kit/integration/knowledge/recipes/backend-queries.md +43 -1
  8. package/skills/sodax-dapp-kit/integration/knowledge/recipes/invalidations.md +8 -6
  9. package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +1 -1
  10. package/skills/sodax-dapp-kit/integration/knowledge/recipes/wallet-connectivity.md +26 -1
  11. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +8 -0
  12. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +2 -1
  13. package/skills/sodax-sdk/backend-api/SKILL.md +2 -1
  14. package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +1 -1
  15. package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +9 -1
  16. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +2 -0
  17. package/skills/sodax-sdk/integration/knowledge/features/money-market.md +1 -1
  18. package/skills/sodax-sdk/integration/knowledge/features/sponsoring.md +6 -0
  19. package/skills/sodax-sdk/integration/knowledge/features/swap.md +9 -1
  20. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +27 -2
  21. package/skills/sodax-sdk/integration/knowledge/quickstart.md +42 -0
  22. package/skills/sodax-sdk/integration/knowledge/recipes/initialize-sodax.md +1 -1
  23. package/skills/sodax-sdk/integration/knowledge/reference/chain-keys.md +4 -4
  24. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +10 -2
  25. package/skills/sodax-sdk/sponsoring/SKILL.md +1 -1
package/AGENTS.md CHANGED
@@ -144,7 +144,7 @@ To add another meta skill later: drop `skills/<name>/SKILL.md` + a flat `knowled
144
144
 
145
145
  - **SKILL.md frontmatter is load-bearing.** For a broad top-level skill at `skills/<broad>/SKILL.md`, `name` must equal the directory basename (e.g. `name: sodax-sdk`). For a nested granular skill at `skills/<broad>/<feature>/SKILL.md`, `name` must equal `<broad>-<feature>` (e.g. `name: sodax-sdk-swap`) — namespaced so each granular name stays unique and never collides with its parent (these names are still validated even though granular skills are bundled, not registered). `description` triggers selection — write it concretely with explicit trigger phrases (the agent looks at description alone to decide whether to load the skill). See existing skills for examples.
146
146
  - **`description:` MUST be a single-quoted YAML scalar.** The [`vercel-labs/skills` CLI](https://github.com/vercel-labs/skills) parses frontmatter with strict YAML 1.2 — a plain (unquoted) scalar that contains `: ` (colon-space, the YAML mapping indicator) fails to parse and the skill is silently skipped at install time. Wrap every description in single quotes (`description: '...'`), doubling any apostrophe inside (`'` → `''`). Block scalars (`>-`) are also valid YAML but churn diffs and change rendering — prefer single quotes. The `check:ai-structural` validator parses each frontmatter through a real YAML parser to catch violations; it's stricter than the bash-grep check it replaced for exactly this reason.
147
- - **Optional frontmatter: `license` + `metadata`.** Beyond the required `name` / `description`, every SKILL.md also carries `license: MIT` (matches `package.json`) and a `metadata` block with `version` and `author: sodax`. These are the portable optional fields the [`vercel-labs/skills` CLI](https://github.com/vercel-labs/skills) and skills.sh understand (`metadata` is free-form k/v; `version` conventionally tracks semver). **Quote the version** (`version: '0.0.1'`) — an unquoted two-segment value like `1.0` would parse as the YAML number `1`. Keep `metadata.version` in lockstep with `package.json`'s `version` — bump both together at release. The fields are additive; `check:ai-structural` only asserts `name` / `description` and does not whitelist, so extra keys are safe.
147
+ - **Optional frontmatter: `license` + `metadata`.** Beyond the required `name` / `description`, every SKILL.md also carries `license: MIT` (matches `package.json`) and a `metadata` block with `version` and `author: sodax`. These are the portable optional fields the [`vercel-labs/skills` CLI](https://github.com/vercel-labs/skills) and skills.sh understand (`metadata` is free-form k/v; `version` conventionally tracks semver). **Quote the version** (`version: '0.0.1'`) — an unquoted two-segment value like `1.0` would parse as the YAML number `1`. The fields are additive; `check:ai-structural` only asserts `name` / `description` and does not whitelist, so extra keys are safe.
148
148
  - **Skills link into knowledge by relative path.** From a SKILL.md, target paths look like `./integration/knowledge/ai-rules.md` or `./migration-v1-to-v2/knowledge/README.md`. Cross-mode links (between the two subtrees of the same skill) use a `<other-mode>/knowledge/<target>` segment, prefixed by `../` repeated enough times to climb out of the source subtree: depth-0 knowledge files (e.g. `<mode>/knowledge/README.md`, `quickstart.md`) use a `../../` prefix; depth-1 files (e.g. `<mode>/knowledge/features/*.md`, `<mode>/knowledge/recipes/*.md`) use `../../../`. The `check-skills.sh` validator verifies all resolve.
149
149
  - **Cross-SDK-package references are forbidden.** A skill MUST NOT link to (or cite a relative/absolute path into) a skill belonging to a different SDK package **family** (`sdk`, `wallet-sdk-core`, `wallet-sdk-react`, `dapp-kit`). Concretely: `sodax-dapp-kit` knowledge MUST NOT reference `sodax-sdk`, `sodax-wallet-sdk-react`, or `sodax-wallet-sdk-core` content via `../../<other-skill>/...`, GitHub URLs, or any other clickable form. Use prose pointers naming the sibling skill instead (e.g., *"load the `sodax-sdk` skill (integration mode)"*). **Intra-family links are allowed**: integration ↔ migration-v1-to-v2 subtrees within the SAME broad skill, broad ↔ granular within the same family (e.g. `sodax-sdk` ↔ `sodax-sdk/swap`), and granular ↔ granular under the same broad parent. These all ship together and document the same SDK package.
150
150
  - **Knowledge files** retain the structure they had under each package's `ai-exported/<mode>/` tree: `README.md`, `ai-rules.md`, `features/`, `recipes/`, `reference/`, plus `architecture.md`, `quickstart.md`, `chain-specifics.md`, and `breaking-changes/` where applicable. New files go under whichever subdirectory fits; both skills and knowledge are expected to evolve as the SDK does.
@@ -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.2",
8
8
  "license": "MIT",
9
9
  "description": "AI-agent skills and knowledge for consumers of @sodax/* SDKs (Claude Code, Codex, Cursor, …)",
10
10
  "keywords": [
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: sodax-dapp-kit-auxiliary-services
3
- description: 'Granular skill for the @sodax/dapp-kit v2 auxiliary surfaces — partner fee claiming (useFeeClaimSwap, useApproveToken, useSetSwapPreference, useGetAutoSwapPreferences, useIsTokenApproved), recovery (useHubAssetBalances, useWithdrawHubAsset), read-only backend queries (useBackendIntentByTxHash, useBackendUserIntents, useBackendOrderbook, useBackendMoneyMarketPosition), the Swaps API v2 client hooks (useSwapsApiQuote, useSwapsApiSubmitTx, useSwapsApiStatus), sponsored Stellar account activation (useStellarGate, useStellarAccountActive, useStellarAccountStatus, useSponsorConfig, useActivateStellarAccount), and shared utilities (useSodaxContext, useHubProvider, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useEstablishTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), activating a Stellar account for a user who holds no XLM, or cross-cutting utilities (token balances, gas estimation, Stellar trustlines). Covers BOTH integration and migration. Links into the parent sodax-dapp-kit knowledge tree.'
3
+ description: 'Granular skill for the @sodax/dapp-kit v2 auxiliary surfaces — partner fee claiming (useFeeClaimSwap, useApproveToken, useSetSwapPreference, useGetAutoSwapPreferences, useIsTokenApproved), recovery (useHubAssetBalances, useWithdrawHubAsset), read-only backend queries (useBackendIntentByTxHash, useBackendUserIntents, useBackendOrderbook, useBackendMoneyMarketPosition), the Swaps API v2 client hooks (useSwapsApiQuote, useSwapsApiSubmitTx, useSwapsApiStatus), sponsored Stellar account activation (useStellarGate, useStellarAccountActive, useStellarAccountStatus, useSponsorConfig, useActivateStellarAccount), and shared utilities (useSodaxContext, useHubProvider, useBalances, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useEstablishTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), activating a Stellar account for a user who holds no XLM, or cross-cutting utilities (token balances, gas estimation, Stellar trustlines). Covers BOTH integration and migration. Links into the parent sodax-dapp-kit knowledge tree.'
4
4
  license: MIT
5
5
  metadata:
6
6
  version: '0.0.1'
@@ -19,7 +19,7 @@ Granular skill for the smaller `@sodax/dapp-kit` v2 surfaces grouped together: *
19
19
  - **Recovery:** `useHubAssetBalances` (list stuck hub assets) → `useWithdrawHubAsset` (withdraw one back to a spoke). Follows a *known* failed cross-chain op — investigate the failure first.
20
20
  - **Backend reads (no wallet):** intent tracking (`useBackendIntentByTxHash` polls 1s, `useBackendIntentByHash`, `useBackendUserIntents`), orderbook (`useBackendOrderbook` — `pagination` nests under `params`), MM data (`useBackendMoneyMarketPosition` etc.), and the Swaps API v2 client (`useSwapsApi*` — e.g. `useSwapsApiSubmitTx`, `useSwapsApiSubmitTxStatus`, `useSwapsApiQuote`).
21
21
  - **Stellar prerequisites:** `useStellarGate` sequences the ordered prerequisites — the account must EXIST (sponsored activation, free to the user), must TRUST the token, and only then must be able to PAY for the trustline it needs. A freshly activated account holds zero XLM. An account that already holds the trustline needs no XLM at all, which is why affordability is checked last. A failed check sets `checkFailed` with `error`/`retry` — render it, or the fail-closed gate becomes an unexplained dead button. Lower-level: `useStellarAccountStatus`, `useStellarAccountActive`, `useSponsorConfig`, `useActivateStellarAccount`.
22
- - **Shared utilities:** `useSodaxContext`, `useHubProvider`, `useXBalances` (needs `xService` from wallet-sdk-react), `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`, `useEstimateGas`, `useStellarTrustlineCheck` / `useEstablishTrustline`.
22
+ - **Shared utilities:** `useSodaxContext`, `useHubProvider`, `useBalances` (SDK-backed — no `xService`, reads via `SodaxProvider`) / `useXBalances` (needs `xService` from wallet-sdk-react), `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`, `useEstimateGas`, `useStellarTrustlineCheck` / `useEstablishTrustline`.
23
23
 
24
24
  ## Integration workflow (new v2 code)
25
25
 
@@ -132,6 +132,7 @@ import {
132
132
  useSodaxContext,
133
133
  useSafeMutation,
134
134
  unwrapResult,
135
+ invalidateBalances,
135
136
  type MutationHookParams,
136
137
  type SafeUseMutationResult,
137
138
  } from '@sodax/dapp-kit';
@@ -149,8 +150,8 @@ export function useSwap<K extends SpokeChainKey = SpokeChainKey>({
149
150
  ...mutationOptions,
150
151
  mutationFn: async vars => unwrapResult(await sodax.swaps.swap({ ...vars, raw: false })),
151
152
  onSuccess: async (data, vars, ctx) => {
152
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });
153
- queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.dstChainKey] });
153
+ // Covers both balance query families; they never prefix-match each other.
154
+ invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
154
155
  await mutationOptions?.onSuccess?.(data, vars, ctx);
155
156
  },
156
157
  });
@@ -274,7 +275,8 @@ Worked examples:
274
275
  // @ai-snippets-skip
275
276
  queryKey: ['mm', 'userReservesData', spokeChainKey, userAddress]
276
277
  queryKey: ['mm', 'allowance', srcChainKey, token, action]
277
- queryKey: ['shared', 'xBalances', xChainId, tokens, address]
278
+ queryKey: ['shared', 'balances', chainKey, tokens, address] // useBalances
279
+ queryKey: ['shared', 'xBalances', xChainId, tokens, address] // useXBalances
278
280
  mutationKey: ['mm', 'supply']
279
281
  queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo', tokenId, poolKey] });
280
282
  ```
@@ -286,7 +288,8 @@ Hooks organized by feature domain in `src/hooks/`:
286
288
  ```
287
289
  hooks/
288
290
  ├── shared/ # useSodaxContext, useSafeMutation, unwrapResult, useEstimateGas,
289
- │ # useDeriveUserWalletAddress, useGetUserHubWalletAddress, useXBalances,
291
+ │ # useDeriveUserWalletAddress, useGetUserHubWalletAddress,
292
+ │ # useBalances, useXBalances, invalidateBalances,
290
293
  │ # useStellarTrustlineCheck, useEstablishTrustline (+ deprecated useRequestTrustline)
291
294
  ├── provider/ # useHubProvider
292
295
  ├── swap/ # useQuote, useSwap, useStatus, useSwapAllowance, useSwapApprove,
@@ -64,6 +64,15 @@ useBackendMoneyMarketAssetBorrowers({ params, queryOptions });
64
64
  useBackendAllMoneyMarketBorrowers({ params: { pagination: { offset, limit } }, queryOptions });
65
65
  ```
66
66
 
67
+ ### Oracle data
68
+
69
+ ```ts
70
+ // @ai-snippets-skip
71
+ useBackendOracleMarkets({ queryOptions }); // staleTime 60s; discovery: quote, intervals, symbols
72
+ // from/to are UNIX seconds over the half-open range [from, to), at most 5000 buckets; staleTime 10s
73
+ useBackendOracleCandles({ params: { symbol, interval, from, to }, queryOptions });
74
+ ```
75
+
67
76
  ### Swaps API (`sodax.api.swaps`)
68
77
 
69
78
  Typed React Query wrappers over the backend **Swaps API v2** — one `useSwapsApi*` hook per endpoint of `sodax.api.swaps.*` (21 total: tokens, quote, deadline, allowance, approve, create / submit / cancel intent, status, intent hash / packet / extra-data, intent lookups, limit orders, gas estimate, fees, submit-tx + status). They call the backend HTTP API and are distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive `sodax.swaps` (the on-chain `SwapService`). Reads take `{ params, queryOptions }`; the six actions (`approve`, `createIntent`, `submitIntent`, `cancelIntent`, `createLimitOrder`, `submitTx`) are mutations taking `{ mutationOptions }`, with domain inputs flowing through `mutate(vars)`.
@@ -87,6 +96,43 @@ await createIntent({ body: { ...intentBody, partnerFee } });
87
96
 
88
97
  See the `sodax-sdk` skill (integration mode), `swaps-api.md` § `partnerFee`.
89
98
 
99
+ ### API key (`x-api-key`)
100
+
101
+ The backend guards `POST /swaps/*` with an API-key check. There is ONE instance-wide key: configure it
102
+ once on the provider config — `<SodaxProvider config={{ apiKey }}>` — and every `sodax.api.*` call these
103
+ hooks make carries it. Override per request via the hooks' existing `apiConfig` param
104
+ (`RequestOverrideConfig`), which also accepts `apiKey`:
105
+
106
+ ```ts
107
+ // @ai-snippets-skip
108
+ const { data: quote } = useSwapsApiQuote({
109
+ params: { body: quoteBody, apiConfig: { apiKey: 'partner-api-key' } },
110
+ });
111
+ ```
112
+
113
+ Never put the key in a `queryKey` (the hooks already exclude `apiConfig` from their keys). Auth failures
114
+ surface with `context.status` `401`/`403` — nothing but a corrected key fixes them, so treat them as
115
+ terminal in your UI; the transient verification `503` is retried by the wire client. See the
116
+ `sodax-sdk` skill (integration mode), `swaps-api.md` § API key, for the precedence order.
117
+
118
+ Every retrying `useSwapsApi*` hook already handles this: its default `retry` is `retryUnlessAuthFailure`
119
+ (exported from `@sodax/dapp-kit`), which retries transport blips up to 3 times but never replays a
120
+ 401/403. `useSwapsApiStatus` and `useSwapsApiSubmitTxStatus` additionally stop their 1s poll on a
121
+ rejected key, instead of re-requesting forever. So an invalid key surfaces once, fast, on `error`.
122
+
123
+ Override or compose it through `queryOptions` / `mutationOptions` when you want different behaviour:
124
+
125
+ ```ts
126
+ // @ai-snippets-skip
127
+ const { data: quote } = useSwapsApiQuote({
128
+ params: { body: quoteBody },
129
+ queryOptions: { retry: (count, error) => !isAuthFailure(error) && count < 5 },
130
+ });
131
+ ```
132
+
133
+ `isAuthFailure` (re-exported from `@sodax/sdk`) is the same guard the default uses — prefer it over
134
+ re-deriving `context.status`, so your UI and the hooks agree on what counts as terminal.
135
+
90
136
  `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
137
 
92
138
  ```ts
@@ -138,7 +184,8 @@ Cross-cutting hooks used by other features.
138
184
  // @ai-snippets-skip
139
185
  useSodaxContext(); // Access the Sodax SDK instance
140
186
  useHubProvider(); // Hub chain (Sonic) provider
141
- useXBalances({ params, queryOptions }); // Cross-chain token balances
187
+ useBalances({ params, queryOptions }); // SDK-backed wallet balances (no xService)
188
+ useXBalances({ params, queryOptions }); // Cross-chain token balances (needs xService)
142
189
  useDeriveUserWalletAddress({ params, queryOptions }); // Hub wallet address (CREATE3)
143
190
  useGetUserHubWalletAddress({ params, queryOptions }); // Hub wallet via wallet router
144
191
  useEstimateGas({ mutationOptions }); // Gas estimation for raw tx
@@ -173,6 +220,36 @@ const xService = useXService({ xChainType: getXChainType(xChainId) });
173
220
  const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });
174
221
  ```
175
222
 
223
+ ### `useBalances` shape (SDK-backed, no `xService`)
224
+
225
+ `useBalances` is the SDK-backed successor to `useXBalances`: it reads wallet balances straight from the core SDK (`sodax.spoke.getWalletBalances`) via the `SodaxProvider` context, so it needs **no** `xService` from `@sodax/wallet-sdk-react`. Both hooks still exist — prefer `useBalances` when the app already has a `SodaxProvider`; keep `useXBalances` when you're wiring balances through the wallet layer.
226
+
227
+ ```ts
228
+ // @ai-snippets-skip
229
+ type UseBalancesParams = ReadHookParams<Record<string, bigint>, {
230
+ chainKey: SpokeChainKey | undefined; // the chain the read executes against
231
+ tokens: readonly XToken[]; // tokens to fetch balances for
232
+ address: string | undefined;
233
+ }>;
234
+ ```
235
+
236
+ The query runs only when `chainKey`, `address`, and `tokens.length > 0` are all present, refetching every 5s (same interval as `useXBalances`). `data` is a `Record<string, bigint>` mapping each token address to its balance in smallest units. queryKey: `['shared', 'balances', chainKey, tokens.map(t => [t.symbol, t.address]), address]`.
237
+
238
+ **`chainKey` decides the chain that is read.** The SDK ignores `token.chainKey`, so a token that does not live on `chainKey` reads as `0n` rather than erroring — commit the chain and the token list in the same state update. (`useXBalances` is the opposite: it derives the chain from `xTokens[0].chainKey` and ignores the `xChainId` you pass.)
239
+
240
+ **Failure model.** A token that could not be read is logged by the SDK and reported as `0n` — a flaky RPC and an empty wallet look the same, always in the conservative direction (under-reporting blocks a spend, never permits one). The query errors only when the whole batch is unusable: a mismatched `token.chainKey`, an RPC every token depends on, or a batch in which no token could be read at all.
241
+
242
+ **Chain-specific values.** Stellar XLM reports the *spendable* amount — total minus the minimum reserve and selling liabilities, not the raw balance. Bitcoin returns `0n` for Rune tokens, whose amounts the UTXO endpoint does not carry.
243
+
244
+ ```tsx
245
+ // @ai-snippets-skip
246
+ // No `xService` — just the SodaxProvider context the hook reads internally.
247
+ const { data: balances } = useBalances({ params: { chainKey, address, tokens } });
248
+ const usdcBalance = balances?.[usdc.address] ?? 0n;
249
+ ```
250
+
251
+ After a mutation, invalidate with the `invalidateBalances(queryClient, chainKey)` helper exported from `@sodax/dapp-kit` — it covers both `['shared','balances']` and `['shared','xBalances']`, which never match each other. Every dapp-kit mutation hook already calls it.
252
+
176
253
  ### Stellar prerequisites — use `useStellarGate`
177
254
 
178
255
  Stellar has ordered prerequisites for a destination account, and they are invisible until they bite:
@@ -321,7 +398,10 @@ rather than on the HTTP status.
321
398
  When the server rate-limits a key it also supplies `error.context.retryAfterSeconds`; render "try again
322
399
  in Ns" instead of a generic "try later". The SDK never auto-retries a rate limit.
323
400
 
324
- Requires `api.sponsoringApiConfig` (at minimum `apiKey`) on the `SodaxProvider` config. An api key
401
+ On the packaged gateway no sponsoring-specific credential is needed: the instance-wide key from
402
+ `<SodaxProvider config={{ apiKey }}>` (`new Sodax({ apiKey })`) is inherited by sponsoring.
403
+ `api.sponsoringApiConfig.apiKey` is the credential for an independently hosted sponsoring service, and
404
+ wins wherever the slice points. An api key
325
405
  in a browser bundle is public by nature; the service's per-key quotas, fleet cap, per-IP throttle,
326
406
  and origin gating are the real controls. Proxy through your own backend if that is not acceptable.
327
407
 
@@ -333,12 +413,16 @@ and origin gating are the real controls. Proxy through your own backend if that
333
413
  | `useSwapsApiSubmitTxStatus` | 1s | requires `txHash` + `srcChainKey`; stops on `solved` / `failed` |
334
414
  | `useSwapsApiStatus` | 1s | solver intent status; stops on status `3` / `4` |
335
415
  | `useBackendOrderbook` | none | `staleTime: 30s` — fresh-window, no background refetch |
416
+ | `useBackendOracleMarkets` | none | `staleTime: 60s` |
417
+ | `useBackendOracleCandles` | none | `staleTime: 10s` — matches the ~10s server-side cache |
336
418
  | `useExpiredUtxos` (bitcoin) | 60s | refetchInterval |
337
419
  | `useQuote` (swap) | 3s | refetchInterval |
338
420
  | `useStatus` (swap) | 3s | stops on status `3`/`4`, and after 40 consecutive NOT_FOUND fetches |
339
421
  | `useSwapAllowance` (swap) | 2s | refetchInterval |
340
422
  | `useMMAllowance` (mm) | 5s | refetchInterval; `enabled: false` for borrow/withdraw actions |
341
423
  | Reserves data (mm) | 5s | `useReservesData` / `useReservesHumanized` / user position hooks |
424
+ | `useBalances` | 5s | refetchInterval |
425
+ | `useXBalances` | 5s | refetchInterval |
342
426
  | Most others | None | |
343
427
 
344
428
  All overridable via `queryOptions.refetchInterval`.
@@ -346,6 +430,6 @@ All overridable via `queryOptions.refetchInterval`.
346
430
  ## Cross-references
347
431
 
348
432
  - [`../recipes/backend-queries.md`](../recipes/backend-queries.md) — worked examples for intent tracking, orderbook, MM data.
349
- - [`../recipes/wallet-connectivity.md`](../recipes/wallet-connectivity.md) — `useXBalances` worked example.
433
+ - [`../recipes/wallet-connectivity.md`](../recipes/wallet-connectivity.md) — `useBalances` / `useXBalances` worked examples.
350
434
  - [`features/auxiliary-services.md`](../../../migration-v1-to-v2/knowledge/features/auxiliary-services.md) — v1 → v2 porting.
351
435
  - `sodax-sdk`: `integration/knowledge/features/auxiliary-services.md` — underlying SDK auxiliary surfaces (partner, recovery, backendApi).
@@ -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).
@@ -31,6 +31,13 @@ Read-only data hooks. No wallet connection required.
31
31
  | `useBackendMoneyMarketAssetBorrowers` | Borrowers for an asset |
32
32
  | `useBackendAllMoneyMarketBorrowers` | All borrowers |
33
33
 
34
+ ### Oracle
35
+
36
+ | Hook | Purpose |
37
+ |------|---------|
38
+ | `useBackendOracleMarkets` | Oracle candle discovery: quote, intervals, symbols (cached 60s) |
39
+ | `useBackendOracleCandles` | USD OHLC candles for a symbol over `[from, to)` in UNIX seconds (cached 10s) |
40
+
34
41
  ### Swaps API (`sodax.api.swaps`)
35
42
 
36
43
  | Hook | Purpose |
@@ -95,6 +102,41 @@ function Orderbook() {
95
102
  }
96
103
  ```
97
104
 
105
+ ## Oracle Candles
106
+
107
+ ```tsx
108
+ import { useState } from 'react';
109
+ import { useBackendOracleCandles, useBackendOracleMarkets } from '@sodax/dapp-kit';
110
+
111
+ function DailyEthCandles() {
112
+ const { data: markets, isLoading } = useBackendOracleMarkets();
113
+ // `from`/`to` are UNIX seconds over the half-open range [from, to), at most 5000 buckets.
114
+ // Hold the window end in state: deriving it from `Date.now()` during render changes the query
115
+ // key on every render that crosses a second boundary, so the query refetches from scratch.
116
+ const [to, setTo] = useState(() => Math.floor(Date.now() / 1000));
117
+ const { data } = useBackendOracleCandles({
118
+ params: { symbol: 'ETH', interval: '1d', from: to - 30 * 86400, to },
119
+ });
120
+
121
+ if (isLoading) return <div>Loading...</div>;
122
+ if (!markets?.symbols.includes('ETH')) return <div>No ETH candle data</div>;
123
+ return (
124
+ <>
125
+ <button type="button" onClick={() => setTo(Math.floor(Date.now() / 1000))}>
126
+ Refresh
127
+ </button>
128
+ <ul>
129
+ {data?.candles.map(candle => (
130
+ <li key={candle.timestamp}>
131
+ O {candle.open} H {candle.high} L {candle.low} C {candle.close}
132
+ </li>
133
+ ))}
134
+ </ul>
135
+ </>
136
+ );
137
+ }
138
+ ```
139
+
98
140
  ## Money Market Dashboard
99
141
 
100
142
  ```tsx
@@ -136,7 +178,7 @@ import type { SubmitTxRequestV2 } from '@sodax/sdk';
136
178
 
137
179
  function SubmitButton({ request, baseURL }: { request: SubmitTxRequestV2; baseURL: string }) {
138
180
  const { mutateAsync: submitSwapTx, isPending } = useSwapsApiSubmitTx({
139
- mutationOptions: { retry: 5 }, // overrides default retry: 3
181
+ mutationOptions: { retry: 5 }, // overrides the default `retryUnlessAuthFailure` (3 retries, never on 401/403)
140
182
  });
141
183
 
142
184
  const handleSubmit = async () => {
@@ -58,15 +58,17 @@ Each feature mutation hook invalidates the related read keys. Common patterns:
58
58
 
59
59
  | Mutation | Invalidates |
60
60
  |---|---|
61
- | `useSwap` | `['shared', 'xBalances', srcChainKey]`, `['shared', 'xBalances', dstChainKey]` |
62
- | `useBridge` | Same as `useSwap` (xBalances on both chains). |
63
- | `useSupply`, `useWithdraw`, `useBorrow`, `useRepay` | `['mm', 'userReservesData']`, `['shared', 'xBalances', srcChainKey]`, plus reserves data on the affected token. |
64
- | `useStake`, `useUnstake`, `useClaim`, `useCancelUnstake`, `useInstantUnstake` | `['staking', 'info']`, `['staking', 'unstakingInfo']`, `['shared', 'xBalances', srcChainKey]`. |
65
- | `useDexDeposit`, `useDexWithdraw` | `['dex', 'poolBalances']`, `['shared', 'xBalances', srcChainKey]`. |
61
+ | `useSwap` | `invalidateBalances(queryClient, srcChainKey, dstChainKey)` |
62
+ | `useBridge` | Same as `useSwap` (balances on both chains). |
63
+ | `useSupply`, `useWithdraw`, `useBorrow`, `useRepay` | `['mm', 'userReservesData']`, `invalidateBalances(queryClient, srcChainKey)`, plus reserves data on the affected token. |
64
+ | `useStake`, `useUnstake`, `useClaim`, `useCancelUnstake`, `useInstantUnstake` | `['staking', 'info']`, `['staking', 'unstakingInfo']`, `invalidateBalances(queryClient, srcChainKey)`. |
65
+ | `useDexDeposit`, `useDexWithdraw` | `['dex', 'poolBalances']`, `invalidateBalances(queryClient, srcChainKey)`. |
66
66
  | `useSupplyLiquidity`, `useDecreaseLiquidity`, `useClaimRewards` | `['dex', 'positionInfo', tokenId]`, `['dex', 'poolBalances']`. |
67
- | `useMigrateIcxToSoda`, etc. | `['shared', 'xBalances']` for source + destination chains. |
67
+ | `useMigrateIcxToSoda`, etc. | `invalidateBalances(queryClient, …)` for source + destination chains. |
68
68
  | Approve hooks (`useSwapApprove`, etc.) | The corresponding allowance read (`['swap', 'allowance']`, etc.). |
69
69
 
70
+ `invalidateBalances(queryClient, ...chainKeys)` is exported from `@sodax/dapp-kit`; it invalidates BOTH `['shared','balances', chainKey]` (`useBalances`) and `['shared','xBalances', chainKey]` (`useXBalances`), skipping `undefined` and collapsing duplicates. React Query matches keys element-wise, so one never matches the other — hand-rolling a single key leaves the other hook stale. Use the helper in your own mutations too.
71
+
70
72
  The exact keys are derived from `vars` at success time — so a successful supply on Base only invalidates Base-side reserves, not Arbitrum's.
71
73
 
72
74
  ## Adding cross-feature invalidations
@@ -250,7 +250,7 @@ console.log({ swap, isError, error, swapsInFlight });
250
250
 
251
251
  ### Balance display
252
252
 
253
- Balances come from `@sodax/wallet-sdk-react`, not from dapp-kit. See `wallet-connectivity.md` for `useXBalances`.
253
+ Two options, both in dapp-kit: `useBalances` (SDK-backed, needs only a `SodaxProvider`) or `useXBalances` (wallet-layer, needs an `xService` from `@sodax/wallet-sdk-react`). See `wallet-connectivity.md`.
254
254
 
255
255
  ## Types
256
256
 
@@ -12,7 +12,8 @@ Connect wallets and pass wallet providers to feature hooks.
12
12
  | `useHubProvider` | `@sodax/dapp-kit` | Utility | Access the hub chain (Sonic) provider |
13
13
  | `useDeriveUserWalletAddress` | `@sodax/dapp-kit` | Query | Derive hub wallet address from spoke address (CREATE3) |
14
14
  | `useGetUserHubWalletAddress` | `@sodax/dapp-kit` | Query | Derive hub wallet address via wallet router |
15
- | `useXBalances` | `@sodax/dapp-kit` | Query | Cross-chain token balances for an address |
15
+ | `useBalances` | `@sodax/dapp-kit` | Query | SDK-backed wallet token balances (no `xService`) |
16
+ | `useXBalances` | `@sodax/dapp-kit` | Query | Cross-chain token balances for an address (needs `xService`) |
16
17
  | `useEstimateGas` | `@sodax/dapp-kit` | Mutation | Estimate gas for raw transactions |
17
18
  | `useStellarTrustlineCheck` | `@sodax/dapp-kit` | Query | Check if Stellar account has sufficient trustline |
18
19
  | `useEstablishTrustline` | `@sodax/dapp-kit` | Mutation | Request a Stellar trustline for a token |
@@ -80,6 +81,30 @@ function TokenBalance({ address, xTokens }: { address: string; xTokens: readonly
80
81
  }
81
82
  ```
82
83
 
84
+ ### SDK-backed alternative: `useBalances`
85
+
86
+ `useBalances` reads wallet balances straight from the core SDK (`sodax.spoke.getWalletBalances`) via the `SodaxProvider` context, so it drops the `xService` requirement — no `@sodax/wallet-sdk-react` hook needed. Prefer it when the app already has a `SodaxProvider`; the params collapse to `chainKey`, the `tokens` list, and the `address`.
87
+
88
+ The two hooks are not drop-in equivalents — check these before migrating a screen:
89
+
90
+ - `chainKey` decides the chain read; `token.chainKey` is ignored, so a token from another chain reads as `0n` rather than erroring. `useXBalances` is the opposite: it derives the chain from `xTokens[0].chainKey` and ignores the `xChainId` you pass.
91
+ - A token that could not be read is logged by the SDK and reported as `0n`, so it is indistinguishable from an empty wallet. The query errors only when the entire batch is unusable.
92
+ - Stellar XLM is the *spendable* amount (total minus minimum reserve and selling liabilities); Bitcoin Rune tokens read as `0n` because the UTXO endpoint carries no rune amounts.
93
+
94
+
95
+ ```tsx
96
+ import { useBalances } from '@sodax/dapp-kit';
97
+ import { ChainKeys, type XToken } from '@sodax/sdk';
98
+
99
+ function TokenBalanceViaSdk({ address, tokens }: { address: string; tokens: readonly XToken[] }) {
100
+ const chainKey = ChainKeys.BSC_MAINNET;
101
+ // No `xService` — the hook reads the SDK instance from the SodaxProvider context.
102
+ const { data: balances } = useBalances({ params: { chainKey, address, tokens } });
103
+
104
+ // balances is a map of token address → balance (bigint), refetched every 5s
105
+ }
106
+ ```
107
+
83
108
  ## Use Wallet Provider in Feature Hooks
84
109
 
85
110
  All mutation hooks accept no arguments at initialization level. The `walletProvider` flows through `mutate(vars)`:
@@ -165,6 +165,13 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
165
165
  | `useBackendMoneyMarketAssetBorrowers` | Borrowers for an asset |
166
166
  | `useBackendAllMoneyMarketBorrowers` | All borrowers |
167
167
 
168
+ ### Oracle data
169
+
170
+ | Hook | Purpose |
171
+ |---|---|
172
+ | `useBackendOracleMarkets` | Candle discovery: quote, intervals, symbols (`staleTime: 60s`) |
173
+ | `useBackendOracleCandles` | USD OHLC candles for a symbol over `[from, to)` (`staleTime: 10s`) |
174
+
168
175
  ## Swaps API (`sodax.api.swaps`)
169
176
 
170
177
  Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`), one per endpoint. Distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive `sodax.swaps` (the `SwapService`).
@@ -250,6 +257,7 @@ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`)
250
257
 
251
258
  | Hook | Type | Purpose |
252
259
  |---|---|---|
260
+ | `useBalances` | Query | SDK-backed wallet token balances (no xService) |
253
261
  | `useXBalances` | Query | Cross-chain token balances |
254
262
  | `useDeriveUserWalletAddress` | Query | Derive hub wallet (CREATE3) |
255
263
  | `useGetUserHubWalletAddress` | Query | Derive hub wallet (wallet router) |
@@ -77,7 +77,8 @@ queryKey: ['staking', 'allowance', srcChainKey, action, srcAddress, amount.toStr
77
77
  // User position reads
78
78
  queryKey: ['mm', 'userReservesData', spokeChainKey, userAddress]
79
79
  queryKey: ['staking', 'info', srcChainKey, srcAddress] // useStakingInfo — second segment is 'info', not 'stakingInfo'
80
- queryKey: ['shared', 'xBalances', xChainId, tokens, address]
80
+ queryKey: ['shared', 'balances', chainKey, tokens, address] // useBalances (SDK-backed)
81
+ queryKey: ['shared', 'xBalances', xChainId, tokens, address] // useXBalances (wallet-layer)
81
82
  queryKey: ['shared', 'nearStorageCheck', chainId, token, accountId] // useNearStorageCheck
82
83
 
83
84
  // Mutation default keys
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: sodax-sdk-backend-api
3
- description: 'Granular skill for the @sodax/sdk v2 BackendApiService — HTTP client to the SODAX backend for intent lookup, swap-tx submission, solver orderbook, money-market position/reserve reads, and (internally) config fetching. Use when the task touches a backend read or write (e.g. "submit swap tx to Sodax backend", "Sodax getIntentByHash", "fetch money market position from Sodax backend", "Sodax orderbook", "Sodax BackendApiService", "implement custom IConfigApiV1 sandbox"). Covers BOTH integration and the load-bearing v1 → v2 Result-wrapping migration. Skill links into the parent sodax-sdk knowledge tree.'
3
+ description: 'Granular skill for the @sodax/sdk v2 BackendApiService — HTTP client to the SODAX backend for intent lookup, swap-tx submission, solver orderbook, money-market position/reserve reads, USD OHLC price candles for charts, and (internally) config fetching. Use when the task touches a backend read or write (e.g. "submit swap tx to Sodax backend", "Sodax getIntentByHash", "fetch money market position from Sodax backend", "Sodax orderbook", "Sodax price candles", "Sodax OHLC chart data", "Sodax oracle markets", "Sodax BackendApiService", "implement custom IConfigApiV1 sandbox"). Covers BOTH integration and the load-bearing v1 → v2 Result-wrapping migration. Skill links into the parent sodax-sdk knowledge tree.'
4
4
  license: MIT
5
5
  metadata:
6
6
  version: '0.0.1'
@@ -17,6 +17,7 @@ Granular skill for `BackendApiService` — `sodax.backendApi`. HTTP client used
17
17
  2. **Which category?**
18
18
  - **Swap-related reads:** `getOrderbook`, `getIntentByHash`, `getIntentByTxHash`, `getUserIntents`. (Swap-tx submission — `sodax.api.swaps.submitTx` / `getSubmitTxStatus` — is on the swaps API client.)
19
19
  - **Money-market position reads:** `getMoneyMarketPosition`, `getAllMoneyMarketAssets`, `getMoneyMarketAsset`, `getMoneyMarketAssetBorrowers`, `getMoneyMarketAssetSuppliers`, `getAllMoneyMarketBorrowers`.
20
+ - **Oracle price reads:** `getOracleMarkets` (quote + intervals + symbols), `getOracleCandles` (USD OHLC buckets for charting). The solver's live mark prices — `GET /v1/intent/oracle` — are a different service and have no SDK wrapper.
20
21
  - **`IConfigApiV1` interface methods (exactly 5):** `getChains`, `getSwapTokens`, `getSwapTokensByChainId`, `getMoneyMarketTokens`, `getMoneyMarketTokensByChainId`.
21
22
  - **Other `BackendApiService` config reads (NOT part of `IConfigApiV1`):** `getAllConfig`, `getMoneyMarketReserveAssets`, `getRelayChainIdMap`.
22
23
  3. **Custom `IConfigApiV1` for sandbox / fixtures?** Every method must return `Promise<Result<T>>` in v2.
@@ -149,7 +149,7 @@ const solanaSpoke = sodax.spoke.getSpokeService(ChainKeys.SOLANA_MAINNET) as Sol
149
149
 
150
150
  ### Pitfall
151
151
 
152
- Solana addresses are base58 PublicKey strings, not `0x…` hex. `GetAddressType<typeof ChainKeys.SOLANA_MAINNET>` resolves to a base58-typed string brand; passing a hex address is a TypeScript error.
152
+ Solana addresses are base58 PublicKey strings, not `0x…` hex. `GetAddressType<typeof ChainKeys.SOLANA_MAINNET>` resolves to `SolanaBase58PublicKey`, which is a plain `string` alias — not a brand — so a hex address compiles and then throws inside `new PublicKey(...)` when the spoke service reads the balance or builds the deposit. Pass the base58 address.
153
153
 
154
154
  ---
155
155
 
@@ -1,6 +1,6 @@
1
1
  # Backend API — `BackendApiService`
2
2
 
3
- HTTP client for backend services. Provides intent lookup, solver orderbook queries, money-market position/reserve reads, and (internally) config fetching. Most consumer-side code uses just `getIntentByHash` / `getIntentByTxHash` and the money-market read methods. Swap-tx submission lives on the sibling swaps API client — `sodax.api.swaps.submitTx` (see below).
3
+ HTTP client for backend services. Provides intent lookup, solver orderbook queries, money-market position/reserve reads, USD OHLC price candles, and (internally) config fetching. Most consumer-side code uses just `getIntentByHash` / `getIntentByTxHash` and the money-market read methods. Swap-tx submission lives on the sibling swaps API client — `sodax.api.swaps.submitTx` (see below).
4
4
 
5
5
  Access: `sodax.backendApi`. Service class: `BackendApiService`. **Feature tag for errors:** every method emits `feature: 'backend'` with `error.context.api: 'backend'` (the HTTP-client layer — the domain feature tags like `'moneyMarket'` belong to the on-chain services, not these backend reads).
6
6
 
@@ -26,6 +26,10 @@ sodax.backendApi.getMoneyMarketAssetBorrowers(...): Promise<Result<...>>;
26
26
  sodax.backendApi.getMoneyMarketAssetSuppliers(...): Promise<Result<...>>;
27
27
  sodax.backendApi.getAllMoneyMarketBorrowers(...): Promise<Result<...>>;
28
28
 
29
+ // Oracle price reads (USD OHLC candles for charts)
30
+ sodax.backendApi.getOracleMarkets(config?): Promise<Result<OracleMarketsResponse>>; // { quote, intervals, symbols }
31
+ sodax.backendApi.getOracleCandles(params, config?): Promise<Result<OracleCandlesResponse>>; // params: { symbol, interval: '1m'|'5m'|'1h'|'1d', from, to } — UNIX SECONDS, half-open [from, to), max 5000 buckets
32
+
29
33
  // Config-API methods (used internally by ConfigService — implements `IConfigApiV1`)
30
34
  sodax.backendApi.getAllConfig(config?): Promise<Result<GetAllConfigApiResponse>>;
31
35
  sodax.backendApi.getChains(config?): Promise<Result<GetChainsApiResponse>>;
@@ -37,6 +41,10 @@ sodax.backendApi.getMoneyMarketTokensByChainId(...): Promise<Result<XToken[]>>;
37
41
  sodax.backendApi.getRelayChainIdMap(config?): Promise<Result<GetRelayChainIdMapApiResponse>>;
38
42
  ```
39
43
 
44
+ Oracle typing: `getOracleMarkets().intervals[].key` is `string`, not the `OracleCandleInterval` union — discovery stays tolerant of an interval a newer backend serves, so narrow it with the exported `isOracleCandleInterval(key)` guard (or membership-test `ORACLE_CANDLE_INTERVALS`) before passing it to `getOracleCandles`. The candles response `interval` echoes what you sent and IS strictly validated.
45
+
46
+ Oracle candles: `open`/`high`/`low`/`close` are USD **decimal strings** (convert them yourself) and `timestamp` is the bucket START in UNIX seconds. `final` marks the still-forming current bucket: branch on `final === false` (re-poll while that holds), never on the field's presence — the backend omits it on closed candles today, but the type is `boolean`. A valid range with no stored candles resolves `ok: true` with `candles: []`; an unknown symbol currently produces the same successful empty result rather than a 404. A zero-width/reversed range, another invalid parameter, or a range over 5000 buckets is a 400, surfacing as `HTTP_REQUEST_FAILED` with `error.context.status === 400`. The solver's live mark prices (`GET /v1/intent/oracle`) are a separate service with no SDK wrapper.
47
+
40
48
  All methods return `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` where the error carries `feature: 'backend'`, `error.context.api === 'backend'`, and `context.endpoint`.
41
49
 
42
50
  Every data / token / money-market response is validated at runtime against a valibot schema (like `sodax.api.swaps`): a 2xx body that fails the contract resolves to `EXTERNAL_API_ERROR` with `context.reason: 'invalid_response_shape'` rather than a mistyped value. The config/relay reads — `getAllConfig`, `getSpokeChainConfig`, `getRelayChainIdMap` — are **not** schema-validated (the `SodaxConfig` shape is too large to mirror faithfully, and `ConfigService` already version-gates and falls back to packaged defaults, so it relies on no response-shape guarantee).
@@ -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
 
@@ -1,6 +1,6 @@
1
1
  # Money Market — `MoneyMarketService`
2
2
 
3
- Cross-chain lending and borrowing. Supply, borrow, withdraw, repay across 21 spoke chains. Position state lives on the hub.
3
+ Cross-chain lending and borrowing. Supply, borrow, withdraw, repay across the supported spoke chains (`moneyMarketSupportedTokens` in `@sodax/types` is the source of truth). Position state lives on the hub.
4
4
 
5
5
  Access: `sodax.moneyMarket`. Service class: `MoneyMarketService`. Feature tag for errors: `'moneyMarket'`.
6
6
 
@@ -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.
@@ -93,6 +93,48 @@ const stakingConfig = await sodax.staking.getStakingConfig();
93
93
  const pools = sodax.dex.clService.getPools(); // synchronous in v2
94
94
  ```
95
95
 
96
+ ### Wallet balances (`sodax.spoke.getWalletBalance` / `getWalletBalances`)
97
+
98
+ Chain-agnostic reads of the balances a user's own address holds — the SDK dispatches to the right
99
+ chain family and reads the native coin or that chain's token standard (EVM erc20, Solana SPL, Sui
100
+ coin, Soroban contract, IRC-2, NEP-141, SIP-010, Injective bank denom, Bitcoin UTXOs). Distinct from
101
+ `getDeposit`, which reads the protocol asset manager rather than the user.
102
+
103
+ ```ts
104
+ // @ai-snippets-skip
105
+ const one = await sodax.spoke.getWalletBalance({
106
+ srcChainKey: ChainKeys.ARBITRUM_MAINNET,
107
+ srcAddress: '0x…', // the user
108
+ token: usdc, // a full XToken living on srcChainKey (token.chainKey is ignored)
109
+ });
110
+ // one: Result<bigint> — smallest units
111
+
112
+ const many = await sodax.spoke.getWalletBalances({
113
+ srcChainKey: ChainKeys.ARBITRUM_MAINNET,
114
+ srcAddress: '0x…',
115
+ tokens: [usdc, weth],
116
+ });
117
+ // many: Result<Record<string, bigint>> — smallest units, keyed by token.address
118
+ if (many.ok) console.log(many.value[usdc.address]);
119
+ ```
120
+
121
+ Contract worth internalising:
122
+
123
+ - **A token that could not be read is logged and reported as `0n`**, so one flaky token never
124
+ discards the balances that did resolve. The flip side: a caller cannot tell a failed read from an
125
+ empty wallet. The direction is deliberately conservative — under-reporting blocks a spend, it
126
+ never permits one. Wire a `logger` into `new Sodax({ logger })` to surface those failures.
127
+ - The `Result` fails when the whole batch is unusable — an unknown chain key, a single shared
128
+ round-trip every token depends on (ICON's `tryAggregate`, Injective's portfolio fetch), or a batch
129
+ in which NO token could be read, which would otherwise render as "this wallet is empty on every
130
+ asset".
131
+ - Batching is per chain: EVM/Sonic use multicall3, ICON one `tryAggregate`, Injective one portfolio
132
+ fetch, Stellar one shared network + account fetch; the rest fan out per token.
133
+ - **Chain-specific values.** Stellar XLM reports the *spendable* amount (total minus the minimum
134
+ reserve and selling liabilities). Bitcoin reads native BTC from its UTXO set and returns `0n` for
135
+ Rune tokens, whose amounts that endpoint does not carry. Hedera's native balance is rescaled from
136
+ the EVM layer's 18-decimal "weibar" to HBAR's canonical 8 decimals.
137
+
96
138
  ## 7. Build raw transactions (no wallet)
97
139
 
98
140
  For sign-elsewhere flows (gnosis safe, hardware wallet, custom multi-sig), use `raw: true`. The SDK builds the unsigned payload; your application signs and broadcasts:
@@ -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: {
@@ -1,6 +1,6 @@
1
1
  # Chain keys
2
2
 
3
- 21 supported chains. The `ChainKey` type is the union of every `ChainKeys.*` value. **`SpokeChainKey` is the same union — it includes Sonic.** The "spoke" naming refers to how feature services type their `srcChainKey` parameter (they accept the hub too — bridge / swap / staking etc. all run from Sonic as source via the hub-wallet abstraction). When you specifically need "EVM chains excluding the hub" use `EVM_SPOKE_ONLY_CHAIN_KEYS` / `isEvmSpokeOnlyChainKeyType`.
3
+ The `ChainKey` type is the union of every `ChainKeys.*` value — the table below is the full set. **`SpokeChainKey` is the same union — it includes Sonic.** The "spoke" naming refers to how feature services type their `srcChainKey` parameter (they accept the hub too — bridge / swap / staking etc. all run from Sonic as source via the hub-wallet abstraction). When you specifically need "EVM chains excluding the hub" use `EVM_SPOKE_ONLY_CHAIN_KEYS` / `isEvmSpokeOnlyChainKeyType`.
4
4
 
5
5
  | `ChainKeys.*` | String value | Family | Hub vs spoke | Address type |
6
6
  |---|---|---|---|---|
@@ -37,9 +37,9 @@
37
37
 
38
38
  | Type | What it is |
39
39
  |---|---|
40
- | `ChainKey` | Union of all `ChainKeys.*` values (22 chains). |
41
- | `SpokeChainKey` | Same union as `ChainKey` — includes Sonic (22 chains). For "EVM chains excluding the hub" use `EvmSpokeOnlyChainKey`. |
42
- | `EvmChainKey` | Subset of `ChainKey` for the 14 EVM chains. |
40
+ | `ChainKey` | Union of all `ChainKeys.*` values. |
41
+ | `SpokeChainKey` | Same union as `ChainKey` — includes Sonic. For "EVM chains excluding the hub" use `EvmSpokeOnlyChainKey`. |
42
+ | `EvmChainKey` | Subset of `ChainKey` for the EVM chains. |
43
43
  | `HubChainKey` | The literal `'sonic'`. |
44
44
 
45
45
  ### Chain-family helpers
@@ -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`
@@ -192,6 +193,13 @@ import {
192
193
  type SwapResponse,
193
194
  type CreateIntentResult,
194
195
  type TxHashPair,
196
+ type OracleCandleInterval, // '1m' | '5m' | '1h' | '1d'
197
+ ORACLE_CANDLE_INTERVALS, // runtime array of the served intervals
198
+ isOracleCandleInterval, // narrows a markets `key` (string) to OracleCandleInterval
199
+ type OracleMarketInterval, // `key` is `string`: discovery tolerates an interval this version doesn't know
200
+ type OracleMarketsResponse,
201
+ type OracleCandle, // OHLC prices are USD decimal strings; timestamp is UNIX seconds
202
+ type OracleCandlesResponse,
195
203
  } from '@sodax/sdk';
196
204
  ```
197
205
 
@@ -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