DocsSDK

SDK

@qvault/sdk is the reference client for the QVAULT program. It covers the phrase, WOTS keys, vault addresses, instruction builders, preflight checks and chain discovery. It is pure TypeScript, runs in browsers and Node.js, and depends on @solana/web3.js 1.x, @noble/hashes and @scure/bip39. All signing is local. The SDK never sends your phrase or keys anywhere.

Install#

Coming soon. The repository is private while the program is pre-audit, so there is no public npm package yet. This page documents the API that the QVAULT web app uses, so you can review it now.

npm install @qvault/sdk @solana/web3.js   # not yet published

Phrase handling#

import {
  generatePhrase,
  validatePhrase,
  normalizePhrase,
  phraseToSeed,
} from '@qvault/sdk'

// 24 BIP39 words, 256 bits from crypto.getRandomValues
const phrase = generatePhrase()
// true: 24 words, valid checksum
validatePhrase(phrase)
// 'word word' (trim, lowercase, single spaces)
normalizePhrase('  Word  WORD ')
// 64-byte BIP39 seed, empty passphrase
const seed = phraseToSeed(phrase)

Rules for apps:

  • Show a new phrase once, have the user write it down, then verify a few words (the QVAULT app asks for three random positions).
  • Keep the phrase and seed in memory only. Never write them to localStorage, sessionStorage, IndexedDB, logs or analytics.
  • A QVAULT phrase is not a wallet seed. Never import it into a wallet, and never derive it from one.

Vault keys#

import { VaultKey } from '@qvault/sdk'

// vault index 0; optional third argument: programId
const key = new VaultKey(seed, 0)
key.hash          // 32-byte vault hash (public)
key.address       // vault PDA (PublicKey)
// 624-byte WOTS signature; use buildSpend instead
key.sign(message)
key.wipe()        // zero the secret chain values

The secret chain values live in a private field. They are not enumerable and never appear in JSON.stringify or logs.

Find the vault chain#

import { Connection } from '@solana/web3.js'
import { findVaultChain } from '@qvault/sdk'

const connection = new Connection(
  'https://api.devnet.solana.com',
  'confirmed',
)
const chain = await findVaultChain(connection, seed, {
  maxIndex: 1024,
  batch: 8,
})

// [{ index, address, status, lamports, destination }]
// status: 'unopened' | 'open' | 'rolled' | 'closed'
chain.entries
// the first entry that is open or unopened: deposit here, spend from here
chain.live
chain.liveKey   // its VaultKey

Discovery derives index 0, 1, 2, … and reads the addresses with getMultipleAccounts. It needs no server and no getProgramAccounts.

Send a transaction#

Every example below produces instructions. The connected wallet signs as fee payer:

import { toTransaction, transactionSize, MAX_TX_BYTES } from '@qvault/sdk'

async function send(instructions, wallet) {
  const { blockhash, lastValidBlockHeight } =
    await connection.getLatestBlockhash('confirmed')
  // legacy transaction
  const tx = toTransaction(instructions, wallet.publicKey, blockhash)
  if (transactionSize(tx) > MAX_TX_BYTES) throw new Error('too large')
  const signed = await wallet.signTransaction(tx)
  const signature = await connection.sendRawTransaction(signed.serialize())
  // confirm by polling getSignatureStatuses until confirmed
  // or lastValidBlockHeight passes
  return signature
}

Open and deposit#

import { buildOpenVault, buildDeposit } from '@qvault/sdk'
import { PublicKey } from '@solana/web3.js'

// First time: open vault 0 and deposit 0.1 SOL and 600 tokens (base units)
// in one transaction
const mint = new PublicKey('...')
await send(
  buildOpenVault({
    payer: wallet.publicKey,
    vault: chain.liveKey, // { hash }
    lamports: 100_000_000n,
    // from the payer's ATA
    token: { mint, amount: 600_000_000n },
  }),
  wallet,
)

// Later: deposit into the live (open) vault
await send(
  buildDeposit({
    depositor: wallet.publicKey,
    vault: chain.liveKey.address,
    lamports: 50_000_000n,
  }),
  wallet,
)

Withdraw SOL#

A withdrawal uses the vault's one-time key. Run preflightSpend first and sign only if it passes. Persist the SignGuard (see below).

import { Action, VaultKey, preflightSpend, buildSpend } from '@qvault/sdk'

const vault = chain.liveKey
// where the rest rolls
const next = new VaultKey(seed, vault.index + 1)
const recipient = new PublicKey('...')
const amount = 20_000_000n // lamports

const check = await preflightSpend(connection, {
  vault: vault.address,
  action: Action.WithdrawSol,
  amount,
  recipient,
  // or a mint whose balance rolls along
  mint: null,
  nextHash: next.hash,
})
// nothing was signed
if (!check.ok) throw new Error(check.errors.join('; '))

const spend = buildSpend({
  payer: wallet.publicKey,
  vault,
  next,
  action: Action.WithdrawSol,
  amount,
  recipient,
  mint: null,
  // guard refuses a second, different message
  guard,
})
spend.computeUnits // compute limit already included
await send(spend.instructions, wallet)

Withdraw a token#

const check = await preflightSpend(connection, {
  vault: vault.address,
  action: Action.WithdrawToken,
  amount: 250_000_000n,
  recipient,
  mint,
  nextHash: next.hash,
})
if (!check.ok) throw new Error(check.errors.join('; '))
const spend = buildSpend({
  payer: wallet.publicKey,
  vault,
  next,
  action: Action.WithdrawToken,
  amount: 250_000_000n,
  recipient,
  mint,
  guard,
})
await send(spend.instructions, wallet)
// recipient gets 250 tokens;
// the rest of that token and all SOL roll to `next`

Close#

const check = await preflightSpend(connection, {
  vault: vault.address,
  action: Action.Close,
  amount: 0n,
  recipient,
  mint,
})
if (!check.ok) throw new Error(check.errors.join('; '))
const spend = buildSpend({
  payer: wallet.publicKey,
  vault,
  action: Action.Close,
  amount: 0n,
  recipient,
  mint,
  guard,
})
await send(spend.instructions, wallet)
// everything goes to recipient; Close takes no next vault

Sweep a spent vault#

Sweeps are permissionless and need no phrase. Funds can only go to the destination recorded at spend time:

import {
  sweepSolIx,
  sweepTokenIx,
  fetchVault,
  fetchVaultTokens,
} from '@qvault/sdk'

// status 'rolled' or 'closed'
const spent = chain.entries[0]
const destination = spent.destination!
const ixs = [sweepSolIx({ vault: spent.address, destination })]
for (const t of await fetchVaultTokens(connection, spent.address)) {
  if (t.amount > 0n && !t.frozen) {
    ixs.push(
      sweepTokenIx({
        payer: wallet.publicKey,
        vault: spent.address,
        destination,
        mint: t.mint,
        vaultTokenAccount: t.tokenAccount,
      }),
    )
  }
}
await send(ixs, wallet)

SignGuard#

buildSpend accepts a guard with get(vault) and set(vault, messageHex). It refuses to sign a second, different message for the same vault. memorySignGuard() is for tests only. Apps must persist the guard across reloads:

const guard = {
  get: (vault: string) => localStorage.getItem(`qvault:signed:${vault}`),
  set: (vault: string, messageHex: string) =>
    localStorage.setItem(`qvault:signed:${vault}`, messageHex),
}

The stored value is the signed message, which is public once broadcast. Store the signed transaction too, so the original can always be re-broadcast. The QVAULT web app goes further: it keys records by program id and vault hash, stores the message hash and the transaction bytes, and treats a spend as signed once the wallet dialog opens (see Security model).

Lower-level API#

Export Purpose
vaultAddress(hash, programId?) [PublicKey, bump] for a vault hash
associatedTokenAddress(owner, mint) classic SPL ATA
spendMessage(fields) the 184-byte signed message
digits, verifySteps, recoverRoot WOTS internals; verifySteps drives the compute estimate
openVaultIx, depositSolIx, depositTokenIx, spendIx, sweepSolIx, sweepTokenIx, createAtaIdempotentIx single instructions
spendComputeUnits(steps, withMint), computeUnitLimitIx(units) compute budget
decodeVault, decodeTokenAccount, decodeMint account decoders
fetchVault, fetchVaultTokens reads
PROGRAM_ID, CLUSTER, Action, Ix, VaultStatus, MAX_TX_BYTES, CU_PER_VERIFY_STEP constants

Errors#

Where Form
On-chain custom program error: 0x…. PROGRAM_ERRORS[code] maps it to a name, for example PROGRAM_ERRORS[2] === 'InvalidSignature'. All codes are in the Program reference.
preflightSpend { ok, errors: string[], warnings: string[] }. Errors block signing; warnings cover freeze authorities and tokens left behind for a sweep.
Builders throw Error on misuse: a withdrawal without next, Close with a non-zero amount, a signature that is not 624 bytes, or a second message for a guarded vault.
phraseToSeed throws on an invalid phrase
findVaultChain throws if no live vault is found within maxIndex

The QVAULT web app wraps these into typed error codes for its UI. Those codes are internal to the app and not part of the SDK.