# Deriverse Kit Example TypeScript examples for trading on Deriverse with `@deriverse/kit` TS SDK. This repo is two things: - A runnable CLI for safe, dry-run-by-default Deriverse actions. - A developer cookbook showing how to build Deriverse instructions with `@deriverse/kit`, `@solana/kit`, lookup tables, and versioned transactions. It is not a production trading bot. Mainnet commands use real funds when submitted with `--execute`. ## Mainnet Defaults The canonical configuration for this example is Solana mainnet: ```env PROGRAM_ID=DRVSpZ2YUYYKgZP8XtLhAGtT1zYSCKzeHfb4DgRnrgqD VERSION=1 RPC_HTTP=https://api.mainnet-beta.solana.com RPC_WS=wss://api.mainnet-beta.solana.com TOKEN_MINT_A=So11111111111111111111111111111111111111112 TOKEN_MINT_B=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v ``` Useful mainnet addresses and IDs: | Name | Value | | --- | --- | | Deriverse program | `DRVSpZ2YUYYKgZP8XtLhAGtT1zYSCKzeHfb4DgRnrgqD` | | Deriverse version | `1` | | WSOL mint | `So11111111111111111111111111111111111111112` | | USDC mint | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | | USDC token ID | `1` | | WSOL/USDC instrument ID | `0` | Keep a separate mainnet keypair with only the SOL and tokens you intend to use for examples. Public RPC endpoints can rate-limit; use a dedicated RPC provider for serious testing. ## Install And Run Install dependencies: ```bash npm install pnpm install ``` Build the TypeScript CLI: ```bash npm run build pnpm build ``` Show CLI help: ```bash npm start -- --help pnpm start -- --help ``` Run TypeScript during development: ```bash npm run dev -- markets tokens pnpm dev -- markets tokens ``` Create your local `.env`: ```bash cp .env.example .env ``` Set `KEYPAIR_FILENAME` to a Solana JSON keypair: ```env KEYPAIR_FILENAME=./keys/mainnet-trader.json ``` Validate configuration and the live Deriverse deployment: ```bash npm start -- config validate pnpm start -- config validate ``` Inspect the wallet address from your keypair: ```bash npm start -- wallet show pnpm start -- wallet show ``` Initialize `Engine` and print root/community deployment accounts: ```bash npm start -- engine init pnpm start -- engine init ``` ## CLI Discovery List registered tokens: ```bash npm start -- markets tokens pnpm start -- markets tokens ``` List instruments and top-of-book data: ```bash npm start -- markets instruments pnpm start -- markets instruments ``` Show the WSOL/USDC instrument: ```bash npm start -- markets show --instr-id 0 pnpm start -- markets show --instr-id 0 ``` Inspect perpetual market flags: ```bash npm start -- perp markets pnpm start -- perp markets ``` At the time this repo was updated, mainnet readback showed spot instruments and no active perp order books. Perp SDK examples and CLI commands are still included for deployments where an instrument has the `PERP` flag active. ## CLI Account And Trading Examples Show Deriverse client state: ```bash npm start -- account show pnpm start -- account show ``` Show client state and WSOL/USDC orders: ```bash npm start -- account show --instr-id 0 pnpm start -- account show --instr-id 0 ``` State-changing commands are dry-run by default. A dry run builds the SDK instruction and prints the signer, instruction summary, lookup tables, and exact submit command. Dry-run a USDC deposit: ```bash npm start -- deposit --amount 10 --token-id 1 pnpm start -- deposit --amount 10 --token-id 1 ``` Submit the deposit: ```bash npm start -- deposit --amount 10 --token-id 1 --execute pnpm start -- deposit --amount 10 --token-id 1 --execute ``` Dry-run a USDC withdrawal: ```bash npm start -- withdraw --amount 5 --token-id 1 --spot 0 pnpm start -- withdraw --amount 5 --token-id 1 --spot 0 ``` Submit the withdrawal: ```bash npm start -- withdraw --amount 5 --token-id 1 --spot 0 --execute pnpm start -- withdraw --amount 5 --token-id 1 --spot 0 --execute ``` Dry-run a direct USDC-input swap on WSOL/USDC: ```bash npm start -- swap --amount 10 --limit-price 80 --crncy-input true pnpm start -- swap --amount 10 --limit-price 80 --crncy-input true ``` Submit the swap: ```bash npm start -- swap --amount 10 --limit-price 80 --crncy-input true --execute pnpm start -- swap --amount 10 --limit-price 80 --crncy-input true --execute ``` Dry-run a limit bid: ```bash npm start -- spot place --instr-id 0 --side bid --price 50 --qty 0.01 pnpm start -- spot place --instr-id 0 --side bid --price 50 --qty 0.01 ``` Submit the bid: ```bash npm start -- spot place --instr-id 0 --side bid --price 50 --qty 0.01 --execute pnpm start -- spot place --instr-id 0 --side bid --price 50 --qty 0.01 --execute ``` Cancel a known bid order: ```bash npm start -- spot cancel --instr-id 0 --side bid --order-id 123 pnpm start -- spot cancel --instr-id 0 --side bid --order-id 123 ``` Mass-cancel WSOL/USDC spot orders: ```bash npm start -- spot mass-cancel --instr-id 0 pnpm start -- spot mass-cancel --instr-id 0 ``` Replace a quote: ```bash npm start -- spot quote-replace --instr-id 0 --order bid:123:49:0.01 pnpm start -- spot quote-replace --instr-id 0 --order bid:123:49:0.01 ``` Perp examples are guarded by active-market checks: ```bash npm start -- perp deposit --instr-id 0 --amount 10 pnpm start -- perp deposit --instr-id 0 --amount 10 ``` ```bash npm start -- perp place --instr-id 0 --side bid --price 50 --qty 0.01 --leverage 1 pnpm start -- perp place --instr-id 0 --side bid --price 50 --qty 0.01 --leverage 1 ``` ```bash npm start -- perp cancel --instr-id 0 --side bid --order-id 123 pnpm start -- perp cancel --instr-id 0 --side bid --order-id 123 ``` ## How Deriverse SDK Trading Works Most integrations follow this flow: 1. Create Solana RPC and subscription clients. 2. Create `Engine` with mainnet `PROGRAM_ID` and `VERSION`. 3. Call `engine.initialize()`. 4. Load a signer and call `engine.setSigner(signer.address)`. 5. Build one or more `engine.*Instruction(...)` objects. 6. Fetch Deriverse lookup tables. 7. Build a Solana v0 transaction message, sign it, and send/confirm. Compile-checked examples live in `src/examples/`. ### Engine And Signer ```ts import { createKeyPairSignerFromBytes, createSolanaRpc, createSolanaRpcSubscriptions_UNSTABLE, sendAndConfirmTransactionFactory, } from "@solana/kit"; import { Engine, PROGRAM_ID, VERSION } from "@deriverse/kit"; const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com"); const rpcSubscriptions = createSolanaRpcSubscriptions_UNSTABLE("wss://api.mainnet-beta.solana.com"); const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const engine = new Engine(rpc, { programId: PROGRAM_ID, version: VERSION, commitment: "confirmed", }); if (!(await engine.initialize())) { throw new Error("Deriverse Engine failed to initialize"); } const signer = await createKeyPairSignerFromBytes(secretKeyBytes); await engine.setSigner(signer.address); ``` ### Versioned Transaction Submission ```ts import { appendTransactionMessageInstruction, compressTransactionMessageUsingAddressLookupTables, createTransactionMessage, fetchAddressesForLookupTables, getSignatureFromTransaction, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, } from "@solana/kit"; const lookupTableAddresses = [ engine.rootStateModel.lutAddress, engine.clientLutAddress, engine.instruments.get(0)?.header.lutAddress, ].filter((address): address is NonNullable => address != null); const addressesByLookupTableAddress = await fetchAddressesForLookupTables(lookupTableAddresses, rpc); const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); let message = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => setTransactionMessageFeePayerSigner(signer, tx), ); message = appendTransactionMessageInstruction(instruction, message); const compressedMessage = compressTransactionMessageUsingAddressLookupTables( message, addressesByLookupTableAddress, ); const signedTransaction = await signTransactionMessageWithSigners(compressedMessage); await sendAndConfirmTransaction(signedTransaction, { commitment: "confirmed", skipPreflight: false, }); console.log(getSignatureFromTransaction(signedTransaction)); ``` ## SDK Cookbook ### Discover Tokens And Instruments ```ts import { address } from "@solana/kit"; const wsolMint = address("So11111111111111111111111111111111111111112"); const usdcMint = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); const assetTokenId = await engine.getTokenId(wsolMint); const crncyTokenId = await engine.getTokenId(usdcMint); if (assetTokenId == null || crncyTokenId == null) { throw new Error("WSOL or USDC is not registered"); } const instrId = await engine.getInstrId({ assetTokenId, crncyTokenId }); if (instrId == null) { throw new Error("WSOL/USDC instrument not found"); } await engine.updateInstrData({ instrId }); const instrument = engine.instruments.get(instrId); console.log(instrument?.header.spotBestBid, instrument?.header.spotBestAsk); ``` ### Inspect Client State ```ts if (engine.originalClientId == null) { console.log("No Deriverse client account exists yet. A first deposit can create one."); } else { const clientData = await engine.getClientData(); console.log(clientData.clientId); console.log([...clientData.tokens.values()]); const spotState = clientData.spot.get(0); if (spotState != null) { const info = await engine.getClientSpotOrdersInfo({ instrId: 0, clientId: spotState.clientId, }); const orders = await engine.getClientSpotOrders({ instrId: 0, bidsCount: info.bidsCount, asksCount: info.asksCount, bidsEntry: info.bidsEntry, asksEntry: info.asksEntry, }); console.log(orders.bids, orders.asks); } } ``` ### Deposit And Withdraw ```ts const depositUsdc = await engine.depositInstruction({ tokenId: 1, amount: 10, }); const withdrawUsdc = await engine.withdrawInstruction({ tokenId: 1, amount: 5, spot: [{ instrId: 0 }], }); ``` Use `spot: [{ instrId: 0 }]` when you want the withdrawal transaction to include WSOL/USDC temporary account cleanup context. ### Swap ```ts const swapUsdcToWsol = await engine.swapInstruction({ assetMint: wsolMint, crncyMint: usdcMint, amount: 10, limitPrice: 80, crncyInput: true, minAmountOut: 0, }); ``` `crncyInput: true` means the input amount is USDC for WSOL/USDC. Use current market data and your own slippage policy; the numbers here are examples. ### Spot Order Lifecycle ```ts import { OrderType } from "@deriverse/kit"; const placeBid = await engine.newSpotOrderInstruction({ instrId: 0, side: 0, price: 50, qty: 0.01, ioc: 0, orderType: OrderType.limit, }); const cancelBid = await engine.spotOrderCancelInstruction({ instrId: 0, side: 0, orderId: 123, }); const massCancel = await engine.spotMassCancelInstruction({ instrId: 0, }); const quoteReplace = await engine.spotQuotesReplaceInstruction({ instrId: 0, orderType: OrderType.limit, bailOnOrderNotFound: false, orders: [{ side: 0, oldId: 123, newPrice: 49, newQty: 0.01 }], }); ``` `side: 0` is bid and `side: 1` is ask in these examples. ### Perpetual Flow ```ts import { InstrMask, OrderType } from "@deriverse/kit"; await engine.updateInstrData({ instrId: 0 }); const instrument = engine.instruments.get(0); if (instrument != null && (instrument.header.mask & InstrMask.PERP) !== 0) { const perpDeposit = await engine.perpDepositInstruction({ instrId: 0, amount: 10, }); const perpOrder = await engine.newPerpOrderInstruction({ instrId: 0, side: 0, price: 50, qty: 0.01, leverage: 1, ioc: 0, orderType: OrderType.limit, }); const perpCancel = await engine.perpOrderCancelInstruction({ instrId: 0, side: 0, orderId: 123, }); } ``` The current public SDK exposes `perpDepositInstruction`, order, cancel, mass-cancel, quote-replace, and related helpers. This repo does not document a public `perpWithdrawInstruction` because the current SDK root does not expose one. ## Vault Mode (VM) Vault Mode examples are SDK-only in this repo. VM changes are authority-sensitive and multi-step, so they are not exposed as simple CLI commands here. The signer must be the Deriverse client wallet. `vmAuthority` is the separate VM authority address authorized to finalize and manage vault-mode settings. ### Activate And Deactivate VM ```ts const initActivate = await engine.vmInitActivateInstruction({ vmAuthority, }); const finalizeActivate = await engine.vmFinalizeActivateInstruction({ vmAuthority, }); const initDeactivate = await engine.vmInitDeactivateInstruction(); const finalizeDeactivate = await engine.vmFinalizeDeactivateInstruction({ vmAuthority, }); ``` Submit VM init/finalize steps according to the protocol timing and authority requirements. Do not assume all VM lifecycle instructions belong in one transaction. ### Instrument Whitelist Slots ```ts const slotMask = 1; const whitelistInstrIds = [0]; const changeInstrumentWhitelist = await engine.vmChangeListInstruction({ vmAuthority, mask: slotMask, whitelist: whitelistInstrIds, }); ``` `vmChangeListInstruction` accepts up to 8 instrument IDs and a numeric slot permission mask. Use your own policy for which instruments and flags the VM wallet may use. ### Withdrawal Addresses ```ts const addWithdrawalAddress = await engine.vmAddWithdrawalAddressInstruction({ vmAuthority, withdrawalTokenAccount, }); const removeWithdrawalAddress = await engine.vmRemoveWithdrawalAddressInstruction({ vmAuthority, withdrawalAddress, }); ``` The protocol validates withdrawal authority/account relationships during VM direct-withdraw flows. Keep the token account and authority model explicit in your integration. ### VM Withdrawals ```ts const initWithdraw = await engine.vmInitWithdrawInstruction({ tokenId: 1, amount: 5, }); const cancelPendingWithdraw = await engine.vmInitWithdrawCancelInstruction(); const finalizeWithdraw = await engine.vmInitWithdrawFinalizeInstruction({ vmAuthority, tokenId: 1, }); const directWithdraw = await engine.vmDirectWithdrawInstruction({ tokenId: 1, amount: 5, withdrawalTokenAccount, }); ``` ### VM And Kamino ```ts const allowKaminoInVm = await engine.vmAddKaminoInstruction({ vmAuthority, }); const removeKaminoFromVm = await engine.vmRemoveKaminoInstruction({ vmAuthority, }); ``` Kamino operations check VM Kamino whitelisting when Vault Mode is active. ## Kamino Integration Kamino examples are SDK-only in this repo. They use the current public helpers from `@deriverse/kit` and the SDK default Kamino main market. ```ts import { MAIN_KAMINO_MARKET, MAIN_KAMINO_MARKET_LUT } from "@deriverse/kit"; console.log(MAIN_KAMINO_MARKET); console.log(MAIN_KAMINO_MARKET_LUT); ``` ### Discover Reserves, Context, And LUTs ```ts const wsolReserve = await engine.getKaminoReserveByMint({ mint: wsolMint, lendingMarket: MAIN_KAMINO_MARKET, }); const kaminoContext = await engine.refreshKaminoContext({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, }); const kaminoLookupTables = await engine.kaminoLookupTableAddresses({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, }); console.log(wsolReserve, kaminoContext.obligation, kaminoLookupTables.all); ``` Use `kaminoLookupTables.all` together with the Deriverse root/client/instrument lookup tables when submitting Kamino transactions. ### Initialize Kamino Accounts ```ts const obligationExists = await engine.kaminoObligationExists({ lendingMarket: MAIN_KAMINO_MARKET, }); const instrumentAccounts = await engine.kaminoInstrumentAccountsExist({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, }); const initObligation = await engine.kaminoInitObligationInstruction({ lendingMarket: MAIN_KAMINO_MARKET, }); const initInstrument = await engine.kaminoInitInstrumentInstruction({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, }); ``` Check account existence before deciding which init instructions to submit. `kaminoInitInstrumentInstruction` uses cached context, so call `refreshKaminoContext` first when composing your own flow. ### Refresh And Read State ```ts const refreshReserves = await engine.kaminoRefreshReservesInstruction({ lendingMarket: MAIN_KAMINO_MARKET, }); const updateObligation = await engine.kaminoUpdateObligationsInstruction({ lendingMarket: MAIN_KAMINO_MARKET, }); const state = await engine.getKaminoClientState({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, }); console.log(state.deposits, state.borrows, state.maxWithdrawEstimate); ``` ### Change A Kamino Position ```ts await engine.refreshKaminoContext({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, }); const depositCollateralAndBorrow = await engine.kaminoChangePositionInstruction({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, assetIsCollateral: true, collateralDelta: 0.01, borrowDelta: 10, }); const repayAll = await engine.kaminoChangePositionInstruction({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, assetIsCollateral: true, collateralDelta: 0, borrowDelta: 0, repayAll: true, }); const withdrawAll = await engine.kaminoChangePositionInstruction({ instrId: 0, lendingMarket: MAIN_KAMINO_MARKET, assetIsCollateral: true, collateralDelta: 0, borrowDelta: 0, withdrawAll: true, }); ``` `repayAll` requires `borrowDelta: 0`. `withdrawAll` requires `collateralDelta: 0`. Kamino reserve availability, account initialization, obligation health, and VM whitelisting can all affect whether a transaction succeeds. ## Project Scripts ```bash npm run typecheck pnpm typecheck ``` ```bash npm run build pnpm build ``` ```bash npm test pnpm test ``` ```bash npm run check pnpm check ``` `npm run check` and `pnpm check` run typecheck, build, and tests. ## Troubleshooting `config validate` fails: - Confirm `.env` uses the mainnet `PROGRAM_ID` and `VERSION=1`. - Confirm your RPC URL points at Solana mainnet. - Try a dedicated RPC provider if public RPC rate-limits. Keypair loading fails: - `KEYPAIR_FILENAME` must point to a Solana JSON secret key array with 64 integers. - Use a separate trading wallet. Never commit keypair files. Deposit or withdraw fails: - The wallet needs SOL for fees. - The wallet needs the deposited token balance and its associated token account. - Withdrawal requires enough Deriverse client balance and may need spot cleanup context such as `--spot 0`. Swap or order preflight fails: - Re-run `markets show --instr-id 0` and use current book data. - Check token balances, open orders, and slippage limits. - Do not reuse example prices in production. Perp commands fail: - The selected instrument must have the `PERP` flag active. - Current mainnet readback may show no active perp markets. - The SDK currently has no public root-exported `perpWithdrawInstruction`. Vault Mode fails: - Confirm the signer is the Deriverse client wallet. - Confirm `vmAuthority` is the authority expected by the protocol. - Submit lifecycle steps in the intended order. - For direct withdrawals, confirm the withdrawal token account and whitelisted authority/account relationship. Kamino fails: - Call `refreshKaminoContext` before builders that need cached Kamino context. - Check `kaminoObligationExists` and `kaminoInstrumentAccountsExist`. - Include Kamino lookup tables from `kaminoLookupTableAddresses(...).all`. - If VM is active, add Kamino to the VM whitelist with `vmAddKaminoInstruction`. - Reserve availability and obligation health are enforced by Kamino and Deriverse programs. ## Devnet Appendix Mainnet is the default for this repository. The SDK reference also documents a devnet deployment: ```env PROGRAM_ID=CDESjex4EDBKLwx9ZPzVbjiHEHatasb5fhSJZMzNfvw2 VERSION=7 ``` Use devnet only when you intentionally change every related RPC, token, and deployment value.