Start

Quickstart: read a receipt from a program

Take a receipt account in your own Solana program and act on its final output.

A program acts on a model's answer by reading a final receipt. This quickstart builds a small Anchor program that holds a stake on one question to the judge and pays it out on the judge's final answer, then the client that opens the market, asks and settles.

The program

  1. Create the program

    Shell
    anchor init market

    The program builds on Anchor 0.31.1, the version laplace-receipt pins.

  2. Add the crate

    TOML
    [dependencies]
    anchor-lang = "=0.31.1"
    laplace-receipt = { path = "<laplace>/backend/chain/crates/laplace-receipt" }

    <laplace> is the folder that holds the Laplace source. laplace-receipt crate has the details.

  3. Write the market

    Two instructions: open stores the model and the hash of the question and takes the stake; settle reads the receipt and pays the stake to the side the judge named. Below the declare_id! that anchor init wrote:

    Rust
    use anchor_lang::prelude::*;
    
    /// The judge's output is one label token.
    const YES: u16 = 0;
    const NO: u16 = 2;
    
    #[program]
    pub mod market {
        use super::*;
    
        /// Opens a market on one question: the judge model and the hash of the tokens it will be asked.
        pub fn open(ctx: Context<Open>, model: Pubkey, input_hash: [u8; 32], stake: u64) -> Result<()> {
            let m = &mut ctx.accounts.market;
            m.funder = ctx.accounts.funder.key();
            m.yes = ctx.accounts.yes.key();
            m.no = ctx.accounts.no.key();
            m.model = model;
            m.input_hash = input_hash;
            m.stake = stake;
            anchor_lang::system_program::transfer(
                CpiContext::new(
                    ctx.accounts.system_program.to_account_info(),
                    anchor_lang::system_program::Transfer {
                        from: ctx.accounts.funder.to_account_info(),
                        to: ctx.accounts.market.to_account_info(),
                    },
                ),
                stake,
            )
        }
    
        /// Pays the stake out on the judge's final answer.
        pub fn settle(ctx: Context<Settle>) -> Result<()> {
            let answer = laplace_receipt::read(&ctx.accounts.receipt)?;
            let m = &ctx.accounts.market;
            require_keys_eq!(answer.model, m.model, MarketError::WrongModel);
            require!(answer.input_hash == m.input_hash, MarketError::WrongQuestion);
    
            let to = match answer.output[0] {
                YES => ctx.accounts.yes.to_account_info(),
                NO => ctx.accounts.no.to_account_info(),
                _ => ctx.accounts.funder.to_account_info(), // unclear: the stake goes back
            };
            let from = ctx.accounts.market.to_account_info();
            let stake = m.stake;
            **from.try_borrow_mut_lamports()? -= stake;
            **to.try_borrow_mut_lamports()? += stake;
            ctx.accounts.market.stake = 0;
            Ok(())
        }
    }
    
    #[account]
    #[derive(InitSpace)]
    pub struct Market {
        pub funder: Pubkey,
        pub yes: Pubkey,
        pub no: Pubkey,
        pub model: Pubkey,
        pub input_hash: [u8; 32],
        pub stake: u64,
    }
    
    #[derive(Accounts)]
    pub struct Open<'info> {
        #[account(mut)]
        pub funder: Signer<'info>,
        #[account(init, payer = funder, space = 8 + Market::INIT_SPACE)]
        pub market: Account<'info, Market>,
        /// CHECK: receives the stake on yes
        pub yes: UncheckedAccount<'info>,
        /// CHECK: receives the stake on no
        pub no: UncheckedAccount<'info>,
        pub system_program: Program<'info, System>,
    }
    
    #[derive(Accounts)]
    pub struct Settle<'info> {
        #[account(mut, has_one = yes, has_one = no, has_one = funder)]
        pub market: Account<'info, Market>,
        /// CHECK: checked by laplace_receipt::read: owned by the Laplace program and final
        pub receipt: UncheckedAccount<'info>,
        /// CHECK: the market's yes recipient
        #[account(mut)]
        pub yes: UncheckedAccount<'info>,
        /// CHECK: the market's no recipient
        #[account(mut)]
        pub no: UncheckedAccount<'info>,
        /// CHECK: the market's funder
        #[account(mut)]
        pub funder: UncheckedAccount<'info>,
    }
    
    #[error_code]
    pub enum MarketError {
        #[msg("The receipt answers another model")]
        WrongModel,
        #[msg("The receipt answers another question")]
        WrongQuestion,
    }

    laplace_receipt::read refuses any account that is not a Laplace receipt and any receipt that is not final. The two comparisons after it make sure the receipt answers this market's model and this market's question.

  4. Build and deploy

    Shell
    anchor build
    anchor deploy

    anchor build writes the program's IDL to target/idl/market.json, which the client below loads.

The client

The client opens the market on the hash of the question, asks the judge that question, waits for the receipt to be final, and settles. It runs in Node with a keypair file that holds SOL for the stake and the fees, and the offer's fee mint for the request.

TypeScript
import { readFileSync } from 'node:fs'
import { BN, Program, type Idl } from '@coral-xyz/anchor'
import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js'
import { createLaplace, keypairSigner, pda, send, JUDGE_LABELS } from '@laplace/sdk'
import { inputHash } from '@laplace/sdk/vm'
import idl from './target/idl/market.json'

const keypair = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(process.env.KEYPAIR!, 'utf8'))))
const wallet = keypairSigner(keypair)
const laplace = createLaplace({ rpcUrl: process.env.LAPLACE_RPC!, apiUrl: process.env.LAPLACE_API!, wallet })
const market = new Program(idl as Idl, { connection: laplace.connection })

const yes = new PublicKey(process.env.YES!)
const no = new PublicKey(process.env.NO!)
const question = { claim: 'The bridge opened in 1932.', evidence: 'The bridge opened to traffic in March 1932.' }

// 1. Open the market on the hash of the tokens the request will carry.
const tokens = (await laplace.tokenizer('judge')).encode(question)
const hash = await inputHash(tokens)
const account = Keypair.generate()
const open = await market.methods
  .open(pda.model('judge'), Array.from(hash), new BN(1_000_000_000))
  .accounts({ funder: wallet.publicKey, market: account.publicKey, yes, no, systemProgram: SystemProgram.programId })
  .instruction()
await send(laplace.connection, wallet, [open], { extra: [account] })

// 2. Ask the judge, then wait for the receipt to be final.
const { receipt } = await laplace.ask('judge', question)
const answer = await laplace.final(receipt)
console.log(JUDGE_LABELS[answer.output[0]!])

// 3. Settle on it.
const settle = await market.methods
  .settle()
  .accounts({ market: account.publicKey, receipt, yes, no, funder: wallet.publicKey })
  .instruction()
await send(laplace.connection, wallet, [settle])

LAPLACE_RPC and LAPLACE_API are the network's addresses, listed on Addresses. laplace.ask takes the cheapest live offer for the judge and pays its price; Quickstart: ask a model covers the wallet it needs.

laplace.final resolves once the receipt is final: after the answer, the model's window with no challenge standing, and finalize. It throws when the request went void. Until it resolves, settle would fail with the crate's NotFinal.

What settles

The judge's final outputThe stake goes to
0, yesyes
2, nono
1, unclearthe funder

The output that settles is the one standing when the receipt became final. If a watcher challenged the operator's answer and won, it is the watcher's output, the one the model computes.