A behaviour and pipeline DSL for building Bitcoin locking and unlocking scripts.
Contracts define locking_script/2 and optionally unlocking_script/2 callbacks
that build scripts using a chainable pipeline of opcode and data push helpers.
Example
defmodule MyP2PKH do
use BSV.Contract
@impl true
def locking_script(ctx, %{pubkey_hash: pkh}) do
ctx
|> op_dup()
|> op_hash160()
|> push(pkh)
|> op_equalverify()
|> op_checksig()
end
end
script = MyP2PKH.lock(1000, %{pubkey_hash: <<...>>}) |> BSV.Contract.to_script()Using contracts with TxBuilder
Contracts return BSV.Contract.t() structs that carry the module, function,
and parameters needed to build scripts lazily.
Summary
Functions
Attach a transaction context to the contract for signature generation.
Push a value (opcode byte, data binary, or integer) onto the contract script.
Return the size in bytes of the compiled script.
Simulate a contract lock/unlock cycle and verify it against the script interpreter.
Compile the contract and return the script as a binary.
Compile the contract and return the built BSV.Script.
Compile the unlocking contract and return a BSV.Transaction.Input.
Compile the locking contract and return a BSV.Transaction.Output.
Types
@type ctx() :: {BSV.Transaction.t(), non_neg_integer()}
Transaction context: {transaction, input_index}
@type t() :: %BSV.Contract{ ctx: ctx() | nil, mfa: {module(), atom(), list()}, opts: keyword(), script: BSV.Script.t(), subject: non_neg_integer() | map() | nil }
Contract struct
Callbacks
Functions
Attach a transaction context to the contract for signature generation.
@spec script_push(t(), BSV.Script.chunk()) :: t()
Push a value (opcode byte, data binary, or integer) onto the contract script.
@spec script_size(t()) :: non_neg_integer()
Return the size in bytes of the compiled script.
Simulate a contract lock/unlock cycle and verify it against the script interpreter.
Creates a fake locking transaction, then spends it with the unlocking params,
and runs the combined script through BSV.Script.Interpreter.
Returns {:ok, true} on success, {:error, reason} on failure.
Example
{:ok, true} = Contract.simulate(
BSV.Contract.P2PKH,
%{pubkey_hash: pkh},
%{signature: sig, pubkey: pubkey}
)
Compile the contract and return the script as a binary.
@spec to_script(t()) :: BSV.Script.t()
Compile the contract and return the built BSV.Script.
@spec to_txin(t()) :: BSV.Transaction.Input.t()
Compile the unlocking contract and return a BSV.Transaction.Input.
The contract subject must be a map with :source_txid, :source_tx_out_index,
and optionally :source_output and :sequence_number.
@spec to_txout(t()) :: BSV.Transaction.Output.t()
Compile the locking contract and return a BSV.Transaction.Output.