@sodax/skills 2.2.0-rc.7 → 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.
Files changed (23) hide show
  1. package/AGENTS.md +4 -3
  2. package/package.json +3 -2
  3. package/skills/sodax-build/SKILL.md +2 -2
  4. package/skills/sodax-dapp-kit/SKILL.md +23 -5
  5. package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +1 -1
  6. package/skills/sodax-dapp-kit/integration/knowledge/ai-rules.md +3 -0
  7. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +15 -5
  8. package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +13 -1
  9. package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
  10. package/skills/sodax-dapp-kit/integration/knowledge/recipes/dex.md +23 -8
  11. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield-product-anatomy.md +150 -0
  12. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +121 -38
  13. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +6 -3
  14. package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +25 -8
  15. package/skills/sodax-sdk/SKILL.md +2 -1
  16. package/skills/sodax-sdk/integration/knowledge/ai-rules.md +3 -0
  17. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +57 -11
  18. package/skills/sodax-sdk/integration/knowledge/features/sponsoring.md +3 -1
  19. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +5 -0
  20. package/skills/sodax-sdk/integration/knowledge/recipes/initialize-sodax.md +1 -1
  21. package/skills/sodax-sdk/leverage-yield/SKILL.md +14 -7
  22. package/skills/sodax-wallet-sdk-core/SKILL.md +20 -2
  23. 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 six sub-scripts. Each catches a distinct bug class — green guards together prove syntactic + structural correctness, but **NOT** prose-level accuracy.
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-rc.7",
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": "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",
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, and token migration. INTEGRATION (write NEW code) — React hooks wrapping @sodax/sdk with React Query across 11 feature domains (swap, money market, staking, bridge, dex, migration, partner, recovery, bitcoin/Bound Exchange, backend queries, shared). React-only — Node and backend code uses `@sodax/sdk` directly. Use whenever a React dapp needs SODAX feature hooks. Triggers on "use @sodax/dapp-kit", "useSwap", "useMoneyMarket", "useStake", "useBridge", "useDex", "useMigrate", any `use<Feature>` hook name from dapp-kit, "Sodax React hooks", "dapp-kit query / mutation". v2 hook shape: mutation hooks return `SafeUseMutationResult` with `mutateAsyncSafe(vars): Promise<Result<TData>>`. mutationFn unwraps SDK Result<T> and throws on `!ok` so React Query''s native error model engages. Hook-owned invalidations — consumer onSuccess runs after. MIGRATION (port v1 → v2) — a deep canonicalization pass: single-object hook params, mandatory `mutateAsyncSafe`, hook-owned invalidations, throw-on-`Result.!ok` inside `mutationFn`, canonical queryKey/mutationKey conventions. Plus the SDK underneath was reshaped (chain-key-driven routing, `Result<T>` everywhere, `WalletProviderSlot<K, Raw>`). v1 dapp-kit code will not compile against v2. 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.'
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 Swaps API client hooks (useSwapsApiQuote, useSwapsApiSubmitTx, useSwapsApiStatus), sponsored Stellar account activation (useStellarGate, useStellarAccountActive, useStellarAccountStatus, useSponsorConfig, useActivateStellarAccount), and shared utilities (useSodaxContext, useHubProvider, useBalances, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useEstablishTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), activating a Stellar account for a user who holds no XLM, or cross-cutting utilities (token balances, gas estimation, Stellar trustlines). Covers BOTH integration and migration. Links into the parent sodax-dapp-kit knowledge tree.'
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
 
@@ -100,7 +100,9 @@ See the `sodax-sdk` skill (integration mode), `swaps-api.md` § `partnerFee`.
100
100
 
101
101
  The backend guards `POST /swaps/*` with an API-key check. There is ONE instance-wide key: configure it
102
102
  once on the provider config — `<SodaxProvider config={{ apiKey }}>` — and every `sodax.api.*` call these
103
- hooks make carries it. Override per request via the hooks' existing `apiConfig` param
103
+ hooks make carries it. `SodaxProvider` runs in the browser, so a key passed there (or read from
104
+ `NEXT_PUBLIC_*` / `VITE_*`) is public. To keep it private, leave `apiKey` out, point `api.baseURL` and
105
+ `solver.solverApiEndpoint` at the app's own backend proxy, and attach the key there: https://docs.sodax.com/developers/how-to/api-key-good-practices. Override per request via the hooks' existing `apiConfig` param
104
106
  (`RequestOverrideConfig`), which also accepts `apiKey`:
105
107
 
106
108
  ```ts
@@ -429,10 +431,10 @@ rather than on the HTTP status.
429
431
  When the server rate-limits a key it also supplies `error.context.retryAfterSeconds`; render "try again
430
432
  in Ns" instead of a generic "try later". The SDK never auto-retries a rate limit.
431
433
 
432
- On the packaged gateway no sponsoring-specific credential is needed: the instance-wide key from
433
- `<SodaxProvider config={{ apiKey }}>` (`new Sodax({ apiKey })`) is inherited by sponsoring.
434
- `api.sponsoringApiConfig.apiKey` is the credential for an independently hosted sponsoring service, and
435
- wins wherever the slice points. An api key
434
+ Sponsoring needs its own sponsoring-specific key, issued by the SODAX team — a partner portal key is
435
+ rejected there. Set it on `api.sponsoringApiConfig.apiKey`; it wins wherever the slice points. Without it,
436
+ the instance-wide key from `<SodaxProvider config={{ apiKey }}>` is sent to sponsoring whenever the call
437
+ targets a SODAX gateway root, and a portal key sent there fails. An api key
436
438
  in a browser bundle is public by nature; the service's per-key quotas, fleet cap, per-IP throttle,
437
439
  and origin gating are the real controls. Proxy through your own backend if that is not acceptable.
438
440
 
@@ -454,6 +456,14 @@ and origin gating are the real controls. Proxy through your own backend if that
454
456
  | Reserves data (mm) | 5s | `useReservesData` / `useReservesHumanized` / user position hooks |
455
457
  | `useBalances` | 5s | refetchInterval |
456
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 |
457
467
  | Most others | None | |
458
468
 
459
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 } (RAY = 1e27)
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
- // @ai-snippets-skip
191
- const walletProvider = useWalletProvider({ xChainId: ChainKeys.BASE_MAINNET });
192
- const { mutateAsync: decreaseLiquidity } = useDecreaseLiquidity();
193
-
194
- await decreaseLiquidity({
195
- params: { srcChainKey: ChainKeys.BASE_MAINNET, positionId, liquidity: 500_000n, amount0Min: 0n, amount1Min: 0n },
196
- walletProvider,
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).