# @slipp/sdk

TypeScript SDK for integrating **Slipp** (`slipp.trade`) multichain route discovery and prepared swap execution into another application.

## Install

```bash
npm install @slipp/sdk
```

Until the package is published, this repository's `sdk/` folder can be installed from a local path or workspace.

## Quick start

```ts
import { SlippClient, bestRoute } from "@slipp/sdk";

const slipp = new SlippClient({ baseUrl: "https://slipp.trade" });

const usdc = await slipp.resolveToken("base", "0x...USDC");
const destination = await slipp.resolveToken("solana", "...mint...");

const result = await slipp.quote({
  originAsset: usdc.assetId,
  destinationAsset: destination.assetId,
  amount: "100",
  slippageBps: 200,
});

console.log(bestRoute(result.routes));
```

## Permissionless assets

`resolveToken(chain, address)` performs the same verified contract/mint discovery used by the Slipp app. A token does not have to be in the preloaded catalog. Recognition does **not** guarantee liquidity; `quote()` is authoritative for route availability.

Slippage uses basis points: `200` is 2% (the app default) and `1000` is 10%; custom tolerances may exceed 10% up to `9999` (99.99%, preserving a positive minimum). A configured on-chain policy may enforce a lower limit.

For optional capped provider estimation, add `slippageMode: "auto"` to the input. `slippageBps` remains the user's maximum: for example, `slippageBps: 200` allows up to 2%. Jupiter V2 preparation uses RTSE and Relay can estimate its tolerance; estimates outside the ceiling are discarded and rebuilt with the numeric cap. Other routes use the explicit cap.

Preparation may return a tighter `prepared.input.slippageBps` to preserve the already accepted minimum after price movement. Keep the original `acceptedMin` when refreshing; do not widen tolerance or automatically accept a lower output. Multi-stage continuation inputs remain bound to their reviewed asset, wallet, amount and minimum.

## Execution model

If preparation returns HTTP 409 with `code: "QUOTE_CHANGED"`, `SlippApiError.details` contains the fresh display-only `quote` and its `input`. Present the new amount and minimum for explicit user review before calling `prepare` again. Do not automatically accept the lower minimum.

Slipp never receives user private keys. For an executable route:

1. Connect the required wallet(s) in your application.
2. Call `quote()` including `sender`, `recipient`, and `bridgeRecipient` when needed.
3. Let the user review the route and `minAmountOut`.
4. Call `prepare(input, route.provider, route.minAmountOut)` immediately before signing.
5. If `prepared.nearFunding` exists, follow the destination setup flow below before presenting any token deposit. Otherwise present the returned NEAR transactions, Relay EVM/SVM steps, or Intents deposit instruction to the appropriate wallet.
6. Track settlement with `relayStatus()` or `intentsStatus()`.

The prepared plan retains Slipp's server-side amount, chain, recipient, approval and route validation. Your integration is still responsible for showing a clear wallet confirmation UI and for validating wallet/account state immediately before signing.

## Public API / CORS

The SDK uses `/api/sdk/*`. These endpoints are stateless and do not use cookies. By default they return public CORS headers. Set `SLIPP_SDK_ALLOWED_ORIGINS` to a comma-separated origin allowlist if you want to restrict browser integrations in production, for example:

```env
SLIPP_SDK_ALLOWED_ORIGINS=https://partner.example,https://app.example
```

Server-to-server callers are unaffected by browser CORS enforcement.

## Methods

- `tokens()` — current preloaded catalog.
- `resolveToken(chain, address)` — permissionless verified token lookup.
- `quote(input)` — compare eligible Slipp providers / composed routes.
- `prepare(input, provider, acceptedMin)` — get a fresh executable plan bounded by the user's reviewed minimum.
- `relayStatus(requestId)` — Relay settlement status.
- `intentsStatus(depositAddress)` — NEAR Intents status.
- `submitDeposit(...)` — submit an Intents deposit transaction hash when required.
- `bestRoute(routes)` — compares every provider by known gas-adjusted net output. Unknown-net routes remain visible and use minimum output as a fallback; that fallback is not a best-net claim.

## Supported chains

NEAR, Solana, Ethereum, Base, Arbitrum, Optimism, Polygon, BNB Chain, Avalanche, Robinhood Chain, and Arc. Provider availability depends on the selected asset pair and live liquidity.


## Native NEAR and composed NEAR routing

Slipp treats native NEAR as a first-class wallet asset while normalizing to `wrap.near` only where a protocol requires an NEP-141 token. Integrators can use the exported constants instead of hard-coding internal IDs:

```ts
import {
  NATIVE_NEAR_ASSET_ID,
  WRAPPED_NEAR_ASSET_ID,
  NATIVE_SOL_INTENTS_ASSET_ID,
} from "@slipp/sdk";
```

- `NEAR ↔ wNEAR` returns provider `native` and is a direct 1:1 wrap/unwrap, not a DEX trade.
- A route ending in native NEAR can quote through wNEAR and append the reviewed unwrap operation.
- A permissionless NEAR token that is not directly supported by Intents can use a composed `Rhea → NEAR Intents` route when Rhea can reach an Intents-compatible handoff asset.
- Read-only `quote()` calls may omit wallet addresses. Balance checks belong to your execution UI, not route discovery.

### Example: native NEAR → SOL

```ts
const result = await slipp.quote({
  originAsset: NATIVE_NEAR_ASSET_ID,
  destinationAsset: NATIVE_SOL_INTENTS_ASSET_ID,
  amount: "10",
  slippageBps: 200,
});

const route = bestRoute(result.routes);
```

For execution, repeat the quote with source/destination wallet addresses and call `prepare()` immediately before signing.

Maya Protocol (`maya`) and Hyperlane (`hyperlane`) are distinct provider IDs.
For these prepared plans call `await slipp.interchainPreflight(prepared)` immediately before signing.
Poll `slipp.interchainStatus(...)` with the prepared `evmPlan.transport.interchain` binding and submitted source hash. Source confirmation alone does not prove destination settlement. Exact supported identities and parameters are described in `INTERCHAIN-INTEGRATIONS.md` in the application archive.

## Fixed NEAR destination reserve

`SwapInput.maintainNearGasReserve` defaults to ON for final NEAR destinations.
Set it to `false` for OFF. `route.nearDestinationReserve.amount` is always the
fixed 0.5 native NEAR target in yoctoNEAR, separate from token output and fees.
Native-output metadata includes gross, retained, and spendable NEAR amounts.
`prepared.nearDestinationGasReserve` is the final readiness plan, independent of
source `nearGasReserve`. Honor required readiness before execution; do not reserve
again for each hop, split leg, or continuation. No dynamic destination reserve
or configurable amount exists. See `NEAR-DESTINATION-RESERVE.md`.


## Sequential Pathfinder handoffs

`Prepared.composite.first` can contain one bounded `relay-intents` transport before a destination swap. Supported Relay source wallets include Solana and the EVM networks registered in this build. The route is sequential and requires a connected EVM handoff wallet; a destination DEX also needs the destination signing wallet. This does not imply arbitrary recursive compositions or support for every provider/asset combination.

Before any source signature, validate the root assets, sender, recipients, first-leg asset/amount bindings, provider capabilities, expiry and total slippage budget. Persist each submitted source hash immediately, including a partial multi-transaction source leg. Do not resubmit that source leg after a later settlement, wallet or quote error.

Each handoff must show a newly received balance delta at least equal to the first leg's guaranteed minimum. After settlement, prepare the continuation against `composite.finalMinAmountOut`, then recheck account, network, token contracts/decimals and input amount before signing. For a nested transport, its `finalMinAmountOut` funds the outer prepared transport floor, rather than an older indicative quote.

Use `composite.continuationAmount` when present; legacy plans fall back to `composite.first.route.minAmountOut`. A native NEAR handoff ending in a NEAR token can retain the fixed native NEAR shortfall in `composite.nearReserveFromHandoff`. This is the user's NEAR, separate from the destination token output and provider fees. Trusted recently observed NEAR balances can reduce that shortfall; if the pre-sign handoff balance no longer supports the prepared allocation, refresh before submitting. Inner continuation inputs set `maintainNearGasReserve: false`; the aggregate final destination owns the single fixed reserve constraint.

The app uses the shared checks and executor in `lib/composite-execution.ts`. SDK consumers are responsible for implementing these wallet/checkpoint steps; the SDK returns prepared plans and does not autonomously sign or resume them.


## Four wallet stages

`composite.kind === "pathfinder-four-stage"` is a flat, bounded source DEX → Relay → NEAR Intents → destination NEAR DEX/conversion plan. `composite.stages` contains exactly four reviewed primitive blueprints. Only `composite.first` has an executable payload at preparation time. Do not submit a blueprint as a transaction or prepare all future payloads in advance.

Validate all four assets, wallet bindings, minima, expiries and allocated slippage before the source signature. After each stage, persist its transaction hash immediately, prove the newly received reviewed minimum in the handoff wallet, and prepare the next blueprint with its provider and reviewed `route.minAmountOut`. Relay settlement is also required before the Intents stage. Revalidate the fresh payload, exact contracts/decimals, amount and connected wallet immediately before signing. A better refreshed quote leaves surplus in the handoff wallet; it does not increase the next reviewed spend.

`nearReserveFromHandoff` applies once to the third-stage native NEAR arrival, never to the source bridge token. The fourth blueprint already excludes that retained native NEAR from its input. Native NEAR output uses gross/reserve/spendable fields normally; direct NEAR/wNEAR conversion remains a conversion. A failure after any submission requires inspection/continuation at the recorded stage; never replay the entire root plan. See `FOUR-STAGE-ROUTING-AUDIT.md` for scope and validation limits.


## Swap-funded NEAR destination setup

Incoming cross-chain swaps to non-native NEAR tokens must fund any shortfall below the configured 0.5 native NEAR target, including dust and partial balances. Other destinations and NEAR-origin swaps retain their existing behavior. Turning off the optional reserve switch does not bypass mandatory onboarding setup.

A `Prepared` response with `nearFunding` is a deferred token plan. Its root `input.amount` is the original total; `nearFunding.sourceAmount` is the setup allocation; `nearFunding.swapInput.amount` is the token remainder. These two amounts sum exactly to the original input. Never send a root plan with `nearFunding` as a token deposit.

1. Persist the funding plan and a durable ready/submitting/pending/funded checkpoint. Coordinate concurrent tabs and verify wallet/account bindings.
2. Refresh `nearFunding.first` using `prepare(first.input, "intents", nearFunding.requiredNative)`. Validate its original source allocation, recipient and native output minimum before opening the source wallet.
3. Save a submitting checkpoint **before** invoking the wallet; save the returned hash immediately. Deposit the exact source allocation to the refreshed 1Click deposit address.
4. Await setup `SUCCESS` and a fresh recipient native balance of at least `nearFunding.targetBalance`. A provider `FAILED`, missing hash, timeout or RPC error does not authorize replay. Only definite wallet rejection, finalized failed source receipt, or confirmed `REFUNDED` permits another setup attempt.
5. Call `prepare(nearFunding.swapInput, originalProvider, reviewedRootMinimum)` for the token deposit. Revalidate asset/amount/sender/recipient/minimum binding and the fresh native balance. Reject any newly returned setup wrapper; never charge an extra setup allocation.
6. Persist token-submitting before the second wallet call. Track settlement separately from setup. Reopening a funded session must skip the first deposit; repricing the token minimum requires a new user review.

Supported direct 1Click EVM and Solana (native SOL / standard SPL) routes use two source transaction approvals and can deliver to a receive-only NEAR address. Native-handoff composite fallbacks remain available for other tokens and may require extra approvals and a receiving signer. Token-2022 extensions and unsupported mint layouts fail before signing. Source-network fees remain payable by the source wallet. This is sequential execution, not atomic rollback.

## Receive-only NEAR delivery

For EVM/SOL sources buying a NEAR fungible token for an unrelated recipient, use `destinationReceiveOnly: true` and `nearExecutionAccount` derived from the source signer. The new active `near-delivery` provider competes with direct routes. Preparation verifies the account binding. A connected receiving signer keeps existing routing.

The outer input retains the final recipient. `Prepared.nearDelivery.execution` is the existing composite prepared for the source-controlled NEAR account. After its confirmed output, the frontend funds the recipient reserve, pays required token registration and transfers the new token output. Only the source wallet signs; SOL wallets must support verified raw NEAR signing.

The API client prepares plans and does not execute this wrapper automatically. Integrators must persist checkpoints, verify receipts, serialize delivery per controlled account and reconcile uncertain submissions. Do not submit the outer wrapper as a plain composite or replay the swap to retry payout. Refer to `lib/near-delivery.ts` and `app/page.tsx`. Native funding includes recipient reserve shortfall, registration and 0.05 NEAR execution allowance, in addition to existing execution-account reserve requirements. Unused execution funds remain source-controlled.

### NEAR source extension

A NEAR source, including an EVM- or SOL-derived NEAR account, can use separate-address delivery too. Set `nearExecutionAccount` to the exact source NEAR sender when `recipient` differs. Its nested execution is a Rhea prepared plan, rather than a cross-chain composite. For native NEAR, the entered amount is split into the swap amount and the reviewed recipient reserve/registration/execution allowance; preparation verifies their sum. For an FT source, that signing account must have sufficient native NEAR for delivery costs. The receiving wallet does not sign. Ordinary same-account NEAR swaps keep their existing path.

### Confirmation reserve scope

For same-chain NEAR delivery, nested `nearDelivery.execution.input.maintainNearGasReserve` is false because that execution account is the payer rather than the final recipient. Source execution gas checks remain separate. The outer route reserve targets the final recipient. Before source submission, verify its fresh native balance plus reviewed `nativeReserve` reaches 0.5 NEAR, and verify the local signing account covers native input plus `extraBudget`. Recheck recipient readiness before payout; a completed funding step must never count as future funding or be paid twice. See `assertNearDeliveryReady` and `assertNearDeliveryRecipientReady` in the repository implementation. A funded recipient and budgeted payer require no destination sponsor.
