Skip to main content
All articles

CashScript 0.14: Build and Test a Bitcoin Cash Contract

Write a reusable payout check, compile a Bitcoin Cash contract, and test both paths without broadcasting a transaction.

Published Nov 15, 20266 min read

CashScript turns rules about who can spend a Bitcoin Cash output into code that a node can check. This guide follows one payment from source code to a locally validated spend. It uses CashScript 0.14.0, which made user-defined helper functions, top-level constants, and imports available in a stable release. For the previous compiler and its Layla context, see the 0.13 guide.

Start with the spending rules

Say a payer and a recipient want to release a payment only if they both sign. If they never agree, the payer can spend it alone after a specified block-height locktime. This example funds the contract with one unspent transaction output. Both paths spend that same output, so only one can succeed on-chain.

Save this as escrow.cash:

pragma cashscript ^0.14.0;
 
function paysTo(bytes25 destination) returns (bool) {
    return tx.outputs[0].lockingBytecode == destination;
}
 
contract Escrow(pubkey payer, pubkey recipient, int deadline) {
    function release(sig payerSig, sig recipientSig) {
        require(checkSig(payerSig, payer));
        require(checkSig(recipientSig, recipient));
        require(paysTo(new LockingBytecodeP2PKH(hash160(recipient))));
    }
 
    function refund(sig payerSig) {
        require(tx.time >= deadline);
        require(checkSig(payerSig, payer));
        require(paysTo(new LockingBytecodeP2PKH(hash160(payer))));
    }
}

release and refund are entry points the transaction can call. Both use paysTo to check the first output's destination. Signature checks stay in the entry points: the 0.14 compiler disallows checkSig inside a user-defined helper because executing it there can change the bytecode used for signing. The compiler can inline safe helpers or share them using Layla's OP_DEFINE and OP_INVOKE. See the compiler's optimization guide.

The contract checks the destination of output zero. It does not constrain the amount, fees, or any additional outputs; the signer still needs to review those. After the deadline the two-signature path remains valid, and nothing sends the refund automatically.

Compile and test without funds

In a new folder with Node.js 24, install the pinned compiler and SDK:

npm install --save-exact cashc@0.14.0 cashscript@0.14.0

Save the following as escrow.test.mjs next to escrow.cash, then run node --test escrow.test.mjs from that folder. The compiler returns an artifact containing bytecode and the contract interface. The SDK instantiates it with two local keys and a deadline. Every test creates its own mock output so it can spend independently of the others.

The mock uses the May 2026 BCH VM rules and an artificial deadline of block height 900. Each transaction spends 10,000 satoshis and creates one 9,000-satoshi output; the remaining 1,000 satoshis are the fee. These values make the tests easy to follow, rather than prescribing a live deadline or fee.

import assert from "node:assert/strict";
import { createECDH } from "node:crypto";
import { test } from "node:test";
import { compileFile } from "cashc";
import {
    Contract, MockNetworkProvider, SignatureTemplate,
    TransactionBuilder, VmTarget, randomUtxo, utils,
} from "cashscript";
 
const artifact = compileFile("escrow.cash");
const deadline = 900;
 
function makeSigner() {
    const key = createECDH("secp256k1");
    key.generateKeys();
    const signature = new SignatureTemplate(key.getPrivateKey());
    const pubkey = signature.publicKey;
    const payout = Uint8Array.from([0x76, 0xa9, 0x14, ...utils.hash160(pubkey), 0x88, 0xac]);
    return { pubkey, signature, payout };
}
 
function fixture(height = deadline) {
    const provider = new MockNetworkProvider({
        validateTransactions: true, vmTarget: VmTarget.BCH_2026_05,
    });
    provider.setBlockHeight(height);
    const payer = makeSigner();
    const recipient = makeSigner();
    const contract = new Contract(
        artifact, [payer.pubkey, recipient.pubkey, BigInt(deadline)], { provider },
    );
    const utxo = provider.addUtxo(
        contract.address, { ...randomUtxo(), satoshis: 10_000n },
    );
    const spend = (unlocker, to, locktime = 0) => {
        const raw = new TransactionBuilder({ provider })
            .addInput(utxo, unlocker)
            .addOutput({ to, amount: 9_000n })
            .setLocktime(locktime)
            .build();
        return provider.sendRawTransaction(raw);
    };
 
    return { contract, payer, recipient, spend };
}
 
test("both signers can release the payment", async () => {
    const { contract, payer, recipient, spend } = fixture();
    const unlock = contract.unlock.release(payer.signature, recipient.signature);
    assert.match(await spend(unlock, recipient.payout), /^[a-f0-9]{64}$/);
});
 
test("a different signer cannot stand in for the recipient", async () => {
    const { contract, payer, recipient, spend } = fixture();
    const unlock = contract.unlock.release(payer.signature, makeSigner().signature);
    await assert.rejects(() => spend(unlock, recipient.payout), /signature/i);
});
 
test("two signatures cannot redirect the first output", async () => {
    const { contract, payer, recipient, spend } = fixture();
    const unlock = contract.unlock.release(payer.signature, recipient.signature);
    await assert.rejects(() => spend(unlock, payer.payout), /verify/i);
});
 
test("the refund rejects an insufficient locktime", async () => {
    const { contract, payer, spend } = fixture();
    await assert.rejects(
        () => spend(contract.unlock.refund(payer.signature), payer.payout, deadline - 1),
        /locktime/i,
    );
});
 
test("the refund is non-final before the mock chain reaches the deadline", async () => {
    const { contract, payer, spend } = fixture(deadline - 1);
    await assert.rejects(
        () => spend(contract.unlock.refund(payer.signature), payer.payout, deadline),
        /non-final/i,
    );
});
 
test("a different signer cannot refund the payment", async () => {
    const { contract, payer, spend } = fixture();
    await assert.rejects(
        () => spend(contract.unlock.refund(makeSigner().signature), payer.payout, deadline),
        /signature/i,
    );
});
 
test("the refund cannot redirect the first output", async () => {
    const { contract, payer, recipient, spend } = fixture();
    await assert.rejects(
        () => spend(contract.unlock.refund(payer.signature), recipient.payout, deadline),
        /verify/i,
    );
});
 
test("the payer can refund once the mock chain tip reaches the deadline", async () => {
    const { contract, payer, spend } = fixture();
    const result = await spend(
        contract.unlock.refund(payer.signature), payer.payout, deadline,
    );
    assert.match(result, /^[a-f0-9]{64}$/);
});

The validating mock provider uses the spent output's locking bytecode and the BCH VM to check the transaction. The contract's tx.time check constrains the transaction's locktime; it does not read the current chain height. The provider separately checks whether that transaction is final.

With locktime 900, the first eligible block is 901. The 0.14 mock provider accepts the refund once its chain tip reaches 900, matching a node's acceptance for the next block. Setting the correct locktime still fails while the mock tip is 899. These keys and outputs are for local testing only; the mock provider does not broadcast anything.

What to review when moving from 0.13

Read the 0.14 migration notes before rebuilding an existing application. Among the SDK changes, inputs now need their locking bytecode so the builder can check that it matches the unlocker, and the signature-hash enum is named SighashType. Recompile your own sources and compare the resulting artifacts. A change to the bytecode can change the contract address, while already funded outputs still require the original spending rules.

For a production contract, test the exact compiler, artifact, constructor arguments, and VM target that you plan to use. Review destination addresses, fees, change, and the signing interface separately. A passing mock test establishes what the tested spend does; it does not establish that a wallet, service, or deployment handles every failure mode.

Something unclear or out of date? Send a correction.