@sodax/skills 2.0.0 → 2.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -3
- package/package.json +1 -1
- package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +4 -3
- package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +106 -20
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/wallet-connectivity.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +15 -1
- package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/auxiliary-services.md +5 -5
- package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/reference/renamed-hooks.md +1 -1
- package/skills/sodax-sdk/SKILL.md +2 -1
- package/skills/sodax-sdk/integration/knowledge/README.md +1 -0
- package/skills/sodax-sdk/integration/knowledge/features/README.md +1 -0
- package/skills/sodax-sdk/integration/knowledge/features/sponsoring.md +160 -0
- package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +30 -1
- package/skills/sodax-sdk/sponsoring/SKILL.md +83 -0
- 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,
|
|
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
|
@@ -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,
|
|
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
|
-
- **
|
|
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
|
-
- **
|
|
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
|
|
@@ -107,7 +107,7 @@ useDeriveUserWalletAddress({ params, queryOptions }); // Hub wallet address (CRE
|
|
|
107
107
|
useGetUserHubWalletAddress({ params, queryOptions }); // Hub wallet via wallet router
|
|
108
108
|
useEstimateGas({ mutationOptions }); // Gas estimation for raw tx
|
|
109
109
|
useStellarTrustlineCheck({ params, queryOptions });
|
|
110
|
-
|
|
110
|
+
useEstablishTrustline({ mutationOptions }); // useRequestTrustline is its deprecated 2.0.0 wrapper
|
|
111
111
|
useNearStorageCheck({ params, queryOptions }); // NEP-141 storage registration check (NEAR)
|
|
112
112
|
useRegisterNearStorage({ mutationOptions }); // NEP-141 storage_deposit (NEAR)
|
|
113
113
|
useNearStorageGate({ dstChainKey, token, accountId, walletProvider }); // composite NEAR receive-side gate
|
|
@@ -137,32 +137,56 @@ const xService = useXService({ xChainType: getXChainType(xChainId) });
|
|
|
137
137
|
const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });
|
|
138
138
|
```
|
|
139
139
|
|
|
140
|
-
### Stellar
|
|
140
|
+
### Stellar prerequisites — use `useStellarGate`
|
|
141
141
|
|
|
142
|
-
Stellar
|
|
142
|
+
Stellar has ordered prerequisites for a destination account, and they are invisible until they bite:
|
|
143
|
+
the account must **exist** on-chain, must **trust** the destination token, and — only if it does not —
|
|
144
|
+
must be able to **pay** for the trustline it needs. `useStellarGate` sequences them; prefer it over
|
|
145
|
+
wiring the pieces yourself.
|
|
143
146
|
|
|
144
147
|
```ts
|
|
145
148
|
// @ai-snippets-skip — illustrative only; real types pulled into agents below.
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
|
|
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
|
-
});
|
|
149
|
+
// Mirrors useNearStorageGate. Pass the DESTINATION chain/token/amount/account plus the destination
|
|
150
|
+
// wallet provider; the gate owns the `=== STELLAR_MAINNET` test and the native-token exemption.
|
|
151
|
+
const stellar = useStellarGate({ dstChainKey, token, amount, address, walletProvider });
|
|
153
152
|
|
|
154
|
-
//
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
//
|
|
160
|
-
|
|
161
|
-
if (
|
|
162
|
-
|
|
163
|
-
|
|
153
|
+
// Exactly one of these is ever true, in this order:
|
|
154
|
+
if (stellar.needsActivation) await stellar.activate(); // account does not exist — sponsor pays
|
|
155
|
+
if (stellar.needsFunding) { /* send it XLM — needs no trustline */ }
|
|
156
|
+
if (stellar.needsTrustline) await stellar.requestTrustline();
|
|
157
|
+
|
|
158
|
+
// A check FAILED — state unknown, not unmet. Say so and offer the retry; otherwise the action is
|
|
159
|
+
// disabled with nothing on screen explaining why.
|
|
160
|
+
if (stellar.checkFailed) { /* render stellar.error?.message + a button calling stellar.retry() */ }
|
|
161
|
+
|
|
162
|
+
// Gate the downstream action on the whole gate, which also covers the checking and errored windows.
|
|
163
|
+
const disabled = stellar.blocksAction || /* … */ false;
|
|
164
164
|
```
|
|
165
165
|
|
|
166
|
+
Affordability is checked **after** the trustline, and the order matters: an account that already trusts
|
|
167
|
+
the asset needs no XLM, because the sender pays the fee and the subentry reserve is already locked.
|
|
168
|
+
Checking affordability first blocks a correctly-configured user who has merely spent their spendable
|
|
169
|
+
XLM, and tells them to fund an account that needs nothing.
|
|
170
|
+
|
|
171
|
+
`blocksAction` is fail-closed on an unknown state, deliberately: a payment to a non-existent account, or
|
|
172
|
+
of an untrusted asset, fails on-chain, so letting the action through on a failed check risks stranding
|
|
173
|
+
funds. That makes `checkFailed` load-bearing — it is the only way a UI can tell "we could not check"
|
|
174
|
+
apart from "you are missing something", and without it a transient Horizon failure reads to the user as
|
|
175
|
+
an inexplicably dead button.
|
|
176
|
+
|
|
177
|
+
Do NOT hand-roll this as `useStellarTrustlineCheck` + `useEstablishTrustline`. `hasSufficientTrustline`
|
|
178
|
+
**throws** for an account that does not exist, so a `!data` test reads a missing account as "needs a
|
|
179
|
+
trustline" and offers a button that cannot work. Read `isLoading`, never `isPending` — `isPending` stays
|
|
180
|
+
`true` for a disabled query and blocks forever.
|
|
181
|
+
|
|
182
|
+
The lower-level pieces remain available for custom wiring: `useStellarAccountStatus` (existence,
|
|
183
|
+
`canAffordTrustline`, and `trustlineMinXlmStroops` — the XLM one more trustline needs at the network's
|
|
184
|
+
current base reserve — from one Horizon account read), `useStellarAccountActive` (existence only),
|
|
185
|
+
`useStellarTrustlineCheck`, and `useEstablishTrustline` — a canonical mutation hook whose vars are
|
|
186
|
+
`{ token, amount, srcChainKey, walletProvider }` (NOT `account` / `asset`). `useRequestTrustline` still
|
|
187
|
+
exists as a deprecated wrapper preserving the 2.0.0 shape (`{ requestTrustline, isLoading, isRequested,
|
|
188
|
+
error, data }`, positional token ignored); write new code against `useEstablishTrustline`.
|
|
189
|
+
|
|
166
190
|
### NEAR storage registration
|
|
167
191
|
|
|
168
192
|
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 +227,68 @@ const { needsRegistration, blocksAction } = resolveNearStorageGate(dstChainKey,
|
|
|
203
227
|
|
|
204
228
|
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
229
|
|
|
230
|
+
## Stellar account activation (sponsoring)
|
|
231
|
+
|
|
232
|
+
A Stellar account must exist on-chain before it can hold or receive anything, and a brand-new user
|
|
233
|
+
holds 0 XLM. The SODAX sponsoring service pays the account's base reserve via Stellar's
|
|
234
|
+
sponsored-reserve flow. **The user's own wallet must sign** — their signature is what authorises the
|
|
235
|
+
`endSponsoringFutureReserves` operation — so this can never be a server-only call.
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
// @ai-snippets-skip
|
|
239
|
+
useStellarAccountActive({ params: { address }, queryOptions }); // does the account exist on-chain?
|
|
240
|
+
useSponsorConfig({ queryOptions }); // sponsor account, network, fee band
|
|
241
|
+
useActivateStellarAccount({ mutationOptions }); // activate via the sponsor
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Mutation vars:
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
// @ai-snippets-skip
|
|
248
|
+
// An alias for the SDK's own params — every option the service accepts is accepted here.
|
|
249
|
+
type UseActivateStellarAccountVars = ActivateStellarAccountParams;
|
|
250
|
+
// address: string // must be the account walletProvider signs with
|
|
251
|
+
// walletProvider: IStellarWalletProvider // useWalletProvider({ xChainId: ChainKeys.STELLAR_MAINNET })
|
|
252
|
+
// allowSequenceRetry?: boolean // default true — one rebuild + re-sign on a sequence conflict
|
|
253
|
+
// maxHorizonRetries?: number // default 2 — no-prompt re-submits of the SAME payload
|
|
254
|
+
// onSignatureRequired?: (info: { attempt: 1 | 2; reason: 'initial' | 'sequenceConflict' }) => void
|
|
255
|
+
// forceConfigRefresh?: boolean
|
|
256
|
+
// requestConfig?: RequestOverrideConfig
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Four things consumers get wrong:
|
|
260
|
+
|
|
261
|
+
1. **Activation makes the account able to RECEIVE, not to SEND.** A freshly activated account holds
|
|
262
|
+
**zero spendable XLM** (the sponsor covers its reserve; `startingBalance` is `0`), so it cannot pay a
|
|
263
|
+
fee or the reserve its own first trustline would lock. Use `useStellarGate`, which sequences
|
|
264
|
+
activation → trustline → funding; pairing `useStellarTrustlineCheck` with `useEstablishTrustline`
|
|
265
|
+
directly conflates "account missing" with "trustline missing" and offers a button that cannot work.
|
|
266
|
+
Always render `checkFailed` / `error` / `retry` too — a fail-closed gate that cannot explain itself
|
|
267
|
+
is a dead button.
|
|
268
|
+
|
|
269
|
+
2. **`alreadyActive` is a SUCCESS, not a no-op failure.** The result is
|
|
270
|
+
`{ status: 'submitted', hash, attempts }` or `{ status: 'alreadyActive', hash: null, attempts }`.
|
|
271
|
+
Render the second as "already active", not as an error. `attempts: 0` means the client pre-flight
|
|
272
|
+
caught it and the user was never prompted.
|
|
273
|
+
3. **A sequence conflict costs a SECOND wallet prompt.** The sponsor's sequence number is baked into
|
|
274
|
+
the signed payload, so if another activation lands first the transaction must be rebuilt and
|
|
275
|
+
re-signed. Wire `onSignatureRequired` and show the explanation *before* the wallet steals focus —
|
|
276
|
+
it fires immediately before each prompt.
|
|
277
|
+
4. **Never hardcode the sponsor account.** It comes from `useSponsorConfig` / the SDK's own fetch,
|
|
278
|
+
which is what makes sponsor rotation a config change instead of a client release.
|
|
279
|
+
|
|
280
|
+
Failure handling: `error.context.nextAction` carries the caller's next step —
|
|
281
|
+
`fixIntegration` | `checkApiKey` | `rebuildAndResign` | `retrySameRequest` | `backoff` |
|
|
282
|
+
`contactOperator` | `abort` — alongside `retryable` and `requiresNewSignature`. Branch on those
|
|
283
|
+
rather than on the HTTP status.
|
|
284
|
+
|
|
285
|
+
When the server rate-limits a key it also supplies `error.context.retryAfterSeconds`; render "try again
|
|
286
|
+
in Ns" instead of a generic "try later". The SDK never auto-retries a rate limit.
|
|
287
|
+
|
|
288
|
+
Requires `api.sponsoringApiConfig` (at minimum `apiKey`) on the `SodaxProvider` config. An api key
|
|
289
|
+
in a browser bundle is public by nature; the service's per-key quotas, fleet cap, per-IP throttle,
|
|
290
|
+
and origin gating are the real controls. Proxy through your own backend if that is not acceptable.
|
|
291
|
+
|
|
206
292
|
## Default polling intervals
|
|
207
293
|
|
|
208
294
|
| 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
|
-
| `
|
|
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 |
|
|
@@ -235,7 +235,9 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
|
|
|
235
235
|
| `useGetUserHubWalletAddress` | Query | Derive hub wallet (wallet router) |
|
|
236
236
|
| `useEstimateGas` | Mutation | Estimate gas for raw tx |
|
|
237
237
|
| `useStellarTrustlineCheck` | Query | Check Stellar trustline |
|
|
238
|
-
| `
|
|
238
|
+
| `useEstablishTrustline` | Mutation | Request a Stellar trustline (the account pays — needs XLM) |
|
|
239
|
+
| `useRequestTrustline` | Deprecated | 2.0.0-shape wrapper over `useEstablishTrustline`; removed next major |
|
|
240
|
+
| `useStellarGate` | Composite | Sequences the Stellar prerequisites: exists → trustline → can afford; `checkFailed`/`error`/`retry` for a failed check |
|
|
239
241
|
| `useNearStorageCheck` | Query | Check NEP-141 storage registration (NEAR) |
|
|
240
242
|
| `useRegisterNearStorage` | Mutation | Submit NEP-141 `storage_deposit` (NEAR) |
|
|
241
243
|
| `useNearStorageGate` | Hook | Composite NEAR receive-side storage gate |
|
|
@@ -244,6 +246,18 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
|
|
|
244
246
|
| `unwrapResult` | Internal | `Result<T>` → throw / return |
|
|
245
247
|
| `toResult` | Internal | `Promise<T>` → `Result<T>` |
|
|
246
248
|
|
|
249
|
+
## Sponsoring (`sponsoring/`)
|
|
250
|
+
|
|
251
|
+
Stellar accounts must exist on-chain before they can hold or receive anything, and a new user holds 0 XLM.
|
|
252
|
+
These hooks drive the sponsored-reserve activation flow, where the SODAX sponsor pays the base reserve.
|
|
253
|
+
|
|
254
|
+
| Hook | Kind | Purpose |
|
|
255
|
+
| --- | --- | --- |
|
|
256
|
+
| `useStellarAccountActive` | Query | Whether a Stellar account already exists on-chain |
|
|
257
|
+
| `useStellarAccountStatus` | Query | Existence + `canAffordTrustline` + `trustlineMinXlmStroops`, from one Horizon account read |
|
|
258
|
+
| `useSponsorConfig` | Query | Sponsor account, network, fee band, max time bounds |
|
|
259
|
+
| `useActivateStellarAccount` | Mutation | Activate a Stellar account via the sponsor |
|
|
260
|
+
|
|
247
261
|
## Cross-references
|
|
248
262
|
|
|
249
263
|
- [`../features/`](../features/) — per-feature reference docs (params types, return shapes, gotchas).
|
|
@@ -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` / `
|
|
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
|
-
+ //
|
|
99
|
-
+
|
|
100
|
-
+
|
|
101
|
-
+
|
|
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` |
|
|
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,6 +33,7 @@ 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" |
|
|
38
39
|
|
|
@@ -76,7 +77,7 @@ Follow in order. Skipping `ai-rules.md` is the most common cause of agents rever
|
|
|
76
77
|
|
|
77
78
|
1. Read [`integration/knowledge/ai-rules.md`](./integration/knowledge/ai-rules.md) — DO / DO NOT / workflow / stop conditions.
|
|
78
79
|
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`.
|
|
80
|
+
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`.
|
|
80
81
|
4. For specific patterns (init, raw vs signed, chain narrowing, gas, testing, errors, logging), read [`integration/knowledge/recipes/`](./integration/knowledge/recipes/).
|
|
81
82
|
5. Lookups (chain keys, error codes, public API surface, wallet provider types, glossary) → [`integration/knowledge/reference/`](./integration/knowledge/reference/).
|
|
82
83
|
6. Non-EVM quirks (Stellar trustline, BTC PSBT, Solana PDA, ICON, NEAR) → [`integration/knowledge/chain-specifics.md`](./integration/knowledge/chain-specifics.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. |
|
|
@@ -14,6 +14,7 @@ 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. |
|
|
17
18
|
|
|
18
19
|
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
20
|
|
|
@@ -0,0 +1,160 @@
|
|
|
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.getStellarSponsorConfig({ forceRefresh? }); // Result<StellarSponsorConfig>
|
|
27
|
+
sodax.sponsoring.activateStellarAccount({
|
|
28
|
+
address, // must be the account walletProvider signs with
|
|
29
|
+
walletProvider, // IStellarWalletProvider — only signTransaction is used
|
|
30
|
+
allowSequenceRetry?, // default true; one rebuild + re-sign on a sequence conflict
|
|
31
|
+
maxHorizonRetries?, // default 2; no-prompt re-submits of the SAME payload on a 503
|
|
32
|
+
onSignatureRequired?, // fires immediately BEFORE each wallet prompt
|
|
33
|
+
forceConfigRefresh?,
|
|
34
|
+
requestConfig?,
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The raw endpoints stay available as `sodax.api.sponsoring` (`getStellarSponsorConfig`,
|
|
39
|
+
`createStellarSponsoredAccount`) for integrators who build their own XDR.
|
|
40
|
+
|
|
41
|
+
## Two success shapes — both are `ok`
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// @ai-snippets-skip
|
|
45
|
+
type ActivateStellarAccountResult =
|
|
46
|
+
| { status: 'submitted'; hash: string; attempts: 1 | 2 }
|
|
47
|
+
| { status: 'alreadyActive'; hash: null; attempts: 0 | 1 | 2 };
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`alreadyActive` means the account already existed and nothing was submitted — the account is usable,
|
|
51
|
+
so render it as success, not as a no-op failure. `attempts: 0` means the client-side pre-flight
|
|
52
|
+
caught it and the user was never prompted at all.
|
|
53
|
+
|
|
54
|
+
## Errors — branch on `context.nextAction`, not the HTTP status
|
|
55
|
+
|
|
56
|
+
Failures carry the caller's next action on `error.context`, alongside `retryable` and
|
|
57
|
+
`requiresNewSignature`:
|
|
58
|
+
|
|
59
|
+
| `nextAction` | Meaning |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `fixIntegration` | The request was malformed. An SDK/caller bug; never retry as-is. |
|
|
62
|
+
| `checkApiKey` | Missing or invalid api key. A deployment problem. |
|
|
63
|
+
| `rebuildAndResign` | The sponsor's sequence moved. Costs a **new user signature**. |
|
|
64
|
+
| `retrySameRequest` | Transient upstream failure; the signed payload is still valid. |
|
|
65
|
+
| `backoff` | Quota, throttle, draining coordinator, or a transport failure. |
|
|
66
|
+
| `contactOperator` | Sponsor out of budget, or a server fault. Not caller-fixable. |
|
|
67
|
+
| `abort` | Deterministic on-chain rejection. Terminal. |
|
|
68
|
+
|
|
69
|
+
On a per-key quota 429 the error also carries `context.retryAfterSeconds` — seconds until the breached
|
|
70
|
+
window rolls over, floored at 1. Prefer it over a fixed backoff. It comes from the response body rather
|
|
71
|
+
than the `Retry-After` header, because a body needs no CORS opt-in and so survives a browser; note the
|
|
72
|
+
`X-RateLimit-*` headers describe the **per-IP** throttle, not this per-key quota.
|
|
73
|
+
|
|
74
|
+
The SDK does not auto-retry a 429 — it is a load signal for the caller to pace. Only
|
|
75
|
+
`HORIZON_UNAVAILABLE` gets a silent same-payload retry.
|
|
76
|
+
|
|
77
|
+
`classifySponsorError(error)` is exported if you need the same classification for a raw
|
|
78
|
+
`sodax.api.sponsoring` call.
|
|
79
|
+
|
|
80
|
+
**`retryable` is broader than what the SDK auto-retries.** It is `true` for 409, 429, a draining 503
|
|
81
|
+
and every transport failure — but the SDK only ever re-sends on `nextAction: 'retrySameRequest'`.
|
|
82
|
+
Branch on `nextAction`, not `retryable`, if you are deciding whether to re-send.
|
|
83
|
+
|
|
84
|
+
## Analytics
|
|
85
|
+
|
|
86
|
+
With `analytics` enabled the flow emits one `start` and one terminal event under
|
|
87
|
+
`feature: 'sponsoring'`, `action: 'activateStellarAccount'`. Both terminals carry `attempts`
|
|
88
|
+
(`0 | 1 | 2`): `0` means the pre-flight short-circuited or the flow failed before any attempt, and
|
|
89
|
+
`2` is reachable only through the sequence-conflict retry — so `attempts: 2` means a 409 occurred,
|
|
90
|
+
whatever the final outcome was. Success adds `status` (`'submitted' | 'alreadyActive'`) and `hash`;
|
|
91
|
+
failure adds `code`, `httpStatus` and `nextAction`. The HTTP status is deliberately NOT called
|
|
92
|
+
`status`, so the property does not change type between the two events.
|
|
93
|
+
|
|
94
|
+
## Gotchas
|
|
95
|
+
|
|
96
|
+
- **Activation makes the account able to RECEIVE, not to SEND.** The sponsor covers the account's own
|
|
97
|
+
base reserve and `startingBalance` is `0` by contract, so a freshly activated account holds **zero
|
|
98
|
+
spendable XLM** — the reserve sits locked on the sponsor's balance, not in the user's account. It
|
|
99
|
+
cannot pay a transaction fee, and cannot cover the additional base reserve a new subentry locks, so
|
|
100
|
+
it **cannot establish its own first trustline**. The escape is native XLM, which needs no trustline:
|
|
101
|
+
activate → receive XLM → then add trustlines. A non-native destination token therefore has TWO
|
|
102
|
+
prerequisites, not one. Read `canAffordTrustline` from `getStellarAccountStatus` rather than
|
|
103
|
+
inferring capability from `isStellarAccountActive` — and note it is measured against
|
|
104
|
+
`availableBalanceStroops`, not the total, because Stellar locks one base reserve per existing
|
|
105
|
+
subentry. Render `status.trustlineMinXlmStroops` when telling a user how much to send: the base
|
|
106
|
+
reserve is a network setting validators can change, so the SDK reads it from Horizon (cached hourly)
|
|
107
|
+
and `STELLAR_TRUSTLINE_MIN_XLM_STROOPS` is only the fallback for a failed read. Sponsored trustlines
|
|
108
|
+
and fee sponsorship would remove the middle step; neither exists yet.
|
|
109
|
+
- **A sequence conflict costs a second wallet prompt.** The sponsor's sequence number is baked into
|
|
110
|
+
the signed payload, so a conflict forces a rebuild and re-sign. The SDK retries **exactly once**
|
|
111
|
+
and never loops. Wire `onSignatureRequired` and show the explanation *before* the wallet steals
|
|
112
|
+
focus — it fires immediately before each prompt. The server attaches the current sponsor sequence
|
|
113
|
+
to a genuine 409 (`context.sponsorSequence`), so the rebuild skips a Horizon read; it is advisory,
|
|
114
|
+
so the SDK falls back to reading Horizon when it is absent.
|
|
115
|
+
- **Never hardcode the sponsor account.** It is published by the config endpoint and cached briefly;
|
|
116
|
+
that indirection is what makes rotation a config change.
|
|
117
|
+
- **Never broadcast the signed transaction yourself.** It is missing the sponsor's signature until
|
|
118
|
+
the server adds it, so `sendTransaction` / `signAndSendTransaction` would burn the user's prompt on
|
|
119
|
+
a guaranteed `tx_bad_auth`. Only `signTransaction` is used.
|
|
120
|
+
- **Name the signer.** The transaction is sourced by the *sponsor* but must be signed by the account
|
|
121
|
+
being created, so the SDK calls `signTransaction(xdr, { address })`. If you build your own XDR,
|
|
122
|
+
pass `address` too — omit it and a browser wallet signs with whatever account is currently active,
|
|
123
|
+
returning a well-formed envelope with the wrong signature that the server rejects as unsigned.
|
|
124
|
+
(A signer that is not the transaction source is ordinary Stellar — it is how multisig and every
|
|
125
|
+
sponsorship flow work; no wallet refuses it.)
|
|
126
|
+
- **Public network only.** The service rejects a testnet Horizon by design — there is no testnet
|
|
127
|
+
path. A wallet connected to testnet signs over the wrong network id and returns a well-formed
|
|
128
|
+
envelope, so the SDK verifies the signature locally and fails with `VALIDATION_FAILED` rather than
|
|
129
|
+
letting the server report an opaque `400`.
|
|
130
|
+
- **Fee is per-operation; the published totals are a TOTAL.** If you build your own XDR, pass
|
|
131
|
+
`recommendedPerOperationFeeStroops` from the config endpoint verbatim — do not divide the totals,
|
|
132
|
+
and never pass a `BASE_FEE`-style default (100/op → 300 total → rejected against the 3000 floor).
|
|
133
|
+
`operationCount` is published so you can cross-check rather than baking "3 ops" into your own
|
|
134
|
+
contract. The config endpoint always publishes the per-operation band — deriving it from the totals
|
|
135
|
+
would need ceiling division, which is exactly what publishing it removes. The SDK handles all of
|
|
136
|
+
this.
|
|
137
|
+
|
|
138
|
+
## Config
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
// @ai-snippets-skip
|
|
142
|
+
new Sodax({ api: { sponsoringApiConfig: { baseURL, timeout, headers, apiKey } } });
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`baseURL` defaults to the packaged sponsoring endpoint (`DEFAULT_SPONSORING_API_ENDPOINT`,
|
|
146
|
+
`https://api.sodax.com/v1`) and does **not** inherit `baseApiConfig` — the service is routed
|
|
147
|
+
independently. Give it the base URL **including any version or gateway prefix**: the SDK appends only
|
|
148
|
+
`SPONSORING_API_STELLAR_BASE_PATH` (`/sponsorships/stellar`), so a locally-run service that mounts the
|
|
149
|
+
routes at its bare origin is reached with `baseURL: 'http://localhost:3011'`.
|
|
150
|
+
|
|
151
|
+
`apiKey` is folded into `x-api-key`. An api key in a browser bundle is public by nature: the service's
|
|
152
|
+
per-key quotas, fleet-wide daily cap, per-IP throttle, and origin gating are the real controls. Proxy
|
|
153
|
+
through your own backend if that is not acceptable.
|
|
154
|
+
|
|
155
|
+
## Cross-references
|
|
156
|
+
|
|
157
|
+
- React hooks wrapping this service — `useStellarAccountActive`, `useSponsorConfig`,
|
|
158
|
+
`useActivateStellarAccount` — are documented in the `sodax-dapp-kit` skill under its
|
|
159
|
+
auxiliary-services feature doc.
|
|
160
|
+
- 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
|
+
Three methods, all returning `Result<T>` and never throwing:
|
|
22
|
+
`activateStellarAccount`, `isStellarAccountActive`, `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
|
---
|