@sodax/skills 2.0.0 → 2.1.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 (21) hide show
  1. package/AGENTS.md +4 -3
  2. package/package.json +1 -1
  3. package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +4 -3
  4. package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +1 -1
  5. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +130 -20
  6. package/skills/sodax-dapp-kit/integration/knowledge/recipes/wallet-connectivity.md +1 -1
  7. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +32 -1
  8. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +17 -0
  9. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/auxiliary-services.md +5 -5
  10. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/reference/renamed-hooks.md +1 -1
  11. package/skills/sodax-sdk/SKILL.md +3 -1
  12. package/skills/sodax-sdk/bridge-api/SKILL.md +64 -0
  13. package/skills/sodax-sdk/integration/knowledge/README.md +1 -0
  14. package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +18 -0
  15. package/skills/sodax-sdk/integration/knowledge/features/README.md +3 -0
  16. package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +141 -0
  17. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +50 -4
  18. package/skills/sodax-sdk/integration/knowledge/features/sponsoring.md +162 -0
  19. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +30 -1
  20. package/skills/sodax-sdk/sponsoring/SKILL.md +83 -0
  21. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/stellar.md +1 -1
package/AGENTS.md CHANGED
@@ -10,7 +10,7 @@ This package ships **mode-gated broad SDK skills** (`skills/<name>/SKILL.md`, on
10
10
 
11
11
  | SDK package | Broad skill | Granular per-feature skills |
12
12
  |---|---|---|
13
- | `@sodax/sdk` | `sodax-sdk` | `sodax-sdk/swap`, `sodax-sdk/money-market`, `sodax-sdk/bridge`, `sodax-sdk/staking`, `sodax-sdk/dex`, `sodax-sdk/leverage-yield`, `sodax-sdk/migration`, `sodax-sdk/partner`, `sodax-sdk/recovery`, `sodax-sdk/backend-api`, `sodax-sdk/swaps-api` |
13
+ | `@sodax/sdk` | `sodax-sdk` | `sodax-sdk/swap`, `sodax-sdk/money-market`, `sodax-sdk/bridge`, `sodax-sdk/staking`, `sodax-sdk/dex`, `sodax-sdk/leverage-yield`, `sodax-sdk/migration`, `sodax-sdk/partner`, `sodax-sdk/recovery`, `sodax-sdk/sponsoring`, `sodax-sdk/backend-api`, `sodax-sdk/swaps-api` |
14
14
  | `@sodax/wallet-sdk-core` | `sodax-wallet-sdk-core` | `sodax-wallet-sdk-core/evm`, `sodax-wallet-sdk-core/solana`, `sodax-wallet-sdk-core/sui`, `sodax-wallet-sdk-core/bitcoin`, `sodax-wallet-sdk-core/stellar`, `sodax-wallet-sdk-core/icon`, `sodax-wallet-sdk-core/injective`, `sodax-wallet-sdk-core/near`, `sodax-wallet-sdk-core/stacks` |
15
15
  | `@sodax/wallet-sdk-react` | `sodax-wallet-sdk-react` | `sodax-wallet-sdk-react/connect`, `sodax-wallet-sdk-react/wallet-modal`, `sodax-wallet-sdk-react/bridge-to-sdk`, `sodax-wallet-sdk-react/switch-chain`, `sodax-wallet-sdk-react/sign-message`, `sodax-wallet-sdk-react/walletconnect` |
16
16
  | `@sodax/dapp-kit` | `sodax-dapp-kit` | `sodax-dapp-kit/swap`, `sodax-dapp-kit/money-market`, `sodax-dapp-kit/staking`, `sodax-dapp-kit/bridge`, `sodax-dapp-kit/dex`, `sodax-dapp-kit/leverage-yield`, `sodax-dapp-kit/migration`, `sodax-dapp-kit/bitcoin`, `sodax-dapp-kit/auxiliary-services` |
@@ -26,7 +26,7 @@ Pick the consumer's situation, load the listed skills in order. Each entry names
26
26
  | Consumer is… | Load skills (mode) |
27
27
  |---|---|
28
28
  | **Not sure what to build / not a developer** (no SDK, feature, or concrete product chosen yet) | `sodax-build` (front-door ideation: interview → product brief → handoff; it names the dev skills to load next). Skip the moment any SDK / feature / hook is named |
29
- | **Scaffolding ONE specific Core SDK feature** (swap, money-market, bridge, staking, dex, leverage-yield, migration, partner, recovery, backend-api, swaps-api) | `sodax-sdk/<feature>` (granular, covers both modes via internal links). Add `sodax-wallet-sdk-core` (integration) if it signs and lives outside React. Skip the broad `sodax-sdk` skill |
29
+ | **Scaffolding ONE specific Core SDK feature** (swap, money-market, bridge, staking, dex, leverage-yield, migration, partner, recovery, sponsoring, backend-api, swaps-api) | `sodax-sdk/<feature>` (granular, covers both modes via internal links). Add `sodax-wallet-sdk-core` (integration) if it signs and lives outside React. Skip the broad `sodax-sdk` skill |
30
30
  | **Scaffolding ONE specific dapp-kit feature in React** (swap, money-market, staking, bridge, dex, leverage-yield, migration, bitcoin, auxiliary-services) | `sodax-wallet-sdk-react` (integration) → `sodax-dapp-kit/<feature>` (granular, covers both modes via internal links). Skip the broad `sodax-dapp-kit` skill. If the wallet concern is also settled (just a connect button, modal, bridge, etc.), narrow to `sodax-wallet-sdk-react/<concern>` too |
31
31
  | **Scaffolding ONE chain's wallet provider** (backend/Node/non-React: evm, solana, sui, bitcoin, stellar, icon, injective, near, stacks) | `sodax-wallet-sdk-core/<chain>` (granular, covers both modes) → `sodax-sdk/<feature>` for the operation it signs. Skip the broad `sodax-wallet-sdk-core` skill |
32
32
  | **Scaffolding ONE React wallet concern** (connect, wallet-modal, bridge-to-sdk, switch-chain, sign-message, walletconnect) | `sodax-wallet-sdk-react/<concern>` (granular, covers both modes). Skip the broad `sodax-wallet-sdk-react` skill |
@@ -63,7 +63,8 @@ packages/skills/
63
63
  ├── sodax-build/ {SKILL.md, knowledge/ (flat)} — cross-cutting front-door / ideation skill; no mode split, no granular children
64
64
  ├── sodax-sdk/ {SKILL.md, integration/knowledge/, migration-v1-to-v2/knowledge/,
65
65
  │ <feature>/SKILL.md children — swap, money-market, bridge, staking, dex,
66
- │ leverage-yield, migration, partner, recovery, backend-api, swaps-api}
66
+ │ leverage-yield, migration, partner, recovery, sponsoring, backend-api,
67
+ │ swaps-api}
67
68
  ├── sodax-wallet-sdk-core/ {SKILL.md, integration/knowledge/, migration-v1-to-v2/knowledge/,
68
69
  │ <chain>/SKILL.md children — evm, solana, sui, bitcoin, stellar, icon,
69
70
  │ injective, near, stacks}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "2.0.0",
7
+ "version": "2.1.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), and shared utilities (useSodaxContext, useHubProvider, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useRequestTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), 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, 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'
@@ -18,7 +18,8 @@ Granular skill for the smaller `@sodax/dapp-kit` v2 surfaces grouped together: *
18
18
  - **Partner fees:** `useIsTokenApproved` → `useApproveToken` → `useSetSwapPreference` → `useFeeClaimSwap` (returns `IntentAutoSwapResult`, NOT `SwapResponse`); `useGetAutoSwapPreferences`, `useFetchAssetsBalances` for reads.
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
- - **Shared utilities:** `useSodaxContext`, `useHubProvider`, `useXBalances` (needs `xService` from wallet-sdk-react), `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`, `useEstimateGas`, `useStellarTrustlineCheck` / `useRequestTrustline`.
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
23
 
23
24
  ## Integration workflow (new v2 code)
24
25
 
@@ -35,7 +36,7 @@ Granular skill for the smaller `@sodax/dapp-kit` v2 surfaces grouped together: *
35
36
  - **Treating `useFeeClaimSwap` `data` as a `SwapResponse`.** It's `IntentAutoSwapResult`.
36
37
  - **Passing top-level `pagination` to `useBackendOrderbook` / `useBackendAllMoneyMarketBorrowers`.** It nests under `params`; without it those queries are disabled.
37
38
  - **Calling `useXBalances` without `xService`.** Supply `xService` from `@sodax/wallet-sdk-react`'s `useXService`; the request-side key is `xChainId` (the cross-chain abstraction), distinct from the token-side `chainKey`.
38
- - **Treating `useRequestTrustline` as a canonical mutation hook.** It takes a single positional `token` arg and returns `{ requestTrustline, isLoading, ... }`; the callback takes `{ token, amount, srcChainKey, walletProvider }` (NOT `account`/`asset`).
39
+ - **Pairing `useStellarTrustlineCheck` with `useEstablishTrustline` by hand.** Use `useStellarGate`: `hasSufficientTrustline` THROWS for an account that does not exist, so a `!data` test offers a trustline button on a missing account. `useEstablishTrustline` is a canonical mutation hook — vars are `{ token, amount, srcChainKey, walletProvider }` (NOT `account`/`asset`). `useRequestTrustline` is its deprecated 2.0.0-shape wrapper; don't write new code against it.
39
40
  - **Running recovery on successful flows.** Recovery is a workaround for *failed* ops — `useHubAssetBalances` first, then withdraw the specific entry; investigate the original failure.
40
41
  - **Leaving `useBackendIntentByTxHash` polling (1s) running after the intent resolves.**
41
42
 
@@ -245,7 +245,7 @@ Hooks organized by feature domain in `src/hooks/`:
245
245
  hooks/
246
246
  ├── shared/ # useSodaxContext, useSafeMutation, unwrapResult, useEstimateGas,
247
247
  │ # useDeriveUserWalletAddress, useGetUserHubWalletAddress, useXBalances,
248
- │ # useStellarTrustlineCheck, useRequestTrustline
248
+ │ # useStellarTrustlineCheck, useEstablishTrustline (+ deprecated useRequestTrustline)
249
249
  ├── provider/ # useHubProvider
250
250
  ├── swap/ # useQuote, useSwap, useStatus, useSwapAllowance, useSwapApprove,
251
251
  │ # useCancelSwap, useCreateLimitOrder, useCancelLimitOrder
@@ -94,6 +94,30 @@ const { data: status } = useSwapsApiSubmitTxStatus({ params: { txHash, srcChainK
94
94
 
95
95
  > The full `useSwapsApi*` hook list (with polling + types) is in [hooks-index.md](../reference/hooks-index.md); key shapes in [querykey-conventions.md](../reference/querykey-conventions.md). For non-React callers, `sodax.api.swaps` is documented in the `sodax-sdk` skill (integration mode).
96
96
 
97
+ ### Bridge API (`sodax.api.bridge`)
98
+
99
+ Typed React Query wrappers over the backend **Bridge API v2** — `useBridgeApi*` hooks over `sodax.api.bridge.*` (tokens, allowance, approve, create-bridge-intent, submit-tx + status, plus the fee / bridgeable-amount / bridgeable discovery quotes). They are the HTTP-API parallel of the on-chain `bridge/` hooks (`useBridge`/`useBridgeAllowance`/…, which drive `sodax.bridge`). Mirrors the swaps family minus the solver/intent surface; reads take `{ params, queryOptions }`, the three actions (`approve`, `createBridgeIntent`, `submitTx`) are mutations taking `{ mutationOptions }`.
100
+
101
+ ```ts
102
+ // @ai-snippets-skip
103
+ useBridgeApiTokens({ params, queryOptions }); // query → sodax.api.bridge.getTokens
104
+ useBridgeApiCreateBridgeIntent({ mutationOptions }); // mutation → sodax.api.bridge.createBridgeIntent
105
+ useBridgeApiSubmitTxStatus({ params, queryOptions }); // query → sodax.api.bridge.getSubmitTxStatus
106
+ ```
107
+
108
+ Two deltas vs the swaps hooks: the allowance/approve/create body is the **wire DTO** `CreateBridgeIntentParamsV2` (`inputToken`/`inputAmount`/`dstAddress`, not the SDK-domain names), and `useBridgeApiSubmitTx`'s `request` is a `BridgeSubmitTxRequestV2` whose `relayData` is the **FULL `{ address, payload }` object** (no `intent` field):
109
+
110
+ ```ts
111
+ // @ai-snippets-skip
112
+ const { mutateAsync: submitBridgeTx } = useBridgeApiSubmitTx();
113
+ // request: BridgeSubmitTxRequestV2 — { txHash, srcChainKey, walletAddress, relayData } (full envelope)
114
+ await submitBridgeTx({ request, apiConfig: { baseURL: 'https://...' } });
115
+ ```
116
+
117
+ `useBridgeApiSubmitTxStatus` polls (1s) and returns `BridgeSubmitTxStatusResponseV2 | undefined`, running only when **both** `txHash` and `srcChainKey` are supplied; terminal states are `executed` / `failed` (no `posting_execution`). The fee / bridgeable-amount / bridgeable quotes are computable client-side (config + vault math) — prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` for a no-round-trip read; `useBridgeApiFee` / `useBridgeApiBridgeableAmount` / `useBridgeApiIsBridgeable` mirror the backend endpoints for HTTP parity.
118
+
119
+ > Full list in [hooks-index.md](../reference/hooks-index.md); key shapes in [querykey-conventions.md](../reference/querykey-conventions.md). For non-React callers, `sodax.api.bridge` is documented in the `sodax-sdk` skill (integration mode).
120
+
97
121
  ## Shared utilities
98
122
 
99
123
  Cross-cutting hooks used by other features.
@@ -107,7 +131,7 @@ useDeriveUserWalletAddress({ params, queryOptions }); // Hub wallet address (CRE
107
131
  useGetUserHubWalletAddress({ params, queryOptions }); // Hub wallet via wallet router
108
132
  useEstimateGas({ mutationOptions }); // Gas estimation for raw tx
109
133
  useStellarTrustlineCheck({ params, queryOptions });
110
- useRequestTrustline({ mutationOptions });
134
+ useEstablishTrustline({ mutationOptions }); // useRequestTrustline is its deprecated 2.0.0 wrapper
111
135
  useNearStorageCheck({ params, queryOptions }); // NEP-141 storage registration check (NEAR)
112
136
  useRegisterNearStorage({ mutationOptions }); // NEP-141 storage_deposit (NEAR)
113
137
  useNearStorageGate({ dstChainKey, token, accountId, walletProvider }); // composite NEAR receive-side gate
@@ -137,32 +161,56 @@ const xService = useXService({ xChainType: getXChainType(xChainId) });
137
161
  const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });
138
162
  ```
139
163
 
140
- ### Stellar trustlines
164
+ ### Stellar prerequisites — use `useStellarGate`
141
165
 
142
- Stellar accounts that have never held an asset have no trustline — receiving will fail. Pre-flight with `useStellarTrustlineCheck`; fix with `useRequestTrustline`:
166
+ Stellar has ordered prerequisites for a destination account, and they are invisible until they bite:
167
+ the account must **exist** on-chain, must **trust** the destination token, and — only if it does not —
168
+ must be able to **pay** for the trustline it needs. `useStellarGate` sequences them; prefer it over
169
+ wiring the pieces yourself.
143
170
 
144
171
  ```ts
145
172
  // @ai-snippets-skip — illustrative only; real types pulled into agents below.
146
- // useStellarTrustlineCheck reads a trustline (no signing). Pass the resolved Stellar account
147
- // `walletAddress` (e.g. useXAccount('STELLAR').address) — it keys the cache per account, so the
148
- // verdict is never reused across accounts. `chainId` is a `SpokeChainKey` (typed loosely — the hook
149
- // returns `true` for non-Stellar chains, making it safe to gate on conditionally).
150
- const { data: hasTrustline } = useStellarTrustlineCheck({
151
- params: { token, amount, chainId: ChainKeys.STELLAR_MAINNET, walletAddress },
152
- });
173
+ // Mirrors useNearStorageGate. Pass the DESTINATION chain/token/amount/account plus the destination
174
+ // wallet provider; the gate owns the `=== STELLAR_MAINNET` test and the native-token exemption.
175
+ const stellar = useStellarGate({ dstChainKey, token, amount, address, walletProvider });
153
176
 
154
- // useRequestTrustline is NOT a canonical mutation hook — it takes a single positional
155
- // `token` arg and returns { requestTrustline, isLoading, isRequested, error, data }.
156
- // The `requestTrustline` callback signature is:
157
- // ({ token, amount, srcChainKey, walletProvider }) => Promise<string>
158
- // NOTE: fields are `token` / `amount` / `srcChainKey` / `walletProvider` — NOT
159
- // `account` / `asset`. Pass a StellarChainKey for srcChainKey.
160
- const { requestTrustline, isLoading } = useRequestTrustline(token);
161
- if (hasTrustline === false) {
162
- await requestTrustline({ token, amount, srcChainKey: ChainKeys.STELLAR_MAINNET, walletProvider });
163
- }
177
+ // Exactly one of these is ever true, in this order:
178
+ if (stellar.needsActivation) await stellar.activate(); // account does not exist — sponsor pays
179
+ if (stellar.needsFunding) { /* send it XLM — needs no trustline */ }
180
+ if (stellar.needsTrustline) await stellar.requestTrustline();
181
+
182
+ // A check FAILED — state unknown, not unmet. Say so and offer the retry; otherwise the action is
183
+ // disabled with nothing on screen explaining why.
184
+ if (stellar.checkFailed) { /* render stellar.error?.message + a button calling stellar.retry() */ }
185
+
186
+ // Gate the downstream action on the whole gate, which also covers the checking and errored windows.
187
+ const disabled = stellar.blocksAction || /* … */ false;
164
188
  ```
165
189
 
190
+ Affordability is checked **after** the trustline, and the order matters: an account that already trusts
191
+ the asset needs no XLM, because the sender pays the fee and the subentry reserve is already locked.
192
+ Checking affordability first blocks a correctly-configured user who has merely spent their spendable
193
+ XLM, and tells them to fund an account that needs nothing.
194
+
195
+ `blocksAction` is fail-closed on an unknown state, deliberately: a payment to a non-existent account, or
196
+ of an untrusted asset, fails on-chain, so letting the action through on a failed check risks stranding
197
+ funds. That makes `checkFailed` load-bearing — it is the only way a UI can tell "we could not check"
198
+ apart from "you are missing something", and without it a transient Horizon failure reads to the user as
199
+ an inexplicably dead button.
200
+
201
+ Do NOT hand-roll this as `useStellarTrustlineCheck` + `useEstablishTrustline`. `hasSufficientTrustline`
202
+ **throws** for an account that does not exist, so a `!data` test reads a missing account as "needs a
203
+ trustline" and offers a button that cannot work. Read `isLoading`, never `isPending` — `isPending` stays
204
+ `true` for a disabled query and blocks forever.
205
+
206
+ The lower-level pieces remain available for custom wiring: `useStellarAccountStatus` (existence,
207
+ `canAffordTrustline`, and `trustlineMinXlmStroops` — the XLM one more trustline needs at the network's
208
+ current base reserve — from one Horizon account read), `useStellarAccountActive` (existence only),
209
+ `useStellarTrustlineCheck`, and `useEstablishTrustline` — a canonical mutation hook whose vars are
210
+ `{ token, amount, srcChainKey, walletProvider }` (NOT `account` / `asset`). `useRequestTrustline` still
211
+ exists as a deprecated wrapper preserving the 2.0.0 shape (`{ requestTrustline, isLoading, isRequested,
212
+ error, data }`, positional token ignored); write new code against `useEstablishTrustline`.
213
+
166
214
  ### NEAR storage registration
167
215
 
168
216
  NEP-141 accounts must pay a one-time storage bond before they can receive a token — delivering to an unregistered account fails. The receive-side analogue of Stellar trustlines: gate any flow that delivers a token to the user on NEAR (swap output on NEAR, bridge into NEAR, money-market borrow/withdraw to NEAR). Use `useNearStorageGate` for app UI; use the lower-level `useNearStorageCheck` + `useRegisterNearStorage` pair when you need custom wiring.
@@ -203,6 +251,68 @@ const { needsRegistration, blocksAction } = resolveNearStorageGate(dstChainKey,
203
251
 
204
252
  The underlying SDK methods (`isStorageRegistered` / `registerStorage` on the NEAR spoke service, and the `NEAR_STORAGE_DEPOSIT` constant) are documented in the `sodax-sdk` skill (integration mode).
205
253
 
254
+ ## Stellar account activation (sponsoring)
255
+
256
+ A Stellar account must exist on-chain before it can hold or receive anything, and a brand-new user
257
+ holds 0 XLM. The SODAX sponsoring service pays the account's base reserve via Stellar's
258
+ sponsored-reserve flow. **The user's own wallet must sign** — their signature is what authorises the
259
+ `endSponsoringFutureReserves` operation — so this can never be a server-only call.
260
+
261
+ ```ts
262
+ // @ai-snippets-skip
263
+ useStellarAccountActive({ params: { address }, queryOptions }); // does the account exist on-chain?
264
+ useSponsorConfig({ queryOptions }); // sponsor account, network, fee band
265
+ useActivateStellarAccount({ mutationOptions }); // activate via the sponsor
266
+ ```
267
+
268
+ Mutation vars:
269
+
270
+ ```ts
271
+ // @ai-snippets-skip
272
+ // An alias for the SDK's own params — every option the service accepts is accepted here.
273
+ type UseActivateStellarAccountVars = ActivateStellarAccountParams;
274
+ // address: string // must be the account walletProvider signs with
275
+ // walletProvider: IStellarWalletProvider // useWalletProvider({ xChainId: ChainKeys.STELLAR_MAINNET })
276
+ // allowSequenceRetry?: boolean // default true — one rebuild + re-sign on a sequence conflict
277
+ // maxHorizonRetries?: number // default 2 — no-prompt re-submits of the SAME payload
278
+ // onSignatureRequired?: (info: { attempt: 1 | 2; reason: 'initial' | 'sequenceConflict' }) => void
279
+ // forceConfigRefresh?: boolean
280
+ // requestConfig?: RequestOverrideConfig
281
+ ```
282
+
283
+ Four things consumers get wrong:
284
+
285
+ 1. **Activation makes the account able to RECEIVE, not to SEND.** A freshly activated account holds
286
+ **zero spendable XLM** (the sponsor covers its reserve; `startingBalance` is `0`), so it cannot pay a
287
+ fee or the reserve its own first trustline would lock. Use `useStellarGate`, which sequences
288
+ activation → trustline → funding; pairing `useStellarTrustlineCheck` with `useEstablishTrustline`
289
+ directly conflates "account missing" with "trustline missing" and offers a button that cannot work.
290
+ Always render `checkFailed` / `error` / `retry` too — a fail-closed gate that cannot explain itself
291
+ is a dead button.
292
+
293
+ 2. **`alreadyActive` is a SUCCESS, not a no-op failure.** The result is
294
+ `{ status: 'submitted', hash, attempts }` or `{ status: 'alreadyActive', hash: null, attempts }`.
295
+ Render the second as "already active", not as an error. `attempts: 0` means the client pre-flight
296
+ caught it and the user was never prompted.
297
+ 3. **A sequence conflict costs a SECOND wallet prompt.** The sponsor's sequence number is baked into
298
+ the signed payload, so if another activation lands first the transaction must be rebuilt and
299
+ re-signed. Wire `onSignatureRequired` and show the explanation *before* the wallet steals focus —
300
+ it fires immediately before each prompt.
301
+ 4. **Never hardcode the sponsor account.** It comes from `useSponsorConfig` / the SDK's own fetch,
302
+ which is what makes sponsor rotation a config change instead of a client release.
303
+
304
+ Failure handling: `error.context.nextAction` carries the caller's next step —
305
+ `fixIntegration` | `checkApiKey` | `rebuildAndResign` | `retrySameRequest` | `backoff` |
306
+ `contactOperator` | `abort` — alongside `retryable` and `requiresNewSignature`. Branch on those
307
+ rather than on the HTTP status.
308
+
309
+ When the server rate-limits a key it also supplies `error.context.retryAfterSeconds`; render "try again
310
+ in Ns" instead of a generic "try later". The SDK never auto-retries a rate limit.
311
+
312
+ Requires `api.sponsoringApiConfig` (at minimum `apiKey`) on the `SodaxProvider` config. An api key
313
+ in a browser bundle is public by nature; the service's per-key quotas, fleet cap, per-IP throttle,
314
+ and origin gating are the real controls. Proxy through your own backend if that is not acceptable.
315
+
206
316
  ## Default polling intervals
207
317
 
208
318
  | Hook | Polling | Notes |
@@ -15,7 +15,7 @@ Connect wallets and pass wallet providers to feature hooks.
15
15
  | `useXBalances` | `@sodax/dapp-kit` | Query | Cross-chain token balances for an address |
16
16
  | `useEstimateGas` | `@sodax/dapp-kit` | Mutation | Estimate gas for raw transactions |
17
17
  | `useStellarTrustlineCheck` | `@sodax/dapp-kit` | Query | Check if Stellar account has sufficient trustline |
18
- | `useRequestTrustline` | `@sodax/dapp-kit` | Mutation | Request a Stellar trustline for a token |
18
+ | `useEstablishTrustline` | `@sodax/dapp-kit` | Mutation | Request a Stellar trustline for a token |
19
19
  | `useNearStorageCheck` | `@sodax/dapp-kit` | Query | Check if a NEAR account is NEP-141 storage-registered for a token |
20
20
  | `useRegisterNearStorage` | `@sodax/dapp-kit` | Mutation | Submit a NEP-141 `storage_deposit` so a NEAR account can receive a token |
21
21
  | `useNearStorageGate` | `@sodax/dapp-kit` | Hook | Combine the NEAR storage check, registration mutation, and UI gate flags |
@@ -204,6 +204,23 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
204
204
  | `useSwapsApiCreateLimitOrder` | Mutation; builds limit-order intent tx |
205
205
  | `useSwapsApiSubmitTx` | Mutation; `request: SubmitTxRequestV2` |
206
206
 
207
+ ## Bridge API (`sodax.api.bridge`)
208
+
209
+ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`). Distinct from the on-chain `bridge/` hooks (`useBridge`/`useBridgeAllowance`/…), which drive `sodax.bridge` (the `BridgeService`). Smaller than the swaps family (no intent/solver surface). The fee / bridgeable-amount / bridgeable quotes are computable client-side (prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` — no round-trip), but are also mirrored here as HTTP hooks for parity.
210
+
211
+ | Hook | Type / Polling |
212
+ |---|---|
213
+ | `useBridgeApiTokens` | Query; all supported bridge tokens by chain |
214
+ | `useBridgeApiTokensByChain` | Query; supported bridge tokens for one `chainKey` |
215
+ | `useBridgeApiAllowance` | Query; `{ valid }` allowance check (wire-named body) |
216
+ | `useBridgeApiFee` | Query; `{ fee }` partner fee for an amount (per-request `partnerFee` override or configured default) |
217
+ | `useBridgeApiBridgeableAmount` | Query; `{ limit }` deposit capacity / withdrawal liquidity for a pair |
218
+ | `useBridgeApiIsBridgeable` | Query; `{ bridgeable }` whether a (from, to) pair is bridgeable |
219
+ | `useBridgeApiSubmitTxStatus` | Query (1s); requires `txHash` + `srcChainKey`; polls until `executed` / `failed` |
220
+ | `useBridgeApiApprove` | Mutation; builds unsigned approval tx |
221
+ | `useBridgeApiCreateBridgeIntent` | Mutation; builds `{ tx, relayData }` (no intent) |
222
+ | `useBridgeApiSubmitTx` | Mutation; `request: BridgeSubmitTxRequestV2` (FULL relayData envelope) |
223
+
207
224
  ## Partner
208
225
 
209
226
  | Hook | Type | Purpose |
@@ -235,7 +252,9 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
235
252
  | `useGetUserHubWalletAddress` | Query | Derive hub wallet (wallet router) |
236
253
  | `useEstimateGas` | Mutation | Estimate gas for raw tx |
237
254
  | `useStellarTrustlineCheck` | Query | Check Stellar trustline |
238
- | `useRequestTrustline` | Mutation | Request a Stellar trustline |
255
+ | `useEstablishTrustline` | Mutation | Request a Stellar trustline (the account pays — needs XLM) |
256
+ | `useRequestTrustline` | Deprecated | 2.0.0-shape wrapper over `useEstablishTrustline`; removed next major |
257
+ | `useStellarGate` | Composite | Sequences the Stellar prerequisites: exists → trustline → can afford; `checkFailed`/`error`/`retry` for a failed check |
239
258
  | `useNearStorageCheck` | Query | Check NEP-141 storage registration (NEAR) |
240
259
  | `useRegisterNearStorage` | Mutation | Submit NEP-141 `storage_deposit` (NEAR) |
241
260
  | `useNearStorageGate` | Hook | Composite NEAR receive-side storage gate |
@@ -244,6 +263,18 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
244
263
  | `unwrapResult` | Internal | `Result<T>` → throw / return |
245
264
  | `toResult` | Internal | `Promise<T>` → `Result<T>` |
246
265
 
266
+ ## Sponsoring (`sponsoring/`)
267
+
268
+ Stellar accounts must exist on-chain before they can hold or receive anything, and a new user holds 0 XLM.
269
+ These hooks drive the sponsored-reserve activation flow, where the SODAX sponsor pays the base reserve.
270
+
271
+ | Hook | Kind | Purpose |
272
+ | --- | --- | --- |
273
+ | `useStellarAccountActive` | Query | Whether a Stellar account already exists on-chain |
274
+ | `useStellarAccountStatus` | Query | Existence + `canAffordTrustline` + `trustlineMinXlmStroops`, from one Horizon account read |
275
+ | `useSponsorConfig` | Query | Sponsor account, network, fee band, max time bounds |
276
+ | `useActivateStellarAccount` | Mutation | Activate a Stellar account via the sponsor |
277
+
247
278
  ## Cross-references
248
279
 
249
280
  - [`../features/`](../features/) — per-feature reference docs (params types, return shapes, gotchas).
@@ -182,6 +182,23 @@ Typed wrappers over `sodax.api.swaps.*` (one per Swaps API v2 endpoint), all key
182
182
  | `['swapsApi', 'createLimitOrder']` | `useSwapsApiCreateLimitOrder` mutation |
183
183
  | `['swapsApi', 'submitTx']` | `useSwapsApiSubmitTx` mutation |
184
184
 
185
+ ### Bridge API (`sodax.api.bridge`)
186
+
187
+ Typed wrappers over `sodax.api.bridge.*` (one per Bridge API v2 endpoint), all keyed `['bridgeApi', action, ...]`.
188
+
189
+ | Key | Hook |
190
+ |---|---|
191
+ | `['bridgeApi', 'tokens']` | `useBridgeApiTokens` |
192
+ | `['bridgeApi', 'tokens', chainKey]` | `useBridgeApiTokensByChain` |
193
+ | `['bridgeApi', 'allowance', …]` | `useBridgeApiAllowance` |
194
+ | `['bridgeApi', 'fee', inputAmount, partnerFee]` | `useBridgeApiFee` |
195
+ | `['bridgeApi', 'bridgeableAmount', srcChainKey, dstChainKey, inputToken, outputToken]` | `useBridgeApiBridgeableAmount` |
196
+ | `['bridgeApi', 'bridgeable', srcChainKey, dstChainKey, inputToken, outputToken]` | `useBridgeApiIsBridgeable` |
197
+ | `['bridgeApi', 'submitTx', 'status', txHash, srcChainKey]` | `useBridgeApiSubmitTxStatus` — both identifiers required |
198
+ | `['bridgeApi', 'approve']` | `useBridgeApiApprove` mutation |
199
+ | `['bridgeApi', 'createBridgeIntent']` | `useBridgeApiCreateBridgeIntent` mutation |
200
+ | `['bridgeApi', 'submitTx']` | `useBridgeApiSubmitTx` mutation |
201
+
185
202
  ### Leverage Yield
186
203
 
187
204
  | Key | Hook |
@@ -82,7 +82,7 @@ Note: the request param is still `xChainId` (not renamed to `chainKey`). This is
82
82
  + const result = await estimateGas({ tx, chainKey }); // TVars is EstimateGasParams<C> = { tx, chainKey } — no walletProvider
83
83
  ```
84
84
 
85
- ### `useStellarTrustlineCheck` / `useRequestTrustline`
85
+ ### `useStellarTrustlineCheck` / `useEstablishTrustline`
86
86
 
87
87
  ```diff
88
88
  - // Positional args; `destProvider` carried both the signer and the destination chain.
@@ -95,10 +95,10 @@ Note: the request param is still `xChainId` (not renamed to `chainKey`). This is
95
95
 
96
96
  - // The callback took a `spokeProvider`.
97
97
  - await requestTrustline({ token, amount, spokeProvider: destProvider });
98
- + // useRequestTrustline is NOT a canonical mutation: the token is positional, and it returns a
99
- + // `requestTrustline` callback that now takes `srcChainKey` + `walletProvider`.
100
- + const { requestTrustline } = useRequestTrustline(token);
101
- + await requestTrustline({ token, amount, srcChainKey, walletProvider });
98
+ + // useEstablishTrustline is a canonical mutation; vars take `srcChainKey` + `walletProvider`.
99
+ + const { mutateAsyncSafe: establishTrustline } = useEstablishTrustline();
100
+ + await establishTrustline({ token, amount, srcChainKey, walletProvider });
101
+ + // `useRequestTrustline(token)` still resolves, deprecated, with its 2.0.0 return shape.
102
102
  ```
103
103
 
104
104
  ### `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`
@@ -49,7 +49,7 @@ These keep their name but their TypeScript signature is different. Usually requi
49
49
  | `useEstimateGas` | Mutation; vars: `EstimateGasParams<C>` (flat, not `{ params, walletProvider }`-wrapped). |
50
50
  | `useDeriveUserWalletAddress`, `useGetUserHubWalletAddress` | Single-object query shape. |
51
51
  | `useStellarTrustlineCheck` | Single-object shape under `params`: `{ token, amount, chainId, walletAddress }`. Pass the resolved Stellar address (e.g. `useXAccount('STELLAR').address`), not a wallet provider — it keys the cache per account. |
52
- | `useRequestTrustline` | Custom utility hook (NOT a canonical mutation). Takes `(token: string \| undefined)` positionally, returns `{ requestTrustline, isLoading, isRequested, error, data }`. The `requestTrustline` callback takes `{ token, amount, srcChainKey, walletProvider }`. |
52
+ | `useRequestTrustline` → `useEstablishTrustline` | Canonical mutation hook: `{ mutationOptions }` in, `SafeUseMutationResult` out, vars `{ token, amount, srcChainKey, walletProvider }`. `useRequestTrustline` remains as a deprecated wrapper with its 2.0.0 shape — positional `(token: string \| undefined)` (ignored) and `{ requestTrustline, isLoading, isRequested, error, data }` — and is removed in the next major. |
53
53
  | `useBackendOrderbook` / `useBackendAllMoneyMarketBorrowers` | Pagination MUST be nested under `params`: `{ params: { pagination: { offset, limit } } }`. |
54
54
  | `useBackendUserIntents` | Data is `UserIntentsResponse = { items: IntentResponse[], total, offset, limit }` — NOT a bare array. Access `data?.items`. |
55
55
  | `useSwapsApiSubmitTx` / `useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTx` / `useBackendSubmitSwapTxStatus`) | Renamed + moved to the `swapsApi/` namespace (keys now `['swapsApi', …]`). Mutation `apiConfig` moved from hook init to `mutate(vars)`; the status query now requires `srcChainKey`. The rest of the Swaps API v2 is newly wrapped as `useSwapsApi*` hooks. |
@@ -33,8 +33,10 @@ If the user has already picked a single feature, load the matching granular skil
33
33
  | ICX / bnUSD / BALN token migration to SODAX | [`./migration/SKILL.md`](./migration/SKILL.md) | "migrate ICX", "legacy bnUSD", "BALN lockup" (NOT v1→v2 SDK porting) |
34
34
  | Partner fees | [`./partner/SKILL.md`](./partner/SKILL.md) | "claim partner fee", "partner auto-swap preference", "approve partner fee token" |
35
35
  | Stuck-asset recovery | [`./recovery/SKILL.md`](./recovery/SKILL.md) | "recover stuck assets on Sonic", "RecoveryService", "withdrawHubAsset" |
36
+ | Sponsored Stellar account activation | [`./sponsoring/SKILL.md`](./sponsoring/SKILL.md) | "activate a Stellar account", "user has no XLM", "sponsor base reserve", "sodax.sponsoring" |
36
37
  | Backend HTTP client (intents, orderbook, MM reads) | [`./backend-api/SKILL.md`](./backend-api/SKILL.md) | "getIntentByHash", "Sodax backend API", "orderbook", "custom IConfigApiV1" |
37
38
  | Swaps API v2 client (quote, create-intent, submit-tx, fees) | [`./swaps-api/SKILL.md`](./swaps-api/SKILL.md) | "sodax.api.swaps", "swap quote from backend", "submit swap tx", "swaps API v2" |
39
+ | Bridge API v2 client (allowance/approve, create-intent, submit-tx, tokens, fee/bridgeable discovery) | [`./bridge-api/SKILL.md`](./bridge-api/SKILL.md) | "sodax.api.bridge", "createBridgeIntent via backend", "submit bridge tx", "bridge API v2" |
38
40
 
39
41
  Load this broad skill (keep reading below) when:
40
42
 
@@ -76,7 +78,7 @@ Follow in order. Skipping `ai-rules.md` is the most common cause of agents rever
76
78
 
77
79
  1. Read [`integration/knowledge/ai-rules.md`](./integration/knowledge/ai-rules.md) — DO / DO NOT / workflow / stop conditions.
78
80
  2. Read [`integration/knowledge/quickstart.md`](./integration/knowledge/quickstart.md) — install, initialize, first-run troubleshooting.
79
- 3. For your feature, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `migration.md`, `partner.md`, `recovery.md`, `backend-api.md`, `swaps-api.md`.
81
+ 3. For your feature, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `migration.md`, `partner.md`, `recovery.md`, `sponsoring.md`, `backend-api.md`, `swaps-api.md`, `bridge-api.md`.
80
82
  4. For specific patterns (init, raw vs signed, chain narrowing, gas, testing, errors, logging), read [`integration/knowledge/recipes/`](./integration/knowledge/recipes/).
81
83
  5. Lookups (chain keys, error codes, public API surface, wallet provider types, glossary) → [`integration/knowledge/reference/`](./integration/knowledge/reference/).
82
84
  6. Non-EVM quirks (Stellar trustline, BTC PSBT, Solana PDA, ICON, NEAR) → [`integration/knowledge/chain-specifics.md`](./integration/knowledge/chain-specifics.md).
@@ -0,0 +1,64 @@
1
+ ---
2
+ name: sodax-sdk-bridge-api
3
+ description: 'Granular skill for the @sodax/sdk v2 Bridge API client — `sodax.api.bridge` (class BridgeApiService), a typed HTTP client for the backend Bridge API v2 (`/bridge/*`: tokens, allowance/approve, create-bridge-intent, submit-tx + status, fee/bridgeable-amount/bridgeable discovery). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the bridge backend directly (e.g. "sodax.api.bridge", "createBridgeIntent via the backend API", "submit bridge tx", "poll bridge submit-tx status", "bridge API v2", "point bridge at a custom endpoint", "bridgeOptions.useBackendSubmitTx"). For the higher-level end-to-end bridge orchestrator use the `bridge` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
4
+ ---
5
+
6
+ # Bridge API (Core SDK granular skill)
7
+
8
+ Granular skill for `sodax.api.bridge` (class `BridgeApiService`) — the typed HTTP client for the backend
9
+ **Bridge API v2** (`/bridge/*`). `sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the bridge
10
+ client. One method per endpoint; every method returns `Promise<Result<T>>` (never throws) and
11
+ validates the response. Errors carry `feature: 'backend'`, `context.api: 'bridge'`, `context.endpoint`.
12
+
13
+ > Lower-level than `sodax.bridge`: this is the raw backend HTTP surface. For the end-to-end
14
+ > deposit→relay bridge orchestrator, use the [`bridge`](../bridge/SKILL.md) skill. The Bridge API mirrors
15
+ > the [`swaps-api`](../swaps-api/SKILL.md) client minus the solver/intent surface.
16
+
17
+ ## Step 1 — Clarify with user before coding
18
+
19
+ 1. **Which endpoint(s)?** Tokens · allowance/approve/create-bridge-intent · submit-tx/status · fee/bridgeable-amount/bridgeable discovery.
20
+ 2. **Orchestrator or raw API?** If the user just wants "do a bridge", prefer `sodax.bridge` (the `bridge`
21
+ skill). Use `sodax.api.bridge` when they need a single backend call or are building their own flow.
22
+ 3. **Backend availability.** The `/bridge/*` routes are the newest backend surface; confirm the target host
23
+ actually serves them (the on-chain `sodax.bridge` flow needs no backend).
24
+
25
+ ## Integration workflow
26
+
27
+ 1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md) — DO / DO NOT (read first).
28
+ 2. [`../integration/knowledge/features/bridge-api.md`](../integration/knowledge/features/bridge-api.md) — the full client: signatures, deltas vs swaps (no intent, FULL relayData envelope, 5-state tolerant status), common call shapes (create-intent, submit-tx + status), the read-only fee/bridgeable-amount/bridgeable discovery quotes, per-call overrides, `bridgeOptions.useBackendSubmitTx`.
29
+ 3. For the end-to-end bridge flow that wraps these calls → [`../integration/knowledge/features/bridge.md`](../integration/knowledge/features/bridge.md); for the sibling swaps client → [`../integration/knowledge/features/swaps-api.md`](../integration/knowledge/features/swaps-api.md); for the read client (`sodax.backendApi`) → [`../integration/knowledge/features/backend-api.md`](../integration/knowledge/features/backend-api.md).
30
+ 4. Errors are `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` → [`../integration/knowledge/recipes/result-and-errors.md`](../integration/knowledge/recipes/result-and-errors.md) and [`../integration/knowledge/reference/error-codes.md`](../integration/knowledge/reference/error-codes.md).
31
+
32
+ ### Bridge-API-specific anti-patterns
33
+
34
+ - **`try/catch` for failures.** Every method returns `Result<T>` — branch on `result.ok`. `catch` won't fire for HTTP/timeout/validation failures.
35
+ - **Passing `relayData.payload` to `submitTx`.** Unlike the swaps client, bridge `submitTx.relayData` is the FULL `{ address, payload }` object — pass `relayData` as-is (bridge has no `intent.creator` for the backend to rebuild the relay address).
36
+ - **Expecting an `intent` / `intent_hash`.** `createBridgeIntent` returns `{ tx, relayData }` only; submit-tx status terminal success is `status === 'executed' && result.dstIntentTxHash` (no solver `intent_hash`, no `'posting_execution'` state).
37
+ - **Calling `getSubmitTxStatus` with only `txHash`.** Both `txHash` AND `srcChainKey` are required.
38
+ - **Using SDK-domain param names in the body.** The wire DTO uses swaps naming (`inputToken`/`outputToken`/`inputAmount`/`srcAddress`/`dstAddress`); map SDK-domain `srcToken`/`dstToken`/`amount`/`recipient` via `toCreateBridgeIntentParamsV2`.
39
+ - **Round-tripping the discovery quotes when a local read suffices.** `getFee` / `getBridgeableAmount` / `isBridgeable` are computable client-side — prefer `sodax.bridge.getFee` / `getBridgeableAmount` / `isBridgeable` (no network hop). Their backend endpoints exist (mirrored on this client) mainly for non-SDK HTTP callers / parity; the token *list*, by contrast, is only backend-served.
40
+ - **Confusing `sodax.api.bridge` with `sodax.bridge`.** The former is the backend HTTP client; the latter is the on-chain vault orchestrator.
41
+
42
+ ## Migration workflow (on-chain → API)
43
+
44
+ There is **no v1 Bridge API** — the typed `sodax.api.bridge` client is v2-new. The relevant move is from the
45
+ on-chain `sodax.bridge.bridge()` orchestrator to the API client (or to the orchestrator's opt-in backend
46
+ path via `bridgeOptions.useBackendSubmitTx`):
47
+
48
+ 1. [`../integration/knowledge/features/bridge.md`](../integration/knowledge/features/bridge.md) — the on-chain `BridgeService` orchestrator and the `bridgeOptions.useBackendSubmitTx` toggle that routes its spoke-deposit through this API with a client-side fallback.
49
+ 2. For the v1 → v2 reshape of the on-chain bridge itself (chain-key routing, `Result<T>`, error unions) → [`../migration-v1-to-v2/knowledge/features/bridge.md`](../migration-v1-to-v2/knowledge/features/bridge.md).
50
+
51
+ ## Verification
52
+
53
+ 1. `pnpm tsc --noEmit` clean.
54
+ 2. Every `await sodax.api.bridge.<method>(...)` call site has `if (!result.ok)`.
55
+ 3. `submitTx.relayData` is the full `relayData` object (not `relayData.payload`); `getSubmitTxStatus` passes both `txHash` and `srcChainKey`.
56
+ 4. Bodies use the wire DTO names (`inputToken`/`outputToken`/`inputAmount`/`dstAddress`), mapped from SDK-domain params.
57
+
58
+ ## Related granular skills (same family)
59
+
60
+ - [`../bridge/SKILL.md`](../bridge/SKILL.md) — the end-to-end bridge orchestrator (`sodax.bridge`) that wraps these backend calls.
61
+ - [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the sibling swaps HTTP client this mirrors.
62
+ - [`../backend-api/SKILL.md`](../backend-api/SKILL.md) — the `sodax.backendApi` read client (intent / orderbook / money-market reads + config).
63
+
64
+ For multi-feature tasks, load the broad [`sodax-sdk` skill](../SKILL.md).
@@ -17,6 +17,7 @@ This tree documents v2 of the SDK for **new consumers** building against it. If
17
17
  | [`features/partner.md`](features/partner.md) | `PartnerService` — partner-fee handling. |
18
18
  | [`features/recovery.md`](features/recovery.md) | `RecoveryService` — withdraw stuck hub-wallet assets. |
19
19
  | [`features/backend-api.md`](features/backend-api.md) | `BackendApiService` — HTTP client for backend reads + swap-tx submission. |
20
+ | [`features/sponsoring.md`](features/sponsoring.md) | `SponsoringService` — Stellar account activation via sponsored reserves. |
20
21
  | [`recipes/`](recipes/) | Copy-pasteable patterns: SDK initialization, `Result` + error discrimination, raw-tx flow, signed-tx flow, chain-key narrowing + cast-at-boundary, testing (mocks/stubs), gas estimation, backend-server init. |
21
22
  | [`reference/`](reference/) | Lookup tables: 20-chain `ChainKeys` table with family + relay id, `I*WalletProvider` interfaces, 13 `SodaxErrorCode` meanings + per-feature narrow unions, public API surface (incl. `@sodax/types` re-export rule), glossary. |
22
23
  | [`chain-specifics.md`](chain-specifics.md) | Non-EVM quirks — Stellar trustline check/request, Bitcoin PSBT + Bound Exchange auth/session, Solana PDA derivation, ICON Hana wallet + chain-key string, NEAR connector discovery. |
@@ -102,6 +102,24 @@ const exists = await radfi.checkIfTradingWalletExists(personalAddress);
102
102
 
103
103
  **Server-side / raw flows (no interactive sign-in).** A backend that builds raw Bitcoin intents can't run the BIP322 login, so seed a pre-provisioned Bound token instead of authenticating. `RadfiProvider` honors three injection points: `new Sodax({ ... })` with `radfi.accessToken` (and optional `refreshToken`) in the Bitcoin chain config (the constructor seeds them), `radfi.setRadfiAccessToken(token)` at runtime, or a per-action `extras.bound.accessToken` on `createIntent` (the Bitcoin-gated `bound` slot groups Bound/Radfi inputs). If an authenticated Bound call has neither a token nor a configured `apiKey`, `RadfiProvider` throws a legible `RadfiApiError` (the message names the fix: inject via `setRadfiAccessToken` or `new Sodax({ ... })` with `radfi.accessToken`) instead of sending an empty bearer and getting an opaque 403.
104
104
 
105
+ **Backend request signing.** Separate from the per-user token above: if Bound authenticates your service itself, pass `radfi.signRequest` to `new Sodax({ ... })`. The SDK calls it once per outbound Bound request and merges the returned headers onto it, so the credential stays in your closure and never on the SDK config:
106
+
107
+ ```ts
108
+ import { createHmac } from 'node:crypto';
109
+
110
+ new Sodax({
111
+ radfi: {
112
+ signRequest: () => {
113
+ const ts = `${Date.now()}`;
114
+ const signature = createHmac('sha256', secretKey).update(`${secretWord}_${ts}`).digest('hex');
115
+ return { 'x-api-signature': `${signature}_${ts}` };
116
+ },
117
+ },
118
+ });
119
+ ```
120
+
121
+ It receives `{ method, path }`, may be async, and runs on every request (a timestamped signature must not be cached). Its headers merge last, so do not return `Authorization` — that is the per-user token. Server-side only: never ship a credential in a browser bundle.
122
+
105
123
  Other public methods on `RadfiProvider` you may need: `setRadfiAccessToken`, `refreshAccessToken`, `createTradingWallet`, `createWithdrawTransaction`, `requestRadfiSignature`, `getExpiredUtxos`, `buildRenewUtxoTransaction`, `signAndBroadcastRenewUtxo`, `withdrawToUser`, `signAndBroadcastWithdraw`, `getMaxWithdrawable`. Read `RadfiProvider` source for argument shapes — the API surface is broader than typical chain providers.
106
124
 
107
125
  ### Pitfall
@@ -14,6 +14,9 @@ One file per feature service. Each file documents the v2 API surface, common cal
14
14
  | [`partner.md`](partner.md) | `PartnerService` | Partner-fee handling: token approval, auto-swap preferences, fee-claim flows. |
15
15
  | [`recovery.md`](recovery.md) | `RecoveryService` | Withdraw stuck hub-wallet assets back to a spoke chain. |
16
16
  | [`backend-api.md`](backend-api.md) | `BackendApiService` | HTTP client for backend services: swap-tx submission, intent / orderbook lookups, money-market reads. |
17
+ | [`sponsoring.md`](sponsoring.md) | `SponsoringService` | Stellar account activation via sponsored reserves. The sponsor pays the base reserve; the user's wallet signs. |
18
+ | [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API v2 (`sodax.api.swaps`, `/swaps/*`). Quote, create-intent, submit-tx + status, fees. |
19
+ | [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API v2 (`sodax.api.bridge`, `/bridge/*`). Allowance/approve/create-intent, submit-tx + status, tokens. |
17
20
 
18
21
  All feature services are constructed and wired by the `Sodax` facade. You don't instantiate them directly — access them via `sodax.swaps`, `sodax.moneyMarket`, etc. See [`../architecture.md`](../architecture.md) for the service graph.
19
22
 
@@ -0,0 +1,141 @@
1
+ # Bridge API — `BridgeApiService`
2
+
3
+ Typed HTTP client for the backend **Bridge API v2** (`/bridge/*`). Reachable as `sodax.api.bridge`
4
+ (`sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the `BridgeApiService` instance). One method
5
+ per endpoint. Every method returns `Promise<Result<T>>` — it **never throws** — and every
6
+ response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
7
+ `{ ok: false }` rather than an untyped object.
8
+
9
+ Access: `sodax.api.bridge`. Service class: `BridgeApiService`. **Errors:** every failure (network, timeout,
10
+ non-2xx HTTP, or response-shape mismatch) returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with
11
+ `feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path); the underlying failure
12
+ is on `error.cause`. Like `sodax.api.swaps`, the bridge **HTTP client** is uniformly `feature: 'backend'`
13
+ (with a per-service `context.api` tag — `'bridge'`).
14
+
15
+ > Lower-level than `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end).
16
+ > Use `sodax.api.bridge` for a single backend call, or when building your own flow. The Bridge API is
17
+ > served on the base backend host — its routes are `/bridge/*` sub-paths under the same base URL.
18
+
19
+ ## Methods
20
+
21
+ ```ts
22
+ // Tokens
23
+ sodax.api.bridge.getTokens(config?): Promise<Result<GetBridgeTokensResponseV2>>;
24
+ sodax.api.bridge.getTokensByChain(chainKey, config?): Promise<Result<GetBridgeTokensByChainResponseV2>>;
25
+
26
+ // Allowance · approve · create intent — all three share the CreateBridgeIntentParamsV2 body
27
+ sodax.api.bridge.checkAllowance(body: CreateBridgeIntentParamsV2, config?): Promise<Result<BridgeAllowanceCheckResponseV2>>;
28
+ sodax.api.bridge.approve(body: CreateBridgeIntentParamsV2, config?): Promise<Result<BridgeApproveResponseV2>>;
29
+ sodax.api.bridge.createBridgeIntent(body: CreateBridgeIntentParamsV2, config?): Promise<Result<CreateBridgeIntentResponseV2>>;
30
+
31
+ // Submit-tx state machine
32
+ sodax.api.bridge.submitTx(body: BridgeSubmitTxRequestV2, config?): Promise<Result<BridgeSubmitTxResponseV2>>;
33
+ sodax.api.bridge.getSubmitTxStatus(query: BridgeSubmitTxStatusQueryV2, config?): Promise<Result<BridgeSubmitTxStatusResponseV2>>;
34
+
35
+ // Discovery / quote — read-only (computable client-side via sodax.bridge.*; mirrored here for HTTP parity)
36
+ sodax.api.bridge.getFee(body: BridgeFeeRequestV2, config?): Promise<Result<BridgeFeeResponseV2>>;
37
+ sodax.api.bridge.getBridgeableAmount(body: BridgeQuoteRequestV2, config?): Promise<Result<BridgeableAmountResponseV2>>;
38
+ sodax.api.bridge.isBridgeable(body: BridgeQuoteRequestV2, config?): Promise<Result<BridgeableCheckResponseV2>>;
39
+ ```
40
+
41
+ The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers? }`) on every method
42
+ applies per-call overrides that take precedence over the service config (same as the swaps client).
43
+
44
+ ## Deltas vs the Swaps API
45
+
46
+ Bridge is **vault-backed, not solver-based**, so the surface is smaller and a few shapes differ:
47
+
48
+ - **No `intent` struct.** `createBridgeIntent` returns `{ tx, relayData }` (no `intent`); `submitTx` carries
49
+ no `intent` field; there is no quote / deadline / limit-order / cancel / intent-hash / packet surface.
50
+ - **`submitTx.relayData` is the FULL `{ address, payload }` object** (not the `.payload` string the swaps
51
+ client takes). Bridge has no `intent.creator` for the backend to rebuild the relay address, so the client
52
+ must send the whole envelope — dropping the address breaks split-tx-chain relay (Stellar/Solana/Sui/Stacks).
53
+ - **Status lifecycle is 5-state** (`'pending'` → `'relaying'` → `'relayed'` → `'executed'` | `'failed'`) —
54
+ no swaps `'posting_execution'`. Terminal success is `status === 'executed' && result.dstIntentTxHash`
55
+ (no solver `intent_hash`). The status schema is tolerant of unknown states.
56
+ - **Param naming follows the swaps wire convention** (`inputToken`/`outputToken`/`inputAmount`/`srcAddress`/
57
+ `dstAddress`), NOT the SDK-domain `srcToken`/`dstToken`/`amount`/`recipient`. The mapper
58
+ `toCreateBridgeIntentParamsV2(params, extras?)` converts SDK-domain params (and serializes the `bigint`
59
+ amount) to this wire DTO.
60
+ - **Discovery quotes (`getFee` / `getBridgeableAmount` / `isBridgeable`) are computable client-side** — prefer
61
+ `sodax.bridge.getFee(...)` / `getBridgeableAmount(...)` / `isBridgeable({ from, to })` (no round-trip). They
62
+ *also* have backend endpoints (listed above), mirrored on this client for non-SDK HTTP callers / parity.
63
+ The token *list* is backend-served via `getTokens` / `getTokensByChain`.
64
+
65
+ ## Common call shapes
66
+
67
+ ### Allowance · approve · create intent (shared body)
68
+
69
+ ```ts
70
+ const body = {
71
+ srcChainKey, dstChainKey,
72
+ inputToken, // source token address (SDK domain `srcToken`)
73
+ outputToken, // destination token address (SDK domain `dstToken`)
74
+ inputAmount: '1000000', // smallest unit, decimal string (SDK domain `amount`, bigint → string)
75
+ srcAddress, dstAddress, // dstAddress is the SDK domain `recipient`
76
+ };
77
+
78
+ const allowance = await sodax.api.bridge.checkAllowance(body);
79
+ if (allowance.ok && !allowance.value.valid) {
80
+ const approved = await sodax.api.bridge.approve(body); // { tx } — sign + broadcast yourself
81
+ }
82
+
83
+ const created = await sodax.api.bridge.createBridgeIntent(body);
84
+ if (!created.ok) return;
85
+ const { tx, relayData } = created.value; // no `intent`
86
+ ```
87
+
88
+ ### Submit tx + poll status
89
+
90
+ ```ts
91
+ // Sign + broadcast `tx` yourself, then hand the spoke tx hash back with the FULL relayData envelope.
92
+ const submit = await sodax.api.bridge.submitTx({
93
+ txHash, srcChainKey, walletAddress,
94
+ relayData, // the whole { address, payload } object, NOT relayData.payload
95
+ });
96
+ if (!submit.ok) return;
97
+
98
+ // Both txHash AND srcChainKey are required.
99
+ const status = await sodax.api.bridge.getSubmitTxStatus({ txHash, srcChainKey });
100
+ if (status.ok && status.value.data.status === 'executed') {
101
+ status.value.data.result?.dstIntentTxHash; // destination tx hash (no intent_hash)
102
+ }
103
+ // Lifecycle: 'pending' → 'relaying' → 'relayed' → 'executed' | 'failed'.
104
+ ```
105
+
106
+ ## Per-call overrides & custom endpoint
107
+
108
+ Every method accepts a trailing `RequestOverrideConfig` to redirect a single call or attach headers:
109
+
110
+ ```ts
111
+ await sodax.api.bridge.getTokens({ baseURL: 'https://staging.example/v1/be', headers: { 'X-Trace': 'abc' } });
112
+ ```
113
+
114
+ The Bridge API has no dedicated config slice — it always shares the base backend host (`/bridge/*`). To
115
+ move the whole backend (including bridge) to a custom host, use the `CustomApiConfig` `baseApiConfig` slice
116
+ (see [`backend-api.md`](backend-api.md) § "Custom backend").
117
+
118
+ ## Orchestrator integration — `bridgeOptions.useBackendSubmitTx`
119
+
120
+ `new Sodax({ bridgeOptions: { useBackendSubmitTx: true } })` opts the end-to-end `sodax.bridge.bridge()`
121
+ into routing the spoke-deposit through this API (`submit-tx` + status poll) with an automatic fall back to
122
+ the client-side relay on any non-success. **Default OFF.** This is a distinct key from
123
+ `swapsOptions.useBackendSubmitTx`. See [`bridge.md`](bridge.md) and the `CONFIGURE_SDK` doc.
124
+
125
+ ## Error handling
126
+
127
+ ```ts
128
+ const r = await sodax.api.bridge.createBridgeIntent(body);
129
+ if (!r.ok) {
130
+ // r.error: SodaxError<'EXTERNAL_API_ERROR'> — feature: 'backend', context.api: 'bridge',
131
+ // context.endpoint: '/bridge/intents'. The transport / shape-validation failure is on r.error.cause.
132
+ return;
133
+ }
134
+ ```
135
+
136
+ ## Cross-references
137
+
138
+ - `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end): [`bridge.md`](bridge.md).
139
+ - `sodax.api.swaps` (the sibling swaps HTTP client this mirrors): [`swaps-api.md`](swaps-api.md).
140
+ - `BackendApiService` (intent / orderbook / money-market reads + config): [`backend-api.md`](backend-api.md).
141
+ - Error model context fields: [`../reference/error-codes.md`](../reference/error-codes.md).
@@ -13,21 +13,29 @@ A bridge call deposits the source token into its vault on the hub, then triggers
13
13
  ## Public methods
14
14
 
15
15
  ```ts
16
- sodax.bridge.bridge<K>(action: BridgeAction<K, false>): Promise<Result<TxHashPair, SodaxError>>;
17
- sodax.bridge.createBridgeIntent<K, Raw>(action): Promise<Result<IntentTxResult<K, Raw>, SodaxError>>;
16
+ sodax.bridge.bridge<K>(action: BridgeParams<K, false>): Promise<Result<TxHashPair, SodaxError>>;
17
+ sodax.bridge.createBridgeIntent<K, Raw>(action: BridgeParams<K, Raw>): Promise<Result<IntentTxResult<K, Raw>, SodaxError>>;
18
18
  sodax.bridge.approve<K, Raw>(args): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
19
19
  sodax.bridge.isAllowanceValid<K, Raw>(args): Promise<Result<boolean, SodaxError>>;
20
20
 
21
21
  sodax.bridge.getBridgeableAmount(from: XToken, to: XToken): Promise<Result<BridgeLimit, SodaxError>>;
22
22
  sodax.bridge.getBridgeableTokens(from: SpokeChainKey, to: SpokeChainKey, token: string): Result<XToken[], SodaxError>;
23
- // Plus the sync helper:
23
+ // Plus the sync helpers:
24
24
  sodax.bridge.isBridgeable({ from: XToken, to: XToken }): boolean;
25
- sodax.bridge.getFee(inputAmount: bigint): bigint;
25
+ // partnerFee defaults to the configured `bridge.partnerFee`; pass one to preview an `extras.partnerFee` override.
26
+ sodax.bridge.getFee(inputAmount: bigint, partnerFee?: PartnerFee): bigint;
26
27
  ```
27
28
 
28
29
  ## Action params shape
29
30
 
30
31
  ```ts
32
+ type BridgeParams<K extends SpokeChainKey, Raw extends boolean> = {
33
+ params: CreateBridgeIntentParams<K>;
34
+ extras?: BridgeExtras<K>;
35
+ skipSimulation?: boolean;
36
+ timeout?: number; // shared budget for relay/poll; defaults to DEFAULT_RELAY_TX_TIMEOUT
37
+ } & WalletProviderSlot<K, Raw>; // raw: true ⇒ no walletProvider; raw: false ⇒ required, chain-narrowed
38
+
31
39
  type CreateBridgeIntentParams<K extends SpokeChainKey> = {
32
40
  srcChainKey: K;
33
41
  srcAddress: string; // source wallet (spoke chain)
@@ -39,6 +47,44 @@ type CreateBridgeIntentParams<K extends SpokeChainKey> = {
39
47
  };
40
48
  ```
41
49
 
50
+ ### extras (per-action overrides)
51
+
52
+ Chain-specific slots are keyed off `K`, so a non-Stacks action can't set `srcPublicKey` and a non-Bitcoin action can't set `bound`:
53
+
54
+ ```ts
55
+ type BridgeExtras<K extends SpokeChainKey> = (GetChainType<K> extends 'STACKS'
56
+ ? { srcPublicKey?: string }
57
+ : { srcPublicKey?: never }) &
58
+ (GetChainType<K> extends 'BITCOIN' ? { bound?: { accessToken?: string } } : { bound?: never }) & {
59
+ partnerFee?: PartnerFee;
60
+ };
61
+ ```
62
+
63
+ | Slot | When | Notes |
64
+ |---|---|---|
65
+ | `partnerFee` | any chain, optional | Takes precedence over the config-level `bridge.partnerFee` for this call. Omit to use the configured fee. |
66
+ | `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'`). |
67
+ | `bound` | raw Bitcoin TRADING source, optional | Bound Exchange (Radfi) access token; falls back to the `RadfiProvider` instance token. |
68
+
69
+ ```ts
70
+ const result = await sodax.bridge.bridge({
71
+ params: { /* … */ },
72
+ raw: false,
73
+ walletProvider: evmWp,
74
+ extras: { partnerFee: { address: '0xPartner…', percentage: 100 } }, // 100 = 1%
75
+ });
76
+ ```
77
+
78
+ ## Validation rules to respect
79
+
80
+ - **Native BTC dust limit (`BITCOIN_DUST_SATS` = 546 sats).** Native BTC is denominated in satoshis, and outputs below the dust limit are unspendable/rejected by nodes. Bitcoin as **source**: `amount >= 546`. Bitcoin as **destination**: the *post-fee delivered* amount must clear 546 — the partner fee is deducted on the hub in 18-dp vault units, so a percentage fee or a wei-denominated fixed `PartnerFee.amount` can push a nominally valid `amount` under the limit. Both fail `VALIDATION_FAILED` on `field: 'amount'`.
81
+ - **Stacks + `raw: true`** requires `extras.srcPublicKey` (above).
82
+ - Amount must be `> 0n`; both chain keys must be registered spoke chains; both tokens must be supported on their chain and share a vault.
83
+
84
+ ## Routing the spoke deposit through the backend
85
+
86
+ `bridge()` relays client-side by default. `new Sodax({ bridgeOptions: { useBackendSubmitTx: true } })` opts into handing the broadcast deposit to the backend Bridge API instead (`sodax.api.bridge`), which relays server-side and falls back to the client-side relay on any non-success — safe because re-relaying is idempotent. Default is OFF. See [`bridge-api.md`](bridge-api.md).
87
+
42
88
  ## Common call shapes
43
89
 
44
90
  ### Full bridge (recommended for most flows)
@@ -0,0 +1,162 @@
1
+ # Sponsoring — `SponsoringService`
2
+
3
+ Reachable as `sodax.sponsoring`. Activates a Stellar account by having the SODAX sponsor pay its
4
+ XLM base reserve.
5
+
6
+ ## Why this exists
7
+
8
+ A Stellar account must exist on-chain before it can hold or receive anything, and a brand-new SODAX
9
+ user holds 0 XLM — a chicken-and-egg problem. Stellar solves it with *sponsored reserves*: a sponsor
10
+ account pays the reserve inside a `beginSponsoringFutureReserves` → `createAccount` →
11
+ `endSponsoringFutureReserves` operation sandwich.
12
+
13
+ **The user's own wallet must sign.** Their signature is what authorises `endSponsoringFutureReserves`,
14
+ and only their wallet holds that key — so this can never be a server-only call. The client builds and
15
+ signs; the backend validates, co-signs as the sponsor, and submits.
16
+
17
+ The build rules are enforced strictly server-side and every violation is a `400`, which is why they
18
+ live in one tested place in the SDK rather than being copy-pasted per consumer. It also means the
19
+ sponsor account can be rotated without a client release.
20
+
21
+ ## Surface
22
+
23
+ ```ts
24
+ // @ai-snippets-skip
25
+ sodax.sponsoring.isStellarAccountActive({ address }); // Result<boolean>
26
+ sodax.sponsoring.getStellarAccountStatus({ address }); // Result<StellarAccountStatus>
27
+ // { exists, nativeBalanceStroops, availableBalanceStroops, canAffordTrustline, trustlineMinXlmStroops }
28
+ sodax.sponsoring.getStellarSponsorConfig({ forceRefresh? }); // Result<StellarSponsorConfig>
29
+ sodax.sponsoring.activateStellarAccount({
30
+ address, // must be the account walletProvider signs with
31
+ walletProvider, // IStellarWalletProvider — only signTransaction is used
32
+ allowSequenceRetry?, // default true; one rebuild + re-sign on a sequence conflict
33
+ maxHorizonRetries?, // default 2; no-prompt re-submits of the SAME payload on a 503
34
+ onSignatureRequired?, // fires immediately BEFORE each wallet prompt
35
+ forceConfigRefresh?,
36
+ requestConfig?,
37
+ });
38
+ ```
39
+
40
+ The raw endpoints stay available as `sodax.api.sponsoring` (`getStellarSponsorConfig`,
41
+ `createStellarSponsoredAccount`) for integrators who build their own XDR.
42
+
43
+ ## Two success shapes — both are `ok`
44
+
45
+ ```ts
46
+ // @ai-snippets-skip
47
+ type ActivateStellarAccountResult =
48
+ | { status: 'submitted'; hash: string; attempts: 1 | 2 }
49
+ | { status: 'alreadyActive'; hash: null; attempts: 0 | 1 | 2 };
50
+ ```
51
+
52
+ `alreadyActive` means the account already existed and nothing was submitted — the account is usable,
53
+ so render it as success, not as a no-op failure. `attempts: 0` means the client-side pre-flight
54
+ caught it and the user was never prompted at all.
55
+
56
+ ## Errors — branch on `context.nextAction`, not the HTTP status
57
+
58
+ Failures carry the caller's next action on `error.context`, alongside `retryable` and
59
+ `requiresNewSignature`:
60
+
61
+ | `nextAction` | Meaning |
62
+ |---|---|
63
+ | `fixIntegration` | The request was malformed. An SDK/caller bug; never retry as-is. |
64
+ | `checkApiKey` | Missing or invalid api key. A deployment problem. |
65
+ | `rebuildAndResign` | The sponsor's sequence moved. Costs a **new user signature**. |
66
+ | `retrySameRequest` | Transient upstream failure; the signed payload is still valid. |
67
+ | `backoff` | Quota, throttle, draining coordinator, or a transport failure. |
68
+ | `contactOperator` | Sponsor out of budget, or a server fault. Not caller-fixable. |
69
+ | `abort` | Deterministic on-chain rejection. Terminal. |
70
+
71
+ On a per-key quota 429 the error also carries `context.retryAfterSeconds` — seconds until the breached
72
+ window rolls over, floored at 1. Prefer it over a fixed backoff. It comes from the response body rather
73
+ than the `Retry-After` header, because a body needs no CORS opt-in and so survives a browser; note the
74
+ `X-RateLimit-*` headers describe the **per-IP** throttle, not this per-key quota.
75
+
76
+ The SDK does not auto-retry a 429 — it is a load signal for the caller to pace. Only
77
+ `HORIZON_UNAVAILABLE` gets a silent same-payload retry.
78
+
79
+ `classifySponsorError(error)` is exported if you need the same classification for a raw
80
+ `sodax.api.sponsoring` call.
81
+
82
+ **`retryable` is broader than what the SDK auto-retries.** It is `true` for 409, 429, a draining 503
83
+ and every transport failure — but the SDK only ever re-sends on `nextAction: 'retrySameRequest'`.
84
+ Branch on `nextAction`, not `retryable`, if you are deciding whether to re-send.
85
+
86
+ ## Analytics
87
+
88
+ With `analytics` enabled the flow emits one `start` and one terminal event under
89
+ `feature: 'sponsoring'`, `action: 'activateStellarAccount'`. Both terminals carry `attempts`
90
+ (`0 | 1 | 2`): `0` means the pre-flight short-circuited or the flow failed before any attempt, and
91
+ `2` is reachable only through the sequence-conflict retry — so `attempts: 2` means a 409 occurred,
92
+ whatever the final outcome was. Success adds `status` (`'submitted' | 'alreadyActive'`) and `hash`;
93
+ failure adds `code`, `httpStatus` and `nextAction`. The HTTP status is deliberately NOT called
94
+ `status`, so the property does not change type between the two events.
95
+
96
+ ## Gotchas
97
+
98
+ - **Activation makes the account able to RECEIVE, not to SEND.** The sponsor covers the account's own
99
+ base reserve and `startingBalance` is `0` by contract, so a freshly activated account holds **zero
100
+ spendable XLM** — the reserve sits locked on the sponsor's balance, not in the user's account. It
101
+ cannot pay a transaction fee, and cannot cover the additional base reserve a new subentry locks, so
102
+ it **cannot establish its own first trustline**. The escape is native XLM, which needs no trustline:
103
+ activate → receive XLM → then add trustlines. A non-native destination token therefore has TWO
104
+ prerequisites, not one. Read `canAffordTrustline` from `getStellarAccountStatus` rather than
105
+ inferring capability from `isStellarAccountActive` — and note it is measured against
106
+ `availableBalanceStroops`, not the total, because Stellar locks one base reserve per existing
107
+ subentry. Render `status.trustlineMinXlmStroops` when telling a user how much to send: the base
108
+ reserve is a network setting validators can change, so the SDK reads it from Horizon (cached hourly)
109
+ and `STELLAR_TRUSTLINE_MIN_XLM_STROOPS` is only the fallback for a failed read. Sponsored trustlines
110
+ and fee sponsorship would remove the middle step; neither exists yet.
111
+ - **A sequence conflict costs a second wallet prompt.** The sponsor's sequence number is baked into
112
+ the signed payload, so a conflict forces a rebuild and re-sign. The SDK retries **exactly once**
113
+ and never loops. Wire `onSignatureRequired` and show the explanation *before* the wallet steals
114
+ focus — it fires immediately before each prompt. The server attaches the current sponsor sequence
115
+ to a genuine 409 (`context.sponsorSequence`), so the rebuild skips a Horizon read; it is advisory,
116
+ so the SDK falls back to reading Horizon when it is absent.
117
+ - **Never hardcode the sponsor account.** It is published by the config endpoint and cached briefly;
118
+ that indirection is what makes rotation a config change.
119
+ - **Never broadcast the signed transaction yourself.** It is missing the sponsor's signature until
120
+ the server adds it, so `sendTransaction` / `signAndSendTransaction` would burn the user's prompt on
121
+ a guaranteed `tx_bad_auth`. Only `signTransaction` is used.
122
+ - **Name the signer.** The transaction is sourced by the *sponsor* but must be signed by the account
123
+ being created, so the SDK calls `signTransaction(xdr, { address })`. If you build your own XDR,
124
+ pass `address` too — omit it and a browser wallet signs with whatever account is currently active,
125
+ returning a well-formed envelope with the wrong signature that the server rejects as unsigned.
126
+ (A signer that is not the transaction source is ordinary Stellar — it is how multisig and every
127
+ sponsorship flow work; no wallet refuses it.)
128
+ - **Public network only.** The service rejects a testnet Horizon by design — there is no testnet
129
+ path. A wallet connected to testnet signs over the wrong network id and returns a well-formed
130
+ envelope, so the SDK verifies the signature locally and fails with `VALIDATION_FAILED` rather than
131
+ letting the server report an opaque `400`.
132
+ - **Fee is per-operation; the published totals are a TOTAL.** If you build your own XDR, pass
133
+ `recommendedPerOperationFeeStroops` from the config endpoint verbatim — do not divide the totals,
134
+ and never pass a `BASE_FEE`-style default (100/op → 300 total → rejected against the 3000 floor).
135
+ `operationCount` is published so you can cross-check rather than baking "3 ops" into your own
136
+ contract. The config endpoint always publishes the per-operation band — deriving it from the totals
137
+ would need ceiling division, which is exactly what publishing it removes. The SDK handles all of
138
+ this.
139
+
140
+ ## Config
141
+
142
+ ```ts
143
+ // @ai-snippets-skip
144
+ new Sodax({ api: { sponsoringApiConfig: { baseURL, timeout, headers, apiKey } } });
145
+ ```
146
+
147
+ `baseURL` defaults to the packaged sponsoring endpoint (`DEFAULT_SPONSORING_API_ENDPOINT`,
148
+ `https://api.sodax.com/v1`) and does **not** inherit `baseApiConfig` — the service is routed
149
+ independently. Give it the base URL **including any version or gateway prefix**: the SDK appends only
150
+ `SPONSORING_API_STELLAR_BASE_PATH` (`/sponsorships/stellar`), so a locally-run service that mounts the
151
+ routes at its bare origin is reached with `baseURL: 'http://localhost:3011'`.
152
+
153
+ `apiKey` is folded into `x-api-key`. An api key in a browser bundle is public by nature: the service's
154
+ per-key quotas, fleet-wide daily cap, per-IP throttle, and origin gating are the real controls. Proxy
155
+ through your own backend if that is not acceptable.
156
+
157
+ ## Cross-references
158
+
159
+ - React hooks wrapping this service — `useStellarAccountActive`, `useSponsorConfig`,
160
+ `useActivateStellarAccount` — are documented in the `sodax-dapp-kit` skill under its
161
+ auxiliary-services feature doc.
162
+ - Service is new in v2 — there is no v1 equivalent and nothing to port.
@@ -140,10 +140,39 @@ import {
140
140
  // Backend API config + per-call override
141
141
  type ApiConfig, // BaseApiConfig | CustomApiConfig
142
142
  type BaseApiConfig,
143
- type CustomApiConfig, // point the swaps API at its own endpoint
143
+ type CustomApiConfig, // point the swaps / sponsoring API at its own endpoint
144
144
  type SwapsApiConfig,
145
+ type SponsoringApiConfig, // BaseApiConfig & { apiKey? } — own host, own x-api-key
146
+ DEFAULT_SPONSORING_API_ENDPOINT,
147
+ SPONSORING_API_STELLAR_BASE_PATH,
145
148
  type RequestOverrideConfig, // per-call override on any backendApi / sodax.api.swaps method
146
149
 
150
+ // Sponsoring — sodax.sponsoring (Stellar account activation) + sodax.api.sponsoring (wire client)
151
+ SponsoringService,
152
+ SponsoringApiService,
153
+ SPONSOR_CONFIG_TTL_MS, // 60s; mirrors the server's Cache-Control on GET /config
154
+ STELLAR_TRUSTLINE_MIN_XLM_STROOPS, // fallback minimum; prefer status.trustlineMinXlmStroops
155
+ type StellarAccountStatus, // { exists, nativeBalanceStroops, availableBalanceStroops, canAffordTrustline, trustlineMinXlmStroops }
156
+ classifySponsorError, // SodaxError -> { action, retryable, requiresNewSignature, ... }
157
+ type ActivateStellarAccountParams,
158
+ type ActivateStellarAccountResult, // discriminated on status: 'submitted' | 'alreadyActive'
159
+ type SponsorFailureAction, // 'fixIntegration' | 'checkApiKey' | 'rebuildAndResign' | ...
160
+ type SponsorFailureClass,
161
+ type SponsoringOrchestrationError,
162
+ type SponsoringConfigError,
163
+ type SponsoringLookupError,
164
+ type IStellarSponsoringApi,
165
+ type StellarSponsorConfig,
166
+ type StellarSponsoredAccountRequest,
167
+ type StellarSponsoredAccountResponse,
168
+ type SponsoringApiErrorCode, // the 7 wire codes
169
+ SPONSORING_API_ERROR_CODES, // runtime array — membership-test before trusting body.error
170
+ type SponsoringApiErrorResponse,
171
+
172
+ // Structured non-2xx backend failure (on error.cause) — status + parsed body
173
+ BackendHttpError,
174
+ isBackendHttpError, // bundle-safe guard; prefer over instanceof
175
+
147
176
  // Read shapes
148
177
  type Intent,
149
178
  type IntentResponse,
@@ -0,0 +1,83 @@
1
+ ---
2
+ name: sodax-sdk-sponsoring
3
+ description: 'Granular skill for the @sodax/sdk v2 sponsoring feature — `sodax.sponsoring` (class SponsoringService), which activates a Stellar account by having the SODAX backend sponsor pay its XLM base reserve. A brand-new user holds 0 XLM and cannot create their own account; the client builds and signs the begin/create/end sandwich (the user''s signature authorises being sponsored) and the backend co-signs and submits. Use when the task involves activating or funding a new Stellar account, checking whether a Stellar account exists on-chain, or reading the sponsor build parameters (e.g. "activate a Stellar account", "sponsor a Stellar account", "user has no XLM", "account not found on Stellar", "sodax.sponsoring", "sponsored reserve", "base reserve", "createAccount for a new user"). For the raw HTTP endpoints use the `backend-api` skill; for the trustline step that follows activation see the Stellar notes in chain-specifics. Skill links into the parent sodax-sdk knowledge tree.'
4
+ license: MIT
5
+ metadata:
6
+ version: '0.0.1'
7
+ author: sodax
8
+ ---
9
+
10
+ # Sponsoring (Core SDK granular skill)
11
+
12
+ Granular skill for `sodax.sponsoring` (class `SponsoringService`) — Stellar account activation paid for
13
+ by the SODAX sponsor account.
14
+
15
+ A Stellar account must exist on-chain before it can hold or receive anything, and creating one costs an
16
+ XLM base reserve a brand-new user does not have. The sponsor pays it. The user's wallet still signs:
17
+ Stellar's sponsorship sandwich requires the *sponsored* account to authorise
18
+ `endSponsoringFutureReserves`, and only their wallet holds that key — so the client builds and signs,
19
+ and the backend validates, co-signs as sponsor, and submits.
20
+
21
+ Four methods, all returning `Result<T>` and never throwing: `activateStellarAccount`,
22
+ `isStellarAccountActive`, `getStellarAccountStatus`, `getStellarSponsorConfig`.
23
+
24
+ > **Activation makes the account able to RECEIVE, not to SEND.** The sponsor covers the account's own
25
+ > reserve and `startingBalance` is `0`, so a freshly activated account holds **zero spendable XLM** — it
26
+ > cannot pay a fee, and cannot cover the reserve its own first trustline would lock. The way out is
27
+ > native XLM, which needs no trustline: activate → receive XLM → then add trustlines. A non-native
28
+ > destination token therefore has TWO prerequisites, not one. See the Stellar section of
29
+ > [`../integration/knowledge/chain-specifics.md`](../integration/knowledge/chain-specifics.md).
30
+
31
+ ## Step 1 — Clarify with user before coding
32
+
33
+ 1. **Activation, or just a check?** Rendering an "Activate" button needs `isStellarAccountActive`;
34
+ performing it needs `activateStellarAccount`. They handle a Horizon read failure *differently* on
35
+ purpose — see the feature doc.
36
+ 2. **Interactive or headless?** An interactive signer can be prompted a second time when the sponsor's
37
+ sequence moves (the default). A headless caller should set `allowSequenceRetry: false` and own the
38
+ backoff.
39
+ 3. **Is the api key available?** The sponsoring service is `x-api-key` gated and runs on its own host,
40
+ so it needs a `sponsoringApiConfig` slice. Confirm the key comes from an env var — never inlined.
41
+
42
+ ## Integration workflow
43
+
44
+ 1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md) — DO / DO NOT (read first).
45
+ 2. [`../integration/knowledge/features/sponsoring.md`](../integration/knowledge/features/sponsoring.md) — the full surface: the two success shapes, the `nextAction` error table, the double-signature UX, analytics, gotchas, and config.
46
+ 3. Errors are `Result<T, SodaxError>` → [`../integration/knowledge/recipes/result-and-errors.md`](../integration/knowledge/recipes/result-and-errors.md) and [`../integration/knowledge/reference/error-codes.md`](../integration/knowledge/reference/error-codes.md).
47
+ 4. Needs a Stellar wallet provider → [`../integration/knowledge/reference/wallet-providers.md`](../integration/knowledge/reference/wallet-providers.md); for the raw endpoints behind it → [`../integration/knowledge/features/backend-api.md`](../integration/knowledge/features/backend-api.md).
48
+
49
+ ### Sponsoring-specific anti-patterns
50
+
51
+ - **Treating `alreadyActive: true` as a failure.** It is a SUCCESS with `hash: null` — the account already existed and nothing was submitted. Both `status` values mean "the account is usable".
52
+ - **Hardcoding the sponsor public key.** Read it from `getStellarSponsorConfig()`. Hardcoding is what turns a sponsor rotation into a coordinated client release, and a stale value fails as a confusing `400` ("transaction source does not match sponsor account") that reads like an SDK bug.
53
+ - **Branching on `error.message` or on the HTTP status alone.** Branch on `error.context.nextAction`. Two different `503`s want opposite handling: `HORIZON_UNAVAILABLE` → re-submit the same bytes; `SPONSOR_BUDGET_EXHAUSTED` → contact an operator.
54
+ - **Assuming a body's `error` field is a domain code.** Framework exceptions put a human label there (`'Unauthorized'`, `'Bad Request'`), and two paths omit the field entirely — the per-IP throttler's `429` and the server's fallback for an unexpected error (a bare `500`). Membership-test against `SPONSORING_API_ERROR_CODES`, which is why it ships as a runtime array. `classifySponsorError` already does this.
55
+ - **Not surfacing the second signature.** On a sequence conflict the user is prompted again, and the wallet extension steals focus the instant it opens. Wire `onSignatureRequired` so the explanation is already on screen.
56
+ - **Broadcasting the signed XDR yourself.** It is missing the sponsor's signature until the server adds it — broadcasting burns the user's prompt on a guaranteed `tx_bad_auth`. Only `signTransaction` is used, never `sendTransaction`.
57
+ - **Rendering a failed `isStellarAccountActive` as "not active".** It returns `Result`, not a boolean — a transient Horizon blip must not be shown to the user as an inactive account.
58
+
59
+ ## Migration workflow (v1 → v2)
60
+
61
+ The sponsoring feature is **v2-new** — v1 had no equivalent, and there is no v1 shape to port from. A
62
+ consumer arriving from v1 who previously told users to fund their own Stellar account can adopt it
63
+ additively. The general v2 conventions it relies on (`Result<T>`, `SodaxError`, chain-key-first
64
+ narrowing, wallet providers passed per call) are covered in:
65
+
66
+ 1. [`../migration-v1-to-v2/knowledge/breaking-changes/result-and-errors.md`](../migration-v1-to-v2/knowledge/breaking-changes/result-and-errors.md) — the `Result` + `SodaxError` contract.
67
+ 2. [`../migration-v1-to-v2/knowledge/features/backend-api.md`](../migration-v1-to-v2/knowledge/features/backend-api.md) — how backend clients hang off `sodax.api` in v2.
68
+
69
+ ## Verification
70
+
71
+ 1. `pnpm tsc --noEmit` clean.
72
+ 2. Every `await sodax.sponsoring.<method>(...)` call site has `if (!result.ok)`.
73
+ 3. Success handling distinguishes `status: 'submitted'` from `status: 'alreadyActive'`, and treats both as success.
74
+ 4. Failure handling branches on `error.context.nextAction` — not on `message`, not on `status` alone.
75
+ 5. The sponsor account is read from `getStellarSponsorConfig()` (or left to `activateStellarAccount`), never hardcoded.
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.
78
+
79
+ ## Related granular skills (same family)
80
+
81
+ - [`../backend-api/SKILL.md`](../backend-api/SKILL.md) — the raw `sodax.api.sponsoring` wire client and the sibling backend read client.
82
+
83
+ For multi-feature tasks, load the broad [`sodax-sdk` skill](../SKILL.md).
@@ -64,7 +64,7 @@ Merge strategy: flat (`mergeDefaults`).
64
64
  | Method | Signature | Returns |
65
65
  |---|---|---|
66
66
  | `getWalletAddress` | `() => Promise<string>` | Stellar address |
67
- | `signTransaction` | `(tx: XDR) => Promise<XDR>` | signed XDR |
67
+ | `signTransaction` | `(tx: XDR, options?: { address?: string }) => Promise<XDR>` | signed XDR. Pass `address` when a SPECIFIC account must sign (sponsored reserves, multisig) — without it a browser wallet signs with whatever account is active, yielding a well-formed envelope carrying the wrong signature. The private-key provider throws if `address` is not the key it holds. |
68
68
  | `waitForTransactionReceipt` | `(hash: string, options?: Pick<StellarWalletDefaults, 'pollInterval' \| 'pollTimeout'>) => Promise<…>` | tx result; respects `pollInterval` / `pollTimeout` (`networkPassphrase` is NOT accepted per-call) |
69
69
 
70
70
  ---