@sodax/skills 2.2.0-rc.8 → 2.3.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +11 -10
- package/README.md +5 -5
- package/package.json +6 -5
- package/skills/sodax-build/SKILL.md +3 -3
- package/skills/sodax-build/knowledge/README.md +1 -1
- package/skills/sodax-build/knowledge/feature-catalog.md +4 -0
- package/skills/sodax-build/knowledge/glossary.md +1 -0
- package/skills/sodax-build/knowledge/handoff.md +3 -0
- package/skills/sodax-build/knowledge/interview-guide.md +1 -0
- package/skills/sodax-dapp-kit/SKILL.md +23 -5
- package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +4 -1
- package/skills/sodax-dapp-kit/bridge/SKILL.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/ai-rules.md +3 -0
- package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +18 -4
- package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +31 -1
- package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +8 -0
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +17 -3
- package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +24 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/bridge.md +2 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/dex.md +23 -8
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield-product-anatomy.md +150 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +122 -38
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +141 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +14 -3
- package/skills/sodax-dapp-kit/integration/knowledge/reference/public-api.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +8 -0
- package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +27 -10
- package/skills/sodax-dapp-kit/swap/SKILL.md +3 -3
- package/skills/sodax-sdk/SKILL.md +2 -1
- package/skills/sodax-sdk/bridge/SKILL.md +3 -1
- package/skills/sodax-sdk/integration/knowledge/ai-rules.md +3 -0
- package/skills/sodax-sdk/integration/knowledge/architecture.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +5 -3
- package/skills/sodax-sdk/integration/knowledge/features/bridge.md +8 -0
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +81 -12
- package/skills/sodax-sdk/integration/knowledge/features/swap.md +68 -2
- package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +56 -2
- package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +27 -1
- package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +30 -1
- package/skills/sodax-sdk/leverage-yield/SKILL.md +16 -8
- package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/architecture.md +1 -1
- package/skills/sodax-sdk/migration-v1-to-v2/knowledge/reference/sodax-config.md +9 -1
- package/skills/sodax-sdk/swap/SKILL.md +3 -1
- package/skills/sodax-sdk/swaps-api/SKILL.md +3 -2
- package/skills/sodax-wallet-sdk-core/SKILL.md +20 -2
- package/skills/sodax-wallet-sdk-core/evm/SKILL.md +2 -1
- package/skills/sodax-wallet-sdk-core/integration/knowledge/README.md +1 -1
- package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +6 -0
- package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/interfaces.md +4 -1
- package/skills/sodax-wallet-sdk-core/migration-v1-to-v2/knowledge/README.md +1 -1
- package/skills/sodax-wallet-sdk-react/SKILL.md +20 -3
- package/skills/sodax-wallet-sdk-react/integration/knowledge/README.md +2 -1
- package/skills/sodax-wallet-sdk-react/integration/knowledge/ai-rules.md +2 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/architecture.md +10 -6
- package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/05-privy-email-login.tsx +157 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/README.md +1 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/privy-email-login.md +111 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/api-surface.md +14 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/chain-support.md +1 -1
- package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/README.md +1 -1
- package/skills/sodax-wallet-sdk-react/privy/SKILL.md +53 -0
- package/skills/sodax-wallet-sdk-react/wallet-modal/SKILL.md +1 -0
|
@@ -14,19 +14,27 @@ Leveraged-yield ERC-4626 vaults on the Sonic hub. Deposit any token → `lsoda*`
|
|
|
14
14
|
useLeverageYieldDeposit({ mutationOptions }); // build a deposit payload (any token → lsoda*)
|
|
15
15
|
useLeverageYieldWithdraw({ mutationOptions }); // build a withdraw payload (lsoda* → any token; hubWalletSwap)
|
|
16
16
|
useLeverageYieldVaultSwap({ mutationOptions }); // EXECUTE the built payload end-to-end
|
|
17
|
+
useLeverageYieldVaultSwapWithApproval({ mutationOptions }); // same, with a deposit's approval folded in (one EIP-5792 signature)
|
|
17
18
|
useLeverageYieldNotifySolver({ mutationOptions }); // manual-flow: notify the solver after a self-driven relay
|
|
18
19
|
|
|
19
20
|
// Reads
|
|
20
21
|
useLeverageYieldDetailedStatus({ params, queryOptions }); // track a vault swap from its SOURCE tx (3s)
|
|
22
|
+
useLeverageYieldApprovalStrategy({ params: { payload, walletProvider, allowAccountUpgrade? }, queryOptions }); // label the deposit button
|
|
21
23
|
useLeverageYieldQuote({ params, queryOptions }); // vault deposit/withdraw quote (3s) — NOT useQuote
|
|
22
24
|
useLeverageYieldEffectiveApr({ params, queryOptions }); // AAVE + LSD effective net APR (60s)
|
|
23
25
|
useLeverageYieldPosition({ params, queryOptions }); // collateral/debt/ltv/healthFactor/idle (30s)
|
|
24
26
|
useLeverageYieldTotalAssets({ params, queryOptions }); // vault TVL, 18-dp bigint (60s)
|
|
25
27
|
useLeverageYieldPreviewRedeem({ params, queryOptions }); // assets for N shares; price-per-share (60s)
|
|
26
28
|
useLeverageYieldShareBalances({ params, queryOptions }); // per-chain share balances via useQueries (15s)
|
|
29
|
+
|
|
30
|
+
// Vault registry — no hook; static SDK config, read synchronously
|
|
31
|
+
const { sodax } = useSodaxContext();
|
|
32
|
+
const vaults = useMemo(() => sodax.leverageYield.listVaults(), [sodax]); // { name, vault, asset, borrowToken, lsdSource? }[]
|
|
27
33
|
```
|
|
28
34
|
|
|
29
|
-
|
|
35
|
+
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).
|
|
36
|
+
|
|
37
|
+
`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. A post-broadcast failure (verify, relay or post-execution codes) still hands you that tx as `error.context.srcTxHash` / `srcChainKey`, so keep tracking it rather than reporting the vault swap as lost. 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
38
|
|
|
31
39
|
`use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
|
|
32
40
|
transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
|
|
@@ -65,12 +73,15 @@ type UseLeverageYieldNotifySolverVars = SolverExecutionRequest;
|
|
|
65
73
|
useLeverageYieldEffectiveApr({ params: { vault } })
|
|
66
74
|
// → UseQueryResult<LeverageYieldEffectiveApr>
|
|
67
75
|
// LeverageYieldEffectiveApr = LeverageYieldApr & { lsdApr, effectiveSupplyAprRay, effectiveNetAprRay }
|
|
68
|
-
// LeverageYieldApr = { supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }
|
|
76
|
+
// LeverageYieldApr = { supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }
|
|
77
|
+
// rates RAY (1e27); targetLtvBps basis points (8_200 = 82%); leverageMultiplierWad WAD (1e18) and the
|
|
78
|
+
// BORROWED multiple, targetLTV / (1 − targetLTV) — total exposure is 1 + multiplier
|
|
69
79
|
|
|
70
80
|
// useLeverageYieldPosition — live position snapshot
|
|
71
81
|
useLeverageYieldPosition({ params: { vault } })
|
|
72
82
|
// → UseQueryResult<LeverageYieldPosition>
|
|
73
83
|
// LeverageYieldPosition = { collateral, debt, ltv, healthFactor, idleAsset } (all bigint)
|
|
84
|
+
// ltv basis points (10_000 = 100%); healthFactor WAD; amounts 18 dp
|
|
74
85
|
|
|
75
86
|
// useLeverageYieldPreviewRedeem — assets per shares; pass 1e18 for price-per-share
|
|
76
87
|
useLeverageYieldPreviewRedeem({ params: { vault, shares: 10n ** 18n } })
|
|
@@ -85,7 +96,7 @@ useLeverageYieldShareBalances({ params: { vault, holders } })
|
|
|
85
96
|
|
|
86
97
|
## Approval pattern
|
|
87
98
|
|
|
88
|
-
|
|
99
|
+
`useLeverageYieldVaultSwapWithApproval` approves and deposits in one call — one signature on an EIP-5792 wallet — and needs none of the hooks below. A `TX_VERIFICATION_FAILED` with `context.reason === ATOMIC_BATCH_UNCONFIRMED` may still land: never deposit it again — mutate again with `resumeBatchId` / `resumeBatchCallCount` from its `context`, which sends nothing. For the two-step flow, leverage-yield has **no dedicated approve hook**. A deposit is a swap-style intent that bridges `inputToken` from the spoke chain, so it approves the spoke-side asset manager exactly like a swap — reuse the swap hooks. A withdraw needs no spoke-side approval: the payload carries `hubWalletSwap: true` and `vaultSwap` authorises the hub wallet to spend the `lsoda*` shares via a `Connection.sendMessage` the user signs on `srcChainKey`.
|
|
89
100
|
|
|
90
101
|
| Flow | Token approved | Hook |
|
|
91
102
|
|---|---|---|
|
|
@@ -123,6 +134,9 @@ Branch on `data?.ok` for those two hooks only.
|
|
|
123
134
|
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
135
|
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
136
|
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.
|
|
137
|
+
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.
|
|
138
|
+
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×.
|
|
139
|
+
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
140
|
|
|
127
141
|
## Leverage positions (separate from vaults)
|
|
128
142
|
|
|
@@ -15,10 +15,19 @@ useSwapAllowance({ params: { payload, srcChainKey, walletProvider }, queryOption
|
|
|
15
15
|
useStatus({ params: { intentTxHash }, queryOptions }); // Intent execution status (3s)
|
|
16
16
|
// Polls 3s; stops on a terminal source, a rejected API key, or 40 consecutive ambiguous reads.
|
|
17
17
|
useDetailedStatus({ params: { srcChainKey, srcTxHash }, queryOptions }); // Swap status by source tx (3s)
|
|
18
|
+
useSwapApprovalStrategy({ params: { payload, walletProvider }, queryOptions }); // 'not-required' | 'atomic-batch' | 'sequential' (no polling)
|
|
18
19
|
|
|
19
20
|
// Mutations — domain inputs flow through mutate(vars), see Mutation params below
|
|
20
21
|
useSwap({ mutationOptions });
|
|
21
22
|
useSwapApprove({ mutationOptions });
|
|
23
|
+
useSwapWithApproval({ mutationOptions }); // useSwap + approval; one EIP-5792 signature when the wallet can batch
|
|
24
|
+
|
|
25
|
+
// Composite — the whole form as one state machine; see recipes/swap.md § One Hook for the Whole Form
|
|
26
|
+
useSwapLifecycle({ intentParams, srcWalletProvider, dstWalletProvider, chainSwitch?, externalBlocked?, extras?, timeout?, mutationOptions? });
|
|
27
|
+
// → { state, error, next, reset, approvalStrategy, swap, status, stellar, nearStorage }
|
|
28
|
+
// the Stellar and NEAR gates check intentParams.dstAddress; dstWalletProvider must control it for the setup actions
|
|
29
|
+
// state.kind: idle | checking | needsChainSwitch | needsSetup(reason) | ready(approvalStrategy) | submitting
|
|
30
|
+
// | pending (error? after a post-broadcast failure) | unconfirmed (batch may still land — next() re-checks it, never re-sends) | settled | failed
|
|
22
31
|
useCancelSwap({ mutationOptions }); // TVars are FLAT: { srcChainKey, intent, walletProvider }
|
|
23
32
|
useCreateLimitOrder({ mutationOptions }); // No deadline; cancel manually
|
|
24
33
|
useCancelLimitOrder({ mutationOptions }); // TVars are FLAT: { srcChainKey, intent, walletProvider }
|
|
@@ -126,8 +135,23 @@ if (data?.ok) {
|
|
|
126
135
|
}
|
|
127
136
|
```
|
|
128
137
|
|
|
138
|
+
To render it without switching on `source`, collapse it with `summarizeSwapStatus` (from `@sodax/sdk`, re-exported here) — `{ state: 'pending' | 'solved' | 'failed'; hubTxHash?; fillTxHash? }`. `fillTxHash` may be absent even when solved.
|
|
139
|
+
|
|
140
|
+
**Default to `useDetailedStatus`.** It is the only swap status read that answers for every completion path, and it takes the identifiers `swap()` hands back on success (`intentDeliveryInfo.srcChainKey` / `srcTxHash`) and on a post-broadcast failure (`error.context.srcChainKey` / `srcTxHash`).
|
|
141
|
+
|
|
129
142
|
That is what distinguishes it from `useSwapsApiSubmitTxStatus`, which reads the backend record directly — 404 when none exists, and a stale or abandoned record for a swap the client-side fallback completed. A swap whose relay packet has not landed has no hub tx hash and reads as `LOOKUP_FAILED`; that spends the same 40-read budget as a solver `NOT_FOUND`, so a swap nothing can resolve stops instead of polling forever. A dependency outage does **not** spend the budget — it keeps polling so the read recovers on its own.
|
|
130
143
|
|
|
144
|
+
### `useSwapWithApproval` — approve and swap in one signature
|
|
145
|
+
|
|
146
|
+
Same vars as `useSwap`. It calls `sodax.swaps.swapWithApproval`: no approval when the allowance suffices; on an EVM
|
|
147
|
+
spoke whose wallet reports EIP-5792 atomic support, approve + swap as **one batch, one signature**; otherwise approve,
|
|
148
|
+
wait for it to confirm, then swap. `data.approvalStrategy` says which ran. Pair it with `useSwapApprovalStrategy` to
|
|
149
|
+
label the button up front (e.g. "Approve & Swap" vs "Approve, then Swap"), instead of the
|
|
150
|
+
`useSwapAllowance` + `useSwapApprove` + `useSwap` trio. A rejected batch — or a declined account upgrade on a
|
|
151
|
+
`'ready'` wallet — is `USER_REJECTED` and is **not** retried as two transactions. A declined upgrade carries
|
|
152
|
+
`context.reason === ACCOUNT_UPGRADE_DECLINED`; pass `allowAccountUpgrade: false` (in the mutation vars and to
|
|
153
|
+
`useSwapApprovalStrategy`) to swap without the upgrade. dapp-kit never stores that choice — the app decides.
|
|
154
|
+
|
|
131
155
|
## Gotchas
|
|
132
156
|
|
|
133
157
|
1. **`Intent.srcChain` and `Intent.dstChain` keep their v1 names.** Even though request-side params use `srcChainKey`/`dstChainKey`, the read-side `Intent` type didn't rename. Don't blanket-replace these names.
|
|
@@ -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
|
|
|
@@ -11,6 +11,8 @@ Cross-chain token transfers via the hub-and-spoke vault architecture.
|
|
|
11
11
|
| `useBridge` | Mutation | Execute a cross-chain bridge transfer |
|
|
12
12
|
| `useBridgeAllowance` | Query | Check if token approval is needed |
|
|
13
13
|
| `useBridgeApprove` | Mutation | Approve tokens for bridge |
|
|
14
|
+
| `useBridgeWithApproval` | Mutation | Bridge with the approval folded in — one signature on an EIP-5792 wallet |
|
|
15
|
+
| `useBridgeApprovalStrategy` | Query | Which approval path `useBridgeWithApproval` would take, for the button label |
|
|
14
16
|
| `useGetBridgeableAmount` | Query | Available bridgeable amount between two tokens |
|
|
15
17
|
| `useGetBridgeableTokens` | Query | Tokens bridgeable to a destination chain |
|
|
16
18
|
|
|
@@ -186,15 +186,30 @@ function Position({ positionId, poolKey }: { positionId: bigint; poolKey: PoolKe
|
|
|
186
186
|
|
|
187
187
|
## Remove Liquidity
|
|
188
188
|
|
|
189
|
+
Size `amount0Min` / `amount1Min` from the position with `useCreateDecreaseLiquidityParams` (slippage in percent). Zero minimums accept any price. It throws during render when `percentage` or `slippageTolerance` is outside (0, 100], so clamp slider and input values before passing them.
|
|
190
|
+
|
|
189
191
|
```tsx
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
})
|
|
192
|
+
import { isUserRejectedError, useCreateDecreaseLiquidityParams, useDecreaseLiquidity } from '@sodax/dapp-kit';
|
|
193
|
+
import { useWalletProvider } from '@sodax/wallet-sdk-react';
|
|
194
|
+
import { ChainKeys, type Address, type ClPositionInfo, type PoolKey } from '@sodax/sdk';
|
|
195
|
+
|
|
196
|
+
function RemoveLiquidity({ poolKey, tokenId, positionInfo, srcAddress }: { poolKey: PoolKey; tokenId: bigint; positionInfo: ClPositionInfo; srcAddress: Address }) {
|
|
197
|
+
const walletProvider = useWalletProvider({ xChainId: ChainKeys.BASE_MAINNET });
|
|
198
|
+
const { mutateAsyncSafe: decreaseLiquidity, isPending } = useDecreaseLiquidity();
|
|
199
|
+
// positionInfo from usePositionInfo({ params: { tokenId: tokenId.toString(), poolKey } }).data.positionInfo
|
|
200
|
+
const decrease = useCreateDecreaseLiquidityParams({ poolKey, tokenId, percentage: 50, positionInfo, slippageTolerance: 1 });
|
|
201
|
+
|
|
202
|
+
const onRemove = async () => {
|
|
203
|
+
if (!walletProvider) return;
|
|
204
|
+
const result = await decreaseLiquidity({
|
|
205
|
+
params: { ...decrease, srcChainKey: ChainKeys.BASE_MAINNET, srcAddress },
|
|
206
|
+
walletProvider,
|
|
207
|
+
});
|
|
208
|
+
if (!result.ok && !isUserRejectedError(result.error)) console.error(result.error); // surface it in your UI
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
return <button onClick={onRemove} disabled={isPending || !walletProvider}>Remove 50%</button>;
|
|
212
|
+
}
|
|
198
213
|
```
|
|
199
214
|
|
|
200
215
|
## Notes
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# Leverage-yield vault app — product anatomy
|
|
2
|
+
|
|
3
|
+
What a user-facing vault screen has to let people **answer and do**, which hook answers it, the
|
|
4
|
+
states to handle, and how to derive the numbers people read. It describes structure, not layout:
|
|
5
|
+
grid or list, modal or page, tabs, and where risk copy sits are the builder's call.
|
|
6
|
+
|
|
7
|
+
Vaults only. Leverage positions are a different product (see [`../features/leverage-yield.md`](../features/leverage-yield.md) § Leverage positions).
|
|
8
|
+
Call shapes for every hook here are in [`leverage-yield.md`](leverage-yield.md).
|
|
9
|
+
|
|
10
|
+
## The journey
|
|
11
|
+
|
|
12
|
+
| Step | The user must be able to answer | Source |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| **Discover** | Which vaults exist, and what each one holds | `sodax.leverageYield.listVaults()` (no hook; see [Display metadata](#display-metadata)) |
|
|
15
|
+
| **Evaluate** | What does it earn (and can that change)? How big is it? How much leverage and how healthy? What is one share worth? | `useLeverageYieldEffectiveApr`, `useLeverageYieldTotalAssets`, `useLeverageYieldPosition`, `useLeverageYieldPreviewRedeem`, USD via `useReservesUsdFormat` |
|
|
16
|
+
| **Deposit** | From which network and token? What will I receive, and what is the least I accept? Which steps will I sign? | `useLeverageYieldQuote` (vault as `token_dst`), `useSwapAllowance`, `useXBalances` |
|
|
17
|
+
| **Track** | Where is my deposit now, and where can I see each transaction? | `useLeverageYieldDetailedStatus`, [explorer links](#planned-steps-and-explorer-links) |
|
|
18
|
+
| **Hold** | How many shares do I have, on which network, and what are they worth in the asset and in USD? What might they earn? | `useLeverageYieldShareBalances`, `useLeverageYieldPreviewRedeem`, [derived values](#derived-values) |
|
|
19
|
+
| **Withdraw** | How much can I take out, to which token and network, and what is the least I accept? | share balance, `useLeverageYieldQuote` (vault as `token_src`), `useLeverageYieldWithdraw` |
|
|
20
|
+
|
|
21
|
+
## Concepts users get wrong
|
|
22
|
+
|
|
23
|
+
- **Shares are not in the wallet extension.** They live in the user's SODAX hub wallet on Sonic, and there is one hub wallet per source network **and** address. Depositing from Base and from Arbitrum makes two separate share balances. A withdraw spends the shares of the hub wallet it is signed for, so it must be signed on the network, from the address, that deposited. Show balances per network (`useLeverageYieldShareBalances` takes one holder per network).
|
|
24
|
+
- **The APR is a variable estimate.** `effectiveNetAprRay` is steady-state: it assumes today's rates hold and the vault stays at its target LTV. It can go negative when borrowing costs more than the supply side earns. `lsdApr.stale === true` means the staking part is a fallback figure, so label it as an estimate.
|
|
25
|
+
- **Leverage multiplies risk too.** Show exposure as `1 + leverageMultiplierWad` (see [Units](#units)); the multiplier alone is the borrowed part. The health factor is the vault's, not the user's.
|
|
26
|
+
- **A deposit is an intent, not a transfer.** The user signs on their network, SODAX delivers it to Sonic, and a solver fills it. There are no partial fills: an intent whose minimum can no longer be met is not filled, and it expires at its deadline (by default five minutes after the hub block time when it was built). `useLeverageYieldDetailedStatus` then answers from the solver (`FAILED` is status `4`) or keeps reading not-found and stops polling after 40 such reads; give the user a timeout of your own rather than waiting forever. When `vaultSwap` took the backend path (the default), the backend's own record (`userMessage`, `failureReason`, and `relayedForRefundAt` once an expired intent was relayed for refund) is readable with `useLeverageYieldApiSubmitTxStatus` from the source tx and `srcChainKey`: the detailed status routes a failed or abandoned backend record to the solver instead of returning it. Don't promise where or when a refund lands; show the status and, if assets are left in the hub wallet, offer the recovery hooks (`useHubAssetBalances`, `useWithdrawHubAsset`, in [`../features/auxiliary-services.md`](../features/auxiliary-services.md)).
|
|
27
|
+
|
|
28
|
+
## States
|
|
29
|
+
|
|
30
|
+
Handle every row; how each one looks is up to the builder.
|
|
31
|
+
|
|
32
|
+
| State | Detect it with | What the user needs |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| No quote yet / amount empty | `useLeverageYieldQuote` `data === undefined` | The action disabled, with the reason |
|
|
35
|
+
| Amount too low, too high, **or** no route | quote `data.ok === false`, `!isSodaxError(data.error)` and `isNoRouteRefusal(data.error)` | The solver answers all three the same way. Re-quote a mid-size amount to tell them apart: suggest a larger amount only when the refused one was below it, a smaller one only when it was above; otherwise "no route right now, try again shortly" |
|
|
36
|
+
| Other solver refusal | quote `!ok`, not a `SodaxError`: `data.error.detail.code` (`SolverIntentErrorCode`) | The solver's message and a retry |
|
|
37
|
+
| Invalid input | quote `!ok`, `isSodaxError(data.error)` with `code === 'VALIDATION_FAILED'` | Which input to fix |
|
|
38
|
+
| Quote moved | The quote refreshes every 3s | The minimum recomputed on every refresh, and the amounts shown again right before signing |
|
|
39
|
+
| Needs approval | `useSwapAllowance` → `false` (deposits only) | An approve step before the deposit step |
|
|
40
|
+
| Approval takes two prompts | Some tokens (Ethereum USDT today) need `approve(0)` first; the hook still returns one hash | A note that the wallet may ask twice |
|
|
41
|
+
| Wrong network | `useEvmSwitchChain` → `isWrongChain` (load the `sodax-wallet-sdk-react` skill) | A switch-network action instead of the deposit button |
|
|
42
|
+
| Not enough balance or gas | No dedicated error code: compare against `useXBalances` before signing | The shortfall, before they sign |
|
|
43
|
+
| Would revert on the hub | `vaultSwap` simulates the hub-side execution (not for a Sonic source) and fails with `INTENT_CREATION_FAILED`, the RPC revert as `cause` | That the deposit would fail, before they sign |
|
|
44
|
+
| User rejected in the wallet | `isUserRejectedError(result.error)` | Back to the form silently; not an error toast |
|
|
45
|
+
| In flight | `useLeverageYieldDetailedStatus` → `data.ok` with a non-terminal status; `!ok` with `error.context.reason === DETAILED_STATUS_NOT_DELIVERED` means not delivered yet | The current step, and that it is safe to wait |
|
|
46
|
+
| Filled | backend `data.value.data.status === 'solved'`, or solver `data.value.data.status === 3` | Shares shown (they arrive in the hub wallet) |
|
|
47
|
+
| Failed or expired | solver `data.value.data.status === 4` (a failed or abandoned backend record is routed to the solver), or still not found after your own timeout. For `userMessage` / `failureReason` on the backend path, read `useLeverageYieldApiSubmitTxStatus` | What happened and where the funds are, per [Concepts](#concepts-users-get-wrong) |
|
|
48
|
+
| Withdraw more than held | Cap `inputAmount` at the share balance. `getMaxWithdraw*` is in **asset** units, not shares | A max button sized from shares |
|
|
49
|
+
|
|
50
|
+
## Planned steps and explorer links
|
|
51
|
+
|
|
52
|
+
Show the steps before the user signs, then mark each one as it completes. Explorer URL: `baseChainInfo[chainKey].explorer.txUrl + hash`. There is no SDK URL helper.
|
|
53
|
+
|
|
54
|
+
| Deposit step | Transaction | Link on |
|
|
55
|
+
|---|---|---|
|
|
56
|
+
| 1. Approve (only if `useSwapAllowance` is `false`; may be two prompts) | the approve hash | the source network |
|
|
57
|
+
| 2. Sign the deposit on the source network | `intentDeliveryInfo.srcTxHash` | the source network |
|
|
58
|
+
| 3. Deliver to Sonic | `intentDeliveryInfo.dstTxHash` (equals `srcTxHash` when the source is Sonic) | Sonic |
|
|
59
|
+
| 4. Solver fills; shares land in the hub wallet | `result.fillTxHash` on the backend status, or `fill_tx_hash` on the solver status. It may be absent even when filled | the fill's destination network: Sonic for a deposit |
|
|
60
|
+
|
|
61
|
+
A withdraw has no approve step: 1. sign on the network that deposited, 2. deliver to Sonic, 3. solver fills and pays out on `dstChainKey`. `useLeverageYieldVaultSwap` can resolve before the fill on its client-side fallback path, so keep polling `useLeverageYieldDetailedStatus` until a terminal status.
|
|
62
|
+
|
|
63
|
+
## Display metadata
|
|
64
|
+
|
|
65
|
+
The registry entry has no symbol or logo. Both the `lsoda*` share token and the vault's asset are in the hub token config, so resolve them by address and take the logo from the symbol:
|
|
66
|
+
|
|
67
|
+
```tsx
|
|
68
|
+
import { useMemo } from 'react';
|
|
69
|
+
import { tokenLogo, useSodaxContext, type LeverageYieldVault } from '@sodax/dapp-kit';
|
|
70
|
+
|
|
71
|
+
function useVaultDisplay(vault: LeverageYieldVault) {
|
|
72
|
+
const { sodax } = useSodaxContext();
|
|
73
|
+
return useMemo(() => {
|
|
74
|
+
const share = sodax.config.getXTokenFromHubAsset(vault.vault); // lsoda* symbol + decimals
|
|
75
|
+
const asset = sodax.config.getXTokenFromHubAsset(vault.asset); // underlying symbol, e.g. weETH
|
|
76
|
+
return {
|
|
77
|
+
shareSymbol: share?.symbol ?? vault.name,
|
|
78
|
+
assetSymbol: asset?.symbol,
|
|
79
|
+
assetDecimals: asset?.decimals ?? 18,
|
|
80
|
+
logo: tokenLogo(asset?.symbol ?? vault.name),
|
|
81
|
+
};
|
|
82
|
+
}, [sodax, vault]);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`tokenLogo(symbol)` serves the `@sodax/assets` PNGs; both the `lsoda*` and the underlying logos exist. Pick one per screen and keep it consistent.
|
|
87
|
+
|
|
88
|
+
## USD prices
|
|
89
|
+
|
|
90
|
+
Use one source: the money-market reserve prices. Every vault asset is a money-market reserve, keyed by `underlyingAsset`, which equals `vault.asset`. One `useReservesUsdFormat` call prices every vault.
|
|
91
|
+
|
|
92
|
+
```tsx
|
|
93
|
+
import { useReservesUsdFormat } from '@sodax/dapp-kit';
|
|
94
|
+
|
|
95
|
+
function useAssetUsdPrice(asset: string): number | undefined {
|
|
96
|
+
const { data: reserves } = useReservesUsdFormat();
|
|
97
|
+
const reserve = reserves?.find((r) => r.underlyingAsset.toLowerCase() === asset.toLowerCase());
|
|
98
|
+
return reserve ? Number(reserve.priceInUSD) : undefined; // USD per whole token, from the pool oracle
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
USD figures are for display only. Never size `minOutputAmount` from them: that comes from the quote.
|
|
103
|
+
|
|
104
|
+
## Derived values
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { formatUnits } from 'viem';
|
|
108
|
+
|
|
109
|
+
const WAD = 10n ** 18n;
|
|
110
|
+
const RAY = 10n ** 27n;
|
|
111
|
+
|
|
112
|
+
/** Asset units for `shares`, from `useLeverageYieldPreviewRedeem({ params: { vault, shares: WAD } })`. */
|
|
113
|
+
export const shareValue = (shares: bigint, pricePerShare: bigint): bigint => (shares * pricePerShare) / WAD;
|
|
114
|
+
|
|
115
|
+
/** Exposure the depositor holds, in WAD: 1 + the borrowed multiple. */
|
|
116
|
+
export const exposureWad = (leverageMultiplierWad: bigint): bigint => WAD + leverageMultiplierWad;
|
|
117
|
+
|
|
118
|
+
/** Simple-interest projection over `days` at today's APR (asset units). Can be negative. */
|
|
119
|
+
export const projectedInterest = (assets: bigint, aprRay: bigint, days: bigint): bigint =>
|
|
120
|
+
(assets * aprRay * days) / (365n * RAY);
|
|
121
|
+
|
|
122
|
+
export const toUsd = (amount: bigint, decimals: number, priceUsd: number): number =>
|
|
123
|
+
Number(formatUnits(amount, decimals)) * priceUsd;
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Label projections as estimates at today's variable APR, and keep the sign: a negative APR projects a loss.
|
|
127
|
+
|
|
128
|
+
## Units
|
|
129
|
+
|
|
130
|
+
| Value | Unit | Display as |
|
|
131
|
+
|---|---|---|
|
|
132
|
+
| `*AprRay` (`effectiveNetAprRay`, `netAprRay`, …) | RAY, `1e27` = 100% | `Number(v * 10_000n / RAY) / 100` → percent |
|
|
133
|
+
| `targetLtvBps`, position `ltv` | basis points, `10_000` = 100% | `/ 100` → percent |
|
|
134
|
+
| `leverageMultiplierWad` | WAD, borrowed multiple | `1 +` it, as `×` |
|
|
135
|
+
| `healthFactor` | WAD; below `1e18` is liquidatable; `maxUint256` means no debt | `v === maxUint256 ? 'no debt' : formatUnits(v, 18)` |
|
|
136
|
+
| Shares (`lsoda*`) | 18 decimals | `formatUnits(v, 18)` |
|
|
137
|
+
| `getTotalAssets`, `previewRedeem`, position `collateral` / `debt` / `idleAsset` | the vault asset's units (18 decimals today) | `formatUnits(v, assetDecimals)`, then USD |
|
|
138
|
+
| `priceInUSD` | decimal string, USD per whole token | `Number(v)` |
|
|
139
|
+
|
|
140
|
+
## Acceptance
|
|
141
|
+
|
|
142
|
+
The flow is done when the user can:
|
|
143
|
+
|
|
144
|
+
- see every vault with its asset, APR (marked as variable, sign kept), TVL in the asset and USD, exposure, and health;
|
|
145
|
+
- see what they will receive, the minimum they accept, and the steps they will sign, before signing;
|
|
146
|
+
- sign without a zero or hand-picked minimum, and without an unrequested partner fee;
|
|
147
|
+
- follow each step to completion, with a link to each transaction on the right explorer;
|
|
148
|
+
- see their shares per network, worth in the asset and in USD;
|
|
149
|
+
- withdraw from the network that deposited, with the amount capped at their shares;
|
|
150
|
+
- cancel in the wallet without an error, and read a clear message for every state in [States](#states).
|
|
@@ -4,6 +4,8 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
4
4
|
|
|
5
5
|
**Depends on:** [setup.md](setup.md), [wallet-connectivity.md](wallet-connectivity.md)
|
|
6
6
|
|
|
7
|
+
**Building a user-facing screen?** Start from [leverage-yield-product-anatomy.md](leverage-yield-product-anatomy.md): what each step must answer, the states, USD and derived values, and the units table.
|
|
8
|
+
|
|
7
9
|
## Hooks
|
|
8
10
|
|
|
9
11
|
### Mutations
|
|
@@ -13,6 +15,7 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
13
15
|
| `useLeverageYieldDeposit` | Build a deposit payload (any token → `lsoda*`) |
|
|
14
16
|
| `useLeverageYieldWithdraw` | Build a withdraw payload (`lsoda*` → any token) |
|
|
15
17
|
| `useLeverageYieldVaultSwap` | Execute a built payload end-to-end (backend submit-tx by default, client-side relay as fallback) |
|
|
18
|
+
| `useLeverageYieldVaultSwapWithApproval` | `useLeverageYieldVaultSwap` with the deposit's approval folded in — one signature on an EIP-5792 wallet |
|
|
16
19
|
| `useSwapApprove` | Approve the spoke `inputToken` (deposit only — swap-domain hook) |
|
|
17
20
|
|
|
18
21
|
### Queries
|
|
@@ -41,12 +44,28 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
41
44
|
|
|
42
45
|
> 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
46
|
|
|
47
|
+
## List the vaults
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
```tsx
|
|
52
|
+
import { useMemo } from 'react';
|
|
53
|
+
import { useSodaxContext } from '@sodax/dapp-kit';
|
|
54
|
+
|
|
55
|
+
function useVaults() {
|
|
56
|
+
const { sodax } = useSodaxContext();
|
|
57
|
+
return useMemo(() => sodax.leverageYield.listVaults(), [sodax]);
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
44
61
|
## Vault stats + position
|
|
45
62
|
|
|
63
|
+
`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.
|
|
64
|
+
|
|
46
65
|
```tsx
|
|
47
66
|
import { useLeverageYieldEffectiveApr, useLeverageYieldTotalAssets, useLeverageYieldPreviewRedeem, useLeverageYieldPosition } from '@sodax/dapp-kit';
|
|
48
67
|
import type { Address } from '@sodax/sdk';
|
|
49
|
-
import { formatUnits } from 'viem';
|
|
68
|
+
import { formatUnits, maxUint256 } from 'viem';
|
|
50
69
|
|
|
51
70
|
const RAY = 10n ** 27n;
|
|
52
71
|
|
|
@@ -66,12 +85,14 @@ function VaultStats({ vault }: { vault: Address }) {
|
|
|
66
85
|
{netAprPct !== undefined && <p>Net APR: {netAprPct.toFixed(2)}%</p>}
|
|
67
86
|
{tvl !== undefined && <p>TVL: {formatUnits(tvl, 18)}</p>}
|
|
68
87
|
{sharePrice !== undefined && <p>1 share = {formatUnits(sharePrice, 18)} assets</p>}
|
|
69
|
-
{position && <p>Health factor: {formatUnits(position.healthFactor, 18)}</p>}
|
|
88
|
+
{position && <p>Health factor: {position.healthFactor === maxUint256 ? 'no debt' : formatUnits(position.healthFactor, 18)}</p>}
|
|
70
89
|
</div>
|
|
71
90
|
);
|
|
72
91
|
}
|
|
73
92
|
```
|
|
74
93
|
|
|
94
|
+
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.
|
|
95
|
+
|
|
75
96
|
## Share balances across chains
|
|
76
97
|
|
|
77
98
|
`useLeverageYieldShareBalances` returns an **array** — one query per holder. Build `holders` from the chains the user has connected, then aggregate.
|
|
@@ -90,85 +111,148 @@ function ShareTotal({ vault, holders }: { vault: Address; holders: { chainKey: S
|
|
|
90
111
|
|
|
91
112
|
## Deposit (any token → `lsoda*`)
|
|
92
113
|
|
|
93
|
-
|
|
114
|
+
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
115
|
|
|
95
116
|
```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
117
|
import { useState } from 'react';
|
|
100
118
|
import {
|
|
101
|
-
|
|
119
|
+
isUserRejectedError, useLeverageYieldDeposit, useLeverageYieldQuote, useLeverageYieldVaultSwap,
|
|
120
|
+
useSodaxContext, useSwapApprove,
|
|
102
121
|
} from '@sodax/dapp-kit';
|
|
103
122
|
import { useWalletProvider } from '@sodax/wallet-sdk-react';
|
|
104
|
-
import { ChainKeys, type Address
|
|
105
|
-
import { parseUnits } from 'viem';
|
|
123
|
+
import { ChainKeys, type Address } from '@sodax/sdk';
|
|
124
|
+
import { formatUnits, isHex, parseUnits } from 'viem';
|
|
106
125
|
|
|
107
|
-
const
|
|
126
|
+
const SLIPPAGE_BPS = 100n; // 1%; let the user choose, but cap it
|
|
108
127
|
|
|
109
|
-
|
|
128
|
+
const errorMessage = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
|
129
|
+
|
|
130
|
+
/** Partial or invalid input (e.g. "1.2.3", "abc") parses to 0n instead of throwing during render. */
|
|
131
|
+
function toAmount(input: string, decimals: number): bigint {
|
|
132
|
+
try {
|
|
133
|
+
return parseUnits(input.trim(), decimals);
|
|
134
|
+
} catch {
|
|
135
|
+
return 0n;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function DepositForm({ vault, srcAddress, inputToken, decimals }: { vault: Address; srcAddress: string; inputToken: string; decimals: number }) {
|
|
110
140
|
const [amount, setAmount] = useState('');
|
|
141
|
+
const [error, setError] = useState<string>();
|
|
142
|
+
const [busy, setBusy] = useState(false); // spans build → approve → receipt → execute, not just the last mutation
|
|
143
|
+
const { sodax } = useSodaxContext();
|
|
111
144
|
const chainKey = ChainKeys.ARBITRUM_MAINNET;
|
|
112
145
|
const walletProvider = useWalletProvider({ xChainId: chainKey });
|
|
146
|
+
const inputAmount = toAmount(amount, decimals);
|
|
147
|
+
|
|
148
|
+
// Vault as token_dst quotes a deposit. Omit partnerFee here and on the builder unless you add your own.
|
|
149
|
+
const { data: quote } = useLeverageYieldQuote({
|
|
150
|
+
params: {
|
|
151
|
+
payload: inputAmount > 0n ? {
|
|
152
|
+
token_src: inputToken, token_src_blockchain_id: chainKey,
|
|
153
|
+
token_dst: vault, token_dst_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
154
|
+
amount: inputAmount, quote_type: 'exact_input',
|
|
155
|
+
} : undefined,
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
const minOutputAmount = quote?.ok ? (quote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n : undefined;
|
|
113
159
|
|
|
114
160
|
const { mutateAsyncSafe: buildDeposit } = useLeverageYieldDeposit();
|
|
115
161
|
const { mutateAsyncSafe: approve } = useSwapApprove();
|
|
116
|
-
const {
|
|
162
|
+
const { mutateAsyncSafe: vaultSwap, isPending } = useLeverageYieldVaultSwap();
|
|
163
|
+
|
|
164
|
+
const deposit = async (): Promise<string | undefined> => {
|
|
165
|
+
if (!walletProvider || minOutputAmount === undefined) return; // no quote, no deposit
|
|
166
|
+
const built = await buildDeposit({ vault, srcChainKey: chainKey, srcAddress, inputToken, inputAmount, minOutputAmount });
|
|
167
|
+
if (!built.ok) return errorMessage(built.error);
|
|
168
|
+
|
|
169
|
+
// Deposit approves the spoke asset manager (swap-style), only when the allowance is short.
|
|
170
|
+
const allowance = await sodax.swaps.isAllowanceValid({ params: built.value.params, walletProvider });
|
|
171
|
+
if (!allowance.ok) return errorMessage(allowance.error);
|
|
172
|
+
if (!allowance.value) {
|
|
173
|
+
const approval = await approve({ params: built.value.params, walletProvider });
|
|
174
|
+
if (!approval.ok) return isUserRejectedError(approval.error) ? undefined : errorMessage(approval.error);
|
|
175
|
+
// The deposit spends this allowance next, so it must be mined and must not have reverted.
|
|
176
|
+
if (isHex(approval.value)) {
|
|
177
|
+
try {
|
|
178
|
+
const receipt = await walletProvider.waitForTransactionReceipt(approval.value);
|
|
179
|
+
if (receipt.status === 'reverted' || receipt.status === '0x0') return 'Approval reverted';
|
|
180
|
+
} catch (e) {
|
|
181
|
+
return errorMessage(e);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const result = await vaultSwap({ ...built.value, walletProvider }); // lsoda* lands in the hub wallet
|
|
187
|
+
if (!result.ok && !isUserRejectedError(result.error)) return errorMessage(result.error);
|
|
188
|
+
};
|
|
117
189
|
|
|
118
190
|
const handleDeposit = async () => {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
126
|
-
if (!built.ok) return;
|
|
127
|
-
|
|
128
|
-
// Deposit approves the spoke asset manager (swap-style). Gate on useSwapAllowance in render.
|
|
129
|
-
await approve({ params: built.value.params, walletProvider });
|
|
130
|
-
await vaultSwap({ ...built.value, walletProvider }); // spread the payload; lsoda* lands in the hub wallet
|
|
191
|
+
setBusy(true);
|
|
192
|
+
setError(undefined);
|
|
193
|
+
try {
|
|
194
|
+
setError(await deposit());
|
|
195
|
+
} finally {
|
|
196
|
+
setBusy(false);
|
|
197
|
+
}
|
|
131
198
|
};
|
|
132
199
|
|
|
133
200
|
return (
|
|
134
201
|
<div>
|
|
135
202
|
<input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="amount" />
|
|
136
|
-
|
|
203
|
+
{quote?.ok && minOutputAmount !== undefined && (
|
|
204
|
+
<p>You receive ≈ {formatUnits(quote.value.quoted_amount, 18)} shares (at least {formatUnits(minOutputAmount, 18)})</p>
|
|
205
|
+
)}
|
|
206
|
+
{error && <p role="alert">{error}</p>}
|
|
207
|
+
<button onClick={handleDeposit} disabled={busy || isPending || !walletProvider || minOutputAmount === undefined}>Deposit</button>
|
|
137
208
|
</div>
|
|
138
209
|
);
|
|
139
210
|
}
|
|
140
211
|
```
|
|
141
212
|
|
|
213
|
+
Track the result with `useLeverageYieldDetailedStatus` until a terminal status: on its client-side fallback path, `vaultSwap` resolves before the solver fills.
|
|
214
|
+
|
|
142
215
|
## Withdraw (`lsoda*` → any token)
|
|
143
216
|
|
|
144
|
-
No approval step — `hubWalletSwap: true` authorises the share spend via a `sendMessage`.
|
|
217
|
+
No approval step — `hubWalletSwap: true` authorises the share spend via a `sendMessage`. Quote with the vault as `token_src` on the hub.
|
|
145
218
|
|
|
146
219
|
```tsx
|
|
147
|
-
|
|
148
|
-
// walletProvider union; see features/leverage-yield.md for exact per-hook shapes.
|
|
149
|
-
import { useLeverageYieldWithdraw, useLeverageYieldVaultSwap } from '@sodax/dapp-kit';
|
|
220
|
+
import { isUserRejectedError, useLeverageYieldQuote, useLeverageYieldWithdraw, useLeverageYieldVaultSwap } from '@sodax/dapp-kit';
|
|
150
221
|
import { useWalletProvider } from '@sodax/wallet-sdk-react';
|
|
151
222
|
import { ChainKeys, type Address } from '@sodax/sdk';
|
|
152
223
|
|
|
224
|
+
const SLIPPAGE_BPS = 100n;
|
|
225
|
+
|
|
153
226
|
function WithdrawButton({ vault, srcAddress, outputToken, shares }: { vault: Address; srcAddress: string; outputToken: string; shares: bigint }) {
|
|
154
|
-
const chainKey = ChainKeys.ARBITRUM_MAINNET;
|
|
227
|
+
const chainKey = ChainKeys.ARBITRUM_MAINNET; // the network that deposited: its hub wallet holds the shares
|
|
155
228
|
const walletProvider = useWalletProvider({ xChainId: chainKey });
|
|
229
|
+
const { data: quote } = useLeverageYieldQuote({
|
|
230
|
+
params: {
|
|
231
|
+
payload: shares > 0n ? {
|
|
232
|
+
token_src: vault, token_src_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
233
|
+
token_dst: outputToken, token_dst_blockchain_id: chainKey,
|
|
234
|
+
amount: shares, quote_type: 'exact_input',
|
|
235
|
+
} : undefined,
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
const minOutputAmount = quote?.ok ? (quote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n : undefined;
|
|
156
239
|
const { mutateAsyncSafe: buildWithdraw } = useLeverageYieldWithdraw();
|
|
157
|
-
const {
|
|
240
|
+
const { mutateAsyncSafe: vaultSwap, isPending } = useLeverageYieldVaultSwap();
|
|
158
241
|
|
|
159
242
|
const handleWithdraw = async () => {
|
|
160
|
-
if (!walletProvider) return;
|
|
243
|
+
if (!walletProvider || minOutputAmount === undefined) return;
|
|
161
244
|
const built = await buildWithdraw({
|
|
162
245
|
vault, srcChainKey: chainKey, srcAddress,
|
|
163
246
|
dstChainKey: chainKey, outputToken,
|
|
164
|
-
inputAmount: shares,
|
|
165
|
-
minOutputAmount
|
|
247
|
+
inputAmount: shares, // lsoda* shares to burn
|
|
248
|
+
minOutputAmount,
|
|
166
249
|
});
|
|
167
|
-
if (!built.ok) return;
|
|
168
|
-
await vaultSwap({ ...built.value, walletProvider }); // built.value.hubWalletSwap === true
|
|
250
|
+
if (!built.ok) return console.error(built.error); // surface it in your UI
|
|
251
|
+
const result = await vaultSwap({ ...built.value, walletProvider }); // built.value.hubWalletSwap === true
|
|
252
|
+
if (!result.ok && !isUserRejectedError(result.error)) console.error(result.error);
|
|
169
253
|
};
|
|
170
254
|
|
|
171
|
-
return <button onClick={handleWithdraw} disabled={isPending || !walletProvider}>Withdraw</button>;
|
|
255
|
+
return <button onClick={handleWithdraw} disabled={isPending || !walletProvider || minOutputAmount === undefined}>Withdraw</button>;
|
|
172
256
|
}
|
|
173
257
|
```
|
|
174
258
|
|
|
@@ -176,7 +260,7 @@ function WithdrawButton({ vault, srcAddress, outputToken, shares }: { vault: Add
|
|
|
176
260
|
|
|
177
261
|
- **Two roles:** `deposit` / `withdraw` *build* a `LeverageYieldSwapPayload`; `useLeverageYieldVaultSwap` *executes* it. Always spread the built payload into the executor with a `walletProvider`.
|
|
178
262
|
- **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.
|
|
263
|
+
- **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
264
|
- **Configured fee:** vault flows are monetized via `leverageYield.partnerFee` (else the global `fee`). `swaps.partnerFee` does not apply to them.
|
|
181
265
|
- **Withdraw:** no spoke approval — the hub wallet authorises the share spend via `Connection.sendMessage`. Output lands at `recipient` (defaults to `srcAddress`) on `dstChainKey`.
|
|
182
266
|
- **Reads** (`useLeverageYieldEffectiveApr`, `Position`, `TotalAssets`, `PreviewRedeem`) are already unwrapped — read `data` directly. `useLeverageYieldShareBalances` returns an array; aggregate the `shares` yourself.
|