@sodax/skills 2.2.0-rc.4 → 2.2.0-rc.6

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 (33) hide show
  1. package/package.json +1 -1
  2. package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +2 -2
  3. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +4 -4
  4. package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +62 -2
  5. package/skills/sodax-dapp-kit/integration/knowledge/features/money-market.md +1 -1
  6. package/skills/sodax-dapp-kit/integration/knowledge/recipes/backend-queries.md +2 -2
  7. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +165 -0
  8. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +3 -3
  9. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +3 -3
  10. package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +22 -1
  11. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/auxiliary-services.md +1 -1
  12. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/reference/renamed-hooks.md +1 -1
  13. package/skills/sodax-sdk/SKILL.md +3 -3
  14. package/skills/sodax-sdk/backend-api/SKILL.md +1 -1
  15. package/skills/sodax-sdk/bridge-api/SKILL.md +2 -2
  16. package/skills/sodax-sdk/integration/knowledge/architecture.md +36 -1
  17. package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +3 -1
  18. package/skills/sodax-sdk/integration/knowledge/features/README.md +3 -3
  19. package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +1 -1
  20. package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +10 -3
  21. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield-api.md +1 -1
  22. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +178 -3
  23. package/skills/sodax-sdk/integration/knowledge/features/swap.md +8 -1
  24. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +2 -2
  25. package/skills/sodax-sdk/integration/knowledge/recipes/logging.md +2 -2
  26. package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +1 -1
  27. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +37 -1
  28. package/skills/sodax-sdk/leverage-yield/SKILL.md +25 -1
  29. package/skills/sodax-sdk/leverage-yield-api/SKILL.md +2 -2
  30. package/skills/sodax-sdk/swap/SKILL.md +1 -1
  31. package/skills/sodax-sdk/swaps-api/SKILL.md +2 -2
  32. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +1 -1
  33. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/sign-message.md +2 -2
@@ -100,6 +100,8 @@ const balance = await radfi.getBalance(tradingWallet.address);
100
100
  const exists = await radfi.checkIfTradingWalletExists(personalAddress);
101
101
  ```
102
102
 
103
+ **Bound hosts.** Bound serves its API from three hosts and the SDK routes per path family: `/sodax/*` on `svc.bound.exchange`, `/auth/*` + `/wallets/*` on `auth.bound.exchange`, `/transactions/*` on `api.radfi.co`, and `/wallets/balance` + `/utxos` on `api.ums.bound.exchange`. The packaged defaults are correct, so no configuration is needed. `api.bound.exchange` is retired and **refused**: a `radfi.apiUrl`/`authUrl`/`transactionsUrl` still naming it throws at construction, naming the replacement for that field. Two things to know: `api.radfi.co` is a **different registrable domain**, so a Content-Security-Policy `connect-src` or egress allowlist written as `https://*.bound.exchange` will block BTC withdrawal and UTXO renewal; and setting `radfi.apiUrl` yourself sends the **three routed** families to that host (deliberate — it keeps a single-host or proxy setup working and makes a half-migration impossible). To keep the split while moving one family, set `radfi.authUrl` or `radfi.transactionsUrl` explicitly. UMS is not routed by `apiUrl`: `/wallets/balance` and `/utxos` always use `radfi.umsUrl`, so a proxy that must capture all Bound traffic has to override that too.
104
+
103
105
  **Server-side / raw flows (no interactive sign-in).** A backend that builds raw Bitcoin intents can't run the BIP322 login, so seed a pre-provisioned Bound token instead of authenticating. `RadfiProvider` honors three injection points: `new Sodax({ ... })` with `radfi.accessToken` (and optional `refreshToken`) in the Bitcoin chain config (the constructor seeds them), `radfi.setRadfiAccessToken(token)` at runtime, or a per-action `extras.bound.accessToken` on `createIntent` (the Bitcoin-gated `bound` slot groups Bound/Radfi inputs). If an authenticated Bound call has neither a token nor a configured `apiKey`, `RadfiProvider` throws a legible `RadfiApiError` (the message names the fix: inject via `setRadfiAccessToken` or `new Sodax({ ... })` with `radfi.accessToken`) instead of sending an empty bearer and getting an opaque 403.
104
106
 
105
107
  **Backend request signing.** Separate from the per-user token above: if Bound authenticates your service itself, pass `radfi.signRequest` to `new Sodax({ ... })`. The SDK calls it once per outbound Bound request and merges the returned headers onto it, so the credential stays in your closure and never on the SDK config:
@@ -118,7 +120,7 @@ new Sodax({
118
120
  });
119
121
  ```
120
122
 
121
- It receives `{ method, path }`, may be async, and runs on every request (a timestamped signature must not be cached). Its headers merge last, so do not return `Authorization` — that is the per-user token. Server-side only: never ship a credential in a browser bundle.
123
+ It receives `{ method, path, baseUrl }` — `baseUrl` is the resolved Bound host for that call, so a signer holding a per-origin credential can branch on it. It may be async, and runs on every routed request (a timestamped signature must not be cached); UMS calls (`/wallets/balance`, `/utxos`) bypass it and go out unsigned. Its headers merge last, so do not return `Authorization` — that is the per-user token. Server-side only: never ship a credential in a browser bundle.
122
124
 
123
125
  Other public methods on `RadfiProvider` you may need: `setRadfiAccessToken`, `refreshAccessToken`, `createTradingWallet`, `createWithdrawTransaction`, `requestRadfiSignature`, `getExpiredUtxos`, `buildRenewUtxoTransaction`, `signAndBroadcastRenewUtxo`, `withdrawToUser`, `signAndBroadcastWithdraw`, `getMaxWithdrawable`. Read `RadfiProvider` source for argument shapes — the API surface is broader than typical chain providers.
124
126
 
@@ -15,9 +15,9 @@ One file per feature service. Each file documents the v2 API surface, common cal
15
15
  | [`recovery.md`](recovery.md) | `RecoveryService` | Withdraw stuck hub-wallet assets back to a spoke chain. |
16
16
  | [`backend-api.md`](backend-api.md) | `BackendApiService` | HTTP client for backend services: swap-tx submission, intent / orderbook lookups, money-market reads. |
17
17
  | [`sponsoring.md`](sponsoring.md) | `SponsoringService` | Stellar account activation via sponsored reserves. The sponsor pays the base reserve; the user's wallet signs. |
18
- | [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API v2 (`sodax.api.swaps`, `/swaps/*`). Quote, create-intent, submit-tx + status, fees. |
19
- | [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API v2 (`sodax.api.bridge`, `/bridge/*`). Allowance/approve/create-intent, submit-tx + status, tokens. |
20
- | [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API v2 (`sodax.api.leverageYield`, `/leverage-yield/*`). Vault registry + reads, deposit/withdraw quote + intents, submit-tx + status, fees. |
18
+ | [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API (`sodax.api.swaps`, `/swaps/*`). Quote, create-intent, submit-tx + status, fees. |
19
+ | [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API (`sodax.api.bridge`, `/bridge/*`). Allowance/approve/create-intent, submit-tx + status, tokens. |
20
+ | [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API (`sodax.api.leverageYield`, `/leverage-yield/*`). Vault registry + reads, deposit/withdraw quote + intents, submit-tx + status, fees. |
21
21
 
22
22
  All feature services are constructed and wired by the `Sodax` facade. You don't instantiate them directly — access them via `sodax.swaps`, `sodax.moneyMarket`, etc. See [`../architecture.md`](../architecture.md) for the service graph.
23
23
 
@@ -103,7 +103,7 @@ The `IConfigApiV1` interface itself still matters for both patterns — every me
103
103
 
104
104
  - v1 → v2 migration of `BackendApiService` (the load-bearing change: every method now returns `Promise<Result<T>>`): [`features/backend-api.md`](../../../migration-v1-to-v2/knowledge/features/backend-api.md).
105
105
  - The full submit-tx flow with `createIntent` upstream: [`./swap.md`](swap.md) § "Backend submit-tx flow".
106
- - The full typed Swaps API v2 client (`sodax.api.swaps`, 21 endpoints — quote, create-intent, submit-tx, fees, status, …): [`./swaps-api.md`](swaps-api.md).
106
+ - The full typed Swaps API client (`sodax.api.swaps`, 21 endpoints — quote, create-intent, submit-tx, fees, status, …): [`./swaps-api.md`](swaps-api.md).
107
107
  - Partner-fee handling (separate service): [`./partner.md`](partner.md).
108
108
  - Stuck-asset recovery (separate service): [`./recovery.md`](recovery.md).
109
109
  - Error model context fields (`error.context.api`, `error.context.method`): [`../reference/`](../reference/) § 3.
@@ -1,6 +1,6 @@
1
1
  # Bridge API — `BridgeApiService`
2
2
 
3
- Typed HTTP client for the backend **Bridge API v2** (`/bridge/*`). Reachable as `sodax.api.bridge`
3
+ Typed HTTP client for the backend **Bridge API** (`/bridge/*`). Reachable as `sodax.api.bridge`
4
4
  (`sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the `BridgeApiService` instance). One method
5
5
  per endpoint. Every method returns `Promise<Result<T>>` — it **never throws** — and every
6
6
  response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
@@ -8,8 +8,15 @@ response is validated at runtime against a valibot schema, so a backend contract
8
8
 
9
9
  Access: `sodax.api.bridge`. Service class: `BridgeApiService`. **Errors:** every failure (network, timeout,
10
10
  non-2xx HTTP, or response-shape mismatch) returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with
11
- `feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path); the underlying failure
12
- is on `error.cause`. Like `sodax.api.swaps`, the bridge **HTTP client** is uniformly `feature: 'backend'`
11
+ `feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path). The underlying failure
12
+ is preserved on `error.cause` — a `BridgeApiError` from the `@sodax/bridge-api` client this service wraps
13
+ (read its `code`: `NETWORK_ERROR` | `TIMEOUT_ERROR` | `HTTP_ERROR` | `PARSE_ERROR` | `VALIDATION_ERROR`;
14
+ the same code is mirrored on `error.context.code`, and both `BridgeApiError` and the `BridgeApiErrorCode`
15
+ union are re-exported from `@sodax/sdk`). Idempotent
16
+ reads/polls (and pure-compute POSTs like `getFee`) retry transient failures; mutating calls do not —
17
+ except the apiguard's transient key-verification `503`, which the wire client replays for every call
18
+ (the guard rejects before the handler runs). A `401`/`403` is terminal until the consumer fixes the key.
19
+ Like `sodax.api.swaps`, the bridge **HTTP client** is uniformly `feature: 'backend'`
13
20
  (with a per-service `context.api` tag — `'bridge'`).
14
21
 
15
22
  > Lower-level than `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end).
@@ -1,6 +1,6 @@
1
1
  # Leverage Yield API — `LeverageYieldApiService`
2
2
 
3
- Typed HTTP client for the backend **Leverage Yield API v2** (`/leverage-yield/*`). Reachable as
3
+ Typed HTTP client for the backend **Leverage Yield API** (`/leverage-yield/*`). Reachable as
4
4
  `sodax.api.leverageYield` (`sodax.api` is an alias for `sodax.backendApi`; `.leverageYield` is the
5
5
  `LeverageYieldApiService` instance). One method per endpoint (33 total). Every method returns
6
6
  `Promise<Result<T>>` — it **never throws** — and every response is validated at runtime against a valibot
@@ -4,11 +4,13 @@ Leveraged-yield ERC-4626 vaults on the Sonic hub. A vault loops supply → borro
4
4
 
5
5
  Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature tag for errors: `'leverageYield'`.
6
6
 
7
- > **Backend HTTP client:** for the typed `sodax.api.leverageYield` client that calls the backend Leverage Yield API v2 directly (vault reads, deposit/withdraw quotes + intents, submit-tx), see [`leverage-yield-api.md`](leverage-yield-api.md). Opting into `new Sodax({ leverageYield: { useBackendSubmitTx: true } })` routes this service's `vaultSwap` through that client's submit-tx flow (with client-side fallback).
7
+ > **Two products on one service.** Everything above the "Leverage positions" section is the **vault** — one shared ERC-4626 position at a single target LTV, entered and exited as an intent swap. A **leverage position** is the unpooled counterpart: one owner-controlled AAVE account per position, cloned by `LeveragePositionFactory`, with its own eMode category and leverage tier. They share the service and nothing else — vault methods take a `vault` address, position methods take a `position` address or open a new clone.
8
+
9
+ > **Backend HTTP client:** for the typed `sodax.api.leverageYield` client that calls the backend Leverage Yield API directly (vault reads, deposit/withdraw quotes + intents, submit-tx), see [`leverage-yield-api.md`](leverage-yield-api.md). Opting into `new Sodax({ leverageYield: { useBackendSubmitTx: true } })` routes this service's `vaultSwap` through that client's submit-tx flow (with client-side fallback).
8
10
 
9
11
  ## How it works
10
12
 
11
- - A vault holds `asset` (a Sodax vault token like sodaWEETH) as collateral, borrows `borrowToken` (e.g. sodaETH) from the Sodax-forked AAVE pool, swaps it back into the asset, and re-supplies — to a `targetLTV`.
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`.
12
14
  - The ERC-4626 **share token is the vault proxy address itself** (`lsoda*`). Holding shares = holding the leveraged position.
13
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.
14
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.
@@ -169,7 +171,7 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
169
171
 
170
172
  ## Error codes
171
173
 
172
- `feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap'`. Read methods partition on `context.method`.
174
+ `feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap' | 'openPosition' | 'openPositionFromDebtToken' | 'operatePosition' | 'openLeveragePosition' | 'submitLeveragePositionIntent' | 'runLeveragePositionOperation' | 'getPositionLegQuote'`. Read methods partition on `context.method`.
173
175
 
174
176
  | Method | Narrow code union |
175
177
  |---|---|
@@ -181,9 +183,182 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
181
183
  | `approve` | `VALIDATION_FAILED \| APPROVE_FAILED \| UNKNOWN` |
182
184
  | `isAllowanceValid` | `VALIDATION_FAILED \| ALLOWANCE_CHECK_FAILED \| UNKNOWN` (action `'allowanceCheck'`) |
183
185
  | Read methods | `VALIDATION_FAILED \| LOOKUP_FAILED \| UNKNOWN` (with `method` discriminator) |
186
+ | `openPosition`, `openPositionFromDebtToken`, `openLeveragePosition` | `LeverageYieldSwapError \| LeverageYieldLookupError` — the swap subset plus `LOOKUP_FAILED` (hub-wallet / factory resolution). `VALIDATION_FAILED` with `field: 'srcChainKey'` is the Bitcoin refusal |
187
+ | `operatePosition`, `submitLeveragePositionIntent`, `runLeveragePositionOperation` | `LeverageYieldSwapError` |
188
+ | `getPositionLegQuote` | same as `getQuote` — a `SolverErrorResponse` arm plus the lookup subset; guard with `isSodaxError` |
189
+ | `isPositionFundingAllowanceValid` / `approvePositionFunding` | `ALLOWANCE_CHECK_FAILED` / `APPROVE_FAILED` subsets (actions `'allowanceCheck'` / `'approve'`) |
190
+ | Position reads + `getEffectivePositionFee` | `VALIDATION_FAILED \| LOOKUP_FAILED \| UNKNOWN`. A blanked `positionFactory` fails closed here |
184
191
 
185
192
  Relay/tx-verification codes appear **only** on `vaultSwap` — `createVaultIntent` alone stays within the create-intent subset. `notifySolver` (public, for manual orchestration) emits the post-execution subset, which `vaultSwap` also surfaces.
186
193
 
194
+ ## Leverage positions
195
+
196
+ One AAVE account per position, cloned by `LeveragePositionFactory`. AAVE allows one eMode category per address, so a vault forces every depositor into one category and one leverage tier while an owner can hold several positions at different tiers at once. There is **no static registry** — discovery goes through the factory.
197
+
198
+ The factory ships as a packaged default, so `new Sodax()` drives positions with no configuration. Override only to point at a fork or staging deployment (`new Sodax({ leverageYield: { positionFactory: '0x…' } })`). Blanking it deliberately is honoured and factory-backed methods then fail closed with `LOOKUP_FAILED` rather than guessing an address. Position-only reads (`getPositionInfo`, `getPositionAccount`, `getPositionCollateralBalance`, `getPositionPendingState`) target the position directly and never need the factory.
199
+
200
+ > **`@experimental` off the hub.** Proven end to end on Sonic only. From a spoke the inbound half is verified by a fork replay of a real relayed message; the outbound half (an exit or cancel delivering the underlying back to the source chain) has never run on mainnet. **Bitcoin is refused outright** — in TRADING mode the deposit is pulled from the Bound trading wallet and these paths do not derive the hub wallet from it, so a Bitcoin `srcChainKey` returns `VALIDATION_FAILED` (`field: 'srcChainKey'`) instead of funding the wrong wallet.
201
+
202
+ ### Reads
203
+
204
+ ```ts
205
+ sodax.leverageYield.listPositions(owner: Address): Promise<Result<readonly Address[], LeverageYieldLookupError>>;
206
+ sodax.leverageYield.listPositionsForUser(srcChainKey, srcAddress): Promise<Result<readonly Address[], …>>; // POSITIONAL args, not an object
207
+ sodax.leverageYield.getPositionInfo(position: Address): Promise<Result<LeveragePosition, …>>;
208
+ sodax.leverageYield.getPositionAccount(position: Address): Promise<Result<LeveragePositionAccount, …>>;
209
+ sodax.leverageYield.getPositionCollateralBalance(position, collateral?): Promise<Result<LeveragePositionCollateral, …>>;
210
+ sodax.leverageYield.getPositionPendingState(position: Address): Promise<Result<LeveragePositionPendingState, …>>;
211
+ sodax.leverageYield.predictPosition(creator, owner, positionId?): Promise<Result<Address, …>>; // defaults to the next id
212
+ sodax.leverageYield.getEffectivePositionFee(override?): Result<{ feeReceiver: Address; feeBps: number }, …>; // SYNCHRONOUS
213
+ ```
214
+
215
+ | Type | Fields |
216
+ |---|---|
217
+ | `LeveragePosition` | `{ address, owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver }` — static descriptor, fee fixed at creation |
218
+ | `LeveragePositionAccount` | `{ totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor }` — all bigint |
219
+ | `LeveragePositionCollateral` | `{ aToken, balance }` — exact aToken balance in the collateral reserve's decimals |
220
+ | `LeveragePositionPendingState` | `{ kind: number, isLive: boolean, needsSettle: boolean }` |
221
+
222
+ `getPositionAccount` reads `getUserAccountData` on the pool, not the position contract (which keeps no accounting). `healthFactor` is WAD (1e18); the `*Base` figures use the pool oracle's 8-decimal base unit and are **display-only**. Any amount going into a transaction comes from `getPositionCollateralBalance` — dividing base currency back out by a price lands only *near* the balance, and a `decreaseLeverage` asking for more collateral than the position holds does not fail on submission: the hook's `transferFrom` reverts at fill time and the intent silently expires.
223
+
224
+ ### Writes — use the high-level calls
225
+
226
+ `openPosition`, `openPositionFromDebtToken` and `operatePosition` only **post** the intent. Reporting it is a separate `notifySolver` call, and an unreported intent expires unfilled — the owner ends up funded with leverage that never arrives and nothing said so. Three methods pair the two steps, and which one to use is decided by the operation, not by preference:
227
+
228
+ | operation | method | notifies |
229
+ |---|---|---|
230
+ | open, either side | `openLeveragePosition({ side?, params, walletProvider })` | yes |
231
+ | `buildAddLeverage` / `buildDecreaseLeverage` | `submitLeveragePositionIntent({ params: { srcChainKey, srcAddress, calls }, walletProvider })` | yes |
232
+ | `buildPositionWithdraw` / `buildSettlePosition` / `buildCancelPositionOperation` | `runLeveragePositionOperation(…)` | no |
233
+
234
+ `withdraw`, `settle` and `cancel` are synchronous on the hub and need no notification. **The compiler enforces the rows:** `buildAddLeverage` / `buildDecreaseLeverage` return `PositionIntentCall`, the other three return `PositionDirectCall`, and each method accepts only its own. The brands are type-only and erased at runtime. A direct call may ride along in a reporting batch (`[buildSettlePosition, buildAddLeverage]` is the sequence batching exists for); an intent call on the route-only path is refused.
235
+
236
+ ```ts
237
+ sodax.leverageYield.openLeveragePosition<K>(params:
238
+ | ({ side?: 'collateral' } & SpokeExecActionParams<K, false, OpenPositionParams<K>>)
239
+ | ({ side: 'debt' } & SpokeExecActionParams<K, false, OpenPositionFromDebtTokenParams<K>>)
240
+ ): Promise<Result<LeveragePositionIntentResult, LeverageYieldSwapError | LeverageYieldLookupError>>;
241
+
242
+ sodax.leverageYield.submitLeveragePositionIntent<K>(
243
+ params: SpokeExecActionParams<K, false, PositionOperationParams<K, PositionBatchCall>>
244
+ ): Promise<Result<LeveragePositionIntentResult, LeverageYieldSwapError>>;
245
+
246
+ sodax.leverageYield.runLeveragePositionOperation<K>(
247
+ params: SpokeExecActionParams<K, false, PositionOperationParams<K, PositionDirectCall>>
248
+ ): Promise<Result<TxHashPair, LeverageYieldSwapError>>;
249
+
250
+ // LeveragePositionIntentResult = { txHashes: TxHashPair; notified: boolean; notifyError?: string }
251
+ ```
252
+
253
+ **A failed notification is `ok: true`, deliberately.** The money has already moved and the intent is live on the hub; returning a failure would tell the caller nothing happened, and a caller that retries on failure would open a second position. Read `notified` on the value — `false` means nothing will fill the intent before it expires.
254
+
255
+ ### Params shape
256
+
257
+ ```ts
258
+ type PositionFundingParams<K> = {
259
+ srcChainKey: K;
260
+ srcAddress: string; // funds come from here; a failed intent refunds here
261
+ token: string; // token on srcChainKey to fund with
262
+ amount: bigint; // in `token`'s OWN decimals — wrapping to the 18-dp hub reserve happens in the batch
263
+ eModeCategory?: number; // fixed for the life of the position; defaults to 0
264
+ minCollateralOut: bigint; // slippage floor on what the solver must deliver
265
+ partnerFee?: PartnerFee; // percentage variant only; FIXED AT CREATION, capped (see `MAX_POSITION_FEE_BPS` in `packages/sdk/src/leverageYield/LeverageYieldService.ts`); rate and receiver must be set together or not at all; defaults to leverageYield.partnerFee
266
+ };
267
+ type OpenPositionParams<K> = PositionFundingParams<K> & { borrowToken: Address; borrowAmount: bigint };
268
+ type OpenPositionFromDebtTokenParams<K> = PositionFundingParams<K> & { collateral: Address; totalInput: bigint };
269
+ type PositionOperationParams<K, C> = { srcChainKey: K; srcAddress: string; calls: readonly C[] };
270
+ ```
271
+
272
+ There is **no `owner`**: the factory requires `cfg.owner == msg.sender` and the caller is always the funder's own hub wallet. That binding is what makes the refund address safe — `originAddress` decides where a cancelled operation's funds go, and past a deadline anyone may trigger that cancel. To fund someone else, supply into a position they already own: `pool.supply(collateral, amount, position, 0)`.
273
+
274
+ ### Funding approval
275
+
276
+ **Nothing is ever approved to the factory** — it pulls from nobody. Funding is a transfer to `predictPosition(...)` and the clone supplies whatever it finds, batched with the create so a stale prediction reverts and takes the transfer with it rather than stranding tokens. Do not open two positions for one owner concurrently: the owner's own second open is the only thing that can advance the id, and off the hub the deposit has already reached the hub wallet when the batch reverts — recover it with `sodax.recovery`. The one approval that does exist has a spender that **differs by chain** — the user's own hub wallet on the hub (the pull happens inside the routed batch), the spoke asset manager elsewhere:
277
+
278
+ ```ts
279
+ sodax.leverageYield.isPositionFundingAllowanceValid({ srcChainKey, srcAddress, token, amount }): Promise<Result<boolean, …>>;
280
+ sodax.leverageYield.approvePositionFunding({ srcChainKey, srcAddress, token, amount, walletProvider? }): Promise<Result<TxReturnType<K, false>, …>>;
281
+ ```
282
+
283
+ `approvePositionFunding` waits for the approve to land before resolving — `verifyTxHash` returns `{ ok: true }` for EVM without waiting, which is why hand-rolled callers were asking users to approve twice.
284
+
285
+ ### Sizing the leg — do not skip
286
+
287
+ `borrowAmount` / `minCollateralOut` are yours to supply and **computing them from oracle prices does not work**. Leverage is bought through the solver and the two legs do not trade at their oracle ratio: `LeverageHook` supplies whatever the solver actually paid and only *then* borrows against it, so the pool sees `deposit + solver output`, never `deposit × leverage`. Parity sizing gets the borrow rejected with Aave `'36'` (COLLATERAL_CANNOT_COVER_NEW_BORROW) *after* the solver has filled, unwinding the whole fill. It happened twice on mainnet — once at 11.03x where parity predicted 84% LTV against a real 92.06% and a 91% cap.
288
+
289
+ ```ts
290
+ import { sizeLeverageBorrow, projectLeverageLeg, type LeverageLegRequest } from '@sodax/sdk';
291
+
292
+ // LeverageLegRequest = { side, deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd,
293
+ // borrowDecimals, leverage, feeBps? }
294
+ // 1. Oracle-sized, because there is nothing else yet.
295
+ const { borrowAmount, intentInput } = sizeLeverageBorrow(request);
296
+ // LeverageBorrowSizing = { borrowAmount, intentInput, depositUsd, borrowUsd, feeAmount }
297
+
298
+ // 2. Quote `intentInput`, NOT `borrowAmount` — on a debt-side open the user's contribution goes to
299
+ // the solver too. Use getPositionLegQuote: it names the hub reserves the intent actually swaps
300
+ // and quotes gross, the two details a hand-rolled getQuote gets wrong.
301
+ const leg = await sodax.leverageYield.getPositionLegQuote({
302
+ inputHubToken: borrowReserve.underlyingAsset, // the hub RESERVE ADDRESS, not the reserve object
303
+ outputHubToken: collateralReserve.underlyingAsset,
304
+ amount: intentInput,
305
+ });
306
+ if (!leg.ok) throw leg.error; // PositionLegQuote = { quotedAmount }
307
+
308
+ // 3. Now the honest numbers, from the quote.
309
+ const p = projectLeverageLeg(
310
+ request,
311
+ { quotedCollateral: leg.value.quotedAmount, collateralDecimals }, // LeverageLegQuote
312
+ { ltv, liquidationThreshold }, // ReserveRiskParams (numbers, not bps)
313
+ slippagePct,
314
+ );
315
+ if (p.exceedsMaxLtv) throw new Error(`max ~${p.usableMaxLeverage.toFixed(2)}x at this price`);
316
+ // open with { borrowAmount, minCollateralOut: p.minCollateralOut }
317
+ ```
318
+
319
+ `LeverageLegProjection = { minCollateralOut, collateralUsd, debtUsd, ltv, healthFactor, exceedsMaxLtv, usableMaxLeverage, haircut, inputUsd, costUsd, exposureLeverage }`. Four things about it:
320
+
321
+ - **`exceedsMaxLtv` is a hard gate, not a warning.** Post through it and the intent is accepted, then fails at fill.
322
+ - **`usableMaxLeverage` is the real ceiling, strictly below `1 / (1 - ltv)`.** At `ltv` 91% with the solver returning 98.77% of parity it is 9.88x — so an 11.03x that looked fine against parity was never available.
323
+ - **Everything is projected from the FLOOR, not the quote** — the floor is the worst fill the intent permits, so if the floor is safe every fill is. `haircut` and `costUsd` are the exception: expected cost measured from the quote, which is what a payback period should use.
324
+ - **`leverage` is a multiple of the DEPOSIT and the open position reports more.** The borrow is booked in full while the collateral arrives short by the haircut, leaving `deposit × (1 - (L-1)h)` of equity. Always higher, never lower: 2.00x requested at a 4.657% haircut reports **2.0488x**. Display `exposureLeverage`, not the number the user chose.
325
+
326
+ Read `ltv` / `liquidationThreshold` from the eMode category whenever the position sets one — a category's LTV replaces the reserve's own. **On a debt-side open the deposit is not collateral**: it is handed to the solver as part of the input, so the only collateral the position ends up with is what the solver delivers. Counting it on both sides is the other half of that 84%-vs-92% miss; `side: 'debt'` handles it.
327
+
328
+ ### Fees — read them from the POSITION, not from config
329
+
330
+ `getEffectivePositionFee()` answers what a position created *now* would carry, which is what an **open** needs. An existing position's fee was fixed at creation, so config changes and per-call overrides make the two disagree — `getPositionInfo` returns that position's own `feeBps` / `feeReceiver`, and an adjust or exit has to charge those. The fee is given up **on top of** what the solver is paid, so at a non-zero fee an exit sized at the whole collateral balance leaves nothing for it and cannot settle: the input is `balance × 10_000 / (10_000 + feeBps)`.
331
+
332
+ ### Low-level builders
333
+
334
+ Builders return an `EvmRawTransaction` for the caller to run as the hub wallet. Every position write is `onlyOwner` and the owner is the hub wallet, so a builder's transaction sent from the signing address reverts — setting `from` does not help, an address cannot send as another address. Reach for the three high-level methods above; these are the unit they carry.
335
+
336
+ | Builder | Effect |
337
+ |---|---|
338
+ | `buildCreatePositionAndLeverage(…)` | Clone and lever in one tx. `initialAssets` must ALREADY be at the position's address |
339
+ | `buildCreatePositionFromDebtToken(…)` | Open from the **debt** token with no collateral of your own |
340
+ | `buildAddLeverage(…)` | Borrow and swap into more collateral → `PositionIntentCall` |
341
+ | `buildDecreaseLeverage(…)` | Give up collateral to repay debt; with the whole balance this is a close into the debt token → `PositionIntentCall` |
342
+ | `buildPositionWithdraw(…)` | Withdraw collateral out, to any address → `PositionDirectCall` |
343
+ | `buildSettlePosition(…)` | Clear a resolved operation and sweep loose funds to the owner. Permissionless → `PositionDirectCall` |
344
+ | `buildCancelPositionOperation(…)` | Cancel the in-flight operation → `PositionDirectCall` |
345
+
346
+ The two create builders return a `Result` (they need the factory address); the rest target the position directly and return the transaction unwrapped. `encodePositionCalls(txs)` gives the hub-wallet payload if you want to drive `spoke.deposit` / `spoke.sendMessage` yourself.
347
+
348
+ Three behaviours to design around:
349
+
350
+ - **Leverage changes are asynchronous.** `addLeverage` / `decreaseLeverage` only post an intent; poll `getPositionPendingState` instead of treating the receipt as completion. A position refuses a second operation while one is in flight.
351
+ - **Which hash to report.** `TxHashPair` returns both. `srcChainTxHash` is what the user signed; **`dstChainTxHash`** is the hub transaction the intent exists in, and that is the one `notifySolver` needs. On the hub they are the same transaction; from a spoke they are not.
352
+ - **Cancelling returns nothing, because nothing was escrowed.** Posting a position intent moves no funds; cancelling revokes the grant and clears the pending slot.
353
+
354
+ ### Closing a position
355
+
356
+ Two exits, differing in what the owner ends up holding. **Into the collateral:** sell only as much collateral as the debt is worth (`buildDecreaseLeverage`), wait for the fill, then `buildPositionWithdraw` the remainder — two operations, and the withdrawal can pay out to any address. Overshoot the debt slightly; it accrues between quoting and filling, and dust debt left behind blocks the withdrawal entirely. **Into the debt token:** sell the collateral balance in one `buildDecreaseLeverage` (net of `feeBps`, see above); the solver delivers more debt token than is owed, the hook repays and leaves the surplus for `buildSettlePosition` to sweep to the position's `owner` — not to whoever signed.
357
+
358
+ A full exit cannot half-happen: were the delivered amount short of the debt, the hook's withdrawal would leave debt against no collateral and the pool's health-factor check rejects it, reverting the whole fill. Quote the full amount and check the floor covers the debt before posting.
359
+
360
+ Collateral top-ups and debt repayment need no SDK call — AAVE accepts both against an arbitrary account (`pool.supply(collateral, amount, position, 0)`, `pool.repay(borrowToken, amount, 2, position)`), so defending a position never waits on a solver fill.
361
+
187
362
  ## Cross-references
188
363
 
189
364
  - ERC-4626 share-as-token model, APR math, and the deliberate swap-domain duplication: SDK source `packages/sdk/docs/LEVERAGE_YIELD.md`.
@@ -42,6 +42,7 @@ sodax.swaps.createLimitOrderIntent<K, Raw>(/* same as createIntent shape with li
42
42
 
43
43
  sodax.swaps.cancelIntent<K>(/* … */): Promise<Result<TxHashPair, SodaxError>>; // not generic over Raw (only false)
44
44
  sodax.swaps.cancelLimitOrder<K>(/* … */): Promise<Result<TxHashPair, SodaxError>>; // TxHashPair = { srcChainTxHash, dstChainTxHash }
45
+ sodax.swaps.getCancelIntentRelayData(intent: Intent): Result<RelayExtraData>; // `data` for manually relaying a Solana cancel tx
45
46
 
46
47
  sodax.swaps.approve<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
47
48
  sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxError>>;
@@ -49,7 +50,7 @@ sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxEr
49
50
  sodax.swaps.getSwapSpeedTier(params: { srcToken: XToken; dstToken: XToken }): SwapSpeedTierResult;
50
51
  // Synchronous, offline, no Result wrapper — estimates settlement speed from SDK config alone
51
52
  // (no network / on-chain / backend call). SwapSpeedTierResult = { tier: 'fast'|'normal'|'slow', estimatedSeconds }.
52
- // A token tied to a money-market-reserve (sodaAsset) settles faster; an Ethereum leg adds a fixed penalty.
53
+ // A token whose `vault` is a money-market reserve (sodaAsset) settles faster; an Ethereum leg adds a fixed penalty.
53
54
  // Safe to call synchronously while rendering a quote (e.g. an ETA badge next to the output amount).
54
55
 
55
56
  sodax.swaps.getStatus(
@@ -317,6 +318,12 @@ await sodax.swaps.cancelIntent({
317
318
  });
318
319
  ```
319
320
 
321
+ Relay handling is chain-aware and needs no caller input: Solana cancels submit the cancel payload with the spoke tx, Bitcoin cancels relay the signed on-demand payload. On Bitcoin `srcChainTxHash` is the relay's `od:<hash>` id, not a chain tx hash.
322
+
323
+ `params.srcAddress` (optional) overrides the wallet the cancel is sent from; it defaults to the intent's `srcAddress`, or on Bitcoin TRADING mode to `walletProvider.getWalletAddress()` (the intent stores the trading address). A raw (`raw: true`) Bitcoin TRADING-mode cancel must pass it.
324
+
325
+ Relaying a `createCancelIntent` tx yourself: on Solana pass `data: sodax.swaps.getCancelIntentRelayData(intent).value` to `submitIntent` (the create-intent extra data does not match a cancel tx); on Bitcoin the returned value is the signed on-demand payload JSON — relay it via `sodax.spoke.bitcoin.getOnDemandRelayIdentity(json)` (`srcTxHash: 'withdraw'`, `data`, `pollTxHash`).
326
+
320
327
  ## Return shapes
321
328
 
322
329
  | Method | Success type |
@@ -1,6 +1,6 @@
1
1
  # Swaps API — `SwapsApiService`
2
2
 
3
- Typed HTTP client for the backend **Swaps API v2** (`/swaps/*`). Reachable as `sodax.api.swaps`
3
+ Typed HTTP client for the backend **Swaps API** (`/swaps/*`). Reachable as `sodax.api.swaps`
4
4
  (`sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the `SwapsApiService` instance). One method
5
5
  per endpoint (21 total). Every method returns `Promise<Result<T>>` — it **never throws** — and every
6
6
  response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
@@ -95,7 +95,7 @@ Optional on the type, but no default: the backend does not fill it in, and
95
95
  `new Sodax({ fee })` / `new Sodax({ swaps: { partnerFee } })` only reach the
96
96
  `sodax.swaps` orchestrator — not this wire path. Send the same value on quote and
97
97
  create-intent. `checkAllowance` / `approve` inherit the field but ignore it.
98
- Bridge API v2 is different: omitted `partnerFee` falls back to `bridgePartnerFee`.
98
+ The Bridge API is different: omitted `partnerFee` falls back to `bridgePartnerFee`.
99
99
 
100
100
  ## API key
101
101
 
@@ -24,8 +24,8 @@ chain config from the backend but **never** replaces the logger — the backend
24
24
  it.
25
25
 
26
26
  > Combine with the other constructor options freely — pass `logger` alongside `chains` / `api` /
27
- > `solver` overrides in the same object. The constructor splits `logger` off the data override before
28
- > merging, so it never lands in `sodax.instanceConfig`. See [`initialize-sodax.md`](initialize-sodax.md).
27
+ > `solver` overrides in the same object. The merged options land on `sodax.instanceConfig` (including the
28
+ > `logger` key), but the sink the services use is `sodax.config.logger`. See [`initialize-sodax.md`](initialize-sodax.md).
29
29
 
30
30
  ## Custom sink
31
31
 
@@ -162,7 +162,7 @@ Both follow the same shape: action methods get the full exec union (`'EXECUTION_
162
162
 
163
163
  ### Backend / Swaps API (`feature: 'backend'`)
164
164
 
165
- `BackendApiService` (`sodax.backendApi`) and the Swaps API v2 client (`sodax.api.swaps`) are the HTTP-client layer — not domain features. Every method returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with `context.endpoint`, and the transport failure (timeout / non-2xx / response-shape mismatch) preserved on `error.cause`. `context.api` distinguishes the two clients: `'backend'` for `BackendApiService`, `'swaps'` for the `sodax.api.swaps` client.
165
+ `BackendApiService` (`sodax.backendApi`) and the Swaps API client (`sodax.api.swaps`) are the HTTP-client layer — not domain features. Every method returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with `context.endpoint`, and the transport failure (timeout / non-2xx / response-shape mismatch) preserved on `error.cause`. `context.api` distinguishes the two clients: `'backend'` for `BackendApiService`, `'swaps'` for the `sodax.api.swaps` client.
166
166
 
167
167
  ### Leverage Yield (`feature: 'leverageYield'`)
168
168
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Import everything from `@sodax/sdk`. The barrel re-exports the entire `@sodax/types` surface — you don't need a separate `@sodax/types` dependency.
4
4
 
5
- `sodax.api` is an alias for `sodax.backendApi`; `sodax.api.swaps` is the typed Swaps API v2 client (`SwapsApiService`) — see [`../features/swaps-api.md`](../features/swaps-api.md).
5
+ `sodax.api` is an alias for `sodax.backendApi`; `sodax.api.swaps` is the typed Swaps API client (`SwapsApiService`) — see [`../features/swaps-api.md`](../features/swaps-api.md).
6
6
 
7
7
  ### Top-level exports
8
8
 
@@ -15,6 +15,14 @@ import {
15
15
  type SodaxDefaultConfig, // static data contract the backend serves / defaults are built from
16
16
  type DeepPartial,
17
17
 
18
+ // Release identity — see "Config version" below
19
+ CONFIG_VERSION,
20
+ SDK_VERSION,
21
+ configVersionFor,
22
+ formatConfigVersion,
23
+ parseConfigVersion,
24
+ type ParsedConfigVersion,
25
+
18
26
  // Logging (see recipes/logging.md)
19
27
  type SodaxLogger,
20
28
  type SodaxLoggerOption,
@@ -215,6 +223,34 @@ This is a partial list — see `src/index.ts` of the published tarball for the a
215
223
  ---
216
224
 
217
225
 
226
+ ## Config version
227
+
228
+ `CONFIG_VERSION` identifies the SDK release a SODAX config belongs to. The backend serves this same
229
+ constant from the `@sodax/sdk` release it has installed, so comparing the two answers *are the SDK and
230
+ the API on the same release?* It is derived from the package version:
231
+ `major * 1e6 + minor * 1e4 + patch * 100 + (rc ?? 99)`, where the `99` rc slot means "stable".
232
+
233
+ ```ts
234
+ import { CONFIG_VERSION, SDK_VERSION, configVersionFor, formatConfigVersion, parseConfigVersion } from '@sodax/sdk';
235
+
236
+ SDK_VERSION; // '2.0.0-rc.17' — computed from CONFIG_VERSION, so it cannot go stale
237
+ formatConfigVersion(2_020_099); // '2.2.0'
238
+ parseConfigVersion(2_020_006); // { major: 2, minor: 2, patch: 0, rc: 6 }
239
+ configVersionFor('2.2.0'); // 2_020_099
240
+ ```
241
+
242
+ **All three helpers are total** — they return `null` rather than throwing, for anything outside the
243
+ encoding: an out-of-grammar version (`configVersionFor('2.3.0-beta.1')`), a field out of range
244
+ (`configVersionFor('2.2.100')` — minor and patch cap at 99, rc at 98, major at 1..99), or a number that
245
+ is not a config version at all (`parseConfigVersion(235)`, a legacy counter value). Handle the `null`;
246
+ do not assume a value came back.
247
+
248
+ `rc` is `null` for a stable release. `rc: 0` is legal and falsy, so compare against `null` rather than
249
+ testing truthiness.
250
+
251
+ Do not unpack the integer by hand, and do not write your own copy of the formula — the field widths are
252
+ part of the contract and are enforced at release time.
253
+
218
254
  ## Cross-references
219
255
 
220
256
  - [`README.md`](README.md) — reference index.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: sodax-sdk-leverage-yield
3
- description: 'Granular skill for the @sodax/sdk v2 leverage-yield feature only — leveraged-yield ERC-4626 vaults on Sonic via LeverageYieldService. Deposit any token → lsoda* shares, withdraw shares → any token (both as solver-tradeable intent swaps), createVaultIntent/vaultSwap/notifySolver, Sonic-direct approve/isAllowanceValid, and reads (getApr, getEffectiveApr, getPosition, getTotalAssets, preview*, getMaxWithdraw*, getShareBalance*, listVaults). Use when the task is leverage-yield vaults (e.g. "deposit into a leverage vault", "withdraw lsoda shares", "vault APR / effective APR", "leverage vault position / health factor", "lsoda share balance"). New in v2 — integration only, no v1 migration path. Links into the parent sodax-sdk knowledge tree. For React dapps, prefer sodax-dapp-kit.'
3
+ description: 'Granular skill for the @sodax/sdk v2 leverage-yield feature only, covering BOTH products on LeverageYieldService: (1) leveraged-yield ERC-4626 vaults on Sonic — deposit any token → lsoda* shares, withdraw shares → any token (solver-tradeable intent swaps), createVaultIntent/vaultSwap/notifySolver, approve/isAllowanceValid, and reads (getApr, getEffectiveApr, getPosition, getTotalAssets, preview*, getMaxWithdraw*, getShareBalance*, listVaults); and (2) LEVERAGE POSITIONS — one owner-controlled AAVE account per position cloned by LeveragePositionFactory, via openLeveragePosition / submitLeveragePositionIntent / runLeveragePositionOperation, the openPosition / openPositionFromDebtToken / operatePosition low-level pair, position reads (listPositions, listPositionsForUser, getPositionInfo, getPositionAccount, getPositionCollateralBalance, getPositionPendingState, predictPosition), approvePositionFunding, and leg sizing with sizeLeverageBorrow / projectLeverageLeg / getPositionLegQuote. Use when the task is leverage-yield vaults (e.g. "deposit into a leverage vault", "withdraw lsoda shares", "vault APR / effective APR", "lsoda share balance") OR leverage positions (e.g. "open a leverage position", "adjust / increase / decrease leverage", "close a leveraged position", "position health factor / LTV", "size borrowAmount and minCollateralOut", "leveraged long with my own AAVE account"). New in v2 — integration only, no v1 migration path. Links into the parent sodax-sdk knowledge tree. For React dapps, prefer sodax-dapp-kit.'
4
4
  license: MIT
5
5
  metadata:
6
6
  version: '0.0.1'
@@ -13,11 +13,19 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
13
13
 
14
14
  ## Step 1 — Clarify with user before coding
15
15
 
16
+ 0. **Vault or leverage position?** Ask this first — they share the service and nothing else. A **vault** is one pooled ERC-4626 position at a single target LTV, entered/exited as an intent swap (`deposit` / `withdraw` / `vaultSwap`). A **leverage position** is the user's own AAVE account, cloned per position, with its own eMode category and leverage tier (`openLeveragePosition` and friends). "Deposit into a leverage vault" is the first; "open a leverage position", "adjust my leverage", "close my position" is the second. If the answer is positions, jump to Step 1b.
16
17
  1. **Deposit or withdraw?** Deposit = any spoke token → `lsoda*` shares (delivered to the user's hub wallet). Withdraw = `lsoda*` shares (in the hub wallet) → any token on any chain.
17
18
  2. **Build vs execute.** `deposit` / `withdraw` only *build* a `LeverageYieldSwapPayload`; `vaultSwap` *executes* it end-to-end. Spread the built payload into `vaultSwap({ ...payload, walletProvider })`.
18
19
  3. **End-to-end or manual relay?** `vaultSwap` does create → verify → relay → notify. For backend submit-tx, use `createVaultIntent` then relay yourself and finish with the public `notifySolver`.
19
20
  4. **Reads?** `getEffectiveApr` (headline, AAVE + LSD), `getApr` (AAVE-only — can be negative), `getPosition`, `getTotalAssets`, `previewRedeem`, `getMaxWithdrawForUser` / `getShareBalanceForUser` (resolve the hub wallet from a spoke address internally).
20
21
 
22
+ ### Step 1b — leverage positions
23
+
24
+ 1. **Which operation?** It decides the method, and the choice is not stylistic. Open → `openLeveragePosition`. Leverage change (`buildAddLeverage` / `buildDecreaseLeverage`) → `submitLeveragePositionIntent`. Withdraw / settle / cancel → `runLeveragePositionOperation`. The first two report the intent; the third has nothing to report. Sending a leverage change through the route-only path leaves an intent nothing will fill, and it expires without a word — the compiler refuses it via the `PositionIntentCall` / `PositionDirectCall` brands.
25
+ 2. **Which side funds the open?** `side: 'collateral'` deposits the collateral asset. `side: 'debt'` funds with the debt token and the deposit is **not** collateral — it goes to the solver as part of the input, so the only collateral the position gets is what the solver delivers.
26
+ 3. **Have you sized the leg?** `borrowAmount` / `minCollateralOut` must come from `sizeLeverageBorrow` → `getPositionLegQuote` → `projectLeverageLeg`. Oracle parity is wrong and fails *after* the solver fills. Never hand-roll it.
27
+ 4. **Which chain?** Sonic (the hub) is the proven path. A non-hub `srcChainKey` is `@experimental`; Bitcoin is refused outright.
28
+
21
29
  ## Integration workflow
22
30
 
23
31
  1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md).
@@ -37,12 +45,28 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
37
45
  - **Quoting with a different `partnerFee` than the intent charges.** The fee is deducted from the input before the swap, so the quote is sized on a different net input; when the intent's fee is the larger one, the `minOutputAmount` derived from that quote can't be met and the intent never fills. Pass the same `partnerFee` to `getQuote` and to `deposit()` / `vaultSwap()`, or omit it on both.
38
46
  - **Assuming `swaps.partnerFee` monetizes vault flows.** It does not — configure `leverageYield.partnerFee` (or the global `fee`).
39
47
 
48
+ ### Leverage-position anti-patterns
49
+
50
+ - **Sizing `borrowAmount` / `minCollateralOut` from oracle prices.** The hook supplies what the solver actually paid and only then borrows against it, so the pool sees `deposit + solver output`, never `deposit × leverage`. Parity sizing is accepted, the solver fills, and the borrow then reverts with Aave `'36'` — unwinding the fill. Use `sizeLeverageBorrow` + `projectLeverageLeg` with a `getPositionLegQuote` between them, and treat `exceedsMaxLtv` as a hard gate.
51
+ - **Quoting `borrowAmount` instead of `intentInput`.** On a debt-side open the user's own contribution goes to the solver too, so quoting the borrow alone understates the input.
52
+ - **Calling `getQuote` for a position leg.** `getPositionLegQuote` names the hub reserves the intent actually swaps and quotes gross — both details a hand-rolled `getQuote` gets wrong, and both surface only as an unfillable floor. Pass the reserve **address** (`reserve.underlyingAsset`), not the reserve object.
53
+ - **Routing a leverage change through `runLeveragePositionOperation`.** It does not notify, so the intent expires unfilled. The brands refuse it at compile time — do not cast past them.
54
+ - **Treating a resolved open as an open position.** `openLeveragePosition` resolving means the intent is LIVE. Read `notified` on the value; `false` means nothing will fill it. It is deliberately not an error — retrying would open a second position.
55
+ - **Treating the transaction receipt as completion.** `addLeverage` / `decreaseLeverage` are filled by a solver afterwards; poll `getPositionPendingState`.
56
+ - **Reporting `srcChainTxHash` to `notifySolver`.** The intent exists in the **hub** transaction — `dstChainTxHash`. They are the same only on the hub.
57
+ - **Sizing a transaction from `totalCollateralBase`.** Base-currency figures are display-only; use `getPositionCollateralBalance`. An over-sized `decreaseLeverage` does not fail on submission — it reverts at fill and the intent silently expires.
58
+ - **Charging an existing position the configured fee.** `getEffectivePositionFee()` is what a NEW position would carry; an existing one's fee was fixed at creation — read `getPositionInfo`. The fee is given up on top of the solver's payment, so an exit sized at the whole collateral balance cannot settle.
59
+ - **Approving the factory.** It pulls from nobody. Funding is a transfer to `predictPosition(...)`; the one real approval has a spender that differs per chain, which `approvePositionFunding` resolves.
60
+ - **Passing an `owner`.** There is none — the factory requires `cfg.owner == msg.sender` and the caller is always the funder's own hub wallet.
61
+
40
62
  ## Verification
41
63
 
42
64
  1. `pnpm tsc --noEmit` clean.
43
65
  2. Every `await sodax.leverageYield.<method>(...)` has `if (!result.ok)`.
44
66
  3. Deposit/withdraw build a payload that is then run through `vaultSwap` (or `createVaultIntent` + relay + `notifySolver`).
45
67
  4. APR display uses `getEffectiveApr`; share/withdraw sizing from a spoke address uses the `*ForUser` reads.
68
+ 5. Positions: every `borrowAmount` / `minCollateralOut` traces back to `sizeLeverageBorrow` + `projectLeverageLeg` (never oracle parity), `exceedsMaxLtv` is checked before posting, and `notified` is read on every open / leverage change.
69
+ 6. Positions: leverage changes go through `submitLeveragePositionIntent`, not `runLeveragePositionOperation`; `notifySolver` is given `dstChainTxHash`; exits are sized from `getPositionCollateralBalance` and charge the fee from `getPositionInfo`.
46
70
 
47
71
  ## Related granular skills (same family)
48
72
 
@@ -1,12 +1,12 @@
1
1
  ---
2
2
  name: sodax-sdk-leverage-yield-api
3
- description: 'Granular skill for the @sodax/sdk v2 Leverage Yield API client — `sodax.api.leverageYield` (class LeverageYieldApiService), a typed HTTP client for the backend Leverage Yield API v2 (`/leverage-yield/*`, 33 endpoints: vault registry, vault reads (asset/position/APR/effective-APR/LSD-APR/total-assets/previews/share-balance/max-withdraw), deposit & withdraw quote, deadline, allowance/approve, create-deposit-intent & create-withdraw-intent, intent submit/status/cancel/hash/packet/extra-data/fill/get, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the leverage-yield backend directly (e.g. "sodax.api.leverageYield", "leverage vault APR from the backend", "vault position from the API", "leverage-yield deposit quote", "createDepositIntent via the backend API", "leverage-yield API v2"). For the higher-level end-to-end vault-swap orchestrator use the `leverage-yield` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
3
+ description: 'Granular skill for the @sodax/sdk v2 Leverage Yield API client — `sodax.api.leverageYield` (class LeverageYieldApiService), a typed HTTP client for the backend Leverage Yield API (`/leverage-yield/*`, 33 endpoints: vault registry, vault reads (asset/position/APR/effective-APR/LSD-APR/total-assets/previews/share-balance/max-withdraw), deposit & withdraw quote, deadline, allowance/approve, create-deposit-intent & create-withdraw-intent, intent submit/status/cancel/hash/packet/extra-data/fill/get, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the leverage-yield backend directly (e.g. "sodax.api.leverageYield", "leverage vault APR from the backend", "vault position from the API", "leverage-yield deposit quote", "createDepositIntent via the backend API", "leverage-yield API v2"). For the higher-level end-to-end vault-swap orchestrator use the `leverage-yield` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
4
4
  ---
5
5
 
6
6
  # Leverage Yield API (Core SDK granular skill)
7
7
 
8
8
  Granular skill for `sodax.api.leverageYield` (class `LeverageYieldApiService`) — the typed HTTP client for
9
- the backend **Leverage Yield API v2** (`/leverage-yield/*`). `sodax.api` is an alias for `sodax.backendApi`;
9
+ the backend **Leverage Yield API** (`/leverage-yield/*`). `sodax.api` is an alias for `sodax.backendApi`;
10
10
  `.leverageYield` is the leverage-yield client. 33 endpoints, one method each; every method returns
11
11
  `Promise<Result<T>>` (never throws) and validates the response. Errors carry `feature: 'backend'`,
12
12
  `context.api: 'leverageYield'`, `context.endpoint`.
@@ -63,7 +63,7 @@ Read in order. Skipping `ai-rules.md` is the most common cause of agents reverti
63
63
  - [`../partner/SKILL.md`](../partner/SKILL.md) — partner fees on swap.
64
64
  - [`../recovery/SKILL.md`](../recovery/SKILL.md) — stuck-asset recovery for failed swaps.
65
65
  - [`../backend-api/SKILL.md`](../backend-api/SKILL.md) — `sodax.api.swaps.submitTx` and intent / orderbook lookups (step-by-step swap flow + diagnostics).
66
- - [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the typed Swaps API v2 backend client (`sodax.api.swaps`: quote, create-intent, submit-tx, fees) the swap flow calls under the hood.
66
+ - [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the typed Swaps API backend client (`sodax.api.swaps`: quote, create-intent, submit-tx, fees) the swap flow calls under the hood.
67
67
 
68
68
  For tasks spanning multiple features, load the broad [`sodax-sdk` skill](../SKILL.md) instead.
69
69
 
@@ -1,12 +1,12 @@
1
1
  ---
2
2
  name: sodax-sdk-swaps-api
3
- description: 'Granular skill for the @sodax/sdk v2 Swaps API client — `sodax.api.swaps` (class SwapsApiService), a typed HTTP client for the backend Swaps API v2 (`/swaps/*`, 21 endpoints: quote, deadline, allowance/approve, create-intent, intent submit/status/cancel/hash/packet/extra-data, limit orders, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the swaps backend directly (e.g. "get a swap quote from the Sodax backend", "sodax.api.swaps", "submit swap tx", "createIntent via the backend API", "poll submit-tx status", "swaps API v2", "point swaps at a custom endpoint"). For the higher-level end-to-end swap orchestrator use the `swap` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
3
+ description: 'Granular skill for the @sodax/sdk v2 Swaps API client — `sodax.api.swaps` (class SwapsApiService), a typed HTTP client for the backend Swaps API (`/swaps/*`, 21 endpoints: quote, deadline, allowance/approve, create-intent, intent submit/status/cancel/hash/packet/extra-data, limit orders, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the swaps backend directly (e.g. "get a swap quote from the Sodax backend", "sodax.api.swaps", "submit swap tx", "createIntent via the backend API", "poll submit-tx status", "swaps API v2", "point swaps at a custom endpoint"). For the higher-level end-to-end swap orchestrator use the `swap` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
4
4
  ---
5
5
 
6
6
  # Swaps API (Core SDK granular skill)
7
7
 
8
8
  Granular skill for `sodax.api.swaps` (class `SwapsApiService`) — the typed HTTP client for the backend
9
- **Swaps API v2** (`/swaps/*`). `sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the swaps
9
+ **Swaps API** (`/swaps/*`). `sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the swaps
10
10
  client. 21 endpoints, one method each; every method returns `Promise<Result<T>>` (never throws) and
11
11
  validates the response. Errors carry `feature: 'backend'`, `context.api: 'swaps'`, `context.endpoint`.
12
12
 
@@ -8,7 +8,7 @@ Backed by [viem](https://viem.sh). One class covers **every** SODAX EVM spoke ch
8
8
  | Interface | `IEvmWalletProvider` (from `@sodax/types`) |
9
9
  | Discriminant style | **Field presence** (no `type` field) |
10
10
  | Underlying SDK | `viem` |
11
- | Supported chains | Sonic (hub), Ethereum, Arbitrum, Base, BSC, Optimism, Polygon, Avalanche, HyperEVM, Lightlink, Redbelly, Kaia, Hedera |
11
+ | Supported chains | Sonic (hub), Ethereum, Arbitrum, Base, BSC, Optimism, Polygon, Avalanche, HyperEVM, Lightlink, Redbelly, Kaia, Hedera, Robinhood |
12
12
 
13
13
  ---
14
14
 
@@ -58,9 +58,9 @@ Bitcoin's signing flow inspects the connected address and picks the right method
58
58
  | P2SH (legacy multi-sig, `3…`) | ECDSA | Unisat, Xverse, OKX, Hana |
59
59
  | P2PKH (legacy, `1…`) | ECDSA | Unisat, Xverse, OKX, Hana |
60
60
 
61
- If a custom connector implements only one of the two methods, calling `signMessage` from a wrongly-typed address surfaces the error inline.
61
+ The methods live on the connector's `IBitcoinWalletProvider`, not on the connector: `chainRegistry` resolves the provider via `getWalletProvider()` (falling back to `recreateWalletProvider(xAccount)` after a page reload) and dispatches on it. A custom connector must return a provider implementing both methods; if it implements only one, calling `signMessage` from a wrongly-typed address surfaces the error inline.
62
62
 
63
- The same logic mirrors the SDK's `BitcoinSpokeProvider.authenticateWithWallet` — the React layer doesn't reinvent the dispatch.
63
+ The same logic mirrors the SDK's `RadfiProvider.authenticateWithWallet` — the React layer doesn't reinvent the dispatch.
64
64
 
65
65
  ---
66
66