Reference

TypeScript SDK

Every call of @laplace/sdk with its parameters, return value and errors.

@laplace/sdk is the TypeScript surface of Laplace: one client for asking, reading, re-running and disputing, the instruction builders under it, the model runtime in WASM, and a typed client for the HTTP API. This page lists every export with its signature, what it returns and what it throws.

Package

Name@laplace/sdk
Version0.4.1
Module formatES modules only ("type": "module", each entry has types and import)
Dependencies@coral-xyz/anchor 0.31.1, @solana/web3.js 1.99.0, @solana/spl-token 0.4.15, zod 4.6.7, @noble/curves ^1.9.7, bn.js ^5.2.2, @types/bn.js ^5.1.6, buffer ^6.0.3
Shell
npm install @laplace/sdk
Entry pointHolds
@laplace/sdkcreateLaplace, the chain layer (ix, pda, decode, send, sendV1, setPriorityFee, computeUnitPrice), the game logic, the tokenizer, and everything @laplace/sdk/api exports.
@laplace/sdk/vmThe model runtime: laplace-vm compiled to WASM and embedded in the package, with loadModel, VmModel and Run.
@laplace/sdk/apicreateApiClient, ApiClientError and the zod schemas of the HTTP API.
@laplace/sdk/fixturesfixtureNetwork(now?, scenario?) and FIXTURE_USDC: sample data in the API's shapes, for tests.

The package runs in a browser and in Node. It uses the global fetch, crypto.subtle and WebAssembly, and sets globalThis.Buffer when it is missing. The WASM module is inside the package as base64, so there is no file to host.

createLaplace

createLaplace(options: LaplaceOptions): Laplace

TypeScript
import { readFileSync } from 'node:fs'
import { Keypair } from '@solana/web3.js'
import { createLaplace, keypairSigner } from '@laplace/sdk'

const rpcUrl = process.env.LAPLACE_RPC!
const apiUrl = process.env.LAPLACE_API!
const keypair = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync('keypair.json', 'utf8'))))

export const laplace = createLaplace({ rpcUrl, apiUrl, wallet: keypairSigner(keypair) })

The network's rpcUrl and apiUrl are listed on Addresses. The samples on this page use the laplace client made here.

apiUrlstringrequired
The base URL of the Laplace API. Offers, model files and tokenizers are read from it.
rpcUrlstring
The Solana RPC URL. The client opens a web3.js Connection on it with commitment confirmed and disableRetryOnRateLimit, so a 429 from the RPC reaches the caller instead of being retried in place. In a browser this can be the API's relay, apiUrl + '/v1/rpc'.
connectionConnection
A web3.js Connection to use instead of rpcUrl, best made with disableRetryOnRateLimit: true like the client's own. When both are given, connection is used. With neither, the client connects to a validator on the local machine.
walletSigner
The wallet that signs. Leave it out for a client that only reads and re-runs. A call that signs without one throws LaplaceError with stage wallet and the message Connect a wallet first.
priorityFeenumber | 'auto'
The compute-unit price every send carries, in µlamports per compute unit, or 'auto' to follow recent fees on the cluster. Left out, the price already set stays, 'auto' from the start. It sets the same process-wide price as setPriorityFee.

The client that comes back holds every call below, plus two properties:

PropertyTypeHolds
connectionConnectionThe web3.js connection the client reads and sends through.
apiApiClientThe API client for apiUrl, the same object createApiClient(apiUrl) returns. See The API entry.

Laplace is the type of the client: ReturnType<typeof createLaplace>. LaplaceOptions is the type of the options.

The wallet

A wallet is any object of this shape:

TypeScript
type Signer = {
  publicKey: PublicKey
  signTransaction(tx: VersionedTransaction): Promise<VersionedTransaction>
  signMessage(message: Uint8Array): Promise<Uint8Array>
}
publicKeyPublicKeyrequired
The key that pays for and signs every transaction the client sends.
signTransaction(tx) => Promise<VersionedTransaction>required
Signs a v0 transaction and returns it. Every instruction except prove_step is sent this way.
signMessage(bytes) => Promise<Uint8Array>required
Returns the raw 64-byte ed25519 signature over the bytes given. Only sendV1 calls it, for the v1 prove_step transaction that a server key sends through proveStep. A browser wallet is never asked to sign a v1 message.

keypairSigner

keypairSigner(kp: Keypair): Signer

Wraps a web3.js Keypair as a Signer, for scripts, agents and nodes.

A browser wallet is wrapped the same way, from its own signing calls:

TypeScript
import { PublicKey, VersionedTransaction } from '@solana/web3.js'
import type { Signer } from '@laplace/sdk'

type BrowserWallet = {
  publicKey: PublicKey
  signTransaction(tx: VersionedTransaction): Promise<VersionedTransaction>
  signMessage(message: Uint8Array): Promise<Uint8Array>
}

export const toSigner = (w: BrowserWallet): Signer => ({
  publicKey: w.publicKey,
  signTransaction: (tx) => w.signTransaction(tx),
  signMessage: (message) => w.signMessage(message),
})

Asking and reading

ask

laplace.ask(slug: string, input: AskInput, opts?): Promise<{ receipt, signature, tokens, seed }>

Tokenizes the input, picks an offer, and sends one request instruction with a cap on the fee. The offer's price moves from the wallet's associated token account for the offer's mint into the fee escrow, and the receipt account is created in state requested.

TypeScript
const { receipt, signature, tokens, seed } = await laplace.ask('judge', {
  claim: 'The bridge opened in 1932.',
  evidence: 'The bridge opened to traffic in March 1932.',
})

const market = await laplace.ask('market', { text: 'Shipments rose 18% in the third quarter, above guidance.' }, { waitForAnswer: true })
slugstringrequired
The model's slug: judge or market.
inputAskInputrequired
JudgeInput or MarketInput, below.
opts.offerstring
The address of the offer to take. Left out, the client reads GET /v1/offers?model= and takes the first offer that is active and live. The API lists live offers first and sorts each group by price, so that is the cheapest live one.
opts.seedbigint
The u64 written on the receipt. Left out, a random integer below 2^48. The first step of a run writes it into the input page, so it enters every state root after that step and the trace root. No step reads it, so the output does not depend on it.
opts.noncebigint
The u64 in the receipt's address. Left out, the current time in milliseconds times 1,000 plus a random integer below 1,000.
opts.waitForAnswerboolean
When true, the call resolves once the receipt has left requested, through waitFor with its default timeout.
opts.maxFeebigint
The most this request pays, in the mint's base units, sent as the instruction's max_fee. Pass the price your page showed the requester. Left out, the price of the offer as read just before sending. An offer repriced above it in between is refused with FeeAboveMax, and nothing is paid.

The input per model:

ModelTypeFieldsTokenized as
judgeJudgeInputclaim: string, evidence: string[CLS] evidence [SEP] claim [SEP] in uncased WordPiece. At most the model's inputMax, 64 tokens: while the pair is too long, the longer of the two texts loses a token from its end.
marketMarketInputtext: string[CLS] text [SEP] in uncased WordPiece. At most the model's inputMax, 32 tokens: the text keeps its first 30 tokens and the rest are dropped, so a longer headline is read from its start.

AskInput is JudgeInput | MarketInput. Both models read the same WordPiece vocabulary, and the input's shape decides how it is tokenized: an object with text as one text, any other as a claim and its evidence. The token limit is the inputMax of the slug asked, read from GET /v1/models/:slug. The tokenizer keeps every input inside that limit, so the program's InvalidInput is reached only by a request built with ix.request.

Returns:

receiptPublicKey
The receipt's address, derived from the wallet and the nonce before the transaction is sent.
signaturestring
The signature of the confirmed request transaction.
tokensnumber[]
The input as token ids, as written on the receipt.
seedbigint
The seed written on the receipt.

Throws:

ErrorWhen
LaplaceError, stage walletThe client has no wallet, or the wallet did not sign.
LaplaceError, stage buildNo offer for the model is live (No operator is live for <slug>.), there is no account at opts.offer, or the tokenizer file is not in the store or does not hash to what the model's files name.
LaplaceError, stage simulateThe program refused the request: OfferInactive, MintMismatch, FeeAboveMax. A wallet with no token account for the offer's mint is refused with AccountNotInitialized (3012).
LaplaceError, stage confirm or unknownSee LaplaceError. With waitForAnswer, stage confirm and Timed out waiting for the receipt. when no answer arrives in the timeout.
ApiClientErrorThe API did not serve the offers or the model's files.

receipt

laplace.receipt(address: PublicKey | string): Promise<ReceiptAccount>

Reads the receipt account from the chain at commitment confirmed and decodes it. The fields are listed under ReceiptAccount. Throws LaplaceError with stage build and No account at <address>. when the account does not exist.

dispute

laplace.dispute(address: PublicKey | string): Promise<DisputeAccount>

The same for a dispute account. The fields are listed under DisputeAccount.

waitFor

laplace.waitFor(address: PublicKey, until: (r: ReceiptAccount) => boolean, timeoutMs = 600_000): Promise<ReceiptAccount>

Reads the receipt once a second until until(receipt) returns true, then resolves with that receipt. An address with no account yet is read again. Past timeoutMs it throws LaplaceError with stage confirm and Timed out waiting for the receipt.

TypeScript
const answered = await laplace.waitFor(receipt, (r) => r.state !== 'requested')

final

laplace.final(address: PublicKey | string): Promise<{ model, inputHash, output }>

Waits until the receipt is final or void, for at most 24 hours, and resolves with what a program reads from a final receipt. It sends nothing: the receipt becomes final when someone sends finalize.

TypeScript
import { JUDGE_LABELS, MARKET_LABELS } from '@laplace/sdk'

const { model, inputHash, output } = await laplace.final(receipt)
const verdict = JUDGE_LABELS[output[0]!] // 'yes', 'unclear' or 'no'

const read = await laplace.final(market.receipt)
const sentiment = MARKET_LABELS[read.output[0]!] // 'negative', 'neutral' or 'positive'
modelPublicKey
The model account the receipt names.
inputHashUint8Array
32 bytes: the SHA-256 of the input tokens, each as a u16 in little-endian bytes.
outputnumber[]
The output as token ids.

Throws LaplaceError with stage confirm: The request was cancelled. when the receipt is void, and Timed out waiting for the receipt. after 24 hours.

tokenizer

laplace.tokenizer(slug: string): Promise<Tokenizer>

Fetches the model's tokenizer file from the API's store by its hash, checks the hash, and returns a WordPiece tokenizer limited to the model's inputMax, read from GET /v1/models/:slug. It is fetched once per client and slug.

TypeScript
type Tokenizer = {
  encode(input: JudgeInput | MarketInput): number[]
  decode(tokens: number[], context?: number[]): string
}
TypeScript
import { MARKET_LABELS } from '@laplace/sdk'

const r = await laplace.receipt(market.receipt)
const tok = await laplace.tokenizer('market')
console.log(tok.decode(r.input), MARKET_LABELS[r.output[0]!])

encode lowercases the text, strips accents, splits it at spaces and punctuation, and cuts each word into the longest pieces in the vocabulary. A word with no such pieces becomes [UNK]. decode turns ids back into lowercase text: it leaves out [CLS], writes [SEP] as [SEP], and joins each ## piece to the word before it. Its context argument is accepted and not used.

Each model's output is one token, an index into its labels:

ExportValue
JUDGE_LABELS['yes', 'unclear', 'no']
MARKET_LABELS['negative', 'neutral', 'positive']

wordpiece(vocabText: string, max = 64): Tokenizer is the tokenizer itself, for callers that hold the vocabulary file: vocabText is the file's text, one piece per line, and max the token limit. JudgeInput, MarketInput and Tokenizer are exported as types.

Running a model

model

laplace.model(slug: string, onProgress?: (p: Progress) => void): Promise<VmModel>

Loads a model into WASM and returns it. In order:

  1. Reads the model's file list from GET /v1/models/:slug/files.
  2. Fetches the program file and the weights file from the store by hash, and checks that each one's SHA-256 is the hash it was asked for by.
  3. Loads both into the VM, which computes the program root, the weights root and the init root from the bytes.
  4. Reads the Model account from the chain and compares the three roots with the ones registered there.

The model is loaded once per client and slug. onProgress is called during the first load with { phase: 'loading', done, total } in bytes, where total is the size of the two files. The returned VmModel is described under The VM entry.

Throws LaplaceError with stage build: The model file <hash>… is not in the store., The model file <hash>… does not hash to what its manifest names. (<hash> is the first 12 characters of the file's hash), The model files do not match the roots registered on chain., or No account at <address>. when the model is not registered. Throws ApiClientError when the API does not serve the file list.

rerun

laplace.rerun(address: PublicKey | string, opts?): Promise<RerunResult>

Reads the receipt, loads its model with model, runs every step on the receipt's input and seed, and compares the bits with the answer standing on the receipt. It needs no wallet and sends nothing.

TypeScript
const result = await laplace.rerun(receipt, {
  onProgress: (p) => console.log(p.phase, p.done, p.total),
})
console.log(result.matches, result.traceRoot)
opts.onProgress(p: Progress) => void
Called with { phase: 'loading', done, total } in bytes while the model's files load, then with { phase: 'running', done, total } in steps, once after every 2,048 steps.
opts.signalAbortSignal
Stops the run. The call rejects with a DOMException named AbortError.

Returns:

runRun
The run itself, with the state root after every step. challenge and playTurn take it.
outputnumber[]
This run's output as token ids.
traceRootstring
This run's trace root, 64 lowercase hex characters.
outputMatchesboolean
true when this run's output equals the receipt's output, token for token.
traceMatchesboolean
true when this run's trace root equals the receipt's trace root, byte for byte.
matchesboolean
outputMatches && traceMatches.
labelstring | null
The label of this run's output, from the model's labels in GET /v1/models/:slug: yes, unclear or no for the judge, negative, neutral or positive for the market model. null for a model that lists no labels.

On a receipt with no answer on it (requested or void), the run completes and all three comparisons are false.

Throws whatever receipt and model throw, and the AbortError above. Run it again yourself is the guide.

Disputes

The challenge game describes the game these calls play.

challenge

laplace.challenge(address: PublicKey | string, run: Run): Promise<{ dispute, signature }>

Opens a challenge on a receipt with this run's output, its trace root and its state roots at the first split points. The wallet sends a bond equal to the model's into the vault and pays the rent of the dispute account.

TypeScript
const result = await laplace.rerun(receipt)
if (!result.outputMatches) {
  const { dispute, signature } = await laplace.challenge(receipt, result.run)
}
disputePublicKey
The address of the new dispute account.
signaturestring
The signature of the confirmed challenge transaction.

The program refuses with WrongState when the receipt is not answered, WindowClosed after the window, SameOutput when the run's output equals the answer, SelfChallenge when the wallet is the answerer, and PointCount. Each arrives as a LaplaceError with stage simulate.

nextMove

laplace.nextMove(address: PublicKey | string, run: RunLike, signer?: PublicKey): Promise<Move>

Reads the dispute and computes the move of one side from that side's own run, without sending it. signer is the key whose side is computed. It defaults to the wallet's key. The current time is the cluster's block time, or the local clock when the RPC does not return one.

TypeScript
type RunLike = { root(k: number): Uint8Array }

type Move =
  | { kind: 'bisect'; select: number; lo: number; hi: number; points: Uint8Array[] }
  | { kind: 'prove'; step: number }
  | { kind: 'claim-timeout' }
  | { kind: 'wait' }
  | { kind: 'resolved' }
kindWhenCarries
bisectThe dispute is open and this side is on turn.select: the index of the first sub-interval of the other side's points whose end this run disagrees with, or the last sub-interval when it agrees with every point. lo, hi: that sub-interval. points: this run's state roots at its split points, empty when it is one step wide.
proveThe dispute is proving, unless the other side is on turn and its deadline has passed.step: the disputed step, the dispute's lo. The proof itself is sent by proveStep.
claim-timeoutThe other side is on turn and its deadline has passed.
waitThe dispute is open and the other side is on turn inside its deadline. Also when signer is neither side of an unresolved dispute.
resolvedThe dispute is resolved.

playTurn

laplace.playTurn(address: PublicKey | string, run: Run): Promise<PlayedTurn>

Computes the wallet's move with nextMove and sends it. Every move it sends is a v0 transaction the wallet signs whole.

TypeScript
for (;;) {
  const turn = await laplace.playTurn(dispute, run)
  if (turn.kind === 'resolved') break
  await new Promise((r) => setTimeout(r, 2000))
}
MoveSendsResolves with
bisectbisect.{ kind: 'bisect', signature, lo, hi }
proveNothing. The network's keeper proves the last step of every game in proving within seconds, and the nodes prove their own.{ kind: 'proving', step }
claim-timeoutclaim_timeout.{ kind: 'claim-timeout', signature }
wait, resolvedNothing.{ kind: 'wait' } or { kind: 'resolved' }

The program refuses a turn with NotYourTurn, TurnExpired, SelectOutOfRange or PointCount.

proveStep

laplace.proveStep(address: PublicKey | string): Promise<{ signature: string; step: number }>

Proves the one disputed step of a game in proving. It loads the receipt's model, builds the step's payload from an honest run on the receipt's input and seed with VmModel.prove, and sends prove_step as a v1 transaction through sendV1. The program executes the step and settles the game, and the result is the same whoever sends it. It is the call for a server key, such as the keeper's or a node's, whose signMessage signs the v1 message bytes.

TypeScript
const { signature, step } = await laplace.proveStep(dispute)

Throws LaplaceError with stage build and The game is not at its last step. when the dispute is not proving. The program refuses a payload with BadProof or BadStep, and a dispute another proof already settled with WrongState.

claimTimeout

laplace.claimTimeout(address: PublicKey | string): Promise<string>

Sends claim_timeout on a dispute and resolves with the signature. Any wallet can send it. Before the turn's deadline the program refuses with TurnOpen.

computeMove

computeMove(d: DisputeAccount, side: Side, run: RunLike, nowSecs: number): Move

The logic under nextMove, as a plain function with no network access: for a caller that holds the dispute account, its side ('defender' or 'challenger'), its own run and the time in unix seconds. A node that runs models outside WASM plays the game with it.

Closing a receipt

finalize

laplace.finalize(address: PublicKey | string): Promise<string>

Sends finalize and resolves with the signature. Any wallet can send it once the window has ended with no dispute open. The transaction first creates the fee mint's associated token accounts of the answerer and of the protocol's fee recipient when they do not exist, paid by the wallet.

The program refuses with WindowOpen before the window ends and WrongState when the receipt is not answered.

cancel

laplace.cancel(address: PublicKey | string): Promise<string>

Sends cancel_request and resolves with the signature. The whole fee returns to the requester's token account and the receipt becomes void.

The program refuses with AnswerDeadlineOpen before the answer deadline, WrongState when the receipt is not requested, and Unauthorized when the wallet is not the requester.

Operator calls

Each call sends one instruction signed by the wallet, as the operator's authority, and resolves with the signature. Bond and offers is the guide.

CallInstructionArguments
laplace.operator.register()register_operator
laplace.operator.deposit(lamports: bigint)deposit_bondThe SOL to move from the wallet into the vault, in lamports.
laplace.operator.offer(slug: string, price: bigint, mint: PublicKey, active = true)set_offerThe model's slug, the fee per request in the mint's base units, the mint, and whether the offer takes requests.
laplace.operator.requestWithdraw(lamports: bigint)request_withdrawThe free bond to mark for withdrawal, in lamports.
laplace.operator.withdraw()withdraw_bond
laplace.operator.account(key: PublicKey)none, a readThe authority key. Resolves with the OperatorAccount, or throws LaplaceError with stage build when the key is not registered.
TypeScript
import { PublicKey } from '@solana/web3.js'

const mint = new PublicKey(process.env.FEE_MINT!)

await laplace.operator.register()
await laplace.operator.deposit(5_000_000_000n)
await laplace.operator.offer('judge', 20_000n, mint)

The program refuses with InsufficientFreeBond, WithdrawNotReady and NoWithdrawal.

Instruction builders

ix holds one builder per instruction of the program. Each returns a web3.js TransactionInstruction with its accounts derived and its arguments encoded from the program's IDL. A builder sends nothing: pass its result to send, sendV1 or a transaction of your own. Program instructions describes what each instruction checks and does.

BuilderArguments
ix.initConfig(admin, c)admin: PublicKey, c: ConfigArgs
ix.setConfig(admin, c, newAdmin, registrationOpen)admin: PublicKey, c: ConfigArgs, newAdmin: PublicKey, registrationOpen: boolean
ix.registerModel(publisher, m)publisher: PublicKey, m: ModelArgs
ix.registerOperator(authority)authority: PublicKey
ix.depositBond(authority, lamports)authority: PublicKey, lamports: bigint
ix.requestWithdraw(authority, lamports)authority: PublicKey, lamports: bigint
ix.withdrawBond(authority)authority: PublicKey
ix.setOffer(authority, model, mint, price, active)authority: PublicKey, model: PublicKey (the model account), mint: PublicKey, price: bigint, active: boolean
ix.request(requester, offer, nonce, seed, input, maxFee)requester: PublicKey, offer: { address: PublicKey; model: PublicKey; mint: PublicKey }, nonce: bigint, seed: bigint, input: number[] (token ids), maxFee: bigint (the most the request pays, in the mint's base units)
ix.answer(authority, receipt, model, output, traceRoot)authority: PublicKey, receipt: PublicKey, model: PublicKey, output: number[], traceRoot: Uint8Array
ix.cancelRequest(requester, receipt, mint)requester: PublicKey, receipt: PublicKey, mint: PublicKey (the receipt's fee mint)
ix.challenge(challenger, receipt, model, index, output, traceRoot, points)challenger: PublicKey, receipt: PublicKey, model: PublicKey, index: number (the receipt's disputes count), output: number[], traceRoot: Uint8Array, points: Uint8Array[]
ix.bisect(signer, dispute, select, points)signer: PublicKey, dispute: PublicKey, select: number, points: Uint8Array[]
ix.proveStep(signer, r, payload)signer: PublicKey, r: ResolveAccounts, payload: Uint8Array
ix.claimTimeout(signer, r)signer: PublicKey, r: ResolveAccounts
ix.finalize(signer, r)signer: PublicKey, r: { receipt: PublicKey; mint: PublicKey; answerer: PublicKey; answererIsOperator: boolean; feeRecipient: PublicKey }
TypeScript
type ConfigArgs = {
  feeRecipient: PublicKey
  protocolShareBps: number
  slashWinnerBps: number
  answerDeadlineSecs: number
  turnDeadlineSecs: number
  withdrawCooldownSecs: number
}

type ModelArgs = {
  slug: string
  arch: number
  weightsRoot: Uint8Array
  programRoot: Uint8Array
  initRoot: Uint8Array
  stepCount: number
  statePages: number
  chunkCount: number
  inputMax: number
  outputLen: number
  windowSecs: number
  bondLamports: bigint
  filesHash: Uint8Array
}

type ResolveAccounts = {
  dispute: PublicKey
  receipt: PublicKey
  model: PublicKey
  feeRecipient: PublicKey
  defender: PublicKey
  challenger: PublicKey
  defenderIsOperator: boolean
}

ResolveAccounts is filled from the dispute account (receipt, defender, challenger, defenderIsOperator), the receipt (model) and the Config account (feeRecipient).

A builder given a required account as null or undefined throws a plain Error: <instruction>: account <name> is required.

TypeScript
import { ix, send } from '@laplace/sdk'

const signature = await send(laplace.connection, wallet, [
  ix.registerOperator(wallet.publicKey),
  ix.depositBond(wallet.publicKey, 2_000_000_000n),
])

Addresses

pda derives the program's addresses. Each call returns a PublicKey.

CallSeedsAccount
pda.config()["config"]Config
pda.vault()["vault"]The bond vault
pda.escrow()["escrow"]The fee escrow's authority
pda.escrowToken(mint: PublicKey)The associated token account of pda.escrow() for mintThe fee escrow for one mint
pda.model(slug: string)["model", slug]Model
pda.operator(authority: PublicKey)["operator", authority]Operator
pda.offer(authority: PublicKey, model: PublicKey)["offer", authority, model]Offer
pda.receipt(requester: PublicKey, nonce: bigint)["receipt", requester, nonce], the nonce as a u64 in little-endian bytesReceipt
pda.dispute(receipt: PublicKey, index: number)["dispute", receipt, index], the index as a u16 in little-endian bytesDispute

pdas(programId = PROGRAM_ID) returns the same set of calls for another program id. pda is pdas(). PROGRAM_ID is the program's id as a PublicKey: CdwvX8HQX3r89DpjZEfZ2VmtsxCCVdejrpwd5qD25iHq.

Decoding accounts

decode turns an account's data into a typed object. Each call takes the account's data as a Uint8Array.

CallReturns
decode.config(data)ConfigAccount
decode.model(data)ModelAccount
decode.operator(data)OperatorAccount
decode.offer(data)OfferAccount
decode.receipt(data)ReceiptAccount
decode.dispute(data)DisputeAccount

In the decoded types a key is a PublicKey, a u64 amount is a bigint, a root or hash is a 32-byte Uint8Array, a list of tokens is a number[] cut to its length, and a time is a number of unix seconds. Program accounts gives the meaning of each field.

Data that is not the named account fails in Anchor's coder with a plain Error.

TypeScript
import { accountKind, decode, pda } from '@laplace/sdk'

const info = await laplace.connection.getAccountInfo(pda.config())
if (info && accountKind(info.data) === 'Config') {
  const config = decode.config(info.data)
  console.log(config.protocolShareBps, config.answerDeadlineSecs)
}

ConfigAccount

TypeScript
type ConfigAccount = {
  admin: PublicKey
  feeRecipient: PublicKey
  protocolShareBps: number
  slashWinnerBps: number
  answerDeadlineSecs: number
  turnDeadlineSecs: number
  withdrawCooldownSecs: number
  registrationOpen: boolean
}

ModelAccount

TypeScript
type ModelAccount = {
  publisher: PublicKey
  slug: string
  arch: number
  weightsRoot: Uint8Array
  programRoot: Uint8Array
  initRoot: Uint8Array
  stepCount: number
  statePages: number
  chunkCount: number
  inputMax: number
  outputLen: number
  windowSecs: number
  bondLamports: bigint
  filesHash: Uint8Array
  registeredAt: number
}

OperatorAccount

TypeScript
type OperatorAccount = {
  authority: PublicKey
  bondFree: bigint
  bondLocked: bigint
  withdrawAmount: bigint
  withdrawAt: number
  answered: number
  disputesWon: number
  disputesLost: number
  lastAnswerAt: number
  registeredAt: number
}

OfferAccount

TypeScript
type OfferAccount = {
  operator: PublicKey
  model: PublicKey
  mint: PublicKey
  price: bigint
  active: boolean
  updatedAt: number
}

ReceiptAccount

TypeScript
type ReceiptAccount = {
  model: PublicKey
  operator: PublicKey
  requester: PublicKey
  nonce: bigint
  seed: bigint
  mint: PublicKey
  fee: bigint
  input: number[]
  output: number[]
  traceRoot: Uint8Array
  answerer: PublicKey
  answererIsOperator: boolean
  bond: bigint
  state: 'requested' | 'answered' | 'challenged' | 'final' | 'void'
  requestedAt: number
  answerDeadline: number
  answeredAt: number
  windowEndsAt: number
  windowRemaining: number
  dispute: PublicKey | null
  disputes: number
  finalizedAt: number
}

dispute is null when no dispute is open. output is empty before the answer.

DisputeAccount

TypeScript
type DisputeAccount = {
  receipt: PublicKey
  index: number
  defender: PublicKey
  defenderIsOperator: boolean
  challenger: PublicKey
  defenderOutput: number[]
  defenderTrace: Uint8Array
  challengerOutput: number[]
  challengerTrace: Uint8Array
  bond: bigint
  lo: number
  hi: number
  loRoot: Uint8Array
  hiRoot: Uint8Array
  hiOwner: Side
  points: Uint8Array[]
  turn: Side
  deadline: number
  turns: number
  state: 'open' | 'proving' | 'resolved'
  winner: Side
  resolvedBy: 'step' | 'timeout'
  computedRoot: Uint8Array
  openedAt: number
  resolvedAt: number
}

Side is 'defender' | 'challenger'. winner, resolvedBy, computedRoot and resolvedAt are set when the state is resolved.

Other chain exports

ExportIs
accountKind(data: Uint8Array)The account an account's data is, by its discriminator: 'Config', 'Vault', 'Model', 'Operator', 'Offer', 'Receipt', 'Dispute', or null.
coderAnchor's BorshCoder for the program's IDL, the coder decode and ix use.
ReceiptStates['requested', 'answered', 'challenged', 'final', 'void']
DisputeStates['open', 'proving', 'resolved']
PROGRAM_ERRORSThe program's errors by code: Record<number, { name: string; msg: string }>.

Sending transactions

Every client call that signs goes through one of two functions, which are exported for instructions you build yourself. Both put a compute-unit price on the transaction (Priority fees) and follow it to its outcome the same way.

send

send(connection: Connection, signer: Signer, instructions: TransactionInstruction[], opts?): Promise<string>

Sends the instructions as one v0 transaction paid by signer and resolves with its signature once it is confirmed.

opts.computeUnitsnumber
The compute-unit limit. Left out, the limit is what the simulation used plus 20% and 1,000 units, at most 1,400,000.
opts.extraKeypair[]
More keypairs that sign the transaction, besides signer.

The transaction opens with two Compute Budget instructions, SetComputeUnitLimit and SetComputeUnitPrice, so the priority fee is paid on the limit, not on 1,400,000 units.

In order: it reads the latest blockhash and the compute-unit price, simulates the transaction at 1,400,000 units, sets the limit, asks the wallet to sign, sends the signed bytes, and follows the signature. A transaction that fails in simulation is never shown to the wallet. A send that errors at the RPC is followed like any other, since it may have reached the cluster.

Following reads the signature's status every 1.5 s until the transaction is confirmed, fails, or its blockhash expires. A read that errors is tried again. When the outcome stays unreadable for two minutes the call throws at stage unknown, with the signature.

sendV1

sendV1(connection: Connection, signer: Signer, instructions: TransactionInstruction[], computeUnits = 1_400_000): Promise<string>

Sends the instructions as one v1 transaction, which carries up to 4096 bytes, and resolves with its signature once it is confirmed. The transaction is signed by its payer alone, through signer.signMessage over the message bytes. Its priority fee is in the v1 header, in lamports for the whole limit: the compute-unit price times computeUnits, divided by 1,000,000 and rounded up. The cluster's preflight checks it before it is sent. proveStep sends prove_step this way. One step on chain describes why.

Priority fees

Every transaction the SDK sends carries a compute-unit price, set once for the process.

setPriorityFee(microLamports: number | 'auto'): void

Sets the price every later send uses: a fixed number of µlamports per compute unit, or 'auto', which is the starting value. createLaplace({ priorityFee }) calls it.

computeUnitPrice(connection: Connection): Promise<number>

The price a send uses now, in µlamports per compute unit. A fixed price is returned as set. With 'auto' it is the 75th percentile of the non-zero fees getRecentPrioritizationFees returns, at least 10,000 and at most 2,000,000, read once every 30 seconds per connection. A failed read counts as no fees, so the price is 10,000.

TypeScript
import { computeUnitPrice, setPriorityFee } from '@laplace/sdk'

setPriorityFee(50_000)
const price = await computeUnitPrice(laplace.connection) // 50000
setPriorityFee('auto')

In a browser the relay at /v1/rpc serves getRecentPrioritizationFees, so 'auto' works through it.

compileV1 and serializeV1

compileV1(payer: PublicKey, instructions: TransactionInstruction[], blockhash: Uint8Array, computeUnits = 1_400_000, priorityFee = 0n): { bytes: Uint8Array; signers: PublicKey[] }

Compiles a v1 message. blockhash is the 32 raw bytes of a recent blockhash. bytes is what each signer signs, and signers lists them in signing order, the payer first. The message sets the compute-unit limit to computeUnits and the loaded-accounts data limit to 2 MiB, and when priorityFee is above 0 it carries that many lamports as the transaction's priority fee.

serializeV1(message, signatures: Uint8Array[]): Uint8Array

Returns the wire transaction: the message bytes, then one 64-byte signature per signer in signer order. It throws a plain Error when the result is larger than V1_MAX_BYTES, which is 4096.

TypeScript
import { PublicKey } from '@solana/web3.js'
import { compileV1, ix, serializeV1 } from '@laplace/sdk'

const { blockhash } = await laplace.connection.getLatestBlockhash('confirmed')
const message = compileV1(wallet.publicKey, [ix.withdrawBond(wallet.publicKey)], new PublicKey(blockhash).toBytes())
const wire = serializeV1(message, [await wallet.signMessage(message.bytes)])

LaplaceError

Every failure of a call that reads the chain or sends a transaction is a LaplaceError:

TypeScript
import { LaplaceError } from '@laplace/sdk'

try {
  await laplace.finalize(receipt)
} catch (e) {
  if (e instanceof LaplaceError && e.programError?.name === 'WindowOpen') {
    console.log('The window is still open.')
  } else {
    throw e
  }
}
namestring
'LaplaceError'.
stageStagerequired
Where the call failed: one of the stages below.
messagestringrequired
One sentence. For a refusal by the program: The program refused it: <name>.
programError{ code: number; name: string }
Set when the laplace program itself refused the transaction.
logsstring[]
The transaction's program logs, when the failure produced any.
signaturestring
The transaction's signature, set once it was signed and sent: at confirm, the failed or expired transaction; at unknown, the one still to look up.

Stage is 'build' | 'wallet' | 'simulate' | 'send' | 'confirm' | 'unknown'. A send error is followed by its signature rather than raised, so the calls raise these five:

stageRaised when
buildSomething the call needs before sending is not there: no account at an address, no live offer, a model file missing from the store or not matching its hash, model files not matching the roots on chain. sendV1 raises it for instructions that need a second signer.
walletThe client has no wallet, or the wallet's signing call threw. Nothing was sent.
simulateThe transaction failed in simulation. Nothing was sent. For send this is the simulation before signing. For sendV1 it is the cluster's preflight.
confirmThe transaction landed and failed, or its blockhash expired before it landed (The transaction expired before it landed.). waitFor and final raise it on their timeouts, and final on a void receipt.
unknownThe transaction was sent and its outcome could not be read for two minutes. It may still land: read the receipt or account it writes, or look up signature, before sending again.

programError

programError names the first error the laplace program raised in the transaction's logs:

  • one of the program's own errors, codes 6000 to 6026, with its name. Program errors lists each one and what raises it.
  • an Anchor framework error, with Anchor's name and number, such as AccountNotInitialized (3012) for an account that does not exist.
  • an SPL Token error from a transfer the program made, by name: InsufficientFunds (1), MintMismatch (3), OwnerMismatch (4), AccountFrozen (17), or TokenError<code> for another.
  • an error of another program, named by the first 8 characters of its id and the code, as <id>:<code>.

programErrorFromLogs(logs: string[] | null | undefined): { code: number; name: string } | undefined is the function that reads it, for logs you hold yourself.

Other errors

ErrorFrom
ApiClientErrorAny read through laplace.api, including the ones inside ask, tokenizer and model.
DOMException named AbortErrorA run stopped through its signal.
A plain ErrorAn instruction builder missing an account, decode on data of another account, serializeV1 past 4,096 bytes, loadModel and readProgramHeader on files that are not a model.

The VM entry

@laplace/sdk/vm is the model runtime on its own: load a model from its two files, run it, read the state root after any step, and build or check the payload of one step. laplace.model and laplace.rerun are built on it.

TypeScript
import { loadModel, toHex } from '@laplace/sdk/vm'

const files = await laplace.api.modelFiles('market')
const bytes = async (hash: string) => new Uint8Array(await (await fetch(laplace.api.fileUrl(hash))).arrayBuffer())

const vm = await loadModel(await bytes(files.program.hash), await bytes(files.weights.hash))
const tokens = (await laplace.tokenizer('market')).encode({ text: 'Shipments rose 18% in the third quarter, above guidance.' })

const run = await vm.run(tokens, 7n)
console.log(run.output, toHex(run.traceRoot))

const k = 1000
const payload = vm.prove(tokens, 7n, k)
const stepped = vm.verify(payload, k, run.root(k), tokens, 7n)
console.log(stepped !== null && toHex(stepped.root) === toHex(run.root(k + 1)))

loadModel

loadModel(program: Uint8Array, weights: Uint8Array): Promise<VmModel>

Loads a model from the bytes of its program file and its weights file. The WASM module is instantiated on the first call and shared by every model after it. Throws a plain Error, These files are not a Laplace model., when the VM does not accept them.

loadModel checks nothing against the chain. Compare programRoot, weightsRoot and initRoot with the Model account yourself, or use laplace.model, which does.

VmModel

MemberTypeIs
programRootUint8ArrayThe Merkle root of the step program, 32 bytes.
weightsRootUint8ArrayThe Merkle root of the weights, 32 bytes.
initRootUint8ArrayThe state root before step 0, 32 bytes.
stepCountnumberThe number of steps in a run.
headerModelHeaderWhat the program file's header declares.
step(k)(k: number) => StepInfoWhat step k does.
run(input, seed, opts?)Promise<Run>A full run.
prove(input, seed, k, fault?)Uint8ArrayThe prove_step payload for step k of a run on this input and seed.
verify(payload, lo, loRoot, input, seed){ root: Uint8Array; op: string } | nullOne step executed from a payload.
TypeScript
type ModelHeader = { arch: number; inputMax: number; outputLen: number; statePages: number; stepCount: number; pageNames: string[] }

type StepInfo = {
  index: number
  op: string
  opCode: number
  reads: { leaf: number; name: string }[]
  writes: { leaf: number; name: string } | null
  chunk: number | null
}

type Progress = { phase: 'loading' | 'running'; done: number; total: number }

type Fault = { step: number; word: number; delta: number }

step(k) reads step k from the program file. op is the operator's name from OP_NAMES and opCode its number. reads are the state pages the step reads and writes the page it writes, each with its leaf index in the state tree and its name. chunk is the index of the weight chunk the step reads, or null.

run(input: number[], seed: bigint, opts?) runs every step and resolves with a Run:

inputnumber[]required
The input as token ids.
seedbigintrequired
The receipt's seed, a u64. The first step writes it into the input page, so it enters the state roots and the trace root, and leaves the output as it is.
opts.onProgress(p: Progress) => void
Called with { phase: 'running', done, total } in steps after every slice.
opts.signalAbortSignal
Stops the run between slices. The call rejects with a DOMException named AbortError.
opts.slicenumber
Steps executed before the run yields to the event loop. Default 2048.
opts.faultFault
Changes one step's result: delta is added to word word of the page that step step writes, or added to and subtracted from alternate words of the whole page when word is past its end. A run made this way differs from every other run from that step on, which is how a dispute is produced on purpose.

prove(input: number[], seed: bigint, k: number, fault?: Fault) returns the bytes prove_step takes for step k: the step, the pages it reads with their proofs against the state root before it, and the weight chunk it reads with its proof. One step on chain gives the layout.

verify(payload: Uint8Array, lo: number, loRoot: Uint8Array, input: number[], seed: bigint) executes the step in a payload the way the program does, from the payload alone: lo is the step's index and loRoot the state root before it. It returns the state root the step leads to and the operator's name, or null when the payload does not check against loRoot and the model's roots.

Run

MemberTypeIs
inputnumber[]The input the run was made on.
seedbigintThe seed it was made with.
outputnumber[]The output as token ids.
traceRootUint8ArrayThe trace root, 32 bytes.
stepCountnumberThe model's step count.
faultFault | undefinedThe fault the run was made with, if any.
root(k)(k: number) => Uint8ArrayThe root after k steps. root(0) is the init root and root(stepCount) is the output leaf.
points(lo, hi)(lo: number, hi: number) => { step: number; root: Uint8Array }[]This run's roots at the split points of [lo, hi].
free()() => voidReleases the run's memory in the WASM module. root and points are not called after it.

Functions and constants

ExportSignatureIs
splitPoints(lo: number, hi: number) => number[]The steps at which the program splits [lo, hi]: lo + floor((hi - lo) * i / 8) for i from 1 to 7, every interior step when hi - lo is 8 or less, and none when it is 1 or less.
inputHash(tokens: number[]) => Promise<Uint8Array>The SHA-256 of the tokens, each as a u16 in little-endian bytes. The input hash a receipt reader gets.
outputLeaf(tokens: number[]) => Promise<Uint8Array>The last leaf of a trace: the SHA-256 of the bytes of laplace.output, the token count as a u16, then the tokens as u16, all little-endian.
toHex(b: Uint8Array) => stringBytes as lowercase hex.
fromHex(h: string) => Uint8ArrayHex as bytes.
readProgramHeader(program: Uint8Array) => ModelHeaderThe header of a program file. Throws a plain Error, Not a Laplace program file., on other bytes.
OP_NAMESreadonly string[]The operators' names by code, 0 to 19: load (0), embed (1), add-row (2), matvec (3), norm-stats (4 and 8), norm-apply (5), norm-sum (6), activation (7), residual (9), scores (11), softmax (13), weighted-sum (14), argmax (16), output (19). Codes 10, 12, 15, 17 and 18 hold an empty string.

A full run in Node takes 1.2 s for judge and about 12 s for market, as measured.

The API entry

@laplace/sdk/api is a typed client for the HTTP API. Every answer is parsed with the zod schema the server validates with. HTTP API gives each route's parameters and each shape field by field.

createApiClient

createApiClient(baseUrl: string, options?): ApiClient

baseUrlstringrequired
The API's base URL. Trailing slashes are dropped.
options.fetchtypeof fetch
The fetch to use. Default: the global one.
options.credentialsRequestCredentials
Passed to every request.
options.headersRecord<string, string>
Sent with every request.
TypeScript
import { ApiClientError, createApiClient } from '@laplace/sdk/api'

const api = createApiClient(apiUrl)

const { items, nextCursor } = await api.receipts({ model: 'judge', state: 'answered', limit: 10 })

try {
  const detail = await api.receipt(items[0]!.address)
  console.log(detail.state, detail.output?.label)
} catch (e) {
  if (e instanceof ApiClientError && e.code === 'NOT_FOUND') console.log('No receipt at this address.')
  else throw e
}
CallRouteResolves with
api.health()GET /healthHealth
api.network()GET /v1/networkNetwork
api.models()GET /v1/modelsModelList
api.model(slug)GET /v1/models/:slugModelDetail
api.modelFiles(slug)GET /v1/models/:slug/filesModelFiles
api.fileUrl(hash)noneThe URL of GET /v1/files/:hash, as a string.
api.operators()GET /v1/operatorsOperatorList
api.operator(key)GET /v1/operators/:keyOperatorDetail
api.offers(model?)GET /v1/offersOfferList
api.receipts(query?)GET /v1/receiptsReceiptPage. query takes model, operator, requester, state, cursor, limit.
api.receipt(address)GET /v1/receipts/:addressReceiptDetail
api.disputes(query?)GET /v1/disputesDisputeList. query takes receipt, operator, state.
api.dispute(address)GET /v1/disputes/:addressDisputeDetail
api.referenceDispute()GET /v1/disputes/referenceDisputeDetail
api.upload(slug, kind, bytes)POST /v1/filesUpload. kind is 'manifest', 'weights', 'program' or 'tokenizer'. A refusal is a plain Error with the message <code>: <message>.
api.eventsUrl(filter?)noneThe URL of GET /v1/events for an EventSource. filter takes receipt and dispute.
api.httpThe client under these calls: get(path, schema, call?), post(path, schema, body?, call?), request(method, path, schema, body?, call?), url(path, query?) and streamUrl(path, query?). call takes query, signal and headers.
TypeScript
import type { LaplaceEvent } from '@laplace/sdk/api'

const stream = new EventSource(laplace.api.eventsUrl({ receipt: receipt.toBase58() }))
stream.addEventListener('receipt', (message) => {
  const event = JSON.parse(message.data) as LaplaceEvent
  if (event.type === 'receipt') console.log(event.data.state)
})

ApiClientError

Thrown by every call above except upload, fileUrl and eventsUrl, whenever the API answers with its error envelope or a status that is not a success.

namestring
'ApiClientError'.
statusnumber
The HTTP status.
codestring
The envelope's error.code, such as NOT_FOUND.
messagestring
The envelope's error.message.
bodyApiErrorBody
The whole envelope: body.error holds code, message, retryable, stage, and where they apply fieldErrors, programError, retryAfterSeconds and requestId.

An answer that is not JSON, or a failed status with no envelope, becomes an envelope with the code UPSTREAM_UNAVAILABLE for a status of 500 or more and INTERNAL_ERROR below it, and the message The API answered HTTP <status>. An answer that does not fit its schema throws zod's ZodError.

Schemas

Each schema is a zod schema, and each name in the second list is also exported as the TypeScript type of its parsed value. The shapes are on HTTP API.

GroupNames
PrimitivesAddress, Signature, Timestamp, U64, Hex, Amount
EnumsReceiptState, DisputeState, Side, Task, TransactionKind, FileKind
PartsMint, Tokens, Output, Claim, Point, Turn, Transaction, DisputeResult
ResourcesModel, ModelDetail, ModelFiles, Offer, Operator, OperatorDetail, Receipt, ReceiptDetail, Dispute, DisputeDetail, Network
ListsModelList, OperatorList, OfferList, DisputeList, ReceiptPage, and list(item), which builds { items: item[] }
QueriesReceiptQuery, DisputeQuery, OfferQuery, EventQuery
Other answersHealth, Upload
Errorserrors.ApiError (the envelope), errors.ErrorCode (the codes), errors.status (the HTTP status of each code)

Types: Model, ModelDetail, ModelFiles, Offer, Operator, OperatorDetail, Receipt, ReceiptDetail, ReceiptState, Dispute, DisputeDetail, DisputeResult, Turn, Transaction, Network, Mint, Point, ErrorCode, ApiClient, and LaplaceEvent, the union of what GET /v1/events sends.

CONTRACT_VERSION is the version of these shapes: '0.1.0'.

From the main entry, Side is the TypeScript type 'defender' | 'challenger' of the chain layer. Import the zod schema Side from @laplace/sdk/api.