SDK examples
Runnable samples live in src/sample of the SDK repository (they are not in the npm package). Clone the repo, pnpm install, then e.g. pnpm sample:counter.
| Sample | Shows |
|---|---|
counter.ts | Full session lifecycle with every step type |
instant.ts | instantSimulation with every read type |
failure-modes.ts | The four failure signals on a receipt |
batch-categories.ts | Every batch read category |
contract-vitest.test.ts | A Vitest suite driving a contract through a session, pinned to a fork point |
trace.ts | Profile an on-chain transaction from its trace |
trace-vitest.test.ts | Traces end to end, on-chain and simulated, mapped to source |
locked-stx-vitest.test.ts | PoX locked-STX unlock with AdvanceBlocks |
sbtc-deposit-vitest.test.ts | sBTC deposit with a forged burn header hash |
brotocol-pegin-vitest.test.ts | BTC peg-in with a forged transaction and SPV proof |
hbtc-vault-vitest.test.ts | Vault deposit, reward and time-locked redeem |
zest-borrow-vitest.test.ts, granite-leverage-vitest.test.ts | Lending flows with a replaced price-feed decoder |
A contract test
ts
import { describe, expect, it } from 'vitest'
import { uintCV } from '@stacks/transactions'
import { createSimulationSession, submitSimulationSteps, callContract, getStxBalance } from 'stxer'
describe('my-contract', () => {
it('deposits', async () => {
const id = await createSimulationSession({ skip_tracing: true })
await submitSimulationSteps(id, {
steps: [{ SetContractCode: ['SP….my-contract', MY_SOURCE, 6] }],
})
const r = await callContract(id, {
sender: 'SP…', contract: 'SP….my-contract', functionName: 'deposit', functionArgs: [uintCV(100)],
})
expect(r.pcAborted).toBe(false)
expect(r.vmError).toBeNull()
expect(await getStxBalance(id, 'SP…')).toBeGreaterThan(0n)
})
})Profile a transaction
ts
import { getTransactionTrace, flattenTrace, traceNodeSelfCost } from 'stxer'
const trace = await getTransactionTrace({
blockHeight: 1018838,
blockHash: '0x89945f0d9956794d453adb28d78302002a1d16885d8b4de3ee598ec69c631a54',
txid: '0xc1bfb9616c51a17859c48f1716eefdd5ea9646f59b8e6c082033370ae17e33fa',
})
const byContract = new Map<string, number>()
for (const { node, contractId = '' } of flattenTrace(trace.root)) {
byContract.set(contractId, (byContract.get(contractId) ?? 0) + traceNodeSelfCost(node).runtime)
}
console.table([...byContract].sort((a, b) => b[1] - a[1]))Preview a wallet transaction
ts
import { instantSimulation } from 'stxer'
const { receipt } = await instantSimulation({ transaction: signedOrUnsignedHex })
if (receipt.post_condition_aborted) warn('post condition would abort', receipt.vm_error)
else if (receipt.vm_error) warn('runtime error', receipt.vm_error)
else if (receipt.result.startsWith('08')) warn('contract returned an error', receipt.result)