@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
@@ -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
- Build → approve-if-needed → execute. The built payload is spread straight into `vaultSwap`.
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
- useLeverageYieldDeposit, useLeverageYieldVaultSwap, useSwapAllowance, useSwapApprove,
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, type PartnerFee } from '@sodax/sdk';
105
- import { parseUnits } from 'viem';
122
+ import { ChainKeys, type Address } from '@sodax/sdk';
123
+ import { formatUnits, isHex, parseUnits } from 'viem';
106
124
 
107
- const DEPOSIT_PARTNER_FEE: PartnerFee = { address: '0xYourFeeReceiver…', percentage: 100 }; // 1%
125
+ const SLIPPAGE_BPS = 100n; // 1%; let the user choose, but cap it
108
126
 
109
- function DepositForm({ vault, srcAddress, inputToken }: { vault: Address; srcAddress: string; inputToken: string }) {
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 { mutateAsync: vaultSwap, isPending } = useLeverageYieldVaultSwap();
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
- if (!walletProvider) return;
120
- const built = await buildDeposit({
121
- vault, srcChainKey: chainKey, srcAddress, inputToken,
122
- inputAmount: parseUnits(amount, 18),
123
- minOutputAmount: 0n, // size via useLeverageYieldQuote (token_dst = vault), then subtract slippage
124
- partnerFee: DEPOSIT_PARTNER_FEE, // per-intent fee — must match the quote's post-fee amount
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
- <button onClick={handleDeposit} disabled={isPending || !walletProvider}>Deposit</button>
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
- // @ai-snippets-skip — illustrative end-to-end flow (builder + executor) across a broad
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 { mutateAsync: vaultSwap, isPending } = useLeverageYieldVaultSwap();
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, // lsoda* shares to burn
165
- minOutputAmount: 0n, // size via useLeverageYieldQuote (token_src = vault), then subtract slippage
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` — NOT dust-trimmed, apply a margin for a MAX withdraw |
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 reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
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
- - **Quoting on the pre-fee amount.** A deposit's per-intent `partnerFee` is deducted from `inputAmount` before the swap — quote on the post-fee amount or `minOutputAmount` is unfillable.
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. Withdraw flows do not gate on `useSwapAllowance`.
62
- 5. Mutation flows use `mutateAsyncSafe` and branch on `result.ok`; reads read `data` directly (no `.ok`/`.value`).
63
- 6. 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`.
64
- 7. Positions: funding is gated on `useLeveragePositionFundingAllowance` + `useApproveLeveragePositionFunding`, and `borrowAmount` / `minCollateralOut` trace back to `sizeLeverageBorrow` + `projectLeverageLeg`.
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) and `useQuote` (size `minOutputAmount`) live here.
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, and stuck-asset recovery across Sonic (hub) + 20 spoke chains. INTEGRATION (write NEW v2 code) — hub-and-spoke architecture across EVM and non-EVM chains; covers intent-based swaps, lending/borrowing (money market), staking, bridging, concentrated-liquidity DEX, token migration, partner fees, and stuck-asset recovery. Use whenever a non-React or backend codebase calls `@sodax/sdk` directly (Node scripts, indexers, bots, server APIs, custom non-React browser flows). Triggers on "use @sodax/sdk", "swap with Sodax", "Sodax bridge", "Sodax money market", "Sodax staking", "cross-chain DeFi", "Sonic hub", any `Sodax` / `ChainKeys` / `Result<T>` / `SodaxError` symbol. For React dapps, prefer `sodax-dapp-kit` instead. MIGRATION (port v1 → v2) — the v2 reshape 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.'
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 is WAD (`1e18`). `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.
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 (the swap-style deposit handles its own approvals)
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: ChainKeys.ARBITRUM_MAINNET,
139
+ srcChainKey,
123
140
  srcAddress: '0x…',
124
- inputToken: '0x…weETHonArbitrum',
125
- inputAmount: parseUnits('1', 18),
126
- minOutputAmount: 0n, // quote via sodax.leverageYield.getQuote (token_dst = vault), then apply slippage
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: '0x…weETHonArbitrum',
188
+ outputToken,
145
189
  inputAmount: shareBalance, // lsoda* to burn
146
- minOutputAmount: 0n, // quote via sodax.leverageYield.getQuote (token_src = vault)
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 }`, RAY/WAD) |
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) |
@@ -152,13 +152,15 @@ routes at its bare origin is reached with `baseURL: 'http://localhost:3011'`.
152
152
 
153
153
  `apiKey` is folded into `x-api-key`. An api key in a browser bundle is public by nature: the service's
154
154
  per-key quotas, fleet-wide daily cap, per-IP throttle, and origin gating are the real controls. Proxy
155
- through your own backend if that is not acceptable.
155
+ through your own backend if that is not acceptable: https://docs.sodax.com/developers/how-to/api-key-good-practices.
156
156
 
157
157
  The instance-wide `new Sodax({ apiKey })` is **gated** here, unlike every other backend service: it is
158
158
  inherited only when the call targets a SODAX gateway (the packaged sponsoring default or the resolved
159
159
  shared root), and the check runs per request against the effective target, so a per-call `baseURL`
160
160
  override cannot carry it off-gateway. A custom sponsoring origin never receives it. The slice `apiKey`
161
161
  above is the credential for independently hosted sponsoring and wins wherever the slice points.
162
+ Sponsoring keys come from their own registry (issued by the SODAX team, not the partner portal), so a
163
+ portal key that reaches sponsoring through inheritance is rejected — always set the slice `apiKey`.
162
164
 
163
165
  ## Cross-references
164
166
 
@@ -107,9 +107,14 @@ instance-wide key, `new Sodax({ apiKey })`, sent on every backend request — th
107
107
  `RequestOverrideConfig`:
108
108
 
109
109
  ```ts
110
+ // Server-side only — a key in a browser bundle is public
110
111
  await sodax.api.swaps.createIntent(body, { apiKey: 'per-request-key' });
111
112
  ```
112
113
 
114
+ The key belongs on a server. Never read it from `NEXT_PUBLIC_*` / `VITE_*` / `REACT_APP_*` — those are
115
+ inlined into the client bundle. When the SDK runs in a browser, point `api.baseURL` and
116
+ `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.
117
+
113
118
  Precedence, highest first: per-call `headers['x-api-key']` (any casing) → per-call `apiKey` → a
114
119
  configured explicit `x-api-key` header (`api.headers` / `setHeaders`) → the configured `apiKey`. That
115
120
  full order is what the data, swaps, and bridge transports resolve; sponsoring's tier 3 is its own
@@ -18,7 +18,7 @@ const result = sodax.config.isValidSpokeChainKey(ChainKeys.ARBITRUM_MAINNET);
18
18
  import { Sodax, ChainKeys, type SodaxOptions } from '@sodax/sdk';
19
19
 
20
20
  // `SodaxOptions` = `DeepPartial<SodaxDefaultConfig>` (the data override) plus the client-side options:
21
- // `logger`, the global `fee`, the global `apiKey` (one instance-wide key, sent as `x-api-key` on every backend request; override per request via `RequestOverrideConfig.apiKey`), and per-feature options on `swaps` / `bridge` (e.g. `{ useBackendSubmitTx: false }` — opt out of the default-on backend 2-step flow).
21
+ // `logger`, the global `fee`, the global `apiKey` (one instance-wide key, sent as `x-api-key` on every backend request; override per request via `RequestOverrideConfig.apiKey`; server-side only — in a browser, proxy instead, see https://docs.sodax.com/developers/how-to/api-key-good-practices), and per-feature options on `swaps` / `bridge` (e.g. `{ useBackendSubmitTx: false }` — opt out of the default-on backend 2-step flow).
22
22
  const config: SodaxOptions = {
23
23
  // Per-chain overrides — merged with packaged defaults at the field level.
24
24
  chains: {