@sodax/skills 2.2.0-rc.8 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -3
- package/package.json +3 -2
- package/skills/sodax-build/SKILL.md +2 -2
- package/skills/sodax-dapp-kit/SKILL.md +23 -5
- package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/ai-rules.md +3 -0
- package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +8 -0
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +13 -1
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/dex.md +23 -8
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield-product-anatomy.md +150 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +121 -38
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +6 -3
- package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +25 -8
- package/skills/sodax-sdk/SKILL.md +2 -1
- package/skills/sodax-sdk/integration/knowledge/ai-rules.md +3 -0
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +57 -11
- package/skills/sodax-sdk/leverage-yield/SKILL.md +14 -7
- package/skills/sodax-wallet-sdk-core/SKILL.md +20 -2
- package/skills/sodax-wallet-sdk-react/SKILL.md +16 -1
package/AGENTS.md
CHANGED
|
@@ -114,7 +114,7 @@ They exist so agents can load just one workflow (~3 KB) instead of the whole bro
|
|
|
114
114
|
|
|
115
115
|
Granular skills are **one file each** (`<sub-domain>/SKILL.md`). They do **NOT** ship their own `integration/knowledge/` or `migration-v1-to-v2/knowledge/` subtrees — they link directly into the parent broad skill's knowledge tree (`../integration/knowledge/features/<feature>.md`, `../integration/knowledge/recipes/<recipe>.md`, etc.).
|
|
116
116
|
|
|
117
|
-
**Granular skills are bundled, not separately published.** `plugin.json` registers **only the top-level skills** (the broad SDK skills plus the registered meta skill). Each broad skill's directory already contains its nested granular `SKILL.md` files, so installing a broad skill (e.g. `npx skills add … --skill sodax-sdk`) lands every granular file alongside the knowledge tree; the broad SKILL.md's "prefer a granular skill" table then links to `./swap/SKILL.md` etc., which resolve in the consumer's install. Granular skills are deliberately **not** registered because they are not self-contained: a granular `SKILL.md` links **up** into its parent's tree (`../integration/knowledge/...`), and the `skills` CLI copies only a skill's own directory — so installing a granular skill standalone would leave every `../knowledge` link dangling. Keeping the registry to the top-level skills also concentrates skills.sh install telemetry (which drives search ranking) instead of diluting it across the many bundled granular rows. To add a new granular skill, drop a `<feature>/SKILL.md` into the broad skill dir — do **not** add it to `plugin.json`.
|
|
117
|
+
**Granular skills are bundled, not separately published.** `plugin.json` registers **only the top-level skills** (the broad SDK skills plus the registered meta skill). Each broad skill's directory already contains its nested granular `SKILL.md` files, so installing a broad skill (e.g. `npx skills add … --skill sodax-sdk`) lands every granular file alongside the knowledge tree; the broad SKILL.md's "prefer a granular skill" table then links to `./swap/SKILL.md` etc., which resolve in the consumer's install. Granular skills are deliberately **not** registered because they are not self-contained: a granular `SKILL.md` links **up** into its parent's tree (`../integration/knowledge/...`), and the `skills` CLI copies only a skill's own directory — so installing a granular skill standalone would leave every `../knowledge` link dangling. Keeping the registry to the top-level skills also concentrates skills.sh install telemetry (which drives search ranking) instead of diluting it across the many bundled granular rows. To add a new granular skill, drop a `<feature>/SKILL.md` into the broad skill dir and add its row to the parent's "Prefer a granular skill" table (`check:ai-structural` fails without it) — do **not** add it to `plugin.json`. Agents only auto-discover top-level skills, so that row is how they find it.
|
|
118
118
|
|
|
119
119
|
**Family rule:** every granular skill shares its parent broad skill's family. Family is the broad-skill name (`sdk`, `wallet-sdk-core`, `wallet-sdk-react`, `dapp-kit`). Cross-family clickable links remain forbidden; intra-family links (broad ↔ granular, granular ↔ granular within the same broad parent) are explicitly allowed.
|
|
120
120
|
|
|
@@ -162,16 +162,17 @@ To add another meta skill later: drop `skills/<name>/SKILL.md` + a flat `knowled
|
|
|
162
162
|
pnpm --filter @sodax/skills check:ai
|
|
163
163
|
```
|
|
164
164
|
|
|
165
|
-
Chains
|
|
165
|
+
Chains seven sub-scripts. Each catches a distinct bug class — green guards together prove syntactic + structural correctness, but **NOT** prose-level accuracy.
|
|
166
166
|
|
|
167
167
|
| Sub-script | What it enforces | Source of truth | Opt-out |
|
|
168
168
|
|---|---|---|---|
|
|
169
|
-
| `check:ai-structural` | `.claude-plugin/plugin.json` parses and registers exactly the expected broad SDK skills + meta skills (the `EXPECTED_*` arrays in `check-skills.sh` are the source of truth); every SKILL.md (broad + bundled granular + meta) has valid `name:` / `description:` frontmatter; no orphan top-level skill dirs; every relative `.md` link resolves. | this package's filesystem | none — structural |
|
|
169
|
+
| `check:ai-structural` | `.claude-plugin/plugin.json` parses and registers exactly the expected broad SDK skills + meta skills (the `EXPECTED_*` arrays in `check-skills.sh` are the source of truth); every SKILL.md (broad + bundled granular + meta) has valid `name:` / `description:` frontmatter; no orphan top-level skill dirs; every relative `.md` link resolves; every granular skill is linked from its parent SKILL.md (its "Prefer a granular skill" row), every `integration/knowledge/features/*.md` is named in the parent's integration section, and every registered description fits Claude Code's 1,536-character skill-listing cap. | this package's filesystem | none — structural |
|
|
170
170
|
| `check:ai-imports` | Every `import … from '@sodax/<pkg>'` statement in `skills/sodax-<pkg>/{integration,migration-v1-to-v2}/knowledge/**/*.md` + each SDK package's README/AGENTS.md typechecks against `packages/<pkg>/src/index.ts`. Catches deleted / renamed exports. | `packages/<pkg>/src/index.ts` via fixture tsconfig `paths` | none |
|
|
171
171
|
| `check:ai-snippets` | Every fenced ts/tsx code block in `skills/sodax-{dapp-kit,wallet-sdk-react}/{integration,migration-v1-to-v2}/knowledge/**/*.md` typechecks against the real SDK. Catches call-shape drift. Pattern-style blocks can opt out with the marker; real working examples still validate. | same as imports, plus `_ai-snippets-fixture/_preamble.d.ts` ambients | `// @ai-snippets-skip` as first content line of the block |
|
|
172
172
|
| `check:ai-tsx-examples` | Every standalone `.tsx` file under `skills/sodax-<pkg>/integration/knowledge/examples/` typechecks as a complete module against the live `src/`. Catches export drift, hook-shape drift, and renamed-param drift in runnable user-facing examples. | each SDK package's `src/index.ts` (and `xchains/*` sub-paths for wallet-sdk-react) via fixture tsconfig `paths` | none — illustrative blocks live in `.md` via `@ai-snippets-skip`; `integration/knowledge/examples/` is for runnable code only |
|
|
173
173
|
| `check:ai-keys` | Every `queryKey: [...]` / `mutationKey: [...]` literal in `skills/sodax-dapp-kit/{integration,migration-v1-to-v2}/knowledge/**/*.md` has a matching prefix in `packages/dapp-kit/src/hooks/**/*.ts`. Catches `'stakingInfo'` vs `'info'`-style drift. | `packages/dapp-kit/src/hooks/**/*.ts` | `<!-- ai-keys-allow -->` or `// ai-keys-allow` within 3 preceding lines |
|
|
174
174
|
| `check:ai-consistency` | Every polling-interval claim ("polls 3s") near a `useFoo` mention matches the source `refetchInterval` for that hook. | same as keys | `<!-- ai-consistency-allow -->` within 6 preceding lines |
|
|
175
|
+
| `check:ai-safety` | No fenced code block under `skills/` (nor any standalone `.tsx` example) sends a zero minimum output (`minOutputAmount: 0n` and friends) or `skipSimulation: true`. Agents copy examples verbatim, so an unsafe example ships straight into user code; prose may still name the patterns. | this package's filesystem | `ai-safety-allow` in a comment on the same line |
|
|
175
176
|
|
|
176
177
|
Run individually for faster feedback: `pnpm run check:ai-imports`, `pnpm run check:ai-keys`, etc.
|
|
177
178
|
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
7
|
-
"version": "2.2.0
|
|
7
|
+
"version": "2.2.0",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"description": "AI-agent skills and knowledge for consumers of @sodax/* SDKs (Claude Code, Codex, Cursor, …)",
|
|
10
10
|
"keywords": [
|
|
@@ -51,7 +51,8 @@
|
|
|
51
51
|
"check:ai-tsx-examples": "bash ./scripts/check-ai-tsx-examples.sh",
|
|
52
52
|
"check:ai-keys": "bash ./scripts/check-ai-keys.sh",
|
|
53
53
|
"check:ai-consistency": "bash ./scripts/check-ai-consistency.sh",
|
|
54
|
-
"check:ai": "
|
|
54
|
+
"check:ai-safety": "bash ./scripts/check-ai-safety.sh",
|
|
55
|
+
"check:ai": "pnpm run check:ai-structural && pnpm run check:ai-imports && pnpm run check:ai-snippets && pnpm run check:ai-tsx-examples && pnpm run check:ai-keys && pnpm run check:ai-consistency && pnpm run check:ai-safety",
|
|
55
56
|
"ci": "pnpm run pretty && pnpm run check:ai",
|
|
56
57
|
"clean": "rm -rf node_modules && rm -rf .turbo"
|
|
57
58
|
}
|
|
@@ -11,7 +11,7 @@ metadata:
|
|
|
11
11
|
|
|
12
12
|
You are the **ideation layer** that sits upstream of the developer skills (see the package `AGENTS.md` router). Your job: take a person who knows *what they want* but not *which SODAX feature or SDK does it*, and produce a **product brief** + a **handoff** that names the next skill to load. You **do not write app code** — you route to the skills that do.
|
|
13
13
|
|
|
14
|
-
SODAX is **cross-chain DeFi** on a hub-and-spoke model (Sonic is the hub). **Its defining strength is moving value *across* chains** — swapping or bridging between different chains, lending/borrowing cross-chain — so steer ideas toward that cross-chain edge first; it is the main reason to pick SODAX over a single-chain protocol. Other plain-English capabilities: stake, provide liquidity, migrate legacy tokens, take a partner fee, recover stuck funds. The catalog in [`knowledge/feature-catalog.md`](./knowledge/feature-catalog.md) maps each to what an end-user can *do*.
|
|
14
|
+
SODAX is **cross-chain DeFi** on a hub-and-spoke model (Sonic is the hub). **Its defining strength is moving value *across* chains** — swapping or bridging between different chains, lending/borrowing cross-chain — so steer ideas toward that cross-chain edge first; it is the main reason to pick SODAX over a single-chain protocol. Other plain-English capabilities: stake, provide liquidity, earn leveraged yield in a vault (advanced and risk-heavy: only for a semi-technical+ user who asks for leverage, never pitched as savings), migrate legacy tokens, take a partner fee, recover stuck funds. The catalog in [`knowledge/feature-catalog.md`](./knowledge/feature-catalog.md) maps each to what an end-user can *do*.
|
|
15
15
|
|
|
16
16
|
---
|
|
17
17
|
|
|
@@ -25,7 +25,7 @@ SODAX is **cross-chain DeFi** on a hub-and-spoke model (Sonic is the hub). **Its
|
|
|
25
25
|
| `Sodax`, `ChainKeys`, `Result<T>`, `SodaxError`, "backend / bot / script with @sodax/sdk" | `sodax-sdk` |
|
|
26
26
|
| `walletProvider`, `IEvmWalletProvider`, "sign on <chain>", a specific chain provider | `sodax-wallet-sdk-core` |
|
|
27
27
|
| "connect button", "wallet modal", "switch chain", WalletConnect | `sodax-wallet-sdk-react` |
|
|
28
|
-
| A named feature already chosen (swap / money market / staking / bridge / dex / migration / partner / recovery) **with** an SDK in mind | the matching dev skill above |
|
|
28
|
+
| A named feature already chosen (swap / money market / staking / bridge / dex / leverage yield / migration / partner / recovery) **with** an SDK in mind | the matching dev skill above |
|
|
29
29
|
|
|
30
30
|
When in doubt about whether the *what* is decided, ask **one** question: *"Do you already know which SODAX feature you want, or are we still figuring that out?"* — decided → route; not decided → interview.
|
|
31
31
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-dapp-kit
|
|
3
|
-
description: 'Integrate SODAX into a React dapp with @sodax/dapp-kit — React Query hooks for swaps, lending/borrowing, staking, bridging, DEX,
|
|
3
|
+
description: 'Integrate SODAX into a React dapp with @sodax/dapp-kit — React Query hooks for swaps, money market lending/borrowing, staking, bridging, DEX liquidity, leverage-yield vaults (deposit/withdraw, APR / TVL / health) and leverage positions, token migration, Bitcoin trading (Radfi / Bound Exchange), partner fees, recovery, and backend API reads. INTEGRATION (write NEW code) — use whenever a React dapp needs SODAX feature hooks; backend code uses `@sodax/sdk`. Triggers on "use @sodax/dapp-kit", "useSwap", "useMoneyMarket", "useStake", "useBridge", "useDex", "useMigrate", "useLeverageYield", "leverage yield vault in React", "vault UI", any dapp-kit `use<Feature>` hook, "Sodax React hooks". v2 hook shape: mutation hooks return `SafeUseMutationResult` with `mutateAsyncSafe(vars): Promise<Result<TData>>`; mutationFn throws on SDK `!ok`; hooks own their invalidations. MIGRATION (port v1 → v2) — single-object hook params, mandatory `mutateAsyncSafe`, hook-owned invalidations, canonical queryKey/mutationKey conventions, on top of the reshaped SDK (chain-key-driven routing, `Result<T>` everywhere, `WalletProviderSlot<K, Raw>`). Triggers on "migrate @sodax/dapp-kit", "useSpokeProvider gone", "dapp-kit v1 → v2", "invalidateMmQueries broken", "dapp-kit hook signatures changed", v1 fingerprints (positional args, hook-init `spokeProvider`, `useSpokeProvider`, `invalidateMmQueries`, legacy `useMigrate`, `*_MAINNET_CHAIN_ID`). Load this skill if EITHER applies; the body gates by mode.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -20,13 +20,31 @@ AGENTS.md routes you here when you're working with `@sodax/dapp-kit` v2 — eith
|
|
|
20
20
|
For backend / Node → use `sodax-sdk` (dapp-kit is React-only).
|
|
21
21
|
Every dapp-kit consumer also needs wallet connectivity — also load `sodax-wallet-sdk-react`.
|
|
22
22
|
|
|
23
|
+
## Prefer a granular skill if the feature is known
|
|
24
|
+
|
|
25
|
+
If the user has already picked one feature, load the matching granular skill instead of this broad one. It is a few KB of focused workflow and links straight into the right knowledge files, for integration and, where a v1 surface existed, migration.
|
|
26
|
+
|
|
27
|
+
| Feature | Granular skill | Trigger phrases |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| Intent-based swap (market + limit orders) | [`./swap/SKILL.md`](./swap/SKILL.md) | "useSwap", "useQuote", "limit order in React" |
|
|
30
|
+
| Cross-chain lending / borrowing | [`./money-market/SKILL.md`](./money-market/SKILL.md) | "useSupply", "useBorrow", "money market UI" |
|
|
31
|
+
| SODA ↔ xSODA staking | [`./staking/SKILL.md`](./staking/SKILL.md) | "useStake", "instant unstake", "staking UI" |
|
|
32
|
+
| Direct token bridge via vault | [`./bridge/SKILL.md`](./bridge/SKILL.md) | "useBridge", "bridge tokens in React" |
|
|
33
|
+
| Concentrated-liquidity LP | [`./dex/SKILL.md`](./dex/SKILL.md) | "useSupplyLiquidity", "LP position UI", "usePools" |
|
|
34
|
+
| Leverage-yield vaults and leverage positions (on-chain hooks; a user-facing vault screen starts from the [product anatomy](./integration/knowledge/recipes/leverage-yield-product-anatomy.md)) | [`./leverage-yield/SKILL.md`](./leverage-yield/SKILL.md) | "leverage yield vault", "vault UI / screen / dashboard", "deposit into a vault", "lsoda shares", "vault APR / TVL", "useLeverageYieldDeposit", "useLeverageYieldVaultSwap", "open a leverage position" |
|
|
35
|
+
| ICX / bnUSD / BALN token migration | [`./migration/SKILL.md`](./migration/SKILL.md) | "useMigrateIcxToSoda", "migrate bnUSD" (NOT v1→v2 porting) |
|
|
36
|
+
| Bitcoin trading via Radfi | [`./bitcoin/SKILL.md`](./bitcoin/SKILL.md) | "useRadfiAuth", "trading wallet", "Bound Exchange" |
|
|
37
|
+
| Partner fees, recovery, backend reads, the Swaps / Bridge / Leverage Yield API hooks, Stellar account activation, shared utilities (balances, gas, trustlines) | [`./auxiliary-services/SKILL.md`](./auxiliary-services/SKILL.md) | "useFeeClaimSwap", "useWithdrawHubAsset", "useBackendIntentByTxHash", "useSwapsApiQuote", "useLeverageYieldApi*", "useStellarGate", "useXBalances" |
|
|
38
|
+
|
|
39
|
+
Load this broad skill (keep reading below) when the feature is undecided, the task spans several features, or the consumer is porting a full v1 codebase.
|
|
40
|
+
|
|
23
41
|
---
|
|
24
42
|
|
|
25
43
|
## Integration mode (writing new v2 code)
|
|
26
44
|
|
|
27
45
|
Pick this mode when the consumer is a React dapp using `@sodax/dapp-kit` hooks. Common signals:
|
|
28
46
|
|
|
29
|
-
- Any feature hook: `useSwap`, `useMoneyMarket*`, `useStake`, `useBridge`, `useDex*`, `useMigrate*`, `useRadfi*`, `usePartner*`, `useRecovery*`.
|
|
47
|
+
- Any feature hook: `useSwap`, `useMoneyMarket*`, `useStake`, `useBridge`, `useDex*`, `useLeverageYield*`, `useMigrate*`, `useRadfi*`, `usePartner*`, `useRecovery*`.
|
|
30
48
|
- "Wire React Query for SODAX" — `SodaxProvider`, `createSodaxQueryClient`.
|
|
31
49
|
- "Branch on mutation result without try/catch" — `mutateAsyncSafe`.
|
|
32
50
|
- "Custom invalidation on success" — consumer-provided `onSuccess` (note: hook-owned invalidations already run; yours runs *after*).
|
|
@@ -36,8 +54,8 @@ Pick this mode when the consumer is a React dapp using `@sodax/dapp-kit` hooks.
|
|
|
36
54
|
1. Read [`integration/knowledge/ai-rules.md`](./integration/knowledge/ai-rules.md) — DO / DO NOT / workflow / stop conditions.
|
|
37
55
|
2. Read [`integration/knowledge/quickstart.md`](./integration/knowledge/quickstart.md) — install + wire providers + first feature.
|
|
38
56
|
3. Read [`integration/knowledge/architecture.md`](./integration/knowledge/architecture.md) — hook shapes, queryKey conventions, `useSafeMutation`, `unwrapResult`, `Result<T>`.
|
|
39
|
-
4. For each feature you use, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `migration.md`, `bitcoin.md` (Bound Exchange, dapp-kit-unique), `auxiliary-services.md` (partner + recovery + backend + shared).
|
|
40
|
-
5. Recipes → [`integration/knowledge/recipes/`](./integration/knowledge/recipes/) — `setup.md`, `wallet-connectivity.md`, per-feature, `mutation-error-handling.md`, `observability.md`, `invalidations.md`.
|
|
57
|
+
4. For each feature you use, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `leverage-yield.md` (vaults + leverage positions), `migration.md`, `bitcoin.md` (Bound Exchange, dapp-kit-unique), `auxiliary-services.md` (partner + recovery + backend + shared).
|
|
58
|
+
5. Recipes → [`integration/knowledge/recipes/`](./integration/knowledge/recipes/) — `setup.md`, `wallet-connectivity.md`, per-feature, `mutation-error-handling.md`, `observability.md`, `invalidations.md`. Building a user-facing leverage-yield vault screen → [`leverage-yield-product-anatomy.md`](./integration/knowledge/recipes/leverage-yield-product-anatomy.md).
|
|
41
59
|
6. Lookups → [`integration/knowledge/reference/`](./integration/knowledge/reference/) — `hooks-index.md`, `querykey-conventions.md`, `public-api.md`, `glossary.md`.
|
|
42
60
|
|
|
43
61
|
### v2 in one minute
|
|
@@ -46,7 +64,7 @@ Pick this mode when the consumer is a React dapp using `@sodax/dapp-kit` hooks.
|
|
|
46
64
|
2. **Every mutation hook returns `SafeUseMutationResult`** — extends React Query's `UseMutationResult` with `mutateAsyncSafe(vars): Promise<Result<TData>>` (never rejects). Use `mutateAsyncSafe` for sequenced flows; `mutateAsync` for try/catch flows; `mutate` for fire-and-forget render-driven flows.
|
|
47
65
|
3. **`mutationFn` throws on SDK `!ok`.** dapp-kit calls `unwrapResult` on the SDK's `Result<T>`, throwing on failure. This makes React Query's native error model engage (`isError`, `error`, `onError`, `retry`, devtools). `mutateAsyncSafe` packages the throw back into `Result<T>` for ergonomic branching.
|
|
48
66
|
4. **Hook-owned invalidations.** Each mutation hook invalidates the relevant query keys in its `onSuccess`, derived from `vars`. Consumer-provided `onSuccess` runs after. v1's manual `invalidateMmQueries` utilities are gone.
|
|
49
|
-
5. **Canonical queryKey shape.** `[feature, action, ...identifiers]`. First segment matches the directory name (`swap`, `mm`, `bridge`, `staking`, `dex`, `bitcoin`, `partner`, `recovery`, `backend`, `shared`, `migrate`). camelCase. Bigints stringified.
|
|
67
|
+
5. **Canonical queryKey shape.** `[feature, action, ...identifiers]`. First segment matches the directory name (`swap`, `mm`, `bridge`, `staking`, `dex`, `leverageYield`, `bitcoin`, `partner`, `recovery`, `backend`, `shared`, `migrate`). camelCase. Bigints stringified.
|
|
50
68
|
|
|
51
69
|
### Conventions agents must follow (integration)
|
|
52
70
|
|
|
@@ -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
|
|
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 backend API client hooks (Swaps: useSwapsApiQuote, useSwapsApiSubmitTx, useSwapsApiStatus; Bridge: useBridgeApi*; Leverage Yield: useLeverageYieldApi*, e.g. useLeverageYieldApiVaults, useLeverageYieldApiSubmitTxStatus), 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'
|
|
@@ -40,6 +40,9 @@ DO / DO NOT / workflow / stop conditions for AI agents writing v2 dapp-kit code.
|
|
|
40
40
|
- **DO NOT** destructure cross-chain mutation results as arrays — `[a, b] = result.value` is wrong. The shape is `TxHashPair = { srcChainTxHash, dstChainTxHash }` (object). This applies to `useBridge`, `useStake`/`useUnstake`/etc., `useDexDeposit`/`useDexWithdraw`, all four MM mutations, and all four migration mutations.
|
|
41
41
|
- **DO NOT** use legacy chain-id constants (`BSC_MAINNET_CHAIN_ID`, etc.). They're gone in v2 — use `ChainKeys.X_MAINNET`.
|
|
42
42
|
- **DO NOT** reach for `as any` / `as IEvmWalletProvider` casts when wiring `useWalletProvider({ xChainId })` into mutation `mutate(vars)`. v2 supports the broad-union case structurally; the cast is not needed. See `recipes/wallet-connectivity.md` § "No type cast is needed".
|
|
43
|
+
- **DO NOT** send a zero or hand-picked minimum output (`minOutputAmount: 0n` or a literal). Derive it from a live quote for that exact input minus a slippage tolerance in basis points, show both to the user before they sign, and disable the action while there is no quote. The SDK does not reject a zero minimum (swaps and bridge only enforce the 546-sat dust floor on a BTC payout); a zero minimum accepts any fill.
|
|
44
|
+
- **DO NOT** add a `partnerFee` the integrator did not ask for. It is optional; omit it by default, and never copy a fee receiver address from a SODAX demo, doc, or example.
|
|
45
|
+
- **DO NOT** pass `skipSimulation: true` in user-facing flows. The simulation replays the hub-side execution and catches an intent that would revert there before the user signs it.
|
|
43
46
|
|
|
44
47
|
## Stop conditions (defer to user)
|
|
45
48
|
|
|
@@ -456,6 +456,14 @@ and origin gating are the real controls. Proxy through your own backend if that
|
|
|
456
456
|
| Reserves data (mm) | 5s | `useReservesData` / `useReservesHumanized` / user position hooks |
|
|
457
457
|
| `useBalances` | 5s | refetchInterval |
|
|
458
458
|
| `useXBalances` | 5s | refetchInterval |
|
|
459
|
+
| `useLeverageYieldQuote` | 3s | refetchInterval; solver prices go stale |
|
|
460
|
+
| `useLeverageYieldDetailedStatus` | 3s | stops on the answering source's terminal state |
|
|
461
|
+
| `useLeverageYieldApiStatus` / `useLeverageYieldApiSubmitTxStatus` | 1s | stop on a terminal status |
|
|
462
|
+
| `useLeverageYieldShareBalances` | 15s | per holder |
|
|
463
|
+
| `useLeverageYieldPosition` | 30s | refetchInterval |
|
|
464
|
+
| `useLeverageYieldEffectiveApr` / `useLeverageYieldTotalAssets` / `useLeverageYieldPreviewRedeem` | 60s | Sonic RPC reads with no multicall: one APR refresh is six `eth_call`s per vault, so don't shorten these on a vault grid |
|
|
465
|
+
| `useLeveragePositionAccount` / `useLeveragePositionCollateral` | 30s | refetchInterval |
|
|
466
|
+
| `useLeveragePositionPending` | 15s | refetchInterval |
|
|
459
467
|
| Most others | None | |
|
|
460
468
|
|
|
461
469
|
All overridable via `queryOptions.refetchInterval`.
|
|
@@ -24,8 +24,14 @@ useLeverageYieldPosition({ params, queryOptions }); // collateral/debt/ltv/
|
|
|
24
24
|
useLeverageYieldTotalAssets({ params, queryOptions }); // vault TVL, 18-dp bigint (60s)
|
|
25
25
|
useLeverageYieldPreviewRedeem({ params, queryOptions }); // assets for N shares; price-per-share (60s)
|
|
26
26
|
useLeverageYieldShareBalances({ params, queryOptions }); // per-chain share balances via useQueries (15s)
|
|
27
|
+
|
|
28
|
+
// Vault registry — no hook; static SDK config, read synchronously
|
|
29
|
+
const { sodax } = useSodaxContext();
|
|
30
|
+
const vaults = useMemo(() => sodax.leverageYield.listVaults(), [sodax]); // { name, vault, asset, borrowToken, lsdSource? }[]
|
|
27
31
|
```
|
|
28
32
|
|
|
33
|
+
Every read and builder takes the vault's `vault` field (the `lsoda*` proxy address). `useLeverageYieldApiVaults` is the backend REST equivalent of `listVaults()`. For symbols, logos, USD prices and a single units table, see [`../recipes/leverage-yield-product-anatomy.md`](../recipes/leverage-yield-product-anatomy.md).
|
|
34
|
+
|
|
29
35
|
`deposit` / `withdraw` are **builders** — they assemble a `LeverageYieldSwapPayload`, they do NOT broadcast. Spread the built payload into `useLeverageYieldVaultSwap`'s `mutate`, adding the `walletProvider`. `vaultSwap` takes the **backend submit-tx** path by default and falls back to the client-side relay on any non-success, so track the result with `useLeverageYieldDetailedStatus` — it keys on the source tx and answers for whichever path completed. Pass `extras.apiKey` in `mutate` to key the backend leg per action. There is no dedicated leverage-yield approve hook: the swap-style deposit approves the spoke-side asset manager, so reuse `useSwapApprove` / `useSwapAllowance` (see Approval pattern).
|
|
30
36
|
|
|
31
37
|
`use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
|
|
@@ -65,12 +71,15 @@ type UseLeverageYieldNotifySolverVars = SolverExecutionRequest;
|
|
|
65
71
|
useLeverageYieldEffectiveApr({ params: { vault } })
|
|
66
72
|
// → UseQueryResult<LeverageYieldEffectiveApr>
|
|
67
73
|
// LeverageYieldEffectiveApr = LeverageYieldApr & { lsdApr, effectiveSupplyAprRay, effectiveNetAprRay }
|
|
68
|
-
// LeverageYieldApr = { supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }
|
|
74
|
+
// LeverageYieldApr = { supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }
|
|
75
|
+
// rates RAY (1e27); targetLtvBps basis points (8_200 = 82%); leverageMultiplierWad WAD (1e18) and the
|
|
76
|
+
// BORROWED multiple, targetLTV / (1 − targetLTV) — total exposure is 1 + multiplier
|
|
69
77
|
|
|
70
78
|
// useLeverageYieldPosition — live position snapshot
|
|
71
79
|
useLeverageYieldPosition({ params: { vault } })
|
|
72
80
|
// → UseQueryResult<LeverageYieldPosition>
|
|
73
81
|
// LeverageYieldPosition = { collateral, debt, ltv, healthFactor, idleAsset } (all bigint)
|
|
82
|
+
// ltv basis points (10_000 = 100%); healthFactor WAD; amounts 18 dp
|
|
74
83
|
|
|
75
84
|
// useLeverageYieldPreviewRedeem — assets per shares; pass 1e18 for price-per-share
|
|
76
85
|
useLeverageYieldPreviewRedeem({ params: { vault, shares: 10n ** 18n } })
|
|
@@ -123,6 +132,9 @@ Branch on `data?.ok` for those two hooks only.
|
|
|
123
132
|
5. **Quote vault flows with `useLeverageYieldQuote`, never `useQuote`.** `useQuote` deducts the effective *swap* fee (`swaps.partnerFee ?? fee`) while a vault intent charges the effective *leverage-yield* fee (`leverageYield.partnerFee ?? fee`) — they disagree whenever the two feature fees differ, and when the leverage-yield one is larger the `minOutputAmount` you derive is unfillable and the intent never settles. Pass the same per-intent `partnerFee` to `useLeverageYieldQuote` and to `useLeverageYieldDeposit` / `useLeverageYieldVaultSwap`, or omit it on both — either way the two sides resolve the same fee.
|
|
124
133
|
6. **`useLeverageYieldVaultSwap` invalidates xBalances on both chains** (`['shared', 'xBalances', srcChainKey]` and `dstChainKey`) on success. Compose your own `onSuccess` after the hook's — it runs first.
|
|
125
134
|
7. **`useLeverageYieldNotifySolver` is for the manual flow only.** `useLeverageYieldVaultSwap` already notifies the solver internally — only reach for the standalone notify hook when you built the intent with `sodax.leverageYield.createVaultIntent` and relayed it yourself. It does NOT invalidate any queries: its only var is `{ intent_tx_hash }` (no chain context), and the fill lands asynchronously afterward.
|
|
135
|
+
8. **Never send `minOutputAmount: 0n`.** Size it from `useLeverageYieldQuote`'s `quoted_amount` minus a slippage tolerance in basis points, and keep the deposit disabled until the quote is `ok`. A zero minimum accepts any fill.
|
|
136
|
+
9. **Show "Leverage" as `1 + leverageMultiplierWad`.** The multiplier is the borrowed multiple (4.56× at an 82% target LTV); the exposure a depositor holds is 5.56×.
|
|
137
|
+
10. **Don't shorten the vault-stat intervals.** One `useLeverageYieldEffectiveApr` refresh is six Sonic `eth_call`s plus a DefiLlama fetch per vault, with no multicall. A grid of vault cards on the defaults is already the heavy part of the page.
|
|
126
138
|
|
|
127
139
|
## Leverage positions (separate from vaults)
|
|
128
140
|
|
|
@@ -36,6 +36,7 @@ Copy-paste patterns for adding SODAX features to a React app. Each recipe is sel
|
|
|
36
36
|
| [`migration.md`](migration.md) | `useMigrateIcxToSoda`, `useRevertMigrateSodaToIcx`, `useMigratebnUSD`, `useMigrateBaln` |
|
|
37
37
|
| [`dex.md`](dex.md) | `useDexDeposit`, `useSupplyLiquidity`, positions, pools |
|
|
38
38
|
| [`leverage-yield.md`](leverage-yield.md) | `useLeverageYieldDeposit`, `useLeverageYieldWithdraw`, `useLeverageYieldVaultSwap`, APR/position/TVL/share-balance reads |
|
|
39
|
+
| [`leverage-yield-product-anatomy.md`](leverage-yield-product-anatomy.md) | A user-facing vault screen: journey, states, display metadata, USD prices, derived values, units, planned steps + explorer links, acceptance |
|
|
39
40
|
| [`bitcoin.md`](bitcoin.md) | `useRadfiSession`, `useFundTradingWallet`, `useRadfiWithdraw`, UTXO management |
|
|
40
41
|
| [`backend-queries.md`](backend-queries.md) | Intent tracking, orderbook, money market position queries (read-only, no wallet) |
|
|
41
42
|
|
|
@@ -186,15 +186,30 @@ function Position({ positionId, poolKey }: { positionId: bigint; poolKey: PoolKe
|
|
|
186
186
|
|
|
187
187
|
## Remove Liquidity
|
|
188
188
|
|
|
189
|
+
Size `amount0Min` / `amount1Min` from the position with `useCreateDecreaseLiquidityParams` (slippage in percent). Zero minimums accept any price. It throws during render when `percentage` or `slippageTolerance` is outside (0, 100], so clamp slider and input values before passing them.
|
|
190
|
+
|
|
189
191
|
```tsx
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
})
|
|
192
|
+
import { isUserRejectedError, useCreateDecreaseLiquidityParams, useDecreaseLiquidity } from '@sodax/dapp-kit';
|
|
193
|
+
import { useWalletProvider } from '@sodax/wallet-sdk-react';
|
|
194
|
+
import { ChainKeys, type Address, type ClPositionInfo, type PoolKey } from '@sodax/sdk';
|
|
195
|
+
|
|
196
|
+
function RemoveLiquidity({ poolKey, tokenId, positionInfo, srcAddress }: { poolKey: PoolKey; tokenId: bigint; positionInfo: ClPositionInfo; srcAddress: Address }) {
|
|
197
|
+
const walletProvider = useWalletProvider({ xChainId: ChainKeys.BASE_MAINNET });
|
|
198
|
+
const { mutateAsyncSafe: decreaseLiquidity, isPending } = useDecreaseLiquidity();
|
|
199
|
+
// positionInfo from usePositionInfo({ params: { tokenId: tokenId.toString(), poolKey } }).data.positionInfo
|
|
200
|
+
const decrease = useCreateDecreaseLiquidityParams({ poolKey, tokenId, percentage: 50, positionInfo, slippageTolerance: 1 });
|
|
201
|
+
|
|
202
|
+
const onRemove = async () => {
|
|
203
|
+
if (!walletProvider) return;
|
|
204
|
+
const result = await decreaseLiquidity({
|
|
205
|
+
params: { ...decrease, srcChainKey: ChainKeys.BASE_MAINNET, srcAddress },
|
|
206
|
+
walletProvider,
|
|
207
|
+
});
|
|
208
|
+
if (!result.ok && !isUserRejectedError(result.error)) console.error(result.error); // surface it in your UI
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
return <button onClick={onRemove} disabled={isPending || !walletProvider}>Remove 50%</button>;
|
|
212
|
+
}
|
|
198
213
|
```
|
|
199
214
|
|
|
200
215
|
## Notes
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# Leverage-yield vault app — product anatomy
|
|
2
|
+
|
|
3
|
+
What a user-facing vault screen has to let people **answer and do**, which hook answers it, the
|
|
4
|
+
states to handle, and how to derive the numbers people read. It describes structure, not layout:
|
|
5
|
+
grid or list, modal or page, tabs, and where risk copy sits are the builder's call.
|
|
6
|
+
|
|
7
|
+
Vaults only. Leverage positions are a different product (see [`../features/leverage-yield.md`](../features/leverage-yield.md) § Leverage positions).
|
|
8
|
+
Call shapes for every hook here are in [`leverage-yield.md`](leverage-yield.md).
|
|
9
|
+
|
|
10
|
+
## The journey
|
|
11
|
+
|
|
12
|
+
| Step | The user must be able to answer | Source |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| **Discover** | Which vaults exist, and what each one holds | `sodax.leverageYield.listVaults()` (no hook; see [Display metadata](#display-metadata)) |
|
|
15
|
+
| **Evaluate** | What does it earn (and can that change)? How big is it? How much leverage and how healthy? What is one share worth? | `useLeverageYieldEffectiveApr`, `useLeverageYieldTotalAssets`, `useLeverageYieldPosition`, `useLeverageYieldPreviewRedeem`, USD via `useReservesUsdFormat` |
|
|
16
|
+
| **Deposit** | From which network and token? What will I receive, and what is the least I accept? Which steps will I sign? | `useLeverageYieldQuote` (vault as `token_dst`), `useSwapAllowance`, `useXBalances` |
|
|
17
|
+
| **Track** | Where is my deposit now, and where can I see each transaction? | `useLeverageYieldDetailedStatus`, [explorer links](#planned-steps-and-explorer-links) |
|
|
18
|
+
| **Hold** | How many shares do I have, on which network, and what are they worth in the asset and in USD? What might they earn? | `useLeverageYieldShareBalances`, `useLeverageYieldPreviewRedeem`, [derived values](#derived-values) |
|
|
19
|
+
| **Withdraw** | How much can I take out, to which token and network, and what is the least I accept? | share balance, `useLeverageYieldQuote` (vault as `token_src`), `useLeverageYieldWithdraw` |
|
|
20
|
+
|
|
21
|
+
## Concepts users get wrong
|
|
22
|
+
|
|
23
|
+
- **Shares are not in the wallet extension.** They live in the user's SODAX hub wallet on Sonic, and there is one hub wallet per source network **and** address. Depositing from Base and from Arbitrum makes two separate share balances. A withdraw spends the shares of the hub wallet it is signed for, so it must be signed on the network, from the address, that deposited. Show balances per network (`useLeverageYieldShareBalances` takes one holder per network).
|
|
24
|
+
- **The APR is a variable estimate.** `effectiveNetAprRay` is steady-state: it assumes today's rates hold and the vault stays at its target LTV. It can go negative when borrowing costs more than the supply side earns. `lsdApr.stale === true` means the staking part is a fallback figure, so label it as an estimate.
|
|
25
|
+
- **Leverage multiplies risk too.** Show exposure as `1 + leverageMultiplierWad` (see [Units](#units)); the multiplier alone is the borrowed part. The health factor is the vault's, not the user's.
|
|
26
|
+
- **A deposit is an intent, not a transfer.** The user signs on their network, SODAX delivers it to Sonic, and a solver fills it. There are no partial fills: an intent whose minimum can no longer be met is not filled, and it expires at its deadline (by default five minutes after the hub block time when it was built). `useLeverageYieldDetailedStatus` then answers from the solver (`FAILED` is status `4`) or keeps reading not-found and stops polling after 40 such reads; give the user a timeout of your own rather than waiting forever. When `vaultSwap` took the backend path (the default), the backend's own record (`userMessage`, `failureReason`, and `relayedForRefundAt` once an expired intent was relayed for refund) is readable with `useLeverageYieldApiSubmitTxStatus` from the source tx and `srcChainKey`: the detailed status routes a failed or abandoned backend record to the solver instead of returning it. Don't promise where or when a refund lands; show the status and, if assets are left in the hub wallet, offer the recovery hooks (`useHubAssetBalances`, `useWithdrawHubAsset`, in [`../features/auxiliary-services.md`](../features/auxiliary-services.md)).
|
|
27
|
+
|
|
28
|
+
## States
|
|
29
|
+
|
|
30
|
+
Handle every row; how each one looks is up to the builder.
|
|
31
|
+
|
|
32
|
+
| State | Detect it with | What the user needs |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| No quote yet / amount empty | `useLeverageYieldQuote` `data === undefined` | The action disabled, with the reason |
|
|
35
|
+
| Amount too low, too high, **or** no route | quote `data.ok === false`, `!isSodaxError(data.error)` and `isNoRouteRefusal(data.error)` | The solver answers all three the same way. Re-quote a mid-size amount to tell them apart: suggest a larger amount only when the refused one was below it, a smaller one only when it was above; otherwise "no route right now, try again shortly" |
|
|
36
|
+
| Other solver refusal | quote `!ok`, not a `SodaxError`: `data.error.detail.code` (`SolverIntentErrorCode`) | The solver's message and a retry |
|
|
37
|
+
| Invalid input | quote `!ok`, `isSodaxError(data.error)` with `code === 'VALIDATION_FAILED'` | Which input to fix |
|
|
38
|
+
| Quote moved | The quote refreshes every 3s | The minimum recomputed on every refresh, and the amounts shown again right before signing |
|
|
39
|
+
| Needs approval | `useSwapAllowance` → `false` (deposits only) | An approve step before the deposit step |
|
|
40
|
+
| Approval takes two prompts | Some tokens (Ethereum USDT today) need `approve(0)` first; the hook still returns one hash | A note that the wallet may ask twice |
|
|
41
|
+
| Wrong network | `useEvmSwitchChain` → `isWrongChain` (load the `sodax-wallet-sdk-react` skill) | A switch-network action instead of the deposit button |
|
|
42
|
+
| Not enough balance or gas | No dedicated error code: compare against `useXBalances` before signing | The shortfall, before they sign |
|
|
43
|
+
| Would revert on the hub | `vaultSwap` simulates the hub-side execution (not for a Sonic source) and fails with `INTENT_CREATION_FAILED`, the RPC revert as `cause` | That the deposit would fail, before they sign |
|
|
44
|
+
| User rejected in the wallet | `isUserRejectedError(result.error)` | Back to the form silently; not an error toast |
|
|
45
|
+
| In flight | `useLeverageYieldDetailedStatus` → `data.ok` with a non-terminal status; `!ok` with `error.context.reason === DETAILED_STATUS_NOT_DELIVERED` means not delivered yet | The current step, and that it is safe to wait |
|
|
46
|
+
| Filled | backend `data.value.data.status === 'solved'`, or solver `data.value.data.status === 3` | Shares shown (they arrive in the hub wallet) |
|
|
47
|
+
| Failed or expired | solver `data.value.data.status === 4` (a failed or abandoned backend record is routed to the solver), or still not found after your own timeout. For `userMessage` / `failureReason` on the backend path, read `useLeverageYieldApiSubmitTxStatus` | What happened and where the funds are, per [Concepts](#concepts-users-get-wrong) |
|
|
48
|
+
| Withdraw more than held | Cap `inputAmount` at the share balance. `getMaxWithdraw*` is in **asset** units, not shares | A max button sized from shares |
|
|
49
|
+
|
|
50
|
+
## Planned steps and explorer links
|
|
51
|
+
|
|
52
|
+
Show the steps before the user signs, then mark each one as it completes. Explorer URL: `baseChainInfo[chainKey].explorer.txUrl + hash`. There is no SDK URL helper.
|
|
53
|
+
|
|
54
|
+
| Deposit step | Transaction | Link on |
|
|
55
|
+
|---|---|---|
|
|
56
|
+
| 1. Approve (only if `useSwapAllowance` is `false`; may be two prompts) | the approve hash | the source network |
|
|
57
|
+
| 2. Sign the deposit on the source network | `intentDeliveryInfo.srcTxHash` | the source network |
|
|
58
|
+
| 3. Deliver to Sonic | `intentDeliveryInfo.dstTxHash` (equals `srcTxHash` when the source is Sonic) | Sonic |
|
|
59
|
+
| 4. Solver fills; shares land in the hub wallet | `result.fillTxHash` on the backend status, or `fill_tx_hash` on the solver status. It may be absent even when filled | the fill's destination network: Sonic for a deposit |
|
|
60
|
+
|
|
61
|
+
A withdraw has no approve step: 1. sign on the network that deposited, 2. deliver to Sonic, 3. solver fills and pays out on `dstChainKey`. `useLeverageYieldVaultSwap` can resolve before the fill on its client-side fallback path, so keep polling `useLeverageYieldDetailedStatus` until a terminal status.
|
|
62
|
+
|
|
63
|
+
## Display metadata
|
|
64
|
+
|
|
65
|
+
The registry entry has no symbol or logo. Both the `lsoda*` share token and the vault's asset are in the hub token config, so resolve them by address and take the logo from the symbol:
|
|
66
|
+
|
|
67
|
+
```tsx
|
|
68
|
+
import { useMemo } from 'react';
|
|
69
|
+
import { tokenLogo, useSodaxContext, type LeverageYieldVault } from '@sodax/dapp-kit';
|
|
70
|
+
|
|
71
|
+
function useVaultDisplay(vault: LeverageYieldVault) {
|
|
72
|
+
const { sodax } = useSodaxContext();
|
|
73
|
+
return useMemo(() => {
|
|
74
|
+
const share = sodax.config.getXTokenFromHubAsset(vault.vault); // lsoda* symbol + decimals
|
|
75
|
+
const asset = sodax.config.getXTokenFromHubAsset(vault.asset); // underlying symbol, e.g. weETH
|
|
76
|
+
return {
|
|
77
|
+
shareSymbol: share?.symbol ?? vault.name,
|
|
78
|
+
assetSymbol: asset?.symbol,
|
|
79
|
+
assetDecimals: asset?.decimals ?? 18,
|
|
80
|
+
logo: tokenLogo(asset?.symbol ?? vault.name),
|
|
81
|
+
};
|
|
82
|
+
}, [sodax, vault]);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`tokenLogo(symbol)` serves the `@sodax/assets` PNGs; both the `lsoda*` and the underlying logos exist. Pick one per screen and keep it consistent.
|
|
87
|
+
|
|
88
|
+
## USD prices
|
|
89
|
+
|
|
90
|
+
Use one source: the money-market reserve prices. Every vault asset is a money-market reserve, keyed by `underlyingAsset`, which equals `vault.asset`. One `useReservesUsdFormat` call prices every vault.
|
|
91
|
+
|
|
92
|
+
```tsx
|
|
93
|
+
import { useReservesUsdFormat } from '@sodax/dapp-kit';
|
|
94
|
+
|
|
95
|
+
function useAssetUsdPrice(asset: string): number | undefined {
|
|
96
|
+
const { data: reserves } = useReservesUsdFormat();
|
|
97
|
+
const reserve = reserves?.find((r) => r.underlyingAsset.toLowerCase() === asset.toLowerCase());
|
|
98
|
+
return reserve ? Number(reserve.priceInUSD) : undefined; // USD per whole token, from the pool oracle
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
USD figures are for display only. Never size `minOutputAmount` from them: that comes from the quote.
|
|
103
|
+
|
|
104
|
+
## Derived values
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { formatUnits } from 'viem';
|
|
108
|
+
|
|
109
|
+
const WAD = 10n ** 18n;
|
|
110
|
+
const RAY = 10n ** 27n;
|
|
111
|
+
|
|
112
|
+
/** Asset units for `shares`, from `useLeverageYieldPreviewRedeem({ params: { vault, shares: WAD } })`. */
|
|
113
|
+
export const shareValue = (shares: bigint, pricePerShare: bigint): bigint => (shares * pricePerShare) / WAD;
|
|
114
|
+
|
|
115
|
+
/** Exposure the depositor holds, in WAD: 1 + the borrowed multiple. */
|
|
116
|
+
export const exposureWad = (leverageMultiplierWad: bigint): bigint => WAD + leverageMultiplierWad;
|
|
117
|
+
|
|
118
|
+
/** Simple-interest projection over `days` at today's APR (asset units). Can be negative. */
|
|
119
|
+
export const projectedInterest = (assets: bigint, aprRay: bigint, days: bigint): bigint =>
|
|
120
|
+
(assets * aprRay * days) / (365n * RAY);
|
|
121
|
+
|
|
122
|
+
export const toUsd = (amount: bigint, decimals: number, priceUsd: number): number =>
|
|
123
|
+
Number(formatUnits(amount, decimals)) * priceUsd;
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Label projections as estimates at today's variable APR, and keep the sign: a negative APR projects a loss.
|
|
127
|
+
|
|
128
|
+
## Units
|
|
129
|
+
|
|
130
|
+
| Value | Unit | Display as |
|
|
131
|
+
|---|---|---|
|
|
132
|
+
| `*AprRay` (`effectiveNetAprRay`, `netAprRay`, …) | RAY, `1e27` = 100% | `Number(v * 10_000n / RAY) / 100` → percent |
|
|
133
|
+
| `targetLtvBps`, position `ltv` | basis points, `10_000` = 100% | `/ 100` → percent |
|
|
134
|
+
| `leverageMultiplierWad` | WAD, borrowed multiple | `1 +` it, as `×` |
|
|
135
|
+
| `healthFactor` | WAD; below `1e18` is liquidatable; `maxUint256` means no debt | `v === maxUint256 ? 'no debt' : formatUnits(v, 18)` |
|
|
136
|
+
| Shares (`lsoda*`) | 18 decimals | `formatUnits(v, 18)` |
|
|
137
|
+
| `getTotalAssets`, `previewRedeem`, position `collateral` / `debt` / `idleAsset` | the vault asset's units (18 decimals today) | `formatUnits(v, assetDecimals)`, then USD |
|
|
138
|
+
| `priceInUSD` | decimal string, USD per whole token | `Number(v)` |
|
|
139
|
+
|
|
140
|
+
## Acceptance
|
|
141
|
+
|
|
142
|
+
The flow is done when the user can:
|
|
143
|
+
|
|
144
|
+
- see every vault with its asset, APR (marked as variable, sign kept), TVL in the asset and USD, exposure, and health;
|
|
145
|
+
- see what they will receive, the minimum they accept, and the steps they will sign, before signing;
|
|
146
|
+
- sign without a zero or hand-picked minimum, and without an unrequested partner fee;
|
|
147
|
+
- follow each step to completion, with a link to each transaction on the right explorer;
|
|
148
|
+
- see their shares per network, worth in the asset and in USD;
|
|
149
|
+
- withdraw from the network that deposited, with the amount capped at their shares;
|
|
150
|
+
- cancel in the wallet without an error, and read a clear message for every state in [States](#states).
|
|
@@ -4,6 +4,8 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
4
4
|
|
|
5
5
|
**Depends on:** [setup.md](setup.md), [wallet-connectivity.md](wallet-connectivity.md)
|
|
6
6
|
|
|
7
|
+
**Building a user-facing screen?** Start from [leverage-yield-product-anatomy.md](leverage-yield-product-anatomy.md): what each step must answer, the states, USD and derived values, and the units table.
|
|
8
|
+
|
|
7
9
|
## Hooks
|
|
8
10
|
|
|
9
11
|
### Mutations
|
|
@@ -41,12 +43,28 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
41
43
|
|
|
42
44
|
> A deposit is a swap-style intent, so it approves the **spoke asset manager** via the swap-domain hooks — there is no leverage-yield-specific approve hook. A withdraw carries `hubWalletSwap: true` and needs no spoke approval.
|
|
43
45
|
|
|
46
|
+
## List the vaults
|
|
47
|
+
|
|
48
|
+
dapp-kit has no hook for the vault registry: it is static SDK config, so read it synchronously. Each entry is `{ name, vault, asset, borrowToken, lsdSource? }`; pass `vault` (the `lsoda*` proxy address, also the share token) as every hook's `vault` param. `useLeverageYieldApiVaults` is the backend REST equivalent.
|
|
49
|
+
|
|
50
|
+
```tsx
|
|
51
|
+
import { useMemo } from 'react';
|
|
52
|
+
import { useSodaxContext } from '@sodax/dapp-kit';
|
|
53
|
+
|
|
54
|
+
function useVaults() {
|
|
55
|
+
const { sodax } = useSodaxContext();
|
|
56
|
+
return useMemo(() => sodax.leverageYield.listVaults(), [sodax]);
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
44
60
|
## Vault stats + position
|
|
45
61
|
|
|
62
|
+
`leverageMultiplierWad` (on the APR result) is the **borrowed** multiple, `targetLTV / (1 − targetLTV)`; total exposure is `1 + multiplier`, so a "Leverage" label shows the sum. `targetLtvBps` and `position.ltv` are basis points (`8_200` = 82%); `healthFactor` and the multiplier are WAD.
|
|
63
|
+
|
|
46
64
|
```tsx
|
|
47
65
|
import { useLeverageYieldEffectiveApr, useLeverageYieldTotalAssets, useLeverageYieldPreviewRedeem, useLeverageYieldPosition } from '@sodax/dapp-kit';
|
|
48
66
|
import type { Address } from '@sodax/sdk';
|
|
49
|
-
import { formatUnits } from 'viem';
|
|
67
|
+
import { formatUnits, maxUint256 } from 'viem';
|
|
50
68
|
|
|
51
69
|
const RAY = 10n ** 27n;
|
|
52
70
|
|
|
@@ -66,12 +84,14 @@ function VaultStats({ vault }: { vault: Address }) {
|
|
|
66
84
|
{netAprPct !== undefined && <p>Net APR: {netAprPct.toFixed(2)}%</p>}
|
|
67
85
|
{tvl !== undefined && <p>TVL: {formatUnits(tvl, 18)}</p>}
|
|
68
86
|
{sharePrice !== undefined && <p>1 share = {formatUnits(sharePrice, 18)} assets</p>}
|
|
69
|
-
{position && <p>Health factor: {formatUnits(position.healthFactor, 18)}</p>}
|
|
87
|
+
{position && <p>Health factor: {position.healthFactor === maxUint256 ? 'no debt' : formatUnits(position.healthFactor, 18)}</p>}
|
|
70
88
|
</div>
|
|
71
89
|
);
|
|
72
90
|
}
|
|
73
91
|
```
|
|
74
92
|
|
|
93
|
+
Keep these default intervals, especially on a grid of vault cards. There is no multicall: one `useLeverageYieldEffectiveApr` refresh is six Sonic `eth_call`s plus a DefiLlama fetch per vault, and the TVL, share-price and position reads add one call each. Shortening them multiplies RPC load for every open tab. For many vaults, the `useLeverageYieldApi*` reads cost one HTTPS request each and no browser RPC.
|
|
94
|
+
|
|
75
95
|
## Share balances across chains
|
|
76
96
|
|
|
77
97
|
`useLeverageYieldShareBalances` returns an **array** — one query per holder. Build `holders` from the chains the user has connected, then aggregate.
|
|
@@ -90,85 +110,148 @@ function ShareTotal({ vault, holders }: { vault: Address; holders: { chainKey: S
|
|
|
90
110
|
|
|
91
111
|
## Deposit (any token → `lsoda*`)
|
|
92
112
|
|
|
93
|
-
|
|
113
|
+
Quote → derive the minimum → build → approve if needed → execute. The built payload is spread straight into `vaultSwap`. Never send `minOutputAmount: 0n`: it accepts any fill, however bad.
|
|
94
114
|
|
|
95
115
|
```tsx
|
|
96
|
-
// @ai-snippets-skip — illustrative end-to-end flow wiring the builder, the swap-domain
|
|
97
|
-
// allowance/approve hooks, and the executor across a broad walletProvider union. Real
|
|
98
|
-
// call shapes per hook are in features/leverage-yield.md.
|
|
99
116
|
import { useState } from 'react';
|
|
100
117
|
import {
|
|
101
|
-
|
|
118
|
+
isUserRejectedError, useLeverageYieldDeposit, useLeverageYieldQuote, useLeverageYieldVaultSwap,
|
|
119
|
+
useSodaxContext, useSwapApprove,
|
|
102
120
|
} from '@sodax/dapp-kit';
|
|
103
121
|
import { useWalletProvider } from '@sodax/wallet-sdk-react';
|
|
104
|
-
import { ChainKeys, type Address
|
|
105
|
-
import { parseUnits } from 'viem';
|
|
122
|
+
import { ChainKeys, type Address } from '@sodax/sdk';
|
|
123
|
+
import { formatUnits, isHex, parseUnits } from 'viem';
|
|
106
124
|
|
|
107
|
-
const
|
|
125
|
+
const SLIPPAGE_BPS = 100n; // 1%; let the user choose, but cap it
|
|
108
126
|
|
|
109
|
-
|
|
127
|
+
const errorMessage = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
|
128
|
+
|
|
129
|
+
/** Partial or invalid input (e.g. "1.2.3", "abc") parses to 0n instead of throwing during render. */
|
|
130
|
+
function toAmount(input: string, decimals: number): bigint {
|
|
131
|
+
try {
|
|
132
|
+
return parseUnits(input.trim(), decimals);
|
|
133
|
+
} catch {
|
|
134
|
+
return 0n;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function DepositForm({ vault, srcAddress, inputToken, decimals }: { vault: Address; srcAddress: string; inputToken: string; decimals: number }) {
|
|
110
139
|
const [amount, setAmount] = useState('');
|
|
140
|
+
const [error, setError] = useState<string>();
|
|
141
|
+
const [busy, setBusy] = useState(false); // spans build → approve → receipt → execute, not just the last mutation
|
|
142
|
+
const { sodax } = useSodaxContext();
|
|
111
143
|
const chainKey = ChainKeys.ARBITRUM_MAINNET;
|
|
112
144
|
const walletProvider = useWalletProvider({ xChainId: chainKey });
|
|
145
|
+
const inputAmount = toAmount(amount, decimals);
|
|
146
|
+
|
|
147
|
+
// Vault as token_dst quotes a deposit. Omit partnerFee here and on the builder unless you add your own.
|
|
148
|
+
const { data: quote } = useLeverageYieldQuote({
|
|
149
|
+
params: {
|
|
150
|
+
payload: inputAmount > 0n ? {
|
|
151
|
+
token_src: inputToken, token_src_blockchain_id: chainKey,
|
|
152
|
+
token_dst: vault, token_dst_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
153
|
+
amount: inputAmount, quote_type: 'exact_input',
|
|
154
|
+
} : undefined,
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
const minOutputAmount = quote?.ok ? (quote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n : undefined;
|
|
113
158
|
|
|
114
159
|
const { mutateAsyncSafe: buildDeposit } = useLeverageYieldDeposit();
|
|
115
160
|
const { mutateAsyncSafe: approve } = useSwapApprove();
|
|
116
|
-
const {
|
|
161
|
+
const { mutateAsyncSafe: vaultSwap, isPending } = useLeverageYieldVaultSwap();
|
|
162
|
+
|
|
163
|
+
const deposit = async (): Promise<string | undefined> => {
|
|
164
|
+
if (!walletProvider || minOutputAmount === undefined) return; // no quote, no deposit
|
|
165
|
+
const built = await buildDeposit({ vault, srcChainKey: chainKey, srcAddress, inputToken, inputAmount, minOutputAmount });
|
|
166
|
+
if (!built.ok) return errorMessage(built.error);
|
|
167
|
+
|
|
168
|
+
// Deposit approves the spoke asset manager (swap-style), only when the allowance is short.
|
|
169
|
+
const allowance = await sodax.swaps.isAllowanceValid({ params: built.value.params, walletProvider });
|
|
170
|
+
if (!allowance.ok) return errorMessage(allowance.error);
|
|
171
|
+
if (!allowance.value) {
|
|
172
|
+
const approval = await approve({ params: built.value.params, walletProvider });
|
|
173
|
+
if (!approval.ok) return isUserRejectedError(approval.error) ? undefined : errorMessage(approval.error);
|
|
174
|
+
// The deposit spends this allowance next, so it must be mined and must not have reverted.
|
|
175
|
+
if (isHex(approval.value)) {
|
|
176
|
+
try {
|
|
177
|
+
const receipt = await walletProvider.waitForTransactionReceipt(approval.value);
|
|
178
|
+
if (receipt.status === 'reverted' || receipt.status === '0x0') return 'Approval reverted';
|
|
179
|
+
} catch (e) {
|
|
180
|
+
return errorMessage(e);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const result = await vaultSwap({ ...built.value, walletProvider }); // lsoda* lands in the hub wallet
|
|
186
|
+
if (!result.ok && !isUserRejectedError(result.error)) return errorMessage(result.error);
|
|
187
|
+
};
|
|
117
188
|
|
|
118
189
|
const handleDeposit = async () => {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
126
|
-
if (!built.ok) return;
|
|
127
|
-
|
|
128
|
-
// Deposit approves the spoke asset manager (swap-style). Gate on useSwapAllowance in render.
|
|
129
|
-
await approve({ params: built.value.params, walletProvider });
|
|
130
|
-
await vaultSwap({ ...built.value, walletProvider }); // spread the payload; lsoda* lands in the hub wallet
|
|
190
|
+
setBusy(true);
|
|
191
|
+
setError(undefined);
|
|
192
|
+
try {
|
|
193
|
+
setError(await deposit());
|
|
194
|
+
} finally {
|
|
195
|
+
setBusy(false);
|
|
196
|
+
}
|
|
131
197
|
};
|
|
132
198
|
|
|
133
199
|
return (
|
|
134
200
|
<div>
|
|
135
201
|
<input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="amount" />
|
|
136
|
-
|
|
202
|
+
{quote?.ok && minOutputAmount !== undefined && (
|
|
203
|
+
<p>You receive ≈ {formatUnits(quote.value.quoted_amount, 18)} shares (at least {formatUnits(minOutputAmount, 18)})</p>
|
|
204
|
+
)}
|
|
205
|
+
{error && <p role="alert">{error}</p>}
|
|
206
|
+
<button onClick={handleDeposit} disabled={busy || isPending || !walletProvider || minOutputAmount === undefined}>Deposit</button>
|
|
137
207
|
</div>
|
|
138
208
|
);
|
|
139
209
|
}
|
|
140
210
|
```
|
|
141
211
|
|
|
212
|
+
Track the result with `useLeverageYieldDetailedStatus` until a terminal status: on its client-side fallback path, `vaultSwap` resolves before the solver fills.
|
|
213
|
+
|
|
142
214
|
## Withdraw (`lsoda*` → any token)
|
|
143
215
|
|
|
144
|
-
No approval step — `hubWalletSwap: true` authorises the share spend via a `sendMessage`.
|
|
216
|
+
No approval step — `hubWalletSwap: true` authorises the share spend via a `sendMessage`. Quote with the vault as `token_src` on the hub.
|
|
145
217
|
|
|
146
218
|
```tsx
|
|
147
|
-
|
|
148
|
-
// walletProvider union; see features/leverage-yield.md for exact per-hook shapes.
|
|
149
|
-
import { useLeverageYieldWithdraw, useLeverageYieldVaultSwap } from '@sodax/dapp-kit';
|
|
219
|
+
import { isUserRejectedError, useLeverageYieldQuote, useLeverageYieldWithdraw, useLeverageYieldVaultSwap } from '@sodax/dapp-kit';
|
|
150
220
|
import { useWalletProvider } from '@sodax/wallet-sdk-react';
|
|
151
221
|
import { ChainKeys, type Address } from '@sodax/sdk';
|
|
152
222
|
|
|
223
|
+
const SLIPPAGE_BPS = 100n;
|
|
224
|
+
|
|
153
225
|
function WithdrawButton({ vault, srcAddress, outputToken, shares }: { vault: Address; srcAddress: string; outputToken: string; shares: bigint }) {
|
|
154
|
-
const chainKey = ChainKeys.ARBITRUM_MAINNET;
|
|
226
|
+
const chainKey = ChainKeys.ARBITRUM_MAINNET; // the network that deposited: its hub wallet holds the shares
|
|
155
227
|
const walletProvider = useWalletProvider({ xChainId: chainKey });
|
|
228
|
+
const { data: quote } = useLeverageYieldQuote({
|
|
229
|
+
params: {
|
|
230
|
+
payload: shares > 0n ? {
|
|
231
|
+
token_src: vault, token_src_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
232
|
+
token_dst: outputToken, token_dst_blockchain_id: chainKey,
|
|
233
|
+
amount: shares, quote_type: 'exact_input',
|
|
234
|
+
} : undefined,
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
const minOutputAmount = quote?.ok ? (quote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n : undefined;
|
|
156
238
|
const { mutateAsyncSafe: buildWithdraw } = useLeverageYieldWithdraw();
|
|
157
|
-
const {
|
|
239
|
+
const { mutateAsyncSafe: vaultSwap, isPending } = useLeverageYieldVaultSwap();
|
|
158
240
|
|
|
159
241
|
const handleWithdraw = async () => {
|
|
160
|
-
if (!walletProvider) return;
|
|
242
|
+
if (!walletProvider || minOutputAmount === undefined) return;
|
|
161
243
|
const built = await buildWithdraw({
|
|
162
244
|
vault, srcChainKey: chainKey, srcAddress,
|
|
163
245
|
dstChainKey: chainKey, outputToken,
|
|
164
|
-
inputAmount: shares,
|
|
165
|
-
minOutputAmount
|
|
246
|
+
inputAmount: shares, // lsoda* shares to burn
|
|
247
|
+
minOutputAmount,
|
|
166
248
|
});
|
|
167
|
-
if (!built.ok) return;
|
|
168
|
-
await vaultSwap({ ...built.value, walletProvider }); // built.value.hubWalletSwap === true
|
|
249
|
+
if (!built.ok) return console.error(built.error); // surface it in your UI
|
|
250
|
+
const result = await vaultSwap({ ...built.value, walletProvider }); // built.value.hubWalletSwap === true
|
|
251
|
+
if (!result.ok && !isUserRejectedError(result.error)) console.error(result.error);
|
|
169
252
|
};
|
|
170
253
|
|
|
171
|
-
return <button onClick={handleWithdraw} disabled={isPending || !walletProvider}>Withdraw</button>;
|
|
254
|
+
return <button onClick={handleWithdraw} disabled={isPending || !walletProvider || minOutputAmount === undefined}>Withdraw</button>;
|
|
172
255
|
}
|
|
173
256
|
```
|
|
174
257
|
|
|
@@ -176,7 +259,7 @@ function WithdrawButton({ vault, srcAddress, outputToken, shares }: { vault: Add
|
|
|
176
259
|
|
|
177
260
|
- **Two roles:** `deposit` / `withdraw` *build* a `LeverageYieldSwapPayload`; `useLeverageYieldVaultSwap` *executes* it. Always spread the built payload into the executor with a `walletProvider`.
|
|
178
261
|
- **Quotes:** size `minOutputAmount` with `useLeverageYieldQuote` — vault address as `token_dst` (deposit) or `token_src` (withdraw). Not `useQuote`: that one deducts the effective *swap* fee, while the vault intent charges the effective *leverage-yield* fee, so the quote and the intent disagree whenever the two feature fees differ. It returns the SDK `Result` as `data` (branch on `data?.ok`), unlike the other leverage-yield read hooks. Subtract your slippage tolerance.
|
|
179
|
-
- **Fees apply BOTH ways.** Deposits *and* withdrawals are charged the effective leverage-yield fee (`leverageYield.partnerFee ?? fee`); both builders accept an optional `partnerFee` to override it per intent. The fee comes out of `inputAmount` before the swap, so pass the same `partnerFee` to `useLeverageYieldQuote` or the quote is sized on the wrong net input and the intent won't fill. On a withdraw the input token is the vault, so the fee is taken in **`lsoda*` shares** — the receiver accrues vault shares, not the output token.
|
|
262
|
+
- **Fees apply BOTH ways.** Deposits *and* withdrawals are charged the effective leverage-yield fee (`leverageYield.partnerFee ?? fee`); both builders accept an optional `partnerFee` to override it per intent. It is opt-in: leave it out unless the integrator supplied their own receiver address, and never reuse an address from a SODAX demo. The fee comes out of `inputAmount` before the swap, so pass the same `partnerFee` to `useLeverageYieldQuote` or the quote is sized on the wrong net input and the intent won't fill. On a withdraw the input token is the vault, so the fee is taken in **`lsoda*` shares** — the receiver accrues vault shares, not the output token.
|
|
180
263
|
- **Configured fee:** vault flows are monetized via `leverageYield.partnerFee` (else the global `fee`). `swaps.partnerFee` does not apply to them.
|
|
181
264
|
- **Withdraw:** no spoke approval — the hub wallet authorises the share spend via `Connection.sendMessage`. Output lands at `recipient` (defaults to `srcAddress`) on `dstChainKey`.
|
|
182
265
|
- **Reads** (`useLeverageYieldEffectiveApr`, `Position`, `TotalAssets`, `PreviewRedeem`) are already unwrapped — read `data` directly. `useLeverageYieldShareBalances` returns an array; aggregate the `shares` yourself.
|
|
@@ -101,15 +101,18 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
|
|
|
101
101
|
|
|
102
102
|
## Leverage Yield
|
|
103
103
|
|
|
104
|
+
No hook lists the vaults: read the registry with `useSodaxContext().sodax.leverageYield.listVaults()` (synchronous; `{ name, vault, asset, borrowToken, lsdSource? }[]`) and pass `vault` to the hooks below. `targetLtvBps` and position `ltv` are basis points; `healthFactor` and `leverageMultiplierWad` are WAD, and the multiplier is the **borrowed** multiple (exposure = 1 + multiplier).
|
|
105
|
+
|
|
104
106
|
| Hook | Type | Purpose |
|
|
105
107
|
|---|---|---|
|
|
106
108
|
| `useLeverageYieldDeposit` | Mutation | Build a deposit payload (any token → `lsoda*` shares) — spread into `useLeverageYieldVaultSwap` |
|
|
107
109
|
| `useLeverageYieldWithdraw` | Mutation | Build a withdraw payload (`lsoda*` → any token; `hubWalletSwap`) |
|
|
108
110
|
| `useLeverageYieldVaultSwap` | Mutation | Execute a built payload end-to-end; backend submit-tx by default, falling back to the client-side create → verify → relay → notify path. `extras.apiKey` keys the backend leg per action |
|
|
109
111
|
| `useLeverageYieldDetailedStatus` | Query | Track a vault swap from its source tx (`{ srcChainKey, srcTxHash, apiConfig? }`; polls 3s; Result-wrapped; stops on the answering source's terminal state, on a rejected API key, and after 40 consecutive ambiguous reads — solver NOT_FOUND, or a relay with no packet for the tx; outages keep polling). Returns a tagged union — backend submit-tx record or solver answer — narrow on `source`. Unlike `useLeverageYieldApiSubmitTxStatus`, answers for both `vaultSwap()` completion paths |
|
|
112
|
+
| `useLeverageYieldQuote` | Query | Deposit (vault = `token_dst`) or withdraw (vault = `token_src`) quote with the leverage-yield fee (polls 3s; Result-wrapped). Size `minOutputAmount` from `quoted_amount` minus slippage, never `0n` |
|
|
110
113
|
| `useLeverageYieldNotifySolver` | Mutation | Manual-flow notify step (after a self-driven `createVaultIntent` + relay) |
|
|
111
114
|
| `useLeverageYieldEffectiveApr` | Query | AAVE + LSD effective net APR (60s) |
|
|
112
|
-
| `useLeverageYieldPosition` | Query | Live position: collateral, debt, LTV, health factor, idle (30s) |
|
|
115
|
+
| `useLeverageYieldPosition` | Query | Live position: collateral, debt, LTV (bps), health factor (WAD), idle (30s) |
|
|
113
116
|
| `useLeverageYieldTotalAssets` | Query | Vault TVL (18-dp bigint, 60s) |
|
|
114
117
|
| `useLeverageYieldPreviewRedeem` | Query | Assets for N shares; pass `1e18` for price-per-share (60s) |
|
|
115
118
|
| `useLeverageYieldShareBalances` | Query | Per-chain `lsoda*` balances via `useQueries` — returns an array (15s) |
|
|
@@ -242,7 +245,7 @@ Typed React Query wrappers over the backend Leverage Yield API (`sodax.api.lever
|
|
|
242
245
|
| `useLeverageYieldApiVaults` | Query; the deployed-vault registry |
|
|
243
246
|
| `useLeverageYieldApiVault` | Query; one vault descriptor by lsoda* `name` |
|
|
244
247
|
| `useLeverageYieldApiAsset` | Query; the vault's underlying hub asset |
|
|
245
|
-
| `useLeverageYieldApiPosition` | Query; `{ collateral, debt, ltv, healthFactor, idleAsset }` |
|
|
248
|
+
| `useLeverageYieldApiPosition` | Query; `{ collateral, debt, ltv, healthFactor, idleAsset }` as decimal strings (`ltv` bps, `healthFactor` WAD) |
|
|
246
249
|
| `useLeverageYieldApiApr` | Query; AAVE-only steady-state APR (RAY strings; can be negative) |
|
|
247
250
|
| `useLeverageYieldApiEffectiveApr` | Query; combined AAVE + LSD APR — `effectiveNetAprRay` is the headline |
|
|
248
251
|
| `useLeverageYieldApiLsdApr` | Query; off-chain LSD staking-APR snapshot |
|
|
@@ -251,7 +254,7 @@ Typed React Query wrappers over the backend Leverage Yield API (`sodax.api.lever
|
|
|
251
254
|
| `useLeverageYieldApiPreviewWithdraw` | Query; ERC-4626 `previewWithdraw` — shares burned for `assets` |
|
|
252
255
|
| `useLeverageYieldApiPreviewRedeem` | Query; ERC-4626 `previewRedeem` — assets for `shares` |
|
|
253
256
|
| `useLeverageYieldApiShareBalance` | Query; an owner's lsoda* balance (the HUB wallet, not the EOA) |
|
|
254
|
-
| `useLeverageYieldApiMaxWithdraw` | Query; RAW ERC-4626 `maxWithdraw`
|
|
257
|
+
| `useLeverageYieldApiMaxWithdraw` | Query; RAW ERC-4626 `maxWithdraw` in ASSET units, NOT dust-trimmed — never a withdraw's `inputAmount`, which is shares; size a MAX withdraw from `useLeverageYieldApiShareBalance` |
|
|
255
258
|
| `useLeverageYieldApiDepositQuote` | Query; any token → lsoda* (set `query.includeTxData` for `txData`) |
|
|
256
259
|
| `useLeverageYieldApiWithdrawQuote` | Query; lsoda* → any token |
|
|
257
260
|
| `useLeverageYieldApiDeadline` | Query; computed vault-swap deadline |
|
|
@@ -17,7 +17,8 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
17
17
|
1. **Deposit or withdraw?** Deposit = any token → `lsoda*` shares (lands in the hub wallet). Withdraw = `lsoda*` shares → any token on any chain.
|
|
18
18
|
2. **Build vs execute.** `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` only *build* a `LeverageYieldSwapPayload`; `useLeverageYieldVaultSwap` *executes* it (create → relay → notify solver). You always need both.
|
|
19
19
|
3. **Approval?** Deposit approves the spoke `inputToken` via the swap-domain `useSwapApprove` / `useSwapAllowance` (no leverage-yield-specific approve hook). Withdraw needs no approval (`hubWalletSwap: true`).
|
|
20
|
-
4. **Which
|
|
20
|
+
4. **Which vaults?** No hook — read the registry with `useSodaxContext().sodax.leverageYield.listVaults()` (synchronous, wrap in `useMemo`) and pass each entry's `vault` address to the hooks.
|
|
21
|
+
5. **Which reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
|
|
21
22
|
|
|
22
23
|
### Step 1b — leverage positions
|
|
23
24
|
|
|
@@ -32,6 +33,7 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
32
33
|
2. [`../integration/knowledge/architecture.md`](../integration/knowledge/architecture.md) — hook shapes, `mutateAsyncSafe`, `unwrapResult`, queryKey conventions.
|
|
33
34
|
3. [`../integration/knowledge/features/leverage-yield.md`](../integration/knowledge/features/leverage-yield.md) — full hook surface, mutation TVars, read shapes, approval pattern, gotchas.
|
|
34
35
|
4. [`../integration/knowledge/recipes/leverage-yield.md`](../integration/knowledge/recipes/leverage-yield.md) — full worked examples (deposit, withdraw, stats, share balances).
|
|
36
|
+
- **Building a user-facing vault screen?** Read [`../integration/knowledge/recipes/leverage-yield-product-anatomy.md`](../integration/knowledge/recipes/leverage-yield-product-anatomy.md) first: the journey, the states to handle, display metadata, USD prices, derived values, units, and the planned steps with explorer links. Layout stays your call.
|
|
35
37
|
5. Call-shape choice → [`../integration/knowledge/recipes/mutation-error-handling.md`](../integration/knowledge/recipes/mutation-error-handling.md).
|
|
36
38
|
|
|
37
39
|
### Leverage-yield-specific anti-patterns (dapp-kit)
|
|
@@ -40,7 +42,11 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
40
42
|
- **Treating `useLeverageYieldShareBalances` as a single query.** It returns an **array** (one `useQueries` row per holder). Aggregate with `reduce`; the key segment is singular `shareBalance`.
|
|
41
43
|
- **Gating withdraw on an allowance check.** Withdraw carries `hubWalletSwap: true` — the hub wallet authorises the share spend via `sendMessage`. Only `deposit` uses `useSwapAllowance` / `useSwapApprove`.
|
|
42
44
|
- **Reaching for a `useLeverageYieldApprove` hook.** It doesn't exist — the deposit approves the spoke asset manager, so use the swap-domain hooks.
|
|
43
|
-
- **
|
|
45
|
+
- **Sending `minOutputAmount: 0n`.** Always derive it from `useLeverageYieldQuote`'s `quoted_amount` minus a slippage tolerance in basis points, and disable the action until the quote is `ok`. A zero minimum accepts any fill.
|
|
46
|
+
- **Adding a `partnerFee` nobody asked for.** It is optional and opt-in; leave it out unless the integrator gave you their own receiver. Never copy a fee address from a SODAX demo or doc.
|
|
47
|
+
- **Labelling `leverageMultiplierWad` as "Leverage".** It is the borrowed multiple, `targetLTV / (1 − targetLTV)`; exposure is `1 + multiplier`. `targetLtvBps` and `position.ltv` are basis points.
|
|
48
|
+
- **Lowering the vault-read intervals.** The APR read alone is six Sonic `eth_call`s per vault per refresh. Keep the hook defaults on vault cards; only override hooks that poll faster than your app's floor (quotes, status, wallet balances).
|
|
49
|
+
- **Quoting a vault flow with `useQuote`, or with a different fee.** Size `minOutputAmount` with `useLeverageYieldQuote` on the **gross** `inputAmount` — it deducts the effective leverage-yield fee itself, so netting the amount first deducts it twice. Pass it the same `partnerFee` as `useLeverageYieldDeposit` / `useLeverageYieldWithdraw`, or omit it on both. `useQuote` deducts the *swap* fee instead, and whenever the two fees differ the derived `minOutputAmount` can be unfillable.
|
|
44
50
|
|
|
45
51
|
### Leverage-position anti-patterns (dapp-kit)
|
|
46
52
|
|
|
@@ -53,22 +59,33 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
53
59
|
- **Charging an existing position the configured fee.** Read `feeBps` from `useLeveragePositionInfo`; `getEffectivePositionFee()` is what a NEW position would carry.
|
|
54
60
|
- **Treating the mutation receipt as completion.** A solver fills a leverage change afterwards — poll `useLeveragePositionPending`.
|
|
55
61
|
|
|
62
|
+
## Acceptance (what the user can do)
|
|
63
|
+
|
|
64
|
+
Check the running app against these, not only `pnpm tsc`. The full list is in the product anatomy's Acceptance section.
|
|
65
|
+
|
|
66
|
+
- Every vault shows its asset, a variable APR (sign kept), TVL in the asset and USD, exposure (`1 + multiplier`) and health.
|
|
67
|
+
- Before signing, the user sees what they receive, the minimum they accept, and the steps they will sign.
|
|
68
|
+
- Each step links to its transaction on the right explorer, and the flow is followed to a terminal status.
|
|
69
|
+
- Shares are shown per network, in the asset and in USD; withdraw is capped at shares and signed from the network that deposited.
|
|
70
|
+
- Rejecting in the wallet returns to the form quietly; every other state has a clear message.
|
|
71
|
+
|
|
56
72
|
## Verification
|
|
57
73
|
|
|
58
74
|
1. `pnpm tsc --noEmit` clean.
|
|
59
75
|
2. Deposit/withdraw build a payload, then `useLeverageYieldVaultSwap` executes it (`{ ...payload, walletProvider }`).
|
|
60
76
|
3. `useLeverageYieldShareBalances` consumers treat `data` as an array and aggregate.
|
|
61
|
-
4.
|
|
62
|
-
5.
|
|
63
|
-
6.
|
|
64
|
-
7. Positions:
|
|
77
|
+
4. Every `minOutputAmount` is derived from a live `useLeverageYieldQuote` minus slippage; no `0n`, no unrequested `partnerFee`.
|
|
78
|
+
5. Withdraw flows do not gate on `useSwapAllowance`.
|
|
79
|
+
6. Mutation flows use `mutateAsyncSafe` and branch on `result.ok`; reads read `data` directly (no `.ok`/`.value`), except `useLeverageYieldQuote` and `useLeverageYieldDetailedStatus`, whose `data` is the SDK `Result` (branch on `data?.ok`).
|
|
80
|
+
7. Positions: leverage changes use `useSubmitLeveragePositionIntent` (never `useRunLeveragePositionOperation`), `notified` is checked on every open and leverage change, and exits are sized from `useLeveragePositionCollateral` with the fee from `useLeveragePositionInfo`.
|
|
81
|
+
8. Positions: funding is gated on `useLeveragePositionFundingAllowance` + `useApproveLeveragePositionFunding`, and `borrowAmount` / `minCollateralOut` trace back to `sizeLeverageBorrow` + `projectLeverageLeg`.
|
|
65
82
|
|
|
66
83
|
## Related granular skills (same family)
|
|
67
84
|
|
|
68
|
-
- [`../swap/SKILL.md`](../swap/SKILL.md) — `useSwapApprove` / `useSwapAllowance` (spoke-side deposit approval)
|
|
85
|
+
- [`../swap/SKILL.md`](../swap/SKILL.md) — `useSwapApprove` / `useSwapAllowance` (spoke-side deposit approval) live here. Size `minOutputAmount` with `useLeverageYieldQuote`, not the swap skill's `useQuote`.
|
|
69
86
|
- [`../auxiliary-services/SKILL.md`](../auxiliary-services/SKILL.md) — `useXBalances` / gas-estimation utilities used alongside leverage-yield UI.
|
|
70
87
|
|
|
71
|
-
For multi-feature tasks, load the broad [`sodax-dapp-kit` skill](../SKILL.md).
|
|
88
|
+
For multi-feature tasks, load the broad [`sodax-dapp-kit` skill](../SKILL.md). The backend REST hooks (`useLeverageYieldApi*`) are a different surface, documented in the Leverage Yield API section of [`../integration/knowledge/features/auxiliary-services.md`](../integration/knowledge/features/auxiliary-services.md) (granular skill: [`../auxiliary-services/SKILL.md`](../auxiliary-services/SKILL.md)).
|
|
72
89
|
|
|
73
90
|
## Wallet connectivity (different SDK package family)
|
|
74
91
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk
|
|
3
|
-
description: 'Integrate SODAX cross-chain DeFi into a backend, Node script, bot, indexer, or non-React app with @sodax/sdk — swaps, lending/borrowing, staking, bridging, concentrated-liquidity DEX, ICX/bnUSD/BALN token migration, partner fees,
|
|
3
|
+
description: 'Integrate SODAX cross-chain DeFi into a backend, Node script, bot, indexer, or non-React app with @sodax/sdk — intent-based swaps and limit orders, money market lending/borrowing, staking, bridging, concentrated-liquidity DEX, leverage-yield vaults (lsoda* deposit/withdraw, vault APR) and leverage positions, ICX/bnUSD/BALN token migration, partner fees, stuck-asset recovery, Stellar sponsoring, and the typed backend API clients, with Sonic as the hub. INTEGRATION (write NEW v2 code) — use whenever non-React code calls `@sodax/sdk` directly. Triggers on "use @sodax/sdk", "swap with Sodax", "Sodax bridge", "Sodax money market", "Sodax staking", "leverage yield vault", "sodax.leverageYield", "cross-chain DeFi", "Sonic hub", any `Sodax` / `ChainKeys` / `Result<T>` / `SodaxError` symbol. React dapps: prefer `sodax-dapp-kit`. MIGRATION (port v1 → v2) — v2 replaced `*SpokeProvider` classes with chain-key-driven routing, throws with `Result<T>`, module-specific error unions with `SodaxError<C>`, ad-hoc wallet/raw branching with `WalletProviderSlot<K, Raw>`, and static lookup tables with `ConfigService`. Triggers on "migrate Sodax v1", "upgrade @sodax/sdk", "v1 → v2", "useSpokeProvider broken", "Sodax error types changed", v1 fingerprints (`_MAINNET_CHAIN_ID`, `*SpokeProvider`, `xChainId`, `SpokeChainId`, `MoneyMarketError`/`IntentError`/`StakingError`/`BridgeError`/`MigrationError`/`AssetServiceError`/`ConcentratedLiquidityError`/`RelayError`). Load this skill if EITHER applies; the body gates by mode.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -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 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 vaults (lsoda* deposit/withdraw, vault APR, `listVaults`) and leverage positions | [`./leverage-yield/SKILL.md`](./leverage-yield/SKILL.md) | "leverage yield vault", "deposit into a vault", "sodax.leverageYield", "open a leverage position" |
|
|
39
40
|
| Leverage Yield API 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" |
|
|
40
41
|
| Bridge API 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" |
|
|
41
42
|
|
|
@@ -37,6 +37,9 @@ DO / DO NOT / workflow / stop conditions for AI agents writing `@sodax/sdk` v2 c
|
|
|
37
37
|
- **DO NOT** call `getStakeRatio` and treat its return as `Result<bigint>`. It's `Result<[xSodaAmount, previewDepositAmount]>` — a tuple of two bigints.
|
|
38
38
|
- **DO NOT** assume `BalnSwapService` lock-management methods (`stake`, `unstake`, `claim`, `claimUnstaked`, `cancelUnstake`, `getDetailedUserLocks`) return `Result<T>`. They still throw on error in v2 — known carve-out. Wrap them in `try/catch`.
|
|
39
39
|
- **DO NOT** call methods that need a wallet provider with `raw: true` — TypeScript rejects `walletProvider` when `raw: true`. Use `raw: false` + `walletProvider`, or stick to read methods.
|
|
40
|
+
- **DO NOT** send a zero or hand-picked minimum output (`minOutputAmount: 0n` or a literal). Derive it from a live quote for that exact input minus a slippage tolerance in basis points, show both to the user before they sign, and disable the action while there is no quote. The SDK does not reject a zero minimum (swaps and bridge only enforce the 546-sat dust floor on a BTC payout); a zero minimum accepts any fill.
|
|
41
|
+
- **DO NOT** add a `partnerFee` the integrator did not ask for. It is optional; omit it by default, and never copy a fee receiver address from a SODAX demo, doc, or example.
|
|
42
|
+
- **DO NOT** pass `skipSimulation: true` in user-facing flows. The simulation replays the hub-side execution and catches an intent that would revert there before the user signs it.
|
|
40
43
|
|
|
41
44
|
## Stop conditions (defer to user)
|
|
42
45
|
|
|
@@ -13,7 +13,7 @@ Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature ta
|
|
|
13
13
|
- A vault holds `asset` (a Sodax vault token like the weETH vault, `SodaTokens.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`.
|
|
14
14
|
- The ERC-4626 **share token is the vault proxy address itself** (`lsoda*`). Holding shares = holding the leveraged position.
|
|
15
15
|
- **Deposit** = swap any spoke token → `lsoda*`, delivered to the user's **hub wallet** on Sonic. **Withdraw** = swap `lsoda*` (held in the hub wallet) → any token on any chain.
|
|
16
|
-
- **Steady-state APR**: `netAprRay = supplyAprRay + leverageMultiplier × (supplyAprRay − borrowAprRay)`, where `leverageMultiplier = targetLTV / (1 − targetLTV)`. Rates are RAY (`1e27`); the multiplier
|
|
16
|
+
- **Steady-state APR**: `netAprRay = supplyAprRay + leverageMultiplier × (supplyAprRay − borrowAprRay)`, where `leverageMultiplier = targetLTV / (1 − targetLTV)` — the **borrowed** multiple of equity (debt ÷ equity), not total exposure. Exposure (collateral ÷ equity) is `1 + leverageMultiplier` = `1 / (1 − targetLTV)`: at `targetLtvBps` 8200 that is 4.56× borrowed, 5.56× exposure, so a UI label reading "Leverage" shows `1 + multiplier`. Rates are RAY (`1e27`); the multiplier and `healthFactor` are WAD (`1e18`); `targetLtvBps` and the position `ltv` are basis points (`10_000` = 100%). `netAprRay` goes **negative** when the borrow rate exceeds supply — for LSD-backed vaults the LSD's native staking yield (folded in by `getEffectiveApr`) is the real alpha.
|
|
17
17
|
|
|
18
18
|
## Public methods
|
|
19
19
|
|
|
@@ -40,7 +40,7 @@ sodax.leverageYield.getDetailedStatus(key: { srcChainKey, srcTxHash }, config?:
|
|
|
40
40
|
Promise<Result<DetailedLeverageYieldStatus, SodaxError>>;
|
|
41
41
|
sodax.leverageYield.getIntentStatus(request: { intent_tx_hash: string }): Promise<Result<SolverIntentStatusResponse, SodaxError>>;
|
|
42
42
|
|
|
43
|
-
// Sonic-direct allowance for the vault's underlying asset
|
|
43
|
+
// Sonic-direct allowance for the vault's underlying asset — NOT the deposit approval (that is sodax.swaps.isAllowanceValid / approve)
|
|
44
44
|
sodax.leverageYield.approve<R>(params: LeverageYieldApproveParams<R>): Promise<Result<TxReturnType<HubChainKey, R>, SodaxError>>;
|
|
45
45
|
sodax.leverageYield.isAllowanceValid(params: LeverageYieldAllowanceParams): Promise<Result<boolean, SodaxError>>;
|
|
46
46
|
|
|
@@ -117,17 +117,48 @@ type DetailedLeverageYieldStatus =
|
|
|
117
117
|
### Deposit (any token → `lsoda*`)
|
|
118
118
|
|
|
119
119
|
```ts
|
|
120
|
+
const srcChainKey = ChainKeys.ARBITRUM_MAINNET;
|
|
121
|
+
const inputToken = '0x…weETHonArbitrum';
|
|
122
|
+
const inputAmount = parseUnits('1', 18);
|
|
123
|
+
const SLIPPAGE_BPS = 100n; // 1%; take it from the user, capped
|
|
124
|
+
|
|
125
|
+
// Size the minimum from a live quote: vault as token_dst. Never ship 0n — that accepts any fill.
|
|
126
|
+
const quote = await sodax.leverageYield.getQuote({
|
|
127
|
+
token_src: inputToken,
|
|
128
|
+
token_src_blockchain_id: srcChainKey,
|
|
129
|
+
token_dst: vault.vault,
|
|
130
|
+
token_dst_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
131
|
+
amount: inputAmount,
|
|
132
|
+
quote_type: 'exact_input',
|
|
133
|
+
});
|
|
134
|
+
if (!quote.ok) return;
|
|
135
|
+
const minOutputAmount = (quote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n;
|
|
136
|
+
|
|
120
137
|
const built = await sodax.leverageYield.deposit({
|
|
121
138
|
vault: vault.vault,
|
|
122
|
-
srcChainKey
|
|
139
|
+
srcChainKey,
|
|
123
140
|
srcAddress: '0x…',
|
|
124
|
-
inputToken
|
|
125
|
-
inputAmount
|
|
126
|
-
minOutputAmount
|
|
127
|
-
partnerFee: { address: '0x…', percentage: 100 }, // optional 1% per-intent fee
|
|
141
|
+
inputToken,
|
|
142
|
+
inputAmount,
|
|
143
|
+
minOutputAmount,
|
|
128
144
|
});
|
|
129
145
|
if (!built.ok) return;
|
|
130
146
|
|
|
147
|
+
// deposit()/vaultSwap() never approve: the spoke asset manager pulls inputToken, so approve it swap-style first.
|
|
148
|
+
const allowance = await sodax.swaps.isAllowanceValid({ params: built.value.params, walletProvider });
|
|
149
|
+
if (!allowance.ok) return;
|
|
150
|
+
if (!allowance.value) {
|
|
151
|
+
// Pin the chain so the result narrows to an EVM tx hash.
|
|
152
|
+
const approval = await sodax.swaps.approve<typeof srcChainKey, false>({
|
|
153
|
+
params: { ...built.value.params, srcChainKey },
|
|
154
|
+
walletProvider,
|
|
155
|
+
});
|
|
156
|
+
if (!approval.ok) return;
|
|
157
|
+
const receipt = await walletProvider.waitForTransactionReceipt(approval.value);
|
|
158
|
+
// Providers report a revert as viem's 'reverted' or the JSON-RPC '0x0'.
|
|
159
|
+
if (receipt.status === 'reverted' || receipt.status === '0x0') return;
|
|
160
|
+
}
|
|
161
|
+
|
|
131
162
|
const result = await sodax.leverageYield.vaultSwap({ ...built.value, walletProvider });
|
|
132
163
|
if (!result.ok) return;
|
|
133
164
|
const { solverExecutionResponse, intent, intentDeliveryInfo } = result.value;
|
|
@@ -136,20 +167,35 @@ const { solverExecutionResponse, intent, intentDeliveryInfo } = result.value;
|
|
|
136
167
|
### Withdraw (`lsoda*` → any token)
|
|
137
168
|
|
|
138
169
|
```ts
|
|
170
|
+
const outputToken = '0x…weETHonArbitrum';
|
|
171
|
+
const SLIPPAGE_BPS = 100n;
|
|
172
|
+
// Withdraw quote: vault as token_src, on the hub (the shares live in the hub wallet).
|
|
173
|
+
const withdrawQuote = await sodax.leverageYield.getQuote({
|
|
174
|
+
token_src: vault.vault,
|
|
175
|
+
token_src_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
176
|
+
token_dst: outputToken,
|
|
177
|
+
token_dst_blockchain_id: ChainKeys.ARBITRUM_MAINNET,
|
|
178
|
+
amount: shareBalance,
|
|
179
|
+
quote_type: 'exact_input',
|
|
180
|
+
});
|
|
181
|
+
if (!withdrawQuote.ok) return;
|
|
182
|
+
|
|
139
183
|
const built = await sodax.leverageYield.withdraw({
|
|
140
184
|
vault: vault.vault,
|
|
141
185
|
srcChainKey: ChainKeys.ARBITRUM_MAINNET, // user signs the sendMessage here
|
|
142
186
|
srcAddress: '0x…',
|
|
143
187
|
dstChainKey: ChainKeys.ARBITRUM_MAINNET, // token delivered here
|
|
144
|
-
outputToken
|
|
188
|
+
outputToken,
|
|
145
189
|
inputAmount: shareBalance, // lsoda* to burn
|
|
146
|
-
minOutputAmount:
|
|
190
|
+
minOutputAmount: (withdrawQuote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n,
|
|
147
191
|
});
|
|
148
192
|
if (!built.ok) return;
|
|
149
193
|
// built.value.hubWalletSwap === true — no spoke approval; the hub wallet authorises the spend
|
|
150
194
|
await sodax.leverageYield.vaultSwap({ ...built.value, walletProvider });
|
|
151
195
|
```
|
|
152
196
|
|
|
197
|
+
**Partner fee is opt-in.** Omit `partnerFee` unless the integrator supplied their own receiver address. To override the fee per intent, pass the same `partnerFee` to `getQuote` and to `deposit()` / `withdraw()`, and quote the gross `inputAmount`: `getQuote` deducts the fee itself, so both sides end up on the same net input.
|
|
198
|
+
|
|
153
199
|
### Manual create → relay → notify
|
|
154
200
|
|
|
155
201
|
```ts
|
|
@@ -171,10 +217,10 @@ await sodax.leverageYield.notifySolver({ intent_tx_hash: hubIntentTxHash });
|
|
|
171
217
|
| `notifySolver` | `SolverExecutionResponse` (`{ answer, intent_hash }`) |
|
|
172
218
|
| `approve` | `TxReturnType<HubChainKey, R>` |
|
|
173
219
|
| `isAllowanceValid` | `boolean` |
|
|
174
|
-
| `getApr` | `LeverageYieldApr` (`{ supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }
|
|
220
|
+
| `getApr` | `LeverageYieldApr` (`{ supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }` — rates RAY, `targetLtvBps` basis points, multiplier WAD and the **borrowed** multiple) |
|
|
175
221
|
| `getEffectiveApr` | `LeverageYieldEffectiveApr` (= `LeverageYieldApr & { lsdApr, effectiveSupplyAprRay, effectiveNetAprRay }`) |
|
|
176
222
|
| `getLsdApr` | `LeverageYieldLsdApr` (`{ aprRay, label, stale }`) |
|
|
177
|
-
| `getPosition` | `LeverageYieldPosition` (`{ collateral, debt, ltv, healthFactor, idleAsset }`) |
|
|
223
|
+
| `getPosition` | `LeverageYieldPosition` (`{ collateral, debt, ltv, healthFactor, idleAsset }` — `ltv` basis points, `healthFactor` WAD, amounts 18 dp) |
|
|
178
224
|
| `getTotalAssets`, `preview*`, `getMaxWithdraw*`, `getShareBalance*` | `bigint` |
|
|
179
225
|
| `getAsset` | `Address` |
|
|
180
226
|
| `listVaults` / `getVault` / `getVaultByAddress` | `LeverageYieldVault[]` / `LeverageYieldVault \| undefined` (synchronous) |
|
|
@@ -16,8 +16,9 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
16
16
|
0. **Vault or leverage position?** Ask this first — they share the service and nothing else. A **vault** is one pooled ERC-4626 position at a single target LTV, entered/exited as an intent swap (`deposit` / `withdraw` / `vaultSwap`). A **leverage position** is the user's own AAVE account, cloned per position, with its own eMode category and leverage tier (`openLeveragePosition` and friends). "Deposit into a leverage vault" is the first; "open a leverage position", "adjust my leverage", "close my position" is the second. If the answer is positions, jump to Step 1b.
|
|
17
17
|
1. **Deposit or withdraw?** Deposit = any spoke token → `lsoda*` shares (delivered to the user's hub wallet). Withdraw = `lsoda*` shares (in the hub wallet) → any token on any chain.
|
|
18
18
|
2. **Build vs execute.** `deposit` / `withdraw` only *build* a `LeverageYieldSwapPayload`; `vaultSwap` *executes* it end-to-end. Spread the built payload into `vaultSwap({ ...payload, walletProvider })`.
|
|
19
|
-
3. **End-to-end or manual relay?** `vaultSwap`
|
|
20
|
-
4. **
|
|
19
|
+
3. **End-to-end or manual relay?** By default `vaultSwap` creates the intent and hands it to the backend submit-tx flow, which relays and notifies the solver; on any backend non-success it falls back to verify → relay → notify client-side, and then resolves before the fill (opt out of the backend path with `leverageYield: { useBackendSubmitTx: false }`). For a fully manual flow, use `createVaultIntent`, relay yourself, and finish with the public `notifySolver`.
|
|
20
|
+
4. **Which vaults?** `listVaults()` (synchronous registry: `{ name, vault, asset, borrowToken, lsdSource? }`); pass `vault` to every call.
|
|
21
|
+
5. **Reads?** `getEffectiveApr` (headline, AAVE + LSD), `getApr` (AAVE-only — can be negative), `getPosition`, `getTotalAssets`, `previewRedeem`, `getMaxWithdrawForUser` / `getShareBalanceForUser` (resolve the hub wallet from a spoke address internally).
|
|
21
22
|
|
|
22
23
|
### Step 1b — leverage positions
|
|
23
24
|
|
|
@@ -41,6 +42,9 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
41
42
|
- **Using `getApr` as the headline number.** For LSD-backed vaults the AAVE-only spread is often negative; `getEffectiveApr` folds in the LSD staking yield (the real source of return).
|
|
42
43
|
- **Passing a spoke address to `getShareBalance` / `getMaxWithdraw`.** Those take a hub address. Use the `*ForUser(vault, srcChainKey, srcAddress)` variants to resolve the hub wallet first.
|
|
43
44
|
- **Gating withdraw on `approve` / `isAllowanceValid`.** Those are Sonic-direct allowance helpers for the vault's underlying asset; the swap-style withdraw authorises the share spend via a hub-wallet `Connection.sendMessage` (`hubWalletSwap: true`).
|
|
45
|
+
- **Sending `minOutputAmount: 0n`.** Derive it from `sodax.leverageYield.getQuote`'s `quoted_amount` minus a slippage tolerance in basis points. The SDK does not reject zero, and a zero minimum accepts any fill.
|
|
46
|
+
- **Adding a `partnerFee` nobody asked for.** It is optional and opt-in; leave it out unless the integrator gave you their own receiver. Never copy a fee address from a SODAX demo or doc.
|
|
47
|
+
- **Reading `leverageMultiplierWad` as total exposure.** It is the borrowed multiple, `targetLTV / (1 − targetLTV)`; exposure is `1 + multiplier`. `targetLtvBps` and `getPosition().ltv` are basis points.
|
|
44
48
|
- **Quoting a vault flow through `sodax.swaps.getQuote`.** It deducts the effective *swap* fee, while the vault intent charges the effective *leverage-yield* fee (`leverageYield.partnerFee ?? fee`) — the two disagree whenever the feature fees differ. It can be made to agree by passing the leverage-yield fee explicitly (with a zero fee — `{ address, percentage: 0 }` — where that fee is `undefined`, since an explicit `undefined` falls back to the swap fee), but prefer `sodax.leverageYield.getQuote` (`token_dst` = vault for a deposit, `token_src` = vault for a withdraw).
|
|
45
49
|
- **Quoting with a different `partnerFee` than the intent charges.** The fee is deducted from the input before the swap, so the quote is sized on a different net input; when the intent's fee is the larger one, the `minOutputAmount` derived from that quote can't be met and the intent never fills. Pass the same `partnerFee` to `getQuote` and to `deposit()` / `vaultSwap()`, or omit it on both.
|
|
46
50
|
- **Assuming `swaps.partnerFee` monetizes vault flows.** It does not — configure `leverageYield.partnerFee` (or the global `fee`).
|
|
@@ -63,14 +67,17 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
63
67
|
|
|
64
68
|
1. `pnpm tsc --noEmit` clean.
|
|
65
69
|
2. Every `await sodax.leverageYield.<method>(...)` has `if (!result.ok)`.
|
|
66
|
-
3.
|
|
67
|
-
4.
|
|
68
|
-
5.
|
|
69
|
-
6. Positions:
|
|
70
|
+
3. Every `minOutputAmount` comes from `sodax.leverageYield.getQuote` minus slippage; no `0n`, no unrequested `partnerFee`.
|
|
71
|
+
4. Deposit/withdraw build a payload that is then run through `vaultSwap` (or `createVaultIntent` + relay + `notifySolver`).
|
|
72
|
+
5. APR display uses `getEffectiveApr`; share/withdraw sizing from a spoke address uses the `*ForUser` reads.
|
|
73
|
+
6. Positions: every `borrowAmount` / `minCollateralOut` traces back to `sizeLeverageBorrow` + `projectLeverageLeg` (never oracle parity), `exceedsMaxLtv` is checked before posting, and `notified` is read on every open / leverage change.
|
|
74
|
+
7. Positions: leverage changes go through `submitLeveragePositionIntent`, not `runLeveragePositionOperation`; `notifySolver` is given `dstChainTxHash`; exits are sized from `getPositionCollateralBalance` and charge the fee from `getPositionInfo`.
|
|
70
75
|
|
|
71
76
|
## Related granular skills (same family)
|
|
72
77
|
|
|
73
|
-
- [`../swap/SKILL.md`](../swap/SKILL.md) — `vaultSwap` is a leverage-yield copy of the swap intent flow
|
|
78
|
+
- [`../swap/SKILL.md`](../swap/SKILL.md) — `vaultSwap` is a leverage-yield copy of the swap intent flow. Quote `minOutputAmount` with `sodax.leverageYield.getQuote`, not the swap skill's `getQuote`.
|
|
74
79
|
- [`../recovery/SKILL.md`](../recovery/SKILL.md) — recover stuck hub-wallet assets (including `lsoda*` shares) back to a spoke chain.
|
|
75
80
|
|
|
76
81
|
For multi-feature tasks, load the broad [`sodax-sdk` skill](../SKILL.md).
|
|
82
|
+
|
|
83
|
+
Building a user-facing React vault screen? Load the `sodax-dapp-kit` skill's leverage-yield granular skill: its product anatomy covers the journey, the states, USD prices, derived values and the units table.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-wallet-sdk-core
|
|
3
|
-
description: 'Sign and broadcast SODAX transactions from a backend, script, CI, bot, or non-React app with @sodax/wallet-sdk-core — one wallet-provider class per chain family (EVM, Solana, Sui, Bitcoin, Stellar, ICON, Injective, NEAR, Stacks). INTEGRATION (write NEW code) —
|
|
3
|
+
description: 'Sign and broadcast SODAX transactions from a backend, script, CI, bot, or non-React app with @sodax/wallet-sdk-core — one wallet-provider class per chain family (EVM, Solana, Sui, Bitcoin, Stellar, ICON, Injective, NEAR, Stacks). INTEGRATION (write NEW code) — each class accepts a private-key config (Node scripts, CI, bots, indexers) or a browser-extension config (custom non-React browser flows). Use whenever non-React code must instantiate a wallet provider directly. Triggers on "instantiate EvmWalletProvider", "sign a tx from a Node script", "wallet provider for backend", "private-key signing", "wallet-sdk-core setup", any `*WalletProvider` class name. For React dapps prefer `sodax-wallet-sdk-react` — React consumers get a typed `IXxxWalletProvider` via `useWalletProvider(...)`. MIGRATION (port v1 → v2) — changes are additive (same class, config-type and config-shape names). The only mechanical step is replacing deep imports from v1''s flat `wallet-providers/<chain>.ts` layout with barrel imports, plus optionally adopting the new `defaults` field and re-imported library types. Triggers on imports from `@sodax/wallet-sdk-core/wallet-providers/…`, bumping from an older RC, or adopting `defaults` / `*WalletDefaults` / `*Policy` fields. Most projects need no wallet-sdk-core migration — the real target is usually `@sodax/sdk` or `@sodax/types`. Load this skill if EITHER applies; the body gates by mode.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -18,6 +18,24 @@ AGENTS.md routes you here when you're working with `@sodax/wallet-sdk-core` v2
|
|
|
18
18
|
|
|
19
19
|
For React consumers → use `sodax-wallet-sdk-react` (they get the typed wallet provider via `useWalletProvider(...)` and pass it to `@sodax/sdk` calls).
|
|
20
20
|
|
|
21
|
+
## Prefer a granular skill if the chain is known
|
|
22
|
+
|
|
23
|
+
If the task targets one chain family, load its granular skill instead of this broad one. It covers that provider's config, methods and gotchas, for both integration and migration.
|
|
24
|
+
|
|
25
|
+
| Chain family | Granular skill | Trigger phrases |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| EVM (Sonic hub + every EVM spoke) | [`./evm/SKILL.md`](./evm/SKILL.md) | "instantiate EvmWalletProvider", "viem wallet for Sonic / Base / Arbitrum" |
|
|
28
|
+
| Solana | [`./solana/SKILL.md`](./solana/SKILL.md) | "SolanaWalletProvider", "sign a Solana tx from Node" |
|
|
29
|
+
| Sui | [`./sui/SKILL.md`](./sui/SKILL.md) | "SuiWalletProvider", "Sui signing from a script" |
|
|
30
|
+
| Bitcoin (PSBT) | [`./bitcoin/SKILL.md`](./bitcoin/SKILL.md) | "BitcoinWalletProvider", "sign a PSBT" |
|
|
31
|
+
| Stellar | [`./stellar/SKILL.md`](./stellar/SKILL.md) | "StellarWalletProvider", "Stellar signing from a backend" |
|
|
32
|
+
| ICON | [`./icon/SKILL.md`](./icon/SKILL.md) | "IconWalletProvider", "Hana wallet relay" |
|
|
33
|
+
| Injective | [`./injective/SKILL.md`](./injective/SKILL.md) | "InjectiveWalletProvider", "Injective MsgBroadcaster" |
|
|
34
|
+
| NEAR | [`./near/SKILL.md`](./near/SKILL.md) | "NearWalletProvider", "NEAR signing from Node" |
|
|
35
|
+
| Stacks | [`./stacks/SKILL.md`](./stacks/SKILL.md) | "StacksWalletProvider", "Stacks signing from a script" |
|
|
36
|
+
|
|
37
|
+
Load this broad skill (keep reading below) when the task spans several chain families or the chain is undecided.
|
|
38
|
+
|
|
21
39
|
---
|
|
22
40
|
|
|
23
41
|
## Integration mode (writing new v2 code)
|
|
@@ -33,7 +51,7 @@ Direct usage of `@sodax/wallet-sdk-core` is the right choice for:
|
|
|
33
51
|
1. Read [`integration/knowledge/ai-rules.md`](./integration/knowledge/ai-rules.md) — DO / DON'T + workflow + stop conditions.
|
|
34
52
|
2. Read [`integration/knowledge/architecture.md`](./integration/knowledge/architecture.md) — mental model: `BaseWalletProvider`, dual-config discriminants (Bitcoin/Stellar via an explicit `type` field, every other chain via field presence), shallow `defaults` merge, library-exports.
|
|
35
53
|
3. Read [`integration/knowledge/quickstart.md`](./integration/knowledge/quickstart.md) — copy-paste minimal example for the chain you need.
|
|
36
|
-
4. For your chain, read [`integration/knowledge/features/`](./integration/knowledge/features/) — per-chain config table + methods + gotchas
|
|
54
|
+
4. For your chain, read [`integration/knowledge/features/`](./integration/knowledge/features/) — per-chain config table + methods + gotchas, one file per chain family: `evm.md`, `solana.md`, `sui.md`, `bitcoin.md`, `stellar.md`, `icon.md`, `injective.md`, `near.md`, `stacks.md`.
|
|
37
55
|
5. Task-specific recipes → [`integration/knowledge/recipes/`](./integration/knowledge/recipes/) — `setup-private-key.md`, `setup-browser-extension.md`, `sign-and-broadcast.md`, `defaults-and-overrides.md`, `library-exports.md`, `bridge-to-sdk.md` (pass provider to `@sodax/sdk`).
|
|
38
56
|
6. Lookups → [`integration/knowledge/reference/`](./integration/knowledge/reference/) — public API, provider classes, interfaces (`IXxxWalletProvider`), chain support, glossary.
|
|
39
57
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-wallet-sdk-react
|
|
3
|
-
description: 'Add SODAX multi-chain wallet connectivity to a React dapp with @sodax/wallet-sdk-react — connect/disconnect, account & signing hooks, a headless wallet modal, WalletConnect, and bridging the connected wallet into @sodax/sdk. INTEGRATION (write NEW code) —
|
|
3
|
+
description: 'Add SODAX multi-chain wallet connectivity to a React dapp with @sodax/wallet-sdk-react — connect/disconnect, account & signing hooks, a headless wallet modal, EVM chain switching, WalletConnect, and bridging the connected wallet into @sodax/sdk. INTEGRATION (write NEW code) — `SodaxWalletProvider` setup and hook-based UX across EVM, Solana, Sui, Bitcoin, Stellar, ICON, Injective, NEAR and Stacks; WalletConnect for non-injected wallets (Fireblocks/Ledger/mobile); `useWalletProvider` for signing SODAX calls. Triggers on "add wallet connect", "set up SodaxWalletProvider", "useXConnect", "useXAccount", "useWalletProvider", "useWalletModal", "wallet modal", "connect button", "multi-chain wallet UI", "WalletConnect for Fireblocks". Peer deps: `react >= 19`, `@tanstack/react-query 5.x`. MIGRATION (port v1 → v2) — `useXWagmiStore` left the public API (replace each selector with `useXServices` / `useXService({ xChainType })` / `useXConnections` / `useXConnection({ xChainType })`; do NOT rename to `useXWalletStore`, which is not exported), hooks take single-object params, `SodaxWalletProvider` takes `config: SodaxWalletConfig` (no `rpcConfig` / `options` / `initialState`), and chain slots are top-level on `SodaxWalletConfig` (no `chains: { EVM, … }` wrapper). Triggers on "useXWagmiStore is gone", "SodaxWalletProvider props broke", "old wallet-sdk-react hooks", "upgrade @sodax/wallet-sdk-react". Load this skill if EITHER applies; the body gates by mode.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -20,6 +20,21 @@ AGENTS.md routes you here when you're working with `@sodax/wallet-sdk-react` v2
|
|
|
20
20
|
For backend / non-React → use `sodax-wallet-sdk-core` instead.
|
|
21
21
|
For React dapps with hooks wrapping the SDK → also load `sodax-dapp-kit`.
|
|
22
22
|
|
|
23
|
+
## Prefer a granular skill if the concern is known
|
|
24
|
+
|
|
25
|
+
If the task is one wallet concern, load its granular skill instead of this broad one. Each links straight to its recipe, for both integration and migration.
|
|
26
|
+
|
|
27
|
+
| Concern | Granular skill | Trigger phrases |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| Connect / disconnect, account and connection state | [`./connect/SKILL.md`](./connect/SKILL.md) | "useXConnect", "useXAccount", "connect button" |
|
|
30
|
+
| Headless wallet modal and multi-chain UI | [`./wallet-modal/SKILL.md`](./wallet-modal/SKILL.md) | "useWalletModal", "wallet modal", "connect several chains" |
|
|
31
|
+
| Connected wallet → SDK signer | [`./bridge-to-sdk/SKILL.md`](./bridge-to-sdk/SKILL.md) | "useWalletProvider", "pass the wallet to @sodax/sdk" |
|
|
32
|
+
| EVM chain switching / wrong network | [`./switch-chain/SKILL.md`](./switch-chain/SKILL.md) | "useEvmSwitchChain", "wrong network banner" |
|
|
33
|
+
| Sign an arbitrary message | [`./sign-message/SKILL.md`](./sign-message/SKILL.md) | "useXSignMessage", "prove wallet ownership", "SIWE" |
|
|
34
|
+
| WalletConnect / enterprise custody | [`./walletconnect/SKILL.md`](./walletconnect/SKILL.md) | "WalletConnect", "Fireblocks", "Ledger", "mobile-only wallet" |
|
|
35
|
+
|
|
36
|
+
Load this broad skill (keep reading below) for a full wallet setup, several concerns at once, or a v1 port.
|
|
37
|
+
|
|
23
38
|
---
|
|
24
39
|
|
|
25
40
|
## Integration mode (writing new v2 code)
|