@sodax/skills 2.2.0-rc.1 → 2.2.0-rc.3
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 -4
- package/README.md +2 -2
- package/package.json +1 -1
- package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +2 -2
- package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +25 -18
- package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +76 -2
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +2 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/backend-queries.md +42 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/invalidations.md +8 -6
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/wallet-connectivity.md +26 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +49 -0
- package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +43 -1
- package/skills/sodax-sdk/SKILL.md +2 -1
- package/skills/sodax-sdk/backend-api/SKILL.md +2 -1
- package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +2 -2
- package/skills/sodax-sdk/integration/knowledge/features/README.md +2 -1
- package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +9 -1
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield-api.md +234 -0
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +2 -0
- package/skills/sodax-sdk/integration/knowledge/features/money-market.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/quickstart.md +42 -0
- package/skills/sodax-sdk/integration/knowledge/reference/chain-keys.md +4 -4
- package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +7 -0
- package/skills/sodax-sdk/leverage-yield-api/SKILL.md +77 -0
- package/skills/sodax-wallet-sdk-core/evm/SKILL.md +1 -0
- package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +3 -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/sponsoring`, `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`, `sodax-sdk/leverage-yield-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, 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 |
|
|
29
|
+
| **Scaffolding ONE specific Core SDK feature** (swap, money-market, bridge, staking, dex, leverage-yield, migration, partner, recovery, sponsoring, backend-api, swaps-api, leverage-yield-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 |
|
|
@@ -64,7 +64,7 @@ packages/skills/
|
|
|
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
66
|
│ leverage-yield, migration, partner, recovery, sponsoring, backend-api,
|
|
67
|
-
│ swaps-api}
|
|
67
|
+
│ swaps-api, leverage-yield-api}
|
|
68
68
|
├── sodax-wallet-sdk-core/ {SKILL.md, integration/knowledge/, migration-v1-to-v2/knowledge/,
|
|
69
69
|
│ <chain>/SKILL.md children — evm, solana, sui, bitcoin, stellar, icon,
|
|
70
70
|
│ injective, near, stacks}
|
|
@@ -144,7 +144,7 @@ To add another meta skill later: drop `skills/<name>/SKILL.md` + a flat `knowled
|
|
|
144
144
|
|
|
145
145
|
- **SKILL.md frontmatter is load-bearing.** For a broad top-level skill at `skills/<broad>/SKILL.md`, `name` must equal the directory basename (e.g. `name: sodax-sdk`). For a nested granular skill at `skills/<broad>/<feature>/SKILL.md`, `name` must equal `<broad>-<feature>` (e.g. `name: sodax-sdk-swap`) — namespaced so each granular name stays unique and never collides with its parent (these names are still validated even though granular skills are bundled, not registered). `description` triggers selection — write it concretely with explicit trigger phrases (the agent looks at description alone to decide whether to load the skill). See existing skills for examples.
|
|
146
146
|
- **`description:` MUST be a single-quoted YAML scalar.** The [`vercel-labs/skills` CLI](https://github.com/vercel-labs/skills) parses frontmatter with strict YAML 1.2 — a plain (unquoted) scalar that contains `: ` (colon-space, the YAML mapping indicator) fails to parse and the skill is silently skipped at install time. Wrap every description in single quotes (`description: '...'`), doubling any apostrophe inside (`'` → `''`). Block scalars (`>-`) are also valid YAML but churn diffs and change rendering — prefer single quotes. The `check:ai-structural` validator parses each frontmatter through a real YAML parser to catch violations; it's stricter than the bash-grep check it replaced for exactly this reason.
|
|
147
|
-
- **Optional frontmatter: `license` + `metadata`.** Beyond the required `name` / `description`, every SKILL.md also carries `license: MIT` (matches `package.json`) and a `metadata` block with `version` and `author: sodax`. These are the portable optional fields the [`vercel-labs/skills` CLI](https://github.com/vercel-labs/skills) and skills.sh understand (`metadata` is free-form k/v; `version` conventionally tracks semver). **Quote the version** (`version: '0.0.1'`) — an unquoted two-segment value like `1.0` would parse as the YAML number `1`.
|
|
147
|
+
- **Optional frontmatter: `license` + `metadata`.** Beyond the required `name` / `description`, every SKILL.md also carries `license: MIT` (matches `package.json`) and a `metadata` block with `version` and `author: sodax`. These are the portable optional fields the [`vercel-labs/skills` CLI](https://github.com/vercel-labs/skills) and skills.sh understand (`metadata` is free-form k/v; `version` conventionally tracks semver). **Quote the version** (`version: '0.0.1'`) — an unquoted two-segment value like `1.0` would parse as the YAML number `1`. The fields are additive; `check:ai-structural` only asserts `name` / `description` and does not whitelist, so extra keys are safe.
|
|
148
148
|
- **Skills link into knowledge by relative path.** From a SKILL.md, target paths look like `./integration/knowledge/ai-rules.md` or `./migration-v1-to-v2/knowledge/README.md`. Cross-mode links (between the two subtrees of the same skill) use a `<other-mode>/knowledge/<target>` segment, prefixed by `../` repeated enough times to climb out of the source subtree: depth-0 knowledge files (e.g. `<mode>/knowledge/README.md`, `quickstart.md`) use a `../../` prefix; depth-1 files (e.g. `<mode>/knowledge/features/*.md`, `<mode>/knowledge/recipes/*.md`) use `../../../`. The `check-skills.sh` validator verifies all resolve.
|
|
149
149
|
- **Cross-SDK-package references are forbidden.** A skill MUST NOT link to (or cite a relative/absolute path into) a skill belonging to a different SDK package **family** (`sdk`, `wallet-sdk-core`, `wallet-sdk-react`, `dapp-kit`). Concretely: `sodax-dapp-kit` knowledge MUST NOT reference `sodax-sdk`, `sodax-wallet-sdk-react`, or `sodax-wallet-sdk-core` content via `../../<other-skill>/...`, GitHub URLs, or any other clickable form. Use prose pointers naming the sibling skill instead (e.g., *"load the `sodax-sdk` skill (integration mode)"*). **Intra-family links are allowed**: integration ↔ migration-v1-to-v2 subtrees within the SAME broad skill, broad ↔ granular within the same family (e.g. `sodax-sdk` ↔ `sodax-sdk/swap`), and granular ↔ granular under the same broad parent. These all ship together and document the same SDK package.
|
|
150
150
|
- **Knowledge files** retain the structure they had under each package's `ai-exported/<mode>/` tree: `README.md`, `ai-rules.md`, `features/`, `recipes/`, `reference/`, plus `architecture.md`, `quickstart.md`, `chain-specifics.md`, and `breaking-changes/` where applicable. New files go under whichever subdirectory fits; both skills and knowledge are expected to evolve as the SDK does.
|
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ Using the [`skills` CLI](https://github.com/vercel-labs/skills) from Vercel Labs
|
|
|
13
13
|
npx skills@latest add icon-project/sodax-sdks/packages/skills
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
The installable skills listed in `.claude-plugin/plugin.json` land in your repo — the `sodax-build` front-door / ideation skill plus the mode-gated per-SDK-package skills (each with two knowledge subtrees: `integration/` for new v2 code, `migration-v1-to-v2/` for v1→v2 porting)
|
|
16
|
+
The five installable skills listed in `.claude-plugin/plugin.json` land in your repo — the `sodax-build` front-door / ideation skill plus the four mode-gated per-SDK-package skills (each with two knowledge subtrees: `integration/` for new v2 code, `migration-v1-to-v2/` for v1→v2 porting). The CLI does **not** copy the package-level `AGENTS.md`; agents auto-discover each skill from its `SKILL.md` frontmatter. Re-running the command picks up the latest content.
|
|
17
17
|
|
|
18
18
|
> **npm fallback** (web chats or when you prefer a devDependency): `pnpm add -D @sodax/skills`, then point your agent at `node_modules/@sodax/skills/AGENTS.md`. See the [integration guide](https://github.com/icon-project/sodax-sdks/blob/main/docs/ai-integration-guide.md#wire-your-agent).
|
|
19
19
|
|
|
@@ -25,7 +25,7 @@ The installable skills listed in `.claude-plugin/plugin.json` land in your repo
|
|
|
25
25
|
| **Mode-gated per-SDK-package skills** under `skills/sodax-<pkg>/SKILL.md` | One skill per SODAX SDK package. `<pkg>` ∈ `sdk`, `wallet-sdk-core`, `wallet-sdk-react`, `dapp-kit`. Each SKILL.md gates by mode (integration vs migration) at the top of the body. |
|
|
26
26
|
| **Granular skills** bundled inside each broad skill at `skills/sodax-<pkg>/<sub-domain>/SKILL.md` | Every broad skill ships focused single-domain children: `sodax-sdk` / `sodax-dapp-kit` per feature (swap, money-market, bridge, staking, dex, …); `sodax-wallet-sdk-core` per chain (evm, solana, sui, bitcoin, stellar, icon, injective, near, stacks); `sodax-wallet-sdk-react` per connectivity concern (connect, wallet-modal, bridge-to-sdk, switch-chain, sign-message, walletconnect). They install **with** their parent broad skill (not as separate packages); once installed, load one when the task is already scoped to a single sub-domain — it points at exactly the knowledge files for it instead of the whole broad skill. |
|
|
27
27
|
| **Knowledge** under `skills/sodax-<pkg>/{integration,migration-v1-to-v2}/knowledge/` | Long-form supporting docs — features, recipes, reference tables, breaking-change writeups, code examples. Each skill ships both mode subtrees so `npx skills add` copies the full reference together. |
|
|
28
|
-
| **`AGENTS.md`** at the package root | Tool-neutral router: maps the consumer's stated task to the right skill + mode. |
|
|
28
|
+
| **`AGENTS.md`** at the package root | Tool-neutral router: maps the consumer's stated task to the right skill + mode. Ships on npm, so it is the entry point for the `pnpm add -D @sodax/skills` and `file:` installs — the skills CLI does not copy it. |
|
|
29
29
|
|
|
30
30
|
Skills are short and action-oriented (workflow + anti-patterns + links). Knowledge is the lookup material. Don't read knowledge files top-to-bottom — the skill tells the agent which file is relevant for the current task.
|
|
31
31
|
|
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), sponsored Stellar account activation (useStellarGate, useStellarAccountActive, useStellarAccountStatus, useSponsorConfig, useActivateStellarAccount), and shared utilities (useSodaxContext, useHubProvider, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useEstablishTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), activating a Stellar account for a user who holds no XLM, or cross-cutting utilities (token balances, gas estimation, Stellar trustlines). Covers BOTH integration and migration. Links into the parent sodax-dapp-kit knowledge tree.'
|
|
3
|
+
description: 'Granular skill for the @sodax/dapp-kit v2 auxiliary surfaces — partner fee claiming (useFeeClaimSwap, useApproveToken, useSetSwapPreference, useGetAutoSwapPreferences, useIsTokenApproved), recovery (useHubAssetBalances, useWithdrawHubAsset), read-only backend queries (useBackendIntentByTxHash, useBackendUserIntents, useBackendOrderbook, useBackendMoneyMarketPosition), the Swaps API v2 client hooks (useSwapsApiQuote, useSwapsApiSubmitTx, useSwapsApiStatus), sponsored Stellar account activation (useStellarGate, useStellarAccountActive, useStellarAccountStatus, useSponsorConfig, useActivateStellarAccount), and shared utilities (useSodaxContext, useHubProvider, useBalances, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useEstablishTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), activating a Stellar account for a user who holds no XLM, or cross-cutting utilities (token balances, gas estimation, Stellar trustlines). Covers BOTH integration and migration. Links into the parent sodax-dapp-kit knowledge tree.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -19,7 +19,7 @@ Granular skill for the smaller `@sodax/dapp-kit` v2 surfaces grouped together: *
|
|
|
19
19
|
- **Recovery:** `useHubAssetBalances` (list stuck hub assets) → `useWithdrawHubAsset` (withdraw one back to a spoke). Follows a *known* failed cross-chain op — investigate the failure first.
|
|
20
20
|
- **Backend reads (no wallet):** intent tracking (`useBackendIntentByTxHash` polls 1s, `useBackendIntentByHash`, `useBackendUserIntents`), orderbook (`useBackendOrderbook` — `pagination` nests under `params`), MM data (`useBackendMoneyMarketPosition` etc.), and the Swaps API v2 client (`useSwapsApi*` — e.g. `useSwapsApiSubmitTx`, `useSwapsApiSubmitTxStatus`, `useSwapsApiQuote`).
|
|
21
21
|
- **Stellar prerequisites:** `useStellarGate` sequences the ordered prerequisites — the account must EXIST (sponsored activation, free to the user), must TRUST the token, and only then must be able to PAY for the trustline it needs. A freshly activated account holds zero XLM. An account that already holds the trustline needs no XLM at all, which is why affordability is checked last. A failed check sets `checkFailed` with `error`/`retry` — render it, or the fail-closed gate becomes an unexplained dead button. Lower-level: `useStellarAccountStatus`, `useStellarAccountActive`, `useSponsorConfig`, `useActivateStellarAccount`.
|
|
22
|
-
- **Shared utilities:** `useSodaxContext`, `useHubProvider`, `useXBalances` (needs `xService` from wallet-sdk-react), `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`, `useEstimateGas`, `useStellarTrustlineCheck` / `useEstablishTrustline`.
|
|
22
|
+
- **Shared utilities:** `useSodaxContext`, `useHubProvider`, `useBalances` (SDK-backed — no `xService`, reads via `SodaxProvider`) / `useXBalances` (needs `xService` from wallet-sdk-react), `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`, `useEstimateGas`, `useStellarTrustlineCheck` / `useEstablishTrustline`.
|
|
23
23
|
|
|
24
24
|
## Integration workflow (new v2 code)
|
|
25
25
|
|
|
@@ -132,6 +132,7 @@ import {
|
|
|
132
132
|
useSodaxContext,
|
|
133
133
|
useSafeMutation,
|
|
134
134
|
unwrapResult,
|
|
135
|
+
invalidateBalances,
|
|
135
136
|
type MutationHookParams,
|
|
136
137
|
type SafeUseMutationResult,
|
|
137
138
|
} from '@sodax/dapp-kit';
|
|
@@ -149,8 +150,8 @@ export function useSwap<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
149
150
|
...mutationOptions,
|
|
150
151
|
mutationFn: async vars => unwrapResult(await sodax.swaps.swap({ ...vars, raw: false })),
|
|
151
152
|
onSuccess: async (data, vars, ctx) => {
|
|
152
|
-
|
|
153
|
-
queryClient
|
|
153
|
+
// Covers both balance query families; they never prefix-match each other.
|
|
154
|
+
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
|
154
155
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
155
156
|
},
|
|
156
157
|
});
|
|
@@ -217,26 +218,30 @@ Nothing about the hook contract changes and there is no flag to set. What matter
|
|
|
217
218
|
- If the second signature is rejected after the reset landed, the allowance is now zero, so the next
|
|
218
219
|
attempt is a single transaction — retrying is always safe.
|
|
219
220
|
|
|
220
|
-
On the unsigned (backend-API) paths, prefer **`useSwapsApiApproveAndBroadcast`** —
|
|
221
|
-
**`useBridgeApiApproveAndBroadcast`** for a bridge
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
221
|
+
On the unsigned (backend-API) paths, prefer **`useSwapsApiApproveAndBroadcast`** —
|
|
222
|
+
**`useBridgeApiApproveAndBroadcast`** for a bridge, **`useLeverageYieldApiApproveAndBroadcast`** for a
|
|
223
|
+
leverage-yield deposit: each asks its API for the transactions, then signs, broadcasts, and waits for
|
|
224
|
+
each, resolving with `{ approveTxHash, resetTxHash? }` only once the final approval has landed. A
|
|
225
|
+
transaction that mines but reverts rejects the mutation naming that step, so the approve is never
|
|
226
|
+
sent over a reset that did not take. Each also invalidates its own allowance query
|
|
227
|
+
(`['swapsApi','allowance']` / `['bridgeApi','allowance']` / `['leverageYieldApi','allowance']`),
|
|
228
|
+
because confirmation now happens inside the hook. Pick the one matching the action you are about to
|
|
229
|
+
take — each API builds its approval for its own hub spender, so an approval built by one does not
|
|
230
|
+
satisfy the other. Only a leverage-yield **deposit** needs one; a withdraw spends `lsoda*` from the
|
|
231
|
+
hub wallet and never approves.
|
|
232
|
+
|
|
233
|
+
All three accept an optional **`onProgress`** in their mutation vars. It reports each transaction as
|
|
230
234
|
`{ step, phase, index, total, hash?, error? }` — `step` is `'allowance-reset'` or `'approve'`, `phase`
|
|
231
235
|
walks `signing → broadcast → confirmed` (or `failed`), and `index`/`total` give "1 of 2" without the
|
|
232
236
|
caller tracking anything. Advisory: the listener is never awaited, one that throws is ignored rather
|
|
233
237
|
than aborting a broadcast, and the mutation's own result stays the source of truth. It lives in the
|
|
234
238
|
vars rather than the hook options so it is never a stale closure.
|
|
235
239
|
|
|
236
|
-
`useSwapsApiApprove` / `useBridgeApiApprove` still exist and return
|
|
237
|
-
verbatim — use them only when you need to own signing. If you do,
|
|
238
|
-
wait for it to succeed**; the approve is not a valid state
|
|
239
|
-
sending both together spends the user's gas on a certain
|
|
240
|
+
`useSwapsApiApprove` / `useBridgeApiApprove` / `useLeverageYieldApiApprove` still exist and return
|
|
241
|
+
the API's `{ tx, resetTx? }` verbatim — use them only when you need to own signing. If you do,
|
|
242
|
+
broadcast `resetTx` **first and wait for it to succeed**; the approve is not a valid state
|
|
243
|
+
transition until the reset has landed, so sending both together spends the user's gas on a certain
|
|
244
|
+
revert. Waiting is not enough on its own —
|
|
240
245
|
check the receipt's status, because a mined-and-reverted reset leaves the allowance exactly where it
|
|
241
246
|
was.
|
|
242
247
|
|
|
@@ -274,7 +279,8 @@ Worked examples:
|
|
|
274
279
|
// @ai-snippets-skip
|
|
275
280
|
queryKey: ['mm', 'userReservesData', spokeChainKey, userAddress]
|
|
276
281
|
queryKey: ['mm', 'allowance', srcChainKey, token, action]
|
|
277
|
-
queryKey: ['shared', '
|
|
282
|
+
queryKey: ['shared', 'balances', chainKey, tokens, address] // useBalances
|
|
283
|
+
queryKey: ['shared', 'xBalances', xChainId, tokens, address] // useXBalances
|
|
278
284
|
mutationKey: ['mm', 'supply']
|
|
279
285
|
queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo', tokenId, poolKey] });
|
|
280
286
|
```
|
|
@@ -286,7 +292,8 @@ Hooks organized by feature domain in `src/hooks/`:
|
|
|
286
292
|
```
|
|
287
293
|
hooks/
|
|
288
294
|
├── shared/ # useSodaxContext, useSafeMutation, unwrapResult, useEstimateGas,
|
|
289
|
-
│ # useDeriveUserWalletAddress, useGetUserHubWalletAddress,
|
|
295
|
+
│ # useDeriveUserWalletAddress, useGetUserHubWalletAddress,
|
|
296
|
+
│ # useBalances, useXBalances, invalidateBalances,
|
|
290
297
|
│ # useStellarTrustlineCheck, useEstablishTrustline (+ deprecated useRequestTrustline)
|
|
291
298
|
├── provider/ # useHubProvider
|
|
292
299
|
├── swap/ # useQuote, useSwap, useStatus, useSwapAllowance, useSwapApprove,
|
|
@@ -64,6 +64,15 @@ useBackendMoneyMarketAssetBorrowers({ params, queryOptions });
|
|
|
64
64
|
useBackendAllMoneyMarketBorrowers({ params: { pagination: { offset, limit } }, queryOptions });
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
+
### Oracle data
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// @ai-snippets-skip
|
|
71
|
+
useBackendOracleMarkets({ queryOptions }); // staleTime 60s; discovery: quote, intervals, symbols
|
|
72
|
+
// from/to are UNIX seconds over the half-open range [from, to), at most 5000 buckets; staleTime 10s
|
|
73
|
+
useBackendOracleCandles({ params: { symbol, interval, from, to }, queryOptions });
|
|
74
|
+
```
|
|
75
|
+
|
|
67
76
|
### Swaps API (`sodax.api.swaps`)
|
|
68
77
|
|
|
69
78
|
Typed React Query wrappers over the backend **Swaps API v2** — one `useSwapsApi*` hook per endpoint of `sodax.api.swaps.*` (21 total: tokens, quote, deadline, allowance, approve, create / submit / cancel intent, status, intent hash / packet / extra-data, intent lookups, limit orders, gas estimate, fees, submit-tx + status). They call the backend HTTP API and are distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive `sodax.swaps` (the on-chain `SwapService`). Reads take `{ params, queryOptions }`; the six actions (`approve`, `createIntent`, `submitIntent`, `cancelIntent`, `createLimitOrder`, `submitTx`) are mutations taking `{ mutationOptions }`, with domain inputs flowing through `mutate(vars)`.
|
|
@@ -167,6 +176,36 @@ await submitBridgeTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
|
167
176
|
|
|
168
177
|
> 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).
|
|
169
178
|
|
|
179
|
+
### Leverage Yield API (`sodax.api.leverageYield`)
|
|
180
|
+
|
|
181
|
+
Typed React Query wrappers over the backend **Leverage Yield API v2** — `useLeverageYieldApi*` hooks over `sodax.api.leverageYield.*` (vault registry, vault reads, split deposit/withdraw quote + create-intent, deadline, allowance/approve, the intent lifecycle, gas/fees, submit-tx + status). They are the HTTP-API parallel of the on-chain `leverageYield/` hooks (`useLeverageYieldDeposit`/`useLeverageYieldWithdraw`/…, which drive `sodax.leverageYield`). A vault deposit/withdraw IS an intent-based swap, so the intent / gas / fee / submit-tx hooks mirror the swaps family; reads take `{ params, queryOptions }` and the actions are mutations taking `{ mutationOptions }`.
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
// @ai-snippets-skip
|
|
185
|
+
useLeverageYieldApiVaults({ params, queryOptions }); // query → sodax.api.leverageYield.getVaults
|
|
186
|
+
useLeverageYieldApiEffectiveApr({ params, queryOptions }); // query → sodax.api.leverageYield.getEffectiveApr
|
|
187
|
+
useLeverageYieldApiCreateDepositIntent({ mutationOptions }); // mutation → sodax.api.leverageYield.createDepositIntent
|
|
188
|
+
useLeverageYieldApiSubmitTxStatus({ params, queryOptions }); // query → sodax.api.leverageYield.getSubmitTxStatus
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Four deltas worth knowing:
|
|
192
|
+
|
|
193
|
+
- **Create-intent is split.** `useLeverageYieldApiCreateDepositIntent` (any token → `lsoda*`) vs `useLeverageYieldApiCreateWithdrawIntent` (`lsoda*` → any token), each with its own quote hook. Only the deposit path has an allowance step — a withdraw spends `lsoda*` from the hub wallet — so `useLeverageYieldApiAllowance` / `useLeverageYieldApiApprove` take the **deposit** body.
|
|
194
|
+
- **`useLeverageYieldApiSubmitTx`'s `request` carries `operation`.** `LeverageYieldSubmitTxRequestV2` is the swaps `SubmitTxRequestV2` plus a required `operation: 'deposit' | 'withdraw'`; `relayData` is the payload **string**, as for swaps.
|
|
195
|
+
- **Terminal submit-tx status is `solved`**, not the bridge API's `executed` — a vault swap is filled by the solver, so `posting_execution` applies too. `useLeverageYieldApiSubmitTxStatus` polls (1s) while both `txHash` and `srcChainKey` are supplied and stops on `solved` / `failed`, on a set `abandonedAt`, or once the backend rejects the API key.
|
|
196
|
+
- **`lsoda*` shares live in the derived HUB wallet, not the EOA.** Resolve it with `useGetUserHubWalletAddress` before reading `useLeverageYieldApiShareBalance` / `useLeverageYieldApiMaxWithdraw`, or the balance reads as zero.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
// @ai-snippets-skip
|
|
200
|
+
const { mutateAsync: submitVaultTx } = useLeverageYieldApiSubmitTx();
|
|
201
|
+
// request: LeverageYieldSubmitTxRequestV2 — { txHash, srcChainKey, walletAddress, intent, relayData, operation }
|
|
202
|
+
await submitVaultTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Prefer `useLeverageYieldApiApproveAndBroadcast` over `useLeverageYieldApiApprove`: a guarded deposit token can need its stale allowance cleared first, and the approve-and-broadcast hook owns plan → sign → broadcast → wait in that order (reporting each step through `onProgress`) and invalidates `['leverageYieldApi','allowance']` itself.
|
|
206
|
+
|
|
207
|
+
> 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.leverageYield` is documented in the `sodax-sdk` skill (integration mode).
|
|
208
|
+
|
|
170
209
|
## Shared utilities
|
|
171
210
|
|
|
172
211
|
Cross-cutting hooks used by other features.
|
|
@@ -175,7 +214,8 @@ Cross-cutting hooks used by other features.
|
|
|
175
214
|
// @ai-snippets-skip
|
|
176
215
|
useSodaxContext(); // Access the Sodax SDK instance
|
|
177
216
|
useHubProvider(); // Hub chain (Sonic) provider
|
|
178
|
-
|
|
217
|
+
useBalances({ params, queryOptions }); // SDK-backed wallet balances (no xService)
|
|
218
|
+
useXBalances({ params, queryOptions }); // Cross-chain token balances (needs xService)
|
|
179
219
|
useDeriveUserWalletAddress({ params, queryOptions }); // Hub wallet address (CREATE3)
|
|
180
220
|
useGetUserHubWalletAddress({ params, queryOptions }); // Hub wallet via wallet router
|
|
181
221
|
useEstimateGas({ mutationOptions }); // Gas estimation for raw tx
|
|
@@ -210,6 +250,36 @@ const xService = useXService({ xChainType: getXChainType(xChainId) });
|
|
|
210
250
|
const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });
|
|
211
251
|
```
|
|
212
252
|
|
|
253
|
+
### `useBalances` shape (SDK-backed, no `xService`)
|
|
254
|
+
|
|
255
|
+
`useBalances` is the SDK-backed successor to `useXBalances`: it reads wallet balances straight from the core SDK (`sodax.spoke.getWalletBalances`) via the `SodaxProvider` context, so it needs **no** `xService` from `@sodax/wallet-sdk-react`. Both hooks still exist — prefer `useBalances` when the app already has a `SodaxProvider`; keep `useXBalances` when you're wiring balances through the wallet layer.
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
// @ai-snippets-skip
|
|
259
|
+
type UseBalancesParams = ReadHookParams<Record<string, bigint>, {
|
|
260
|
+
chainKey: SpokeChainKey | undefined; // the chain the read executes against
|
|
261
|
+
tokens: readonly XToken[]; // tokens to fetch balances for
|
|
262
|
+
address: string | undefined;
|
|
263
|
+
}>;
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
The query runs only when `chainKey`, `address`, and `tokens.length > 0` are all present, refetching every 5s (same interval as `useXBalances`). `data` is a `Record<string, bigint>` mapping each token address to its balance in smallest units. queryKey: `['shared', 'balances', chainKey, tokens.map(t => [t.symbol, t.address]), address]`.
|
|
267
|
+
|
|
268
|
+
**`chainKey` decides the chain that is read.** The SDK ignores `token.chainKey`, so a token that does not live on `chainKey` reads as `0n` rather than erroring — commit the chain and the token list in the same state update. (`useXBalances` is the opposite: it derives the chain from `xTokens[0].chainKey` and ignores the `xChainId` you pass.)
|
|
269
|
+
|
|
270
|
+
**Failure model.** A token that could not be read is logged by the SDK and reported as `0n` — a flaky RPC and an empty wallet look the same, always in the conservative direction (under-reporting blocks a spend, never permits one). The query errors only when the whole batch is unusable: a mismatched `token.chainKey`, an RPC every token depends on, or a batch in which no token could be read at all.
|
|
271
|
+
|
|
272
|
+
**Chain-specific values.** Stellar XLM reports the *spendable* amount — total minus the minimum reserve and selling liabilities, not the raw balance. Bitcoin returns `0n` for Rune tokens, whose amounts the UTXO endpoint does not carry.
|
|
273
|
+
|
|
274
|
+
```tsx
|
|
275
|
+
// @ai-snippets-skip
|
|
276
|
+
// No `xService` — just the SodaxProvider context the hook reads internally.
|
|
277
|
+
const { data: balances } = useBalances({ params: { chainKey, address, tokens } });
|
|
278
|
+
const usdcBalance = balances?.[usdc.address] ?? 0n;
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
After a mutation, invalidate with the `invalidateBalances(queryClient, chainKey)` helper exported from `@sodax/dapp-kit` — it covers both `['shared','balances']` and `['shared','xBalances']`, which never match each other. Every dapp-kit mutation hook already calls it.
|
|
282
|
+
|
|
213
283
|
### Stellar prerequisites — use `useStellarGate`
|
|
214
284
|
|
|
215
285
|
Stellar has ordered prerequisites for a destination account, and they are invisible until they bite:
|
|
@@ -373,12 +443,16 @@ and origin gating are the real controls. Proxy through your own backend if that
|
|
|
373
443
|
| `useSwapsApiSubmitTxStatus` | 1s | requires `txHash` + `srcChainKey`; stops on `solved` / `failed` |
|
|
374
444
|
| `useSwapsApiStatus` | 1s | solver intent status; stops on status `3` / `4` |
|
|
375
445
|
| `useBackendOrderbook` | none | `staleTime: 30s` — fresh-window, no background refetch |
|
|
446
|
+
| `useBackendOracleMarkets` | none | `staleTime: 60s` |
|
|
447
|
+
| `useBackendOracleCandles` | none | `staleTime: 10s` — matches the ~10s server-side cache |
|
|
376
448
|
| `useExpiredUtxos` (bitcoin) | 60s | refetchInterval |
|
|
377
449
|
| `useQuote` (swap) | 3s | refetchInterval |
|
|
378
450
|
| `useStatus` (swap) | 3s | stops on status `3`/`4`, and after 40 consecutive NOT_FOUND fetches |
|
|
379
451
|
| `useSwapAllowance` (swap) | 2s | refetchInterval |
|
|
380
452
|
| `useMMAllowance` (mm) | 5s | refetchInterval; `enabled: false` for borrow/withdraw actions |
|
|
381
453
|
| Reserves data (mm) | 5s | `useReservesData` / `useReservesHumanized` / user position hooks |
|
|
454
|
+
| `useBalances` | 5s | refetchInterval |
|
|
455
|
+
| `useXBalances` | 5s | refetchInterval |
|
|
382
456
|
| Most others | None | |
|
|
383
457
|
|
|
384
458
|
All overridable via `queryOptions.refetchInterval`.
|
|
@@ -386,6 +460,6 @@ All overridable via `queryOptions.refetchInterval`.
|
|
|
386
460
|
## Cross-references
|
|
387
461
|
|
|
388
462
|
- [`../recipes/backend-queries.md`](../recipes/backend-queries.md) — worked examples for intent tracking, orderbook, MM data.
|
|
389
|
-
- [`../recipes/wallet-connectivity.md`](../recipes/wallet-connectivity.md) — `useXBalances` worked
|
|
463
|
+
- [`../recipes/wallet-connectivity.md`](../recipes/wallet-connectivity.md) — `useBalances` / `useXBalances` worked examples.
|
|
390
464
|
- [`features/auxiliary-services.md`](../../../migration-v1-to-v2/knowledge/features/auxiliary-services.md) — v1 → v2 porting.
|
|
391
465
|
- `sodax-sdk`: `integration/knowledge/features/auxiliary-services.md` — underlying SDK auxiliary surfaces (partner, recovery, backendApi).
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Leveraged-yield ERC-4626 vaults on the Sonic hub. Deposit any token → `lsoda*` vault shares, withdraw shares → any token; plus position / APR / TVL / share-balance reads. New in v2 (no v1 equivalent).
|
|
4
4
|
|
|
5
|
+
> **Backend-API variant:** the hooks below drive the on-chain `LeverageYieldService` (wallet → hub). To call the backend **Leverage Yield API v2** HTTP client (`sodax.api.leverageYield`) directly instead, use the `useLeverageYieldApi*` hooks — typed React Query wrappers over each endpoint (`useLeverageYieldApiVaults`, `useLeverageYieldApiEffectiveApr`, `useLeverageYieldApiDepositQuote` / `useLeverageYieldApiWithdrawQuote`, `useLeverageYieldApiAllowance` / `useLeverageYieldApiApprove`, `useLeverageYieldApiCreateDepositIntent` / `useLeverageYieldApiCreateWithdrawIntent`, `useLeverageYieldApiSubmitTx` / `useLeverageYieldApiSubmitTxStatus`, and the intent-lifecycle/vault-read hooks). Their `queryKey`/`mutationKey` namespace is `leverageYieldApi`. For the endpoint contract, load the `sodax-sdk` skill's leverage-yield-api feature doc.
|
|
6
|
+
|
|
5
7
|
## Hook surface
|
|
6
8
|
|
|
7
9
|
```ts
|
|
@@ -31,6 +31,13 @@ Read-only data hooks. No wallet connection required.
|
|
|
31
31
|
| `useBackendMoneyMarketAssetBorrowers` | Borrowers for an asset |
|
|
32
32
|
| `useBackendAllMoneyMarketBorrowers` | All borrowers |
|
|
33
33
|
|
|
34
|
+
### Oracle
|
|
35
|
+
|
|
36
|
+
| Hook | Purpose |
|
|
37
|
+
|------|---------|
|
|
38
|
+
| `useBackendOracleMarkets` | Oracle candle discovery: quote, intervals, symbols (cached 60s) |
|
|
39
|
+
| `useBackendOracleCandles` | USD OHLC candles for a symbol over `[from, to)` in UNIX seconds (cached 10s) |
|
|
40
|
+
|
|
34
41
|
### Swaps API (`sodax.api.swaps`)
|
|
35
42
|
|
|
36
43
|
| Hook | Purpose |
|
|
@@ -95,6 +102,41 @@ function Orderbook() {
|
|
|
95
102
|
}
|
|
96
103
|
```
|
|
97
104
|
|
|
105
|
+
## Oracle Candles
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
import { useState } from 'react';
|
|
109
|
+
import { useBackendOracleCandles, useBackendOracleMarkets } from '@sodax/dapp-kit';
|
|
110
|
+
|
|
111
|
+
function DailyEthCandles() {
|
|
112
|
+
const { data: markets, isLoading } = useBackendOracleMarkets();
|
|
113
|
+
// `from`/`to` are UNIX seconds over the half-open range [from, to), at most 5000 buckets.
|
|
114
|
+
// Hold the window end in state: deriving it from `Date.now()` during render changes the query
|
|
115
|
+
// key on every render that crosses a second boundary, so the query refetches from scratch.
|
|
116
|
+
const [to, setTo] = useState(() => Math.floor(Date.now() / 1000));
|
|
117
|
+
const { data } = useBackendOracleCandles({
|
|
118
|
+
params: { symbol: 'ETH', interval: '1d', from: to - 30 * 86400, to },
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
if (isLoading) return <div>Loading...</div>;
|
|
122
|
+
if (!markets?.symbols.includes('ETH')) return <div>No ETH candle data</div>;
|
|
123
|
+
return (
|
|
124
|
+
<>
|
|
125
|
+
<button type="button" onClick={() => setTo(Math.floor(Date.now() / 1000))}>
|
|
126
|
+
Refresh
|
|
127
|
+
</button>
|
|
128
|
+
<ul>
|
|
129
|
+
{data?.candles.map(candle => (
|
|
130
|
+
<li key={candle.timestamp}>
|
|
131
|
+
O {candle.open} H {candle.high} L {candle.low} C {candle.close}
|
|
132
|
+
</li>
|
|
133
|
+
))}
|
|
134
|
+
</ul>
|
|
135
|
+
</>
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
98
140
|
## Money Market Dashboard
|
|
99
141
|
|
|
100
142
|
```tsx
|
|
@@ -58,15 +58,17 @@ Each feature mutation hook invalidates the related read keys. Common patterns:
|
|
|
58
58
|
|
|
59
59
|
| Mutation | Invalidates |
|
|
60
60
|
|---|---|
|
|
61
|
-
| `useSwap` | `
|
|
62
|
-
| `useBridge` | Same as `useSwap` (
|
|
63
|
-
| `useSupply`, `useWithdraw`, `useBorrow`, `useRepay` | `['mm', 'userReservesData']`, `
|
|
64
|
-
| `useStake`, `useUnstake`, `useClaim`, `useCancelUnstake`, `useInstantUnstake` | `['staking', 'info']`, `['staking', 'unstakingInfo']`, `
|
|
65
|
-
| `useDexDeposit`, `useDexWithdraw` | `['dex', 'poolBalances']`, `
|
|
61
|
+
| `useSwap` | `invalidateBalances(queryClient, srcChainKey, dstChainKey)` |
|
|
62
|
+
| `useBridge` | Same as `useSwap` (balances on both chains). |
|
|
63
|
+
| `useSupply`, `useWithdraw`, `useBorrow`, `useRepay` | `['mm', 'userReservesData']`, `invalidateBalances(queryClient, srcChainKey)`, plus reserves data on the affected token. |
|
|
64
|
+
| `useStake`, `useUnstake`, `useClaim`, `useCancelUnstake`, `useInstantUnstake` | `['staking', 'info']`, `['staking', 'unstakingInfo']`, `invalidateBalances(queryClient, srcChainKey)`. |
|
|
65
|
+
| `useDexDeposit`, `useDexWithdraw` | `['dex', 'poolBalances']`, `invalidateBalances(queryClient, srcChainKey)`. |
|
|
66
66
|
| `useSupplyLiquidity`, `useDecreaseLiquidity`, `useClaimRewards` | `['dex', 'positionInfo', tokenId]`, `['dex', 'poolBalances']`. |
|
|
67
|
-
| `useMigrateIcxToSoda`, etc. | `
|
|
67
|
+
| `useMigrateIcxToSoda`, etc. | `invalidateBalances(queryClient, …)` for source + destination chains. |
|
|
68
68
|
| Approve hooks (`useSwapApprove`, etc.) | The corresponding allowance read (`['swap', 'allowance']`, etc.). |
|
|
69
69
|
|
|
70
|
+
`invalidateBalances(queryClient, ...chainKeys)` is exported from `@sodax/dapp-kit`; it invalidates BOTH `['shared','balances', chainKey]` (`useBalances`) and `['shared','xBalances', chainKey]` (`useXBalances`), skipping `undefined` and collapsing duplicates. React Query matches keys element-wise, so one never matches the other — hand-rolling a single key leaves the other hook stale. Use the helper in your own mutations too.
|
|
71
|
+
|
|
70
72
|
The exact keys are derived from `vars` at success time — so a successful supply on Base only invalidates Base-side reserves, not Arbitrum's.
|
|
71
73
|
|
|
72
74
|
## Adding cross-feature invalidations
|
|
@@ -250,7 +250,7 @@ console.log({ swap, isError, error, swapsInFlight });
|
|
|
250
250
|
|
|
251
251
|
### Balance display
|
|
252
252
|
|
|
253
|
-
|
|
253
|
+
Two options, both in dapp-kit: `useBalances` (SDK-backed, needs only a `SodaxProvider`) or `useXBalances` (wallet-layer, needs an `xService` from `@sodax/wallet-sdk-react`). See `wallet-connectivity.md`.
|
|
254
254
|
|
|
255
255
|
## Types
|
|
256
256
|
|
|
@@ -12,7 +12,8 @@ Connect wallets and pass wallet providers to feature hooks.
|
|
|
12
12
|
| `useHubProvider` | `@sodax/dapp-kit` | Utility | Access the hub chain (Sonic) provider |
|
|
13
13
|
| `useDeriveUserWalletAddress` | `@sodax/dapp-kit` | Query | Derive hub wallet address from spoke address (CREATE3) |
|
|
14
14
|
| `useGetUserHubWalletAddress` | `@sodax/dapp-kit` | Query | Derive hub wallet address via wallet router |
|
|
15
|
-
| `
|
|
15
|
+
| `useBalances` | `@sodax/dapp-kit` | Query | SDK-backed wallet token balances (no `xService`) |
|
|
16
|
+
| `useXBalances` | `@sodax/dapp-kit` | Query | Cross-chain token balances for an address (needs `xService`) |
|
|
16
17
|
| `useEstimateGas` | `@sodax/dapp-kit` | Mutation | Estimate gas for raw transactions |
|
|
17
18
|
| `useStellarTrustlineCheck` | `@sodax/dapp-kit` | Query | Check if Stellar account has sufficient trustline |
|
|
18
19
|
| `useEstablishTrustline` | `@sodax/dapp-kit` | Mutation | Request a Stellar trustline for a token |
|
|
@@ -80,6 +81,30 @@ function TokenBalance({ address, xTokens }: { address: string; xTokens: readonly
|
|
|
80
81
|
}
|
|
81
82
|
```
|
|
82
83
|
|
|
84
|
+
### SDK-backed alternative: `useBalances`
|
|
85
|
+
|
|
86
|
+
`useBalances` reads wallet balances straight from the core SDK (`sodax.spoke.getWalletBalances`) via the `SodaxProvider` context, so it drops the `xService` requirement — no `@sodax/wallet-sdk-react` hook needed. Prefer it when the app already has a `SodaxProvider`; the params collapse to `chainKey`, the `tokens` list, and the `address`.
|
|
87
|
+
|
|
88
|
+
The two hooks are not drop-in equivalents — check these before migrating a screen:
|
|
89
|
+
|
|
90
|
+
- `chainKey` decides the chain read; `token.chainKey` is ignored, so a token from another chain reads as `0n` rather than erroring. `useXBalances` is the opposite: it derives the chain from `xTokens[0].chainKey` and ignores the `xChainId` you pass.
|
|
91
|
+
- A token that could not be read is logged by the SDK and reported as `0n`, so it is indistinguishable from an empty wallet. The query errors only when the entire batch is unusable.
|
|
92
|
+
- Stellar XLM is the *spendable* amount (total minus minimum reserve and selling liabilities); Bitcoin Rune tokens read as `0n` because the UTXO endpoint carries no rune amounts.
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
import { useBalances } from '@sodax/dapp-kit';
|
|
97
|
+
import { ChainKeys, type XToken } from '@sodax/sdk';
|
|
98
|
+
|
|
99
|
+
function TokenBalanceViaSdk({ address, tokens }: { address: string; tokens: readonly XToken[] }) {
|
|
100
|
+
const chainKey = ChainKeys.BSC_MAINNET;
|
|
101
|
+
// No `xService` — the hook reads the SDK instance from the SodaxProvider context.
|
|
102
|
+
const { data: balances } = useBalances({ params: { chainKey, address, tokens } });
|
|
103
|
+
|
|
104
|
+
// balances is a map of token address → balance (bigint), refetched every 5s
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
83
108
|
## Use Wallet Provider in Feature Hooks
|
|
84
109
|
|
|
85
110
|
All mutation hooks accept no arguments at initialization level. The `walletProvider` flows through `mutate(vars)`:
|
|
@@ -165,6 +165,13 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
|
|
|
165
165
|
| `useBackendMoneyMarketAssetBorrowers` | Borrowers for an asset |
|
|
166
166
|
| `useBackendAllMoneyMarketBorrowers` | All borrowers |
|
|
167
167
|
|
|
168
|
+
### Oracle data
|
|
169
|
+
|
|
170
|
+
| Hook | Purpose |
|
|
171
|
+
|---|---|
|
|
172
|
+
| `useBackendOracleMarkets` | Candle discovery: quote, intervals, symbols (`staleTime: 60s`) |
|
|
173
|
+
| `useBackendOracleCandles` | USD OHLC candles for a symbol over `[from, to)` (`staleTime: 10s`) |
|
|
174
|
+
|
|
168
175
|
## Swaps API (`sodax.api.swaps`)
|
|
169
176
|
|
|
170
177
|
Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`), one per endpoint. Distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive `sodax.swaps` (the `SwapService`).
|
|
@@ -224,6 +231,47 @@ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`)
|
|
|
224
231
|
| `useBridgeApiCreateBridgeIntent` | Mutation; builds `{ tx, relayData }` (no intent) |
|
|
225
232
|
| `useBridgeApiSubmitTx` | Mutation; `request: BridgeSubmitTxRequestV2` (FULL relayData envelope) |
|
|
226
233
|
|
|
234
|
+
## Leverage Yield API (`sodax.api.leverageYield`)
|
|
235
|
+
|
|
236
|
+
Typed React Query wrappers over the backend Leverage Yield API v2 (`sodax.api.leverageYield.*`), one per endpoint. Distinct from the on-chain `leverageYield/` hooks (`useLeverageYieldDeposit`/`useLeverageYieldWithdraw`/…), which drive `sodax.leverageYield` (the `LeverageYieldService`). A vault deposit/withdraw IS an intent-based swap, so the intent / gas / fee / submit-tx hooks mirror the swaps family; the vault registry, vault reads and the split deposit/withdraw quote + create-intent hooks are leverage-yield's own.
|
|
237
|
+
|
|
238
|
+
| Hook | Type / Polling |
|
|
239
|
+
|---|---|
|
|
240
|
+
| `useLeverageYieldApiVaults` | Query; the deployed-vault registry |
|
|
241
|
+
| `useLeverageYieldApiVault` | Query; one vault descriptor by lsoda* `name` |
|
|
242
|
+
| `useLeverageYieldApiAsset` | Query; the vault's underlying hub asset |
|
|
243
|
+
| `useLeverageYieldApiPosition` | Query; `{ collateral, debt, ltv, healthFactor, idleAsset }` |
|
|
244
|
+
| `useLeverageYieldApiApr` | Query; AAVE-only steady-state APR (RAY strings; can be negative) |
|
|
245
|
+
| `useLeverageYieldApiEffectiveApr` | Query; combined AAVE + LSD APR — `effectiveNetAprRay` is the headline |
|
|
246
|
+
| `useLeverageYieldApiLsdApr` | Query; off-chain LSD staking-APR snapshot |
|
|
247
|
+
| `useLeverageYieldApiTotalAssets` | Query; total assets under management |
|
|
248
|
+
| `useLeverageYieldApiPreviewDeposit` | Query; ERC-4626 `previewDeposit` — shares for `assets` |
|
|
249
|
+
| `useLeverageYieldApiPreviewWithdraw` | Query; ERC-4626 `previewWithdraw` — shares burned for `assets` |
|
|
250
|
+
| `useLeverageYieldApiPreviewRedeem` | Query; ERC-4626 `previewRedeem` — assets for `shares` |
|
|
251
|
+
| `useLeverageYieldApiShareBalance` | Query; an owner's lsoda* balance (the HUB wallet, not the EOA) |
|
|
252
|
+
| `useLeverageYieldApiMaxWithdraw` | Query; RAW ERC-4626 `maxWithdraw` — NOT dust-trimmed, apply a margin for a MAX withdraw |
|
|
253
|
+
| `useLeverageYieldApiDepositQuote` | Query; any token → lsoda* (set `query.includeTxData` for `txData`) |
|
|
254
|
+
| `useLeverageYieldApiWithdrawQuote` | Query; lsoda* → any token |
|
|
255
|
+
| `useLeverageYieldApiDeadline` | Query; computed vault-swap deadline |
|
|
256
|
+
| `useLeverageYieldApiAllowance` | Query; `{ valid }` — the DEPOSIT body only (withdraw needs no spoke allowance) |
|
|
257
|
+
| `useLeverageYieldApiStatus` | Query (1s); polls until status `3` (SOLVED) / `4` (FAILED) |
|
|
258
|
+
| `useLeverageYieldApiIntentHash` | Query; keccak256 of an intent struct |
|
|
259
|
+
| `useLeverageYieldApiIntentPacket` | Query; long-polls the relayer for the fill packet (no client interval) |
|
|
260
|
+
| `useLeverageYieldApiIntentExtraData` | Query; relay extra-data for submit |
|
|
261
|
+
| `useLeverageYieldApiFilledIntent` | Query; on-chain fill state by tx hash |
|
|
262
|
+
| `useLeverageYieldApiIntent` | Query; decoded intent struct by tx hash |
|
|
263
|
+
| `useLeverageYieldApiEstimateGas` | Query; gas estimate for a raw tx |
|
|
264
|
+
| `useLeverageYieldApiPartnerFee` | Query; partner fee for an amount |
|
|
265
|
+
| `useLeverageYieldApiSolverFee` | Query; protocol (solver) fee for an amount |
|
|
266
|
+
| `useLeverageYieldApiSubmitTxStatus` | Query (1s); requires `txHash` + `srcChainKey`; polls until `solved` / `failed` / `abandonedAt` |
|
|
267
|
+
| `useLeverageYieldApiApprove` | Mutation; builds unsigned approval tx(s) — `{ tx, resetTx? }`, ordering is yours to handle |
|
|
268
|
+
| `useLeverageYieldApiApproveAndBroadcast` | Mutation; builds **and** signs/broadcasts/waits — preferred; `{ approveTxHash, resetTxHash? }`; optional `onProgress` per step |
|
|
269
|
+
| `useLeverageYieldApiCreateDepositIntent` | Mutation; builds `{ tx, intent, relayData }` (any token → lsoda*) |
|
|
270
|
+
| `useLeverageYieldApiCreateWithdrawIntent` | Mutation; builds `{ tx, intent, relayData }` (lsoda* → any token) |
|
|
271
|
+
| `useLeverageYieldApiSubmitIntent` | Mutation; submits broadcast intent to the relay |
|
|
272
|
+
| `useLeverageYieldApiCancelIntent` | Mutation; builds unsigned cancel tx |
|
|
273
|
+
| `useLeverageYieldApiSubmitTx` | Mutation; `request: LeverageYieldSubmitTxRequestV2` — the swaps body PLUS a required `operation: 'deposit' \| 'withdraw'` |
|
|
274
|
+
|
|
227
275
|
## Partner
|
|
228
276
|
|
|
229
277
|
| Hook | Type | Purpose |
|
|
@@ -250,6 +298,7 @@ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`)
|
|
|
250
298
|
|
|
251
299
|
| Hook | Type | Purpose |
|
|
252
300
|
|---|---|---|
|
|
301
|
+
| `useBalances` | Query | SDK-backed wallet token balances (no xService) |
|
|
253
302
|
| `useXBalances` | Query | Cross-chain token balances |
|
|
254
303
|
| `useDeriveUserWalletAddress` | Query | Derive hub wallet (CREATE3) |
|
|
255
304
|
| `useGetUserHubWalletAddress` | Query | Derive hub wallet (wallet router) |
|
|
@@ -77,7 +77,8 @@ queryKey: ['staking', 'allowance', srcChainKey, action, srcAddress, amount.toStr
|
|
|
77
77
|
// User position reads
|
|
78
78
|
queryKey: ['mm', 'userReservesData', spokeChainKey, userAddress]
|
|
79
79
|
queryKey: ['staking', 'info', srcChainKey, srcAddress] // useStakingInfo — second segment is 'info', not 'stakingInfo'
|
|
80
|
-
queryKey: ['shared', '
|
|
80
|
+
queryKey: ['shared', 'balances', chainKey, tokens, address] // useBalances (SDK-backed)
|
|
81
|
+
queryKey: ['shared', 'xBalances', xChainId, tokens, address] // useXBalances (wallet-layer)
|
|
81
82
|
queryKey: ['shared', 'nearStorageCheck', chainId, token, accountId] // useNearStorageCheck
|
|
82
83
|
|
|
83
84
|
// Mutation default keys
|
|
@@ -201,6 +202,47 @@ Typed wrappers over `sodax.api.bridge.*` (one per Bridge API v2 endpoint), all k
|
|
|
201
202
|
| `['bridgeApi', 'createBridgeIntent']` | `useBridgeApiCreateBridgeIntent` mutation |
|
|
202
203
|
| `['bridgeApi', 'submitTx']` | `useBridgeApiSubmitTx` mutation |
|
|
203
204
|
|
|
205
|
+
### Leverage Yield API (`sodax.api.leverageYield`)
|
|
206
|
+
|
|
207
|
+
Typed wrappers over `sodax.api.leverageYield.*` (one per Leverage Yield API v2 endpoint), all keyed `['leverageYieldApi', action, ...]`.
|
|
208
|
+
|
|
209
|
+
| Key | Hook |
|
|
210
|
+
|---|---|
|
|
211
|
+
| `['leverageYieldApi', 'vaults']` | `useLeverageYieldApiVaults` |
|
|
212
|
+
| `['leverageYieldApi', 'vault', name]` | `useLeverageYieldApiVault` |
|
|
213
|
+
| `['leverageYieldApi', 'asset', vault]` | `useLeverageYieldApiAsset` |
|
|
214
|
+
| `['leverageYieldApi', 'position', vault]` | `useLeverageYieldApiPosition` |
|
|
215
|
+
| `['leverageYieldApi', 'apr', vault]` | `useLeverageYieldApiApr` |
|
|
216
|
+
| `['leverageYieldApi', 'effectiveApr', vault]` | `useLeverageYieldApiEffectiveApr` |
|
|
217
|
+
| `['leverageYieldApi', 'lsdApr', vault]` | `useLeverageYieldApiLsdApr` |
|
|
218
|
+
| `['leverageYieldApi', 'totalAssets', vault]` | `useLeverageYieldApiTotalAssets` |
|
|
219
|
+
| `['leverageYieldApi', 'previewDeposit', vault, assets]` | `useLeverageYieldApiPreviewDeposit` |
|
|
220
|
+
| `['leverageYieldApi', 'previewWithdraw', vault, assets]` | `useLeverageYieldApiPreviewWithdraw` |
|
|
221
|
+
| `['leverageYieldApi', 'previewRedeem', vault, shares]` | `useLeverageYieldApiPreviewRedeem` |
|
|
222
|
+
| `['leverageYieldApi', 'shareBalance', vault, owner]` | `useLeverageYieldApiShareBalance` |
|
|
223
|
+
| `['leverageYieldApi', 'maxWithdraw', vault, owner]` | `useLeverageYieldApiMaxWithdraw` |
|
|
224
|
+
| `['leverageYieldApi', 'depositQuote', …]` | `useLeverageYieldApiDepositQuote` |
|
|
225
|
+
| `['leverageYieldApi', 'withdrawQuote', …]` | `useLeverageYieldApiWithdrawQuote` |
|
|
226
|
+
| `['leverageYieldApi', 'deadline', …]` | `useLeverageYieldApiDeadline` |
|
|
227
|
+
| `['leverageYieldApi', 'allowance', …]` | `useLeverageYieldApiAllowance` |
|
|
228
|
+
| `['leverageYieldApi', 'status', intentTxHash]` | `useLeverageYieldApiStatus` |
|
|
229
|
+
| `['leverageYieldApi', 'intentHash', …]` | `useLeverageYieldApiIntentHash` |
|
|
230
|
+
| `['leverageYieldApi', 'intentPacket', …]` | `useLeverageYieldApiIntentPacket` |
|
|
231
|
+
| `['leverageYieldApi', 'intentExtraData', …]` | `useLeverageYieldApiIntentExtraData` |
|
|
232
|
+
| `['leverageYieldApi', 'filledIntent', txHash]` | `useLeverageYieldApiFilledIntent` |
|
|
233
|
+
| `['leverageYieldApi', 'intent', txHash]` | `useLeverageYieldApiIntent` |
|
|
234
|
+
| `['leverageYieldApi', 'estimateGas', …]` | `useLeverageYieldApiEstimateGas` |
|
|
235
|
+
| `['leverageYieldApi', 'partnerFee', amount]` | `useLeverageYieldApiPartnerFee` |
|
|
236
|
+
| `['leverageYieldApi', 'solverFee', amount]` | `useLeverageYieldApiSolverFee` |
|
|
237
|
+
| `['leverageYieldApi', 'submitTx', 'status', txHash, srcChainKey]` | `useLeverageYieldApiSubmitTxStatus` — both identifiers required |
|
|
238
|
+
| `['leverageYieldApi', 'approve']` | `useLeverageYieldApiApprove` mutation |
|
|
239
|
+
| `['leverageYieldApi', 'approveAndBroadcast']` | `useLeverageYieldApiApproveAndBroadcast` mutation |
|
|
240
|
+
| `['leverageYieldApi', 'createDepositIntent']` | `useLeverageYieldApiCreateDepositIntent` mutation |
|
|
241
|
+
| `['leverageYieldApi', 'createWithdrawIntent']` | `useLeverageYieldApiCreateWithdrawIntent` mutation |
|
|
242
|
+
| `['leverageYieldApi', 'submitIntent']` | `useLeverageYieldApiSubmitIntent` mutation |
|
|
243
|
+
| `['leverageYieldApi', 'cancelIntent']` | `useLeverageYieldApiCancelIntent` mutation |
|
|
244
|
+
| `['leverageYieldApi', 'submitTx']` | `useLeverageYieldApiSubmitTx` mutation |
|
|
245
|
+
|
|
204
246
|
### Leverage Yield
|
|
205
247
|
|
|
206
248
|
| Key | Hook |
|
|
@@ -36,6 +36,7 @@ If the user has already picked a single feature, load the matching granular skil
|
|
|
36
36
|
| Sponsored Stellar account activation | [`./sponsoring/SKILL.md`](./sponsoring/SKILL.md) | "activate a Stellar account", "user has no XLM", "sponsor base reserve", "sodax.sponsoring" |
|
|
37
37
|
| Backend HTTP client (intents, orderbook, MM reads) | [`./backend-api/SKILL.md`](./backend-api/SKILL.md) | "getIntentByHash", "Sodax backend API", "orderbook", "custom IConfigApiV1" |
|
|
38
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
|
+
| Leverage Yield API v2 client (vault reads, APR, deposit/withdraw quote + intents) | [`./leverage-yield-api/SKILL.md`](./leverage-yield-api/SKILL.md) | "sodax.api.leverageYield", "vault APR from backend", "vault position from API", "leverage-yield API v2" |
|
|
39
40
|
| 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" |
|
|
40
41
|
|
|
41
42
|
Load this broad skill (keep reading below) when:
|
|
@@ -78,7 +79,7 @@ Follow in order. Skipping `ai-rules.md` is the most common cause of agents rever
|
|
|
78
79
|
|
|
79
80
|
1. Read [`integration/knowledge/ai-rules.md`](./integration/knowledge/ai-rules.md) — DO / DO NOT / workflow / stop conditions.
|
|
80
81
|
2. Read [`integration/knowledge/quickstart.md`](./integration/knowledge/quickstart.md) — install, initialize, first-run troubleshooting.
|
|
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`.
|
|
82
|
+
3. For your feature, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `leverage-yield.md`, `migration.md`, `partner.md`, `recovery.md`, `sponsoring.md`, `backend-api.md`, `swaps-api.md`, `bridge-api.md`, `leverage-yield-api.md`.
|
|
82
83
|
4. For specific patterns (init, raw vs signed, chain narrowing, gas, testing, errors, logging), read [`integration/knowledge/recipes/`](./integration/knowledge/recipes/).
|
|
83
84
|
5. Lookups (chain keys, error codes, public API surface, wallet provider types, glossary) → [`integration/knowledge/reference/`](./integration/knowledge/reference/).
|
|
84
85
|
6. Non-EVM quirks (Stellar trustline, BTC PSBT, Solana PDA, ICON, NEAR) → [`integration/knowledge/chain-specifics.md`](./integration/knowledge/chain-specifics.md).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk-backend-api
|
|
3
|
-
description: 'Granular skill for the @sodax/sdk v2 BackendApiService — HTTP client to the SODAX backend for intent lookup, swap-tx submission, solver orderbook, money-market position/reserve reads, and (internally) config fetching. Use when the task touches a backend read or write (e.g. "submit swap tx to Sodax backend", "Sodax getIntentByHash", "fetch money market position from Sodax backend", "Sodax orderbook", "Sodax BackendApiService", "implement custom IConfigApiV1 sandbox"). Covers BOTH integration and the load-bearing v1 → v2 Result-wrapping migration. Skill links into the parent sodax-sdk knowledge tree.'
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 BackendApiService — HTTP client to the SODAX backend for intent lookup, swap-tx submission, solver orderbook, money-market position/reserve reads, USD OHLC price candles for charts, and (internally) config fetching. Use when the task touches a backend read or write (e.g. "submit swap tx to Sodax backend", "Sodax getIntentByHash", "fetch money market position from Sodax backend", "Sodax orderbook", "Sodax price candles", "Sodax OHLC chart data", "Sodax oracle markets", "Sodax BackendApiService", "implement custom IConfigApiV1 sandbox"). Covers BOTH integration and the load-bearing v1 → v2 Result-wrapping migration. Skill links into the parent sodax-sdk knowledge tree.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -17,6 +17,7 @@ Granular skill for `BackendApiService` — `sodax.backendApi`. HTTP client used
|
|
|
17
17
|
2. **Which category?**
|
|
18
18
|
- **Swap-related reads:** `getOrderbook`, `getIntentByHash`, `getIntentByTxHash`, `getUserIntents`. (Swap-tx submission — `sodax.api.swaps.submitTx` / `getSubmitTxStatus` — is on the swaps API client.)
|
|
19
19
|
- **Money-market position reads:** `getMoneyMarketPosition`, `getAllMoneyMarketAssets`, `getMoneyMarketAsset`, `getMoneyMarketAssetBorrowers`, `getMoneyMarketAssetSuppliers`, `getAllMoneyMarketBorrowers`.
|
|
20
|
+
- **Oracle price reads:** `getOracleMarkets` (quote + intervals + symbols), `getOracleCandles` (USD OHLC buckets for charting). The solver's live mark prices — `GET /v1/intent/oracle` — are a different service and have no SDK wrapper.
|
|
20
21
|
- **`IConfigApiV1` interface methods (exactly 5):** `getChains`, `getSwapTokens`, `getSwapTokensByChainId`, `getMoneyMarketTokens`, `getMoneyMarketTokensByChainId`.
|
|
21
22
|
- **Other `BackendApiService` config reads (NOT part of `IConfigApiV1`):** `getAllConfig`, `getMoneyMarketReserveAssets`, `getRelayChainIdMap`.
|
|
22
23
|
3. **Custom `IConfigApiV1` for sandbox / fixtures?** Every method must return `Promise<Result<T>>` in v2.
|
|
@@ -149,7 +149,7 @@ const solanaSpoke = sodax.spoke.getSpokeService(ChainKeys.SOLANA_MAINNET) as Sol
|
|
|
149
149
|
|
|
150
150
|
### Pitfall
|
|
151
151
|
|
|
152
|
-
Solana addresses are base58 PublicKey strings, not `0x…` hex. `GetAddressType<typeof ChainKeys.SOLANA_MAINNET>` resolves to a
|
|
152
|
+
Solana addresses are base58 PublicKey strings, not `0x…` hex. `GetAddressType<typeof ChainKeys.SOLANA_MAINNET>` resolves to `SolanaBase58PublicKey`, which is a plain `string` alias — not a brand — so a hex address compiles and then throws inside `new PublicKey(...)` when the spoke service reads the balance or builds the deposit. Pass the base58 address.
|
|
153
153
|
|
|
154
154
|
---
|
|
155
155
|
|
|
@@ -240,7 +240,7 @@ Deposits **from** NEAR (`deposit()` / `fillIntent()` on the NEAR spoke service)
|
|
|
240
240
|
| Chain | Notes |
|
|
241
241
|
|---|---|
|
|
242
242
|
| **Sui** (`SUI_MAINNET`) | Address: 32-byte `0x…` (different from EVM addresses despite the prefix). Wallet provider `ISuiWalletProvider` uses `@mysten/sui` under the hood. Reads and submission go over gRPC-web (`grpc_url`, default `https://fullnode.mainnet.sui.io`; `rpc_url` remains a deprecated alias that wins when set) — Mysten's public fullnodes stopped serving JSON-RPC in July 2026, and `sui-node` drops it in October 2026. |
|
|
243
|
-
| **Stacks** (`STACKS_MAINNET`) | Address: `SP…` (mainnet) / `ST…` (testnet). Uses `@stacks/transactions` for tx construction. |
|
|
243
|
+
| **Stacks** (`STACKS_MAINNET`) | Address: `SP…` (mainnet) / `ST…` (testnet). Uses `@stacks/transactions` for tx construction. Wallet-signed deposits use post-condition mode `Deny` with exact spend caps (uSTX for native; one cap per fungible token the SIP-10 contract defines), so wallets display the exact spend and anything beyond it aborts on-chain. FT deposits resolve the on-chain asset names via the node's contract-interface endpoint and fail before signing if that lookup fails; `raw: true` skips the lookup — the serialized payload cannot carry post-conditions. |
|
|
244
244
|
| **Injective** (`INJECTIVE_MAINNET`) | Cosmos-ecosystem chain. Address: `inj1…`. Wallet provider uses `@injectivelabs/sdk-ts`. |
|
|
245
245
|
|
|
246
246
|
Each has its own `I*WalletProvider` interface with chain-specific signing methods. The `chainType` discriminant on every `I*WalletProvider` instance lets you narrow at runtime without `instanceof`.
|
|
@@ -17,9 +17,10 @@ One file per feature service. Each file documents the v2 API surface, common cal
|
|
|
17
17
|
| [`sponsoring.md`](sponsoring.md) | `SponsoringService` | Stellar account activation via sponsored reserves. The sponsor pays the base reserve; the user's wallet signs. |
|
|
18
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
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. |
|
|
20
|
+
| [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API v2 (`sodax.api.leverageYield`, `/leverage-yield/*`). Vault registry + reads, deposit/withdraw quote + intents, submit-tx + status, fees. |
|
|
20
21
|
|
|
21
22
|
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.
|
|
22
23
|
|
|
23
24
|
## Cross-references to migration
|
|
24
25
|
|
|
25
|
-
For the v1 → v2 port playbook on each feature, see the matching file in [`features/`](../../../migration-v1-to-v2/knowledge/features/) — same filename, different angle. **Exception:** features introduced in v2 with no v1 equivalent (`leverage-yield.md`) have no migration sibling — there is nothing to port.
|
|
26
|
+
For the v1 → v2 port playbook on each feature, see the matching file in [`features/`](../../../migration-v1-to-v2/knowledge/features/) — same filename, different angle. **Exception:** features introduced in v2 with no v1 equivalent (`leverage-yield.md`, `leverage-yield-api.md`, `swaps-api.md`) have no migration sibling — there is nothing to port.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Backend API — `BackendApiService`
|
|
2
2
|
|
|
3
|
-
HTTP client for backend services. Provides intent lookup, solver orderbook queries, money-market position/reserve reads, and (internally) config fetching. Most consumer-side code uses just `getIntentByHash` / `getIntentByTxHash` and the money-market read methods. Swap-tx submission lives on the sibling swaps API client — `sodax.api.swaps.submitTx` (see below).
|
|
3
|
+
HTTP client for backend services. Provides intent lookup, solver orderbook queries, money-market position/reserve reads, USD OHLC price candles, and (internally) config fetching. Most consumer-side code uses just `getIntentByHash` / `getIntentByTxHash` and the money-market read methods. Swap-tx submission lives on the sibling swaps API client — `sodax.api.swaps.submitTx` (see below).
|
|
4
4
|
|
|
5
5
|
Access: `sodax.backendApi`. Service class: `BackendApiService`. **Feature tag for errors:** every method emits `feature: 'backend'` with `error.context.api: 'backend'` (the HTTP-client layer — the domain feature tags like `'moneyMarket'` belong to the on-chain services, not these backend reads).
|
|
6
6
|
|
|
@@ -26,6 +26,10 @@ sodax.backendApi.getMoneyMarketAssetBorrowers(...): Promise<Result<...>>;
|
|
|
26
26
|
sodax.backendApi.getMoneyMarketAssetSuppliers(...): Promise<Result<...>>;
|
|
27
27
|
sodax.backendApi.getAllMoneyMarketBorrowers(...): Promise<Result<...>>;
|
|
28
28
|
|
|
29
|
+
// Oracle price reads (USD OHLC candles for charts)
|
|
30
|
+
sodax.backendApi.getOracleMarkets(config?): Promise<Result<OracleMarketsResponse>>; // { quote, intervals, symbols }
|
|
31
|
+
sodax.backendApi.getOracleCandles(params, config?): Promise<Result<OracleCandlesResponse>>; // params: { symbol, interval: '1m'|'5m'|'1h'|'1d', from, to } — UNIX SECONDS, half-open [from, to), max 5000 buckets
|
|
32
|
+
|
|
29
33
|
// Config-API methods (used internally by ConfigService — implements `IConfigApiV1`)
|
|
30
34
|
sodax.backendApi.getAllConfig(config?): Promise<Result<GetAllConfigApiResponse>>;
|
|
31
35
|
sodax.backendApi.getChains(config?): Promise<Result<GetChainsApiResponse>>;
|
|
@@ -37,6 +41,10 @@ sodax.backendApi.getMoneyMarketTokensByChainId(...): Promise<Result<XToken[]>>;
|
|
|
37
41
|
sodax.backendApi.getRelayChainIdMap(config?): Promise<Result<GetRelayChainIdMapApiResponse>>;
|
|
38
42
|
```
|
|
39
43
|
|
|
44
|
+
Oracle typing: `getOracleMarkets().intervals[].key` is `string`, not the `OracleCandleInterval` union — discovery stays tolerant of an interval a newer backend serves, so narrow it with the exported `isOracleCandleInterval(key)` guard (or membership-test `ORACLE_CANDLE_INTERVALS`) before passing it to `getOracleCandles`. The candles response `interval` echoes what you sent and IS strictly validated.
|
|
45
|
+
|
|
46
|
+
Oracle candles: `open`/`high`/`low`/`close` are USD **decimal strings** (convert them yourself) and `timestamp` is the bucket START in UNIX seconds. `final` marks the still-forming current bucket: branch on `final === false` (re-poll while that holds), never on the field's presence — the backend omits it on closed candles today, but the type is `boolean`. A valid range with no stored candles resolves `ok: true` with `candles: []`; an unknown symbol currently produces the same successful empty result rather than a 404. A zero-width/reversed range, another invalid parameter, or a range over 5000 buckets is a 400, surfacing as `HTTP_REQUEST_FAILED` with `error.context.status === 400`. The solver's live mark prices (`GET /v1/intent/oracle`) are a separate service with no SDK wrapper.
|
|
47
|
+
|
|
40
48
|
All methods return `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` where the error carries `feature: 'backend'`, `error.context.api === 'backend'`, and `context.endpoint`.
|
|
41
49
|
|
|
42
50
|
Every data / token / money-market response is validated at runtime against a valibot schema (like `sodax.api.swaps`): a 2xx body that fails the contract resolves to `EXTERNAL_API_ERROR` with `context.reason: 'invalid_response_shape'` rather than a mistyped value. The config/relay reads — `getAllConfig`, `getSpokeChainConfig`, `getRelayChainIdMap` — are **not** schema-validated (the `SodaxConfig` shape is too large to mirror faithfully, and `ConfigService` already version-gates and falls back to packaged defaults, so it relies on no response-shape guarantee).
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
# Leverage Yield API — `LeverageYieldApiService`
|
|
2
|
+
|
|
3
|
+
Typed HTTP client for the backend **Leverage Yield API v2** (`/leverage-yield/*`). Reachable as
|
|
4
|
+
`sodax.api.leverageYield` (`sodax.api` is an alias for `sodax.backendApi`; `.leverageYield` is the
|
|
5
|
+
`LeverageYieldApiService` instance). One method per endpoint (33 total). Every method returns
|
|
6
|
+
`Promise<Result<T>>` — it **never throws** — and every response is validated at runtime against a valibot
|
|
7
|
+
schema, so a backend contract drift surfaces as `{ ok: false }` rather than an untyped object.
|
|
8
|
+
|
|
9
|
+
Access: `sodax.api.leverageYield`. Service class: `LeverageYieldApiService`. **Errors:** every failure
|
|
10
|
+
(network, timeout, non-2xx HTTP, or response-shape mismatch) returns
|
|
11
|
+
`Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with `feature: 'backend'`, `context.api: 'leverageYield'`,
|
|
12
|
+
and `context.endpoint` (the path). The underlying failure is preserved on `error.cause`. This differs from
|
|
13
|
+
the feature service (`sodax.leverageYield`), whose errors carry `feature: 'leverageYield'` — the
|
|
14
|
+
leverage-yield **HTTP client** is uniformly `feature: 'backend'`, exactly like `sodax.api.swaps`.
|
|
15
|
+
|
|
16
|
+
A leverage-yield deposit/withdraw **is** an intent-based swap (the vault's `lsoda*` share token is a
|
|
17
|
+
solver-tradeable token), so the intent-relay / gas / fee / submit-tx endpoints share the same wire shapes
|
|
18
|
+
as the Swaps API — this client is the leverage-yield sibling of [`swaps-api.md`](swaps-api.md).
|
|
19
|
+
|
|
20
|
+
## Methods
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
// Vault registry
|
|
24
|
+
sodax.api.leverageYield.getVaults(config?): Promise<Result<GetLeverageVaultsResponseV2>>;
|
|
25
|
+
sodax.api.leverageYield.getVault(name, config?): Promise<Result<GetLeverageVaultResponseV2>>;
|
|
26
|
+
|
|
27
|
+
// Vault reads — all take a { vault } query (some also { owner } / { assets } / { shares })
|
|
28
|
+
sodax.api.leverageYield.getAsset(query: VaultQueryV2, config?): Promise<Result<VaultAssetResponseV2>>;
|
|
29
|
+
sodax.api.leverageYield.getPosition(query: VaultQueryV2, config?): Promise<Result<LeverageYieldPositionV2>>;
|
|
30
|
+
sodax.api.leverageYield.getApr(query: VaultQueryV2, config?): Promise<Result<LeverageYieldAprV2>>;
|
|
31
|
+
sodax.api.leverageYield.getEffectiveApr(query: VaultQueryV2, config?): Promise<Result<LeverageYieldEffectiveAprV2>>;
|
|
32
|
+
sodax.api.leverageYield.getLsdApr(query: VaultQueryV2, config?): Promise<Result<LeverageYieldLsdAprV2>>;
|
|
33
|
+
sodax.api.leverageYield.getTotalAssets(query: VaultQueryV2, config?): Promise<Result<VaultTotalAssetsResponseV2>>;
|
|
34
|
+
sodax.api.leverageYield.previewDeposit(query: VaultAssetsQueryV2, config?): Promise<Result<PreviewDepositResponseV2>>;
|
|
35
|
+
sodax.api.leverageYield.previewWithdraw(query: VaultAssetsQueryV2, config?): Promise<Result<PreviewWithdrawResponseV2>>;
|
|
36
|
+
sodax.api.leverageYield.previewRedeem(query: VaultSharesQueryV2, config?): Promise<Result<PreviewRedeemResponseV2>>;
|
|
37
|
+
sodax.api.leverageYield.getShareBalance(query: VaultOwnerQueryV2, config?): Promise<Result<ShareBalanceResponseV2>>;
|
|
38
|
+
sodax.api.leverageYield.getMaxWithdraw(query: VaultOwnerQueryV2, config?): Promise<Result<MaxWithdrawResponseV2>>;
|
|
39
|
+
|
|
40
|
+
// Quote (separate deposit / withdraw) · deadline
|
|
41
|
+
sodax.api.leverageYield.getDepositQuote(body: LeverageYieldDepositQuoteRequestV2, query?: QuoteQueryV2, config?): Promise<Result<QuoteResponseV2>>;
|
|
42
|
+
sodax.api.leverageYield.getWithdrawQuote(body: LeverageYieldWithdrawQuoteRequestV2, query?: QuoteQueryV2, config?): Promise<Result<QuoteResponseV2>>;
|
|
43
|
+
sodax.api.leverageYield.getDeadline(query?: DeadlineQueryV2, config?): Promise<Result<DeadlineResponseV2>>;
|
|
44
|
+
|
|
45
|
+
// Deposit allowance · approve — both share the CreateDepositIntentParamsV2 body (withdraw needs no spoke allowance)
|
|
46
|
+
sodax.api.leverageYield.checkAllowance(body: CreateDepositIntentParamsV2, config?): Promise<Result<AllowanceCheckResponseV2>>;
|
|
47
|
+
sodax.api.leverageYield.approve(body: CreateDepositIntentParamsV2, config?): Promise<Result<ApproveResponseV2>>;
|
|
48
|
+
|
|
49
|
+
// Create intent (separate deposit / withdraw)
|
|
50
|
+
sodax.api.leverageYield.createDepositIntent(body: CreateDepositIntentParamsV2, config?): Promise<Result<CreateIntentResponseV2>>;
|
|
51
|
+
sodax.api.leverageYield.createWithdrawIntent(body: CreateWithdrawIntentParamsV2, config?): Promise<Result<CreateIntentResponseV2>>;
|
|
52
|
+
|
|
53
|
+
// Intent lifecycle: submit · status · cancel · hash · packet · extra-data · fill · get
|
|
54
|
+
sodax.api.leverageYield.submitIntent(body: SubmitIntentRequestV2, config?): Promise<Result<SubmitIntentResponseV2>>;
|
|
55
|
+
sodax.api.leverageYield.getStatus(body: StatusRequestV2, config?): Promise<Result<StatusResponseV2>>;
|
|
56
|
+
sodax.api.leverageYield.cancelIntent(body: CancelIntentRequestV2, config?): Promise<Result<CancelIntentResponseV2>>;
|
|
57
|
+
sodax.api.leverageYield.getIntentHash(body: IntentHashRequestV2, config?): Promise<Result<IntentHashResponseV2>>;
|
|
58
|
+
sodax.api.leverageYield.getSolvedIntentPacket(body: IntentPacketRequestV2, config?): Promise<Result<IntentPacketResponseV2>>;
|
|
59
|
+
sodax.api.leverageYield.getIntentSubmitTxExtraData(body: IntentExtraDataRequestV2, config?): Promise<Result<IntentExtraDataResponseV2>>;
|
|
60
|
+
sodax.api.leverageYield.getFilledIntent(txHash, config?): Promise<Result<IntentStateV2>>;
|
|
61
|
+
sodax.api.leverageYield.getIntent(txHash, config?): Promise<Result<GetIntentResponseV2>>;
|
|
62
|
+
|
|
63
|
+
// Gas · fees
|
|
64
|
+
sodax.api.leverageYield.estimateGas(body: GasEstimateRequestV2, config?): Promise<Result<GasEstimateResponseV2>>;
|
|
65
|
+
sodax.api.leverageYield.getPartnerFee(query: FeeQueryV2, config?): Promise<Result<FeeResponseV2>>;
|
|
66
|
+
sodax.api.leverageYield.getSolverFee(query: FeeQueryV2, config?): Promise<Result<FeeResponseV2>>;
|
|
67
|
+
|
|
68
|
+
// Submit-tx state machine
|
|
69
|
+
sodax.api.leverageYield.submitTx(body: LeverageYieldSubmitTxRequestV2, config?): Promise<Result<SubmitTxResponseV2>>;
|
|
70
|
+
sodax.api.leverageYield.getSubmitTxStatus(query: SubmitTxStatusQueryV2, config?): Promise<Result<SubmitTxStatusResponseV2>>;
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers?, apiKey? }`) on
|
|
74
|
+
every method applies per-call overrides that take precedence over the service config (see "Per-call
|
|
75
|
+
overrides" below).
|
|
76
|
+
|
|
77
|
+
## Wire shapes — `bigint` vs decimal strings
|
|
78
|
+
|
|
79
|
+
The intent-bearing request bodies (`cancelIntent`, `getIntentHash`, `getIntentSubmitTxExtraData`,
|
|
80
|
+
`submitTx`) take `IntentRequestV2`, whose numeric fields (`intentId`, `inputAmount`, `minOutputAmount`,
|
|
81
|
+
`deadline`, `srcChain`, `dstChain`) are **`bigint`**; the client serializes them to decimal strings on the
|
|
82
|
+
wire. Server-returned intents (`IntentResponseV2`) and every vault read (`getPosition`, `getApr`,
|
|
83
|
+
`getTotalAssets`, previews, `getShareBalance`, …) come back with numeric fields as decimal **`string`**
|
|
84
|
+
(outbound JSON can't carry bigint). APR rates are RAY (`1e27` = 100%) as decimal strings; the vault-share
|
|
85
|
+
(`lsoda*`) is always 18 decimals. The `amount` / `inputAmount` fields on the quote / create-intent request
|
|
86
|
+
bodies are already decimal **strings**.
|
|
87
|
+
|
|
88
|
+
## Common call shapes
|
|
89
|
+
|
|
90
|
+
### Vault reads
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const vaults = await sodax.api.leverageYield.getVaults();
|
|
94
|
+
if (!vaults.ok) return;
|
|
95
|
+
const vault = vaults.value[0].vault; // hub proxy address (doubles as the lsoda* token)
|
|
96
|
+
|
|
97
|
+
const apr = await sodax.api.leverageYield.getEffectiveApr({ vault });
|
|
98
|
+
if (apr.ok) apr.value.effectiveNetAprRay; // RAY decimal string — the headline number
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Deposit quote
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
const quote = await sodax.api.leverageYield.getDepositQuote({
|
|
105
|
+
vault,
|
|
106
|
+
tokenSrc, tokenSrcChainKey,
|
|
107
|
+
amount: '1000000', // smallest unit of the input token, decimal string
|
|
108
|
+
quoteType: 'exact_input',
|
|
109
|
+
});
|
|
110
|
+
if (!quote.ok) return;
|
|
111
|
+
quote.value.quotedAmount; // expected lsoda* shares, decimal string
|
|
112
|
+
// Pass query `{ includeTxData: true }` (and srcAddress on the body) to also get `txData`.
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Create deposit intent
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const created = await sodax.api.leverageYield.createDepositIntent({
|
|
119
|
+
vault, srcChainKey, srcAddress,
|
|
120
|
+
inputToken,
|
|
121
|
+
inputAmount: '1000000',
|
|
122
|
+
minOutputAmount: '990000', // quotedAmount minus slippage
|
|
123
|
+
deadline: '0', // "0" → no expiry; omit to let the backend default from hub block time
|
|
124
|
+
});
|
|
125
|
+
if (!created.ok) return;
|
|
126
|
+
const { tx, intent, relayData } = created.value;
|
|
127
|
+
// Withdraw is the mirror: createWithdrawIntent({ vault, srcChainKey, srcAddress, dstChainKey,
|
|
128
|
+
// outputToken, inputAmount /* lsoda* shares */, minOutputAmount, recipient? }) — the backend sets
|
|
129
|
+
// hubWalletSwap internally (spends lsoda* from the hub wallet), so withdraw needs no spoke allowance.
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Approve can return TWO transactions
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
// Only a deposit needs a spoke allowance — a withdraw spends lsoda* from the hub wallet.
|
|
136
|
+
const allowance = await sodax.api.leverageYield.checkAllowance(depositBody);
|
|
137
|
+
if (allowance.ok && !allowance.value.valid) {
|
|
138
|
+
const plan = await sodax.api.leverageYield.approve(depositBody);
|
|
139
|
+
if (!plan.ok) return;
|
|
140
|
+
const { tx, resetTx } = plan.value; // ApproveResponseV2
|
|
141
|
+
// `resetTx` appears only for an input token of the 2017 TetherToken lineage, which rejects an
|
|
142
|
+
// allowance change from one non-zero value to another: broadcast AND MINE it before `tx`, or the
|
|
143
|
+
// approve reverts. In @sodax/dapp-kit, useLeverageYieldApiApproveAndBroadcast owns that ordering.
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Submit tx + poll status
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
// `intent` here is the IntentRequestV2 (bigint fields) you hold from createDepositIntent/createWithdrawIntent.
|
|
151
|
+
// `LeverageYieldSubmitTxRequestV2` is the swaps body PLUS a required `operation` discriminator, which the
|
|
152
|
+
// backend needs to record the queued row as a vault deposit or withdrawal.
|
|
153
|
+
const submit = await sodax.api.leverageYield.submitTx({
|
|
154
|
+
txHash, srcChainKey, walletAddress, intent,
|
|
155
|
+
relayData: relayData.payload, // string — the payload, not the RelayExtraData object
|
|
156
|
+
operation: 'deposit', // required: 'deposit' | 'withdraw'
|
|
157
|
+
});
|
|
158
|
+
if (!submit.ok) return;
|
|
159
|
+
|
|
160
|
+
// Both txHash AND srcChainKey are required by the status endpoint.
|
|
161
|
+
const status = await sodax.api.leverageYield.getSubmitTxStatus({ txHash, srcChainKey });
|
|
162
|
+
// A vault swap IS a solver swap, so terminal success is 'solved' — NOT the bridge API's 'executed'.
|
|
163
|
+
if (status.ok && status.value.data.status === 'solved') { /* settled */ }
|
|
164
|
+
// Lifecycle: 'pending' → 'relaying' → 'relayed' → 'posting_execution' → 'solved' | 'failed'.
|
|
165
|
+
// A set `abandonedAt` is terminal too, even while `status` is still non-terminal.
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Status fields — three distinct `status` values (don't conflate)
|
|
169
|
+
|
|
170
|
+
| Call | Field | Type | Values |
|
|
171
|
+
|---|---|---|---|
|
|
172
|
+
| `getStatus` | `StatusResponseV2.status` | **number** (`SwapIntentStatusCodeV2`) | `-1` NOT_FOUND · `1` NOT_STARTED_YET · `2` STARTED_NOT_FINISHED · `3` SOLVED (terminal) · `4` FAILED (terminal). `fillTxHash` is set only when `status === 3`. |
|
|
173
|
+
| `submitTx` | `SubmitTxResponseV2.data.status` | string | `'inserted'` (new) or `'duplicate'` (already submitted — submit-tx is idempotent on `(txHash, srcChainKey)`). |
|
|
174
|
+
| `getSubmitTxStatus` | `SubmitTxStatusResponseV2.data.status` | string | `'pending'` / `'relaying'` / `'relayed'` / `'posting_execution'` / `'posted_execution'` / `'solved'` / `'failed'` (`'solved'` / `'failed'` terminal, as for swaps — `'executed'` is the *bridge* terminal state). A set `abandonedAt` is terminal too. `data.operation` echoes `'leverage_deposit'` / `'leverage_withdraw'` (`SubmitTxOperationV2`). |
|
|
175
|
+
|
|
176
|
+
`getStatus` reports the **solver** intent status as a numeric code (shared with the Swaps API —
|
|
177
|
+
`SwapIntentStatusCodeV2`); the two submit-tx calls report **string** statuses. They are unrelated — don't
|
|
178
|
+
treat one as the other.
|
|
179
|
+
|
|
180
|
+
## Per-call overrides
|
|
181
|
+
|
|
182
|
+
Every method accepts a trailing `RequestOverrideConfig` to redirect a single call to a different host or
|
|
183
|
+
attach request-specific headers (auth, tracing), overriding the service config:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
await sodax.api.leverageYield.getVaults({ baseURL: 'https://staging.example/v1', headers: { 'X-Trace': 'abc' } });
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Custom endpoint for the leverage-yield API
|
|
190
|
+
|
|
191
|
+
The leverage-yield endpoints are `/leverage-yield/*` sub-paths under the same base URL as
|
|
192
|
+
`sodax.backendApi`, and the client shares the **base** backend-API config — there is **no** dedicated
|
|
193
|
+
leverage-yield slice on `ApiConfig` (unlike swaps, which has `swapsApiConfig`). So the flat
|
|
194
|
+
`BaseApiConfig` (or the `baseApiConfig` slice of `CustomApiConfig`) drives it:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
// The gateway ROOT — the client appends `/leverage-yield/*` itself. A legacy `/be`-suffixed value (the
|
|
198
|
+
// data API's own mount) is trimmed back to the root with a warning, configured or per-call.
|
|
199
|
+
const sodax = new Sodax({ api: { baseURL: 'https://api.example/v1' } });
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
To send a single leverage-yield call elsewhere, use the per-call `RequestOverrideConfig` above. See
|
|
203
|
+
[`backend-api.md`](backend-api.md) § "Custom backend" and [`../architecture.md`](../architecture.md).
|
|
204
|
+
|
|
205
|
+
## Backend submit-tx flow (SDK option)
|
|
206
|
+
|
|
207
|
+
Opting into `new Sodax({ leverageYield: { useBackendSubmitTx: true } })` routes the **feature
|
|
208
|
+
service** (`sodax.leverageYield.vaultSwap`) through this client's `submitTx` + `getSubmitTxStatus` (relay +
|
|
209
|
+
post-execution server-side), polling until `'solved'` and falling back to the client-side relay on any
|
|
210
|
+
non-success — the leverage-yield mirror of `swaps.useBackendSubmitTx`, except that it defaults **off**.
|
|
211
|
+
Read the effective value on `sodax.config.leverageYieldUseBackendSubmitTx`. `timeout` is a per-attempt
|
|
212
|
+
budget: the backend attempt gets it and the fallback relay gets a fresh one. See
|
|
213
|
+
[`leverage-yield.md`](leverage-yield.md).
|
|
214
|
+
|
|
215
|
+
## Error handling
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
const r = await sodax.api.leverageYield.getDepositQuote(body);
|
|
219
|
+
if (!r.ok) {
|
|
220
|
+
// r.error: SodaxError<'EXTERNAL_API_ERROR'> — feature: 'backend', context.api: 'leverageYield',
|
|
221
|
+
// context.endpoint: '/leverage-yield/quote/deposit'. The transport failure (HTTP_REQUEST_FAILED /
|
|
222
|
+
// REQUEST_TIMEOUT / a shape-validation issue) is on r.error.cause.
|
|
223
|
+
// A non-2xx also lifts its status onto r.error.context.status, so isAuthFailure(r.error) is true for
|
|
224
|
+
// a 401/403 — a rejected key is terminal, so stop rather than retry.
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## Cross-references
|
|
230
|
+
|
|
231
|
+
- `sodax.leverageYield` (the `LeverageYieldService` orchestrator that builds/executes vault swaps end-to-end): [`leverage-yield.md`](leverage-yield.md). The API client here is the lower-level HTTP surface; the orchestrator is the higher-level flow.
|
|
232
|
+
- `sodax.api.swaps` (the sibling Swaps API client — shares the intent-relay/gas/fee/submit-tx wire shapes): [`swaps-api.md`](swaps-api.md).
|
|
233
|
+
- `BackendApiService` (the sibling client for intent/orderbook/money-market reads): [`backend-api.md`](backend-api.md).
|
|
234
|
+
- Error model context fields: [`../reference/error-codes.md`](../reference/error-codes.md).
|
|
@@ -4,6 +4,8 @@ Leveraged-yield ERC-4626 vaults on the Sonic hub. A vault loops supply → borro
|
|
|
4
4
|
|
|
5
5
|
Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature tag for errors: `'leverageYield'`.
|
|
6
6
|
|
|
7
|
+
> **Backend HTTP client:** for the typed `sodax.api.leverageYield` client that calls the backend Leverage Yield API v2 directly (vault reads, deposit/withdraw quotes + intents, submit-tx), see [`leverage-yield-api.md`](leverage-yield-api.md). Opting into `new Sodax({ leverageYield: { useBackendSubmitTx: true } })` routes this service's `vaultSwap` through that client's submit-tx flow (with client-side fallback).
|
|
8
|
+
|
|
7
9
|
## How it works
|
|
8
10
|
|
|
9
11
|
- A vault holds `asset` (a Sodax vault token like sodaWEETH) as collateral, borrows `borrowToken` (e.g. sodaETH) from the Sodax-forked AAVE pool, swaps it back into the asset, and re-supplies — to a `targetLTV`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Money Market — `MoneyMarketService`
|
|
2
2
|
|
|
3
|
-
Cross-chain lending and borrowing. Supply, borrow, withdraw, repay across
|
|
3
|
+
Cross-chain lending and borrowing. Supply, borrow, withdraw, repay across the supported spoke chains (`moneyMarketSupportedTokens` in `@sodax/types` is the source of truth). Position state lives on the hub.
|
|
4
4
|
|
|
5
5
|
Access: `sodax.moneyMarket`. Service class: `MoneyMarketService`. Feature tag for errors: `'moneyMarket'`.
|
|
6
6
|
|
|
@@ -93,6 +93,48 @@ const stakingConfig = await sodax.staking.getStakingConfig();
|
|
|
93
93
|
const pools = sodax.dex.clService.getPools(); // synchronous in v2
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
### Wallet balances (`sodax.spoke.getWalletBalance` / `getWalletBalances`)
|
|
97
|
+
|
|
98
|
+
Chain-agnostic reads of the balances a user's own address holds — the SDK dispatches to the right
|
|
99
|
+
chain family and reads the native coin or that chain's token standard (EVM erc20, Solana SPL, Sui
|
|
100
|
+
coin, Soroban contract, IRC-2, NEP-141, SIP-010, Injective bank denom, Bitcoin UTXOs). Distinct from
|
|
101
|
+
`getDeposit`, which reads the protocol asset manager rather than the user.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// @ai-snippets-skip
|
|
105
|
+
const one = await sodax.spoke.getWalletBalance({
|
|
106
|
+
srcChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
107
|
+
srcAddress: '0x…', // the user
|
|
108
|
+
token: usdc, // a full XToken living on srcChainKey (token.chainKey is ignored)
|
|
109
|
+
});
|
|
110
|
+
// one: Result<bigint> — smallest units
|
|
111
|
+
|
|
112
|
+
const many = await sodax.spoke.getWalletBalances({
|
|
113
|
+
srcChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
114
|
+
srcAddress: '0x…',
|
|
115
|
+
tokens: [usdc, weth],
|
|
116
|
+
});
|
|
117
|
+
// many: Result<Record<string, bigint>> — smallest units, keyed by token.address
|
|
118
|
+
if (many.ok) console.log(many.value[usdc.address]);
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Contract worth internalising:
|
|
122
|
+
|
|
123
|
+
- **A token that could not be read is logged and reported as `0n`**, so one flaky token never
|
|
124
|
+
discards the balances that did resolve. The flip side: a caller cannot tell a failed read from an
|
|
125
|
+
empty wallet. The direction is deliberately conservative — under-reporting blocks a spend, it
|
|
126
|
+
never permits one. Wire a `logger` into `new Sodax({ logger })` to surface those failures.
|
|
127
|
+
- The `Result` fails when the whole batch is unusable — an unknown chain key, a single shared
|
|
128
|
+
round-trip every token depends on (ICON's `tryAggregate`, Injective's portfolio fetch), or a batch
|
|
129
|
+
in which NO token could be read, which would otherwise render as "this wallet is empty on every
|
|
130
|
+
asset".
|
|
131
|
+
- Batching is per chain: EVM/Sonic use multicall3, ICON one `tryAggregate`, Injective one portfolio
|
|
132
|
+
fetch, Stellar one shared network + account fetch; the rest fan out per token.
|
|
133
|
+
- **Chain-specific values.** Stellar XLM reports the *spendable* amount (total minus the minimum
|
|
134
|
+
reserve and selling liabilities). Bitcoin reads native BTC from its UTXO set and returns `0n` for
|
|
135
|
+
Rune tokens, whose amounts that endpoint does not carry. Hedera's native balance is rescaled from
|
|
136
|
+
the EVM layer's 18-decimal "weibar" to HBAR's canonical 8 decimals.
|
|
137
|
+
|
|
96
138
|
## 7. Build raw transactions (no wallet)
|
|
97
139
|
|
|
98
140
|
For sign-elsewhere flows (gnosis safe, hardware wallet, custom multi-sig), use `raw: true`. The SDK builds the unsigned payload; your application signs and broadcasts:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Chain keys
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `ChainKey` type is the union of every `ChainKeys.*` value — the table below is the full set. **`SpokeChainKey` is the same union — it includes Sonic.** The "spoke" naming refers to how feature services type their `srcChainKey` parameter (they accept the hub too — bridge / swap / staking etc. all run from Sonic as source via the hub-wallet abstraction). When you specifically need "EVM chains excluding the hub" use `EVM_SPOKE_ONLY_CHAIN_KEYS` / `isEvmSpokeOnlyChainKeyType`.
|
|
4
4
|
|
|
5
5
|
| `ChainKeys.*` | String value | Family | Hub vs spoke | Address type |
|
|
6
6
|
|---|---|---|---|---|
|
|
@@ -37,9 +37,9 @@
|
|
|
37
37
|
|
|
38
38
|
| Type | What it is |
|
|
39
39
|
|---|---|
|
|
40
|
-
| `ChainKey` | Union of all `ChainKeys.*` values
|
|
41
|
-
| `SpokeChainKey` | Same union as `ChainKey` — includes Sonic
|
|
42
|
-
| `EvmChainKey` | Subset of `ChainKey` for the
|
|
40
|
+
| `ChainKey` | Union of all `ChainKeys.*` values. |
|
|
41
|
+
| `SpokeChainKey` | Same union as `ChainKey` — includes Sonic. For "EVM chains excluding the hub" use `EvmSpokeOnlyChainKey`. |
|
|
42
|
+
| `EvmChainKey` | Subset of `ChainKey` for the EVM chains. |
|
|
43
43
|
| `HubChainKey` | The literal `'sonic'`. |
|
|
44
44
|
|
|
45
45
|
### Chain-family helpers
|
|
@@ -193,6 +193,13 @@ import {
|
|
|
193
193
|
type SwapResponse,
|
|
194
194
|
type CreateIntentResult,
|
|
195
195
|
type TxHashPair,
|
|
196
|
+
type OracleCandleInterval, // '1m' | '5m' | '1h' | '1d'
|
|
197
|
+
ORACLE_CANDLE_INTERVALS, // runtime array of the served intervals
|
|
198
|
+
isOracleCandleInterval, // narrows a markets `key` (string) to OracleCandleInterval
|
|
199
|
+
type OracleMarketInterval, // `key` is `string`: discovery tolerates an interval this version doesn't know
|
|
200
|
+
type OracleMarketsResponse,
|
|
201
|
+
type OracleCandle, // OHLC prices are USD decimal strings; timestamp is UNIX seconds
|
|
202
|
+
type OracleCandlesResponse,
|
|
196
203
|
} from '@sodax/sdk';
|
|
197
204
|
```
|
|
198
205
|
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: sodax-sdk-leverage-yield-api
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 Leverage Yield API client — `sodax.api.leverageYield` (class LeverageYieldApiService), a typed HTTP client for the backend Leverage Yield API v2 (`/leverage-yield/*`, 33 endpoints: vault registry, vault reads (asset/position/APR/effective-APR/LSD-APR/total-assets/previews/share-balance/max-withdraw), deposit & withdraw quote, deadline, allowance/approve, create-deposit-intent & create-withdraw-intent, intent submit/status/cancel/hash/packet/extra-data/fill/get, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the leverage-yield backend directly (e.g. "sodax.api.leverageYield", "leverage vault APR from the backend", "vault position from the API", "leverage-yield deposit quote", "createDepositIntent via the backend API", "leverage-yield API v2"). For the higher-level end-to-end vault-swap orchestrator use the `leverage-yield` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Leverage Yield API (Core SDK granular skill)
|
|
7
|
+
|
|
8
|
+
Granular skill for `sodax.api.leverageYield` (class `LeverageYieldApiService`) — the typed HTTP client for
|
|
9
|
+
the backend **Leverage Yield API v2** (`/leverage-yield/*`). `sodax.api` is an alias for `sodax.backendApi`;
|
|
10
|
+
`.leverageYield` is the leverage-yield client. 33 endpoints, one method each; every method returns
|
|
11
|
+
`Promise<Result<T>>` (never throws) and validates the response. Errors carry `feature: 'backend'`,
|
|
12
|
+
`context.api: 'leverageYield'`, `context.endpoint`.
|
|
13
|
+
|
|
14
|
+
A leverage-yield deposit/withdraw **is** an intent-based swap (the vault's `lsoda*` share token is
|
|
15
|
+
solver-tradeable), so the intent-relay / gas / fee / submit-tx endpoints share the Swaps API wire shapes —
|
|
16
|
+
this is the leverage-yield sibling of the [`swaps-api`](../swaps-api/SKILL.md) skill.
|
|
17
|
+
|
|
18
|
+
> Lower-level than `sodax.leverageYield`: this is the raw backend HTTP surface. For the end-to-end
|
|
19
|
+
> build→relay→post-execution vault swap orchestrator, use the [`leverage-yield`](../leverage-yield/SKILL.md) skill.
|
|
20
|
+
|
|
21
|
+
## Step 1 — Clarify with user before coding
|
|
22
|
+
|
|
23
|
+
1. **Which endpoint(s)?** Vault registry · vault reads (asset/position/APR/effective-APR/LSD-APR/total-assets/
|
|
24
|
+
previews/share-balance/max-withdraw) · deposit/withdraw quote · deadline · allowance/approve ·
|
|
25
|
+
create-deposit-intent / create-withdraw-intent · intent lifecycle (submit/status/cancel/hash/packet/
|
|
26
|
+
extra-data/fill/get) · gas/fees · submit-tx/status.
|
|
27
|
+
2. **Orchestrator or raw API?** If the user just wants "deposit into / withdraw from a leverage vault",
|
|
28
|
+
prefer `sodax.leverageYield` (the `leverage-yield` skill). Use `sodax.api.leverageYield` when they need a
|
|
29
|
+
single backend call (a vault APR, a position read, a deposit quote, a status poll) or are building their
|
|
30
|
+
own flow.
|
|
31
|
+
3. **Deposit vs withdraw?** Create-intent is split: `createDepositIntent` (any token → `lsoda*`, needs a
|
|
32
|
+
spoke allowance) vs `createWithdrawIntent` (`lsoda*` → any token, hub-wallet swap, no spoke allowance).
|
|
33
|
+
|
|
34
|
+
## Integration workflow
|
|
35
|
+
|
|
36
|
+
1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md) — DO / DO NOT (read first).
|
|
37
|
+
2. [`../integration/knowledge/features/leverage-yield-api.md`](../integration/knowledge/features/leverage-yield-api.md) — the full 33-endpoint client: signatures, wire shapes (bigint vs decimal string), common call shapes (vault reads, deposit quote, create-intent, submit-tx + status), per-call overrides, custom endpoint, the `useBackendSubmitTx` service option.
|
|
38
|
+
3. For the end-to-end vault-swap flow that wraps these calls → [`../integration/knowledge/features/leverage-yield.md`](../integration/knowledge/features/leverage-yield.md); for the intent-sibling swaps client → [`../integration/knowledge/features/swaps-api.md`](../integration/knowledge/features/swaps-api.md).
|
|
39
|
+
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).
|
|
40
|
+
|
|
41
|
+
### Leverage-Yield-API-specific anti-patterns
|
|
42
|
+
|
|
43
|
+
- **`try/catch` for failures.** Every method returns `Result<T>` — branch on `result.ok`. `catch` won't fire for HTTP/timeout/validation failures.
|
|
44
|
+
- **Passing the `RelayExtraData` object** to `submitTx`'s `relayData`. The field is a `string` — pass `relayData.payload`.
|
|
45
|
+
- **Omitting `operation` on `submitTx`.** `LeverageYieldSubmitTxRequestV2` is the swaps body PLUS a required `operation: 'deposit' | 'withdraw'` — the backend records the queued row from it.
|
|
46
|
+
- **Polling for `'executed'`.** A vault swap IS a solver swap, so terminal success is `'solved'` (`'executed'` is the *bridge* API's terminal state). A set `abandonedAt` is terminal too.
|
|
47
|
+
- **Broadcasting `approve`'s `tx` without its `resetTx`.** `ApproveResponseV2` is `{ tx, resetTx? }`; a guarded input token needs `resetTx` MINED first or the approve reverts. In `@sodax/dapp-kit`, prefer `useLeverageYieldApiApproveAndBroadcast`, which owns that ordering.
|
|
48
|
+
- **Stringifying `intent` numerics yourself.** `IntentRequestV2` fields are `bigint`; the client serializes them to decimal strings — pass the bigint intent through as-is.
|
|
49
|
+
- **Checking allowance for a withdraw.** `createWithdrawIntent` is a hub-wallet swap (spends `lsoda*` from the hub wallet) — there is no spoke allowance step. `checkAllowance`/`approve` take the **deposit** params only.
|
|
50
|
+
- **Calling `getSubmitTxStatus` with only `txHash`.** Both `txHash` AND `srcChainKey` are required.
|
|
51
|
+
- **Confusing `sodax.api.leverageYield` with `sodax.leverageYield`.** The former is the backend HTTP client; the latter is the on-chain vault-swap orchestrator.
|
|
52
|
+
|
|
53
|
+
## Migration workflow (v1 → v2)
|
|
54
|
+
|
|
55
|
+
The typed `sodax.api.leverageYield` client is **v2-new** — leverage yield itself has no v1 equivalent, so
|
|
56
|
+
there is nothing to port. The intent-relay / submit-tx request shapes it shares with swaps are covered in
|
|
57
|
+
the swap + backend-api migration docs if you need the deltas:
|
|
58
|
+
|
|
59
|
+
1. [`../migration-v1-to-v2/knowledge/features/swap.md`](../migration-v1-to-v2/knowledge/features/swap.md) — create-intent / submit-tx request-shape changes (`srcChainId` → `srcChainKey`, `relayData` object → string, bigint intent).
|
|
60
|
+
2. [`../migration-v1-to-v2/knowledge/features/backend-api.md`](../migration-v1-to-v2/knowledge/features/backend-api.md) — the `Result`-wrapping HTTP-client contract.
|
|
61
|
+
|
|
62
|
+
## Verification
|
|
63
|
+
|
|
64
|
+
1. `pnpm tsc --noEmit` clean.
|
|
65
|
+
2. Every `await sodax.api.leverageYield.<method>(...)` call site has `if (!result.ok)`.
|
|
66
|
+
3. `submitTx.relayData` is `relayData.payload` (string), `submitTx` carries `operation`, and `getSubmitTxStatus` passes both `txHash` and `srcChainKey`.
|
|
67
|
+
4. Submit-tx status polling stops on `'solved'` / `'failed'` / `abandonedAt` — not on `'executed'`.
|
|
68
|
+
5. Intent-bearing bodies pass the `bigint` `IntentRequestV2` through unmodified (no manual `.toString()`).
|
|
69
|
+
6. Allowance/approve are used only for the deposit path (withdraw is a hub-wallet swap), and a returned `resetTx` is broadcast and mined before `tx`.
|
|
70
|
+
|
|
71
|
+
## Related granular skills (same family)
|
|
72
|
+
|
|
73
|
+
- [`../leverage-yield/SKILL.md`](../leverage-yield/SKILL.md) — the end-to-end vault-swap orchestrator (`sodax.leverageYield`) that wraps these backend calls.
|
|
74
|
+
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the intent-sibling Swaps API client (`sodax.api.swaps`), same intent-relay/gas/fee/submit-tx wire shapes.
|
|
75
|
+
- [`../backend-api/SKILL.md`](../backend-api/SKILL.md) — the sibling `sodax.backendApi` read client (intent / orderbook / money-market reads + config).
|
|
76
|
+
|
|
77
|
+
For multi-feature tasks, load the broad [`sodax-sdk` skill](../SKILL.md).
|
|
@@ -32,6 +32,7 @@ Granular skill for `EvmWalletProvider` — the low-level EVM wallet for backend
|
|
|
32
32
|
- **Passing `publicClient` / `walletClient` / `transport` defaults in browser-extension mode.** They're ignored (provider logs a one-time warn); supply them only in PK mode.
|
|
33
33
|
- **Adding `viem` as a direct dep** when `WalletClient` / `PublicClient` etc. re-export from `@sodax/wallet-sdk-core`.
|
|
34
34
|
- **Assuming nonce management.** There is none — fire parallel sends and you collide; set `defaults.sendTransaction.nonce` or per-call `nonce`.
|
|
35
|
+
- **Skipping `expectedChainId` on chain-specific sends.** Without it the tx goes to whatever chain the wallet is on; with it a mismatch throws and nothing is sent.
|
|
35
36
|
|
|
36
37
|
## Migration workflow (port v1 → v2)
|
|
37
38
|
|
|
@@ -67,7 +67,7 @@ type EvmWalletDefaults = {
|
|
|
67
67
|
| Method | Signature | Returns | Default slice merged |
|
|
68
68
|
|---|---|---|---|
|
|
69
69
|
| `getWalletAddress` | `() => Promise<Address>` | viem `Address` (`` `0x${string}` ``) | — |
|
|
70
|
-
| `sendTransaction` | `(txData: EvmRawTransaction, options?: EvmSendTransactionPolicy) => Promise<Hash>` | viem `Hash` | `defaults.sendTransaction` |
|
|
70
|
+
| `sendTransaction` | `(txData: EvmRawTransaction, options?: EvmSendTransactionPolicy & EvmSendTransactionOptions) => Promise<Hash>` | viem `Hash` | `defaults.sendTransaction` |
|
|
71
71
|
| `waitForTransactionReceipt` | `(txHash: Hash, options?: EvmWaitForTransactionReceiptPolicy) => Promise<EvmRawTransactionReceipt>` | bigint-stringified receipt | `defaults.waitForTransactionReceipt` |
|
|
72
72
|
|
|
73
73
|
The serialised receipt converts all `bigint` fields to `string` so it can be `JSON.stringify`'d safely. This is enforced at the type level — `EvmRawTransactionReceipt` (from `@sodax/types`) is the stringified shape.
|
|
@@ -90,6 +90,8 @@ The serialised receipt converts all `bigint` fields to `string` so it can be `JS
|
|
|
90
90
|
- **`getEvmViemChain` is exhaustive.** If `@sodax/types` adds a new `EvmChainKey`, this function fails to typecheck until the case is added — by design.
|
|
91
91
|
- **HyperEVM is defined inside this package.** `viem/chains` does not ship a HyperEVM config; `wallet-providers/evm/EvmWalletProvider.ts` exports `hyper` via `defineChain`. You shouldn't need it directly — `getEvmViemChain(ChainKeys.HYPEREVM_MAINNET)` returns it.
|
|
92
92
|
- **`rpcUrl` falls back to the viem chain's first public RPC.** Fine for testing — replace with a private RPC for production.
|
|
93
|
+
- **Chain binding is opt-in.** Pass `options.expectedChainId` (`getEvmViemChain(chainKey).id`) and the provider refuses to send when the wallet's active chain differs. The SDK passes it on every signed send it owns: spoke/hub deposits and messages, signed ERC-20 approvals (reset leg included), and the hub-scoped vault, partner, BALN, `Permit2Service` and `Erc4626Service` sends — the last two are bound to Sonic, so calling them with a wallet on another EVM network now throws instead of broadcasting there.
|
|
94
|
+
- **The chain check fails closed.** `eth_chainId` is normalised to a plain `number` before a strict compare; a mismatch or malformed wallet response throws and nothing is sent.
|
|
93
95
|
- **No nonce management.** The provider does not auto-increment / serialise sends. If you fire multiple txs in parallel from the same account, manage nonces yourself via `defaults.sendTransaction.nonce` or per-call `options.nonce`.
|
|
94
96
|
|
|
95
97
|
---
|