Skip to content

Latest commit

 

History

History
340 lines (222 loc) · 6.48 KB

File metadata and controls

340 lines (222 loc) · 6.48 KB

Blockchain API Reference

The Blockchain singleton simulates the OPNet blockchain environment. It manages contracts, blocks, addresses, and transaction context.

Import: import { Blockchain } from '@btc-vision/unit-test-framework'


Initialization & Cleanup

init()

async init(): Promise<void>

Initializes the blockchain VM. Must be called before any contract interaction.

dispose()

dispose(): void

Resets the current execution state. Call in afterEach.

cleanup()

cleanup(): void

Full cleanup including VM bindings. Call in afterAll.

clearContracts()

clearContracts(): void

Unregisters all contracts from the blockchain.


Block Management

blockNumber

get blockNumber(): bigint
set blockNumber(blockNumber: bigint)

Current block height. Default: 1n.

medianTimestamp

get medianTimestamp(): bigint
set medianTimestamp(timestamp: bigint)

Median block timestamp.

mineBlock()

mineBlock(): void

Advances blockNumber by 1. Used to test block-boundary behavior like updates:

await contract.update(v2Address);
Blockchain.mineBlock();
// Update now takes effect
const value = await contract.getValue();

Transaction Context

msgSender

get msgSender(): Address
set msgSender(sender: Address)

The msg.sender for contract calls.

txOrigin

get txOrigin(): Address
set txOrigin(from: Address)

The tx.origin for contract calls. Must be a valid tweaked public key.

transaction

get transaction(): Transaction | null
set transaction(tx: Transaction | null)

The current Bitcoin transaction context (inputs/outputs).


Address Generation

generateRandomAddress()

generateRandomAddress(): Address

Generates a cryptographically random OPNet address.

generateRandomWallet()

generateRandomWallet(): Wallet

Generates a full wallet with both ECDSA and ML-DSA keypairs:

const wallet = Blockchain.generateRandomWallet();
wallet.address;              // Address
wallet.keypair;              // Secp256k1 keypair
wallet.mldsaKeypair;         // ML-DSA keypair
wallet.quantumPublicKeyHex;  // ML-DSA public key (hex)

generateAddress(deployer, salt, from)

generateAddress(deployer: Address, salt: Buffer, from: Address): Address

Deterministic address generation (CREATE2-style).

DEAD_ADDRESS

readonly DEAD_ADDRESS: Address

The dead/burn address (Address.dead()).


Contract Registry

register(contract)

register(contract: ContractRuntime): void

Registers a contract with the blockchain. Required for contract-to-contract calls:

const tokenA = new OP20({ ... });
const swap = new MySwapContract(deployer, swapAddr);

Blockchain.register(tokenA);
Blockchain.register(swap);

unregister(contract)

unregister(contract: ContractRuntime): void

getContract(address)

getContract(address: Address): ContractRuntime

Looks up a registered contract by address.

isContract(address)

isContract(address: Address): boolean

Returns true if the address has a registered contract.


Decimal Utilities

expandTo18Decimals(n)

expandTo18Decimals(n: number): bigint

Converts n to n * 10^18. Example: 100 -> 100_000_000_000_000_000_000n.

expandToDecimal(n, decimals)

expandToDecimal(n: number, decimals: number): bigint

Converts n to n * 10^decimals.

decodeFrom18Decimals(n)

decodeFrom18Decimals(n: bigint): number

Converts n / 10^18 to a number.

decodeFromDecimal(n, decimals)

decodeFromDecimal(n: bigint, decimals: number): number

encodePrice(reserve0, reserve1)

encodePrice(reserve0: bigint, reserve1: bigint): [bigint, bigint]

Encodes a price from AMM reserves (UQ112x112 format).


State Management

backupStates()

backupStates(): void

Saves the current state of all registered contracts.

restoreStates()

restoreStates(): void

Restores previously backed-up states.


ML-DSA Key Management

registerMLDSAPublicKey(address, publicKey)

registerMLDSAPublicKey(address: Address, publicKey: Uint8Array): void

Registers an ML-DSA public key for signature verification.

getMLDSAPublicKey(address)

getMLDSAPublicKey(address: Address): Uint8Array | undefined

Tracking & Debugging

Enable tracing to get detailed output during test execution:

// Gas tracing - logs gas usage per call
Blockchain.traceGas = true;
Blockchain.enableGasTracking();
Blockchain.disableGasTracking();

// Storage pointer tracing
Blockchain.tracePointers = true;
Blockchain.enablePointerTracking();
Blockchain.disablePointerTracking();

// Contract call tracing
Blockchain.traceCalls = true;
Blockchain.enableCallTracking();
Blockchain.disableCallTracking();

// Deployment tracing
Blockchain.traceDeployments = true;

simulateRealEnvironment

simulateRealEnvironment: boolean  // Default: false

When true, simulates a more realistic execution environment.

changeNetwork(network)

changeNetwork(network: Network): void

Switch to a different Bitcoin network (e.g., mainnet, testnet).


Properties Summary

Property Type Default Description
network Network regtest Bitcoin network
blockNumber bigint 1n Current block height
medianTimestamp bigint BigInt(Date.now()) Block median time
msgSender Address Address.dead() Call sender
txOrigin Address Address.dead() Transaction origin
transaction Transaction | null null Current BTC transaction
traceGas boolean false Gas logging
tracePointers boolean false Storage pointer logging
traceCalls boolean false Call logging
traceDeployments boolean false Deployment logging
simulateRealEnvironment boolean false Realistic mode
DEAD_ADDRESS Address Address.dead() Burn address

<- Previous: Assertions | Next: Contract Runtime ->