API
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interfaces
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: ArcConfig
Configuration options for the ARC broadcaster.
export interface ArcConfig {
apiKey?: string;
httpClient?: HttpClient;
deploymentId?: string;
callbackUrl?: string;
callbackToken?: string;
headers?: Record<string, string>;
}
See also: HttpClient
Property apiKey
Authentication token for the ARC API
Property callbackToken
default access token for notification callback endpoint. It will be used as a Authorization header for the http callback
Property callbackUrl
notification callback endpoint for proofs and double spend notification
Property deploymentId
Deployment id used annotating api calls in XDeployment-ID header - this value will be randomly generated if not set
Property headers
additional headers to be attached to all tx submissions.
Property httpClient
The HTTP client used to make requests to the ARC API.
See also: HttpClientLinks: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: BroadcastFailure
Defines the structure of a failed broadcast response.
export interface BroadcastFailure {
status: "error";
code: string;
txid?: string;
description: string;
more?: object;
}
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: BroadcastResponse
Defines the structure of a successful broadcast response.
export interface BroadcastResponse {
status: "success";
txid: string;
message: string;
competingTxs?: string[];
}
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: Broadcaster
Represents the interface for a transaction broadcaster. This interface defines a standard method for broadcasting transactions.
export interface Broadcaster {
broadcast: (transaction: Transaction) => Promise<BroadcastResponse | BroadcastFailure>;
broadcastMany?: (txs: Transaction[]) => Promise<object[]>;
}
See also: BroadcastFailure, BroadcastResponse, Transaction
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: ChainTracker
The Chain Tracker is responsible for verifying the validity of a given Merkle root for a specific block height within the blockchain.
Chain Trackers ensure the integrity of the blockchain by validating new headers against the chain's history. They use accumulated proof-of-work and protocol adherence as metrics to assess the legitimacy of blocks.
Example
const chainTracker = {
isValidRootForHeight: async (root, height) => {
// Implementation to check if the Merkle root is valid for the specified block height.
}
currentHeight: async () => {
// Implementation to get the current block height.
}
};
export default interface ChainTracker {
isValidRootForHeight: (root: string, height: number) => Promise<boolean>;
currentHeight: () => Promise<number>;
}
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: FeeModel
Represents the interface for a transaction fee model. This interface defines a standard method for computing a fee when given a transaction.
See also: Transaction
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: FetchOptions
An interface for configuration of the request to be passed to the fetch method limited to options needed by ts-sdk.
export interface FetchOptions {
method?: string;
headers?: Record<string, string>;
body?: string | null;
}
Property body
An object or null to set request's body.
Property headers
An object literal set request's headers.
Property method
A string to set request's method.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: HttpClient
An interface for HTTP client used to make HTTP requests.
export interface HttpClient {
request: <T = any, D = any>(url: string, options: HttpClientRequestOptions<D>) => Promise<HttpClientResponse<T>>;
}
See also: HttpClientRequestOptions, HttpClientResponse
Property request
Makes a request to the server.
request: <T = any, D = any>(url: string, options: HttpClientRequestOptions<D>) => Promise<HttpClientResponse<T>>
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: HttpClientRequestOptions
An interface for configuration of the request to be passed to the request method.
export interface HttpClientRequestOptions<Data = any> {
method?: string;
headers?: Record<string, string>;
data?: Data;
signal?: AbortSignal;
}
Property data
An object or null to set request's body.
Property headers
An object literal set request's headers.
Property method
A string to set request's method.
Property signal
An optional AbortSignal to cancel the request, including by explicit timeout.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: HttpsNodejs
Node Https module interface limited to options needed by ts-sdk
export interface HttpsNodejs {
request: (url: string, options: HttpClientRequestOptions, callback: (res: any) => void) => NodejsHttpClientRequest;
}
See also: HttpClientRequestOptions, NodejsHttpClientRequest
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: MerklePathLeaf
export interface MerklePathLeaf {
offset: number;
hash?: string;
txid?: boolean;
duplicate?: boolean;
}
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: NodejsHttpClientRequest
Nodejs result of the Node https.request call limited to options needed by ts-sdk
export interface NodejsHttpClientRequest {
write: (chunk: string) => void;
on: (event: string, callback: (data: any) => void) => void;
end: (() => void) & (() => void);
}
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: TransactionInput
Represents an input to a Bitcoin transaction. This interface defines the structure and components required to construct a transaction input in the Bitcoin blockchain.
Example
// Creating a simple transaction input
let txInput = {
sourceTXID: '123abc...',
sourceOutputIndex: 0,
sequence: 0xFFFFFFFF
};
// Using an unlocking script template
txInput.unlockingScriptTemplate = {
sign: async (tx, index) => { ... },
estimateLength: async (tx, index) => { ... }
};
export default interface TransactionInput {
sourceTransaction?: Transaction;
sourceTXID?: string;
sourceOutputIndex: number;
unlockingScript?: UnlockingScript;
unlockingScriptTemplate?: {
sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>;
estimateLength: (tx: Transaction, inputIndex: number) => Promise<number>;
};
sequence?: number;
}
See also: Transaction, UnlockingScript, sign
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: TransactionOutput
Represents an output in a Bitcoin transaction. This interface defines the structure and components necessary to construct a transaction output, which secures owned Bitcoins to be unlocked later.
Example
// Creating a simple transaction output
let txOutput = {
satoshis: 1000,
lockingScript: LockingScript.fromASM('OP_DUP OP_HASH160 ... OP_EQUALVERIFY OP_CHECKSIG'),
change: false
};
export default interface TransactionOutput {
satoshis?: number;
lockingScript: LockingScript;
change?: boolean;
}
See also: LockingScript
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Interface: WhatsOnChainConfig
Configuration options for the WhatsOnChain ChainTracker.
See also: HttpClient
Property apiKey
Authentication token for the WhatsOnChain API
Property httpClient
The HTTP client used to make requests to the API.
See also: HttpClientLinks: API, Interfaces, Classes, Functions, Types, Enums, Variables
Classes
ARC |
Beef |
BeefParty |
BeefTx |
FetchHttpClient |
MerklePath |
NodejsHttpClient |
SatoshisPerKilobyte |
Transaction |
WhatsOnChain |
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: ARC
Represents an ARC transaction broadcaster.
export default class ARC implements Broadcaster {
readonly URL: string;
readonly apiKey: string | undefined;
readonly deploymentId: string;
readonly callbackUrl: string | undefined;
readonly callbackToken: string | undefined;
readonly headers: Record<string, string> | undefined;
constructor(URL: string, config?: ArcConfig);
constructor(URL: string, apiKey?: string);
constructor(URL: string, config?: string | ArcConfig)
async broadcast(tx: Transaction): Promise<BroadcastResponse | BroadcastFailure>
async broadcastMany(txs: Transaction[]): Promise<object[]>
}
See also: ArcConfig, BroadcastFailure, BroadcastResponse, Broadcaster, Transaction
Constructor
Constructs an instance of the ARC broadcaster.
See also: ArcConfigArgument Details
- URL
- The URL endpoint for the ARC API.
- config
- Configuration options for the ARC broadcaster.
Constructor
Constructs an instance of the ARC broadcaster.
Argument Details
- URL
- The URL endpoint for the ARC API.
- apiKey
- The API key used for authorization with the ARC API.
Method broadcast
Broadcasts a transaction via ARC.
See also: BroadcastFailure, BroadcastResponse, TransactionReturns
A promise that resolves to either a success or failure response.
Argument Details
- tx
- The transaction to be broadcasted.
Method broadcastMany
Broadcasts multiple transactions via ARC. Handles mixed responses where some transactions succeed and others fail.
See also: TransactionReturns
A promise that resolves to an array of objects.
Argument Details
- txs
- Array of transactions to be broadcasted.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: Beef
export class Beef {
bumps: MerklePath[] = [];
txs: BeefTx[] = [];
version: number = BEEF_V2;
atomicTxid: string | undefined = undefined;
constructor(version: number = BEEF_V2)
findTxid(txid: string): BeefTx | undefined
makeTxidOnly(txid: string): BeefTx | undefined
findBump(txid: string): MerklePath | undefined
findTransactionForSigning(txid: string): Transaction | undefined
findAtomicTransaction(txid: string): Transaction | undefined
mergeBump(bump: MerklePath): number
mergeRawTx(rawTx: number[], bumpIndex?: number): BeefTx
mergeTransaction(tx: Transaction): BeefTx
removeExistingTxid(txid: string): void
mergeTxidOnly(txid: string): BeefTx
mergeBeefTx(btx: BeefTx): BeefTx
mergeBeef(beef: number[] | Beef): void
isValid(allowTxidOnly?: boolean): boolean
async verify(chainTracker: ChainTracker, allowTxidOnly?: boolean): Promise<boolean>
verifyValid(allowTxidOnly?: boolean): {
valid: boolean;
roots: Record<number, string>;
}
toWriter(writer: Writer): void
toBinary(): number[]
toBinaryAtomic(txid: string): number[]
toHex(): string
static fromReader(br: Reader): Beef
static fromBinary(bin: number[]): Beef
static fromString(s: string, enc: "hex" | "utf8" | "base64" = "hex"): Beef
sortTxs(): {
missingInputs: string[];
notValid: string[];
valid: string[];
withMissingInputs: string[];
txidOnly: string[];
}
clone(): Beef
trimKnownTxids(knownTxids: string[]): void
getValidTxids(): string[]
toLogString(): string
addComputedLeaves(): void
}
See also: BEEF_V2, BeefTx, ChainTracker, MerklePath, Reader, Transaction, Writer, toHex, verify
Method addComputedLeaves
In some circumstances it may be helpful for the BUMP MerklePaths to include leaves that can be computed from row zero.
Method clone
See also: BeefReturns
a shallow copy of this beef
Method findAtomicTransaction
Builds the proof tree rooted at a specific Transaction
.
To succeed, the Beef must contain all the required transaction and merkle path data.
See also: TransactionReturns
Transaction with input SourceTransaction
and MerklePath
populated from this Beef.
Argument Details
- txid
- The id of the target transaction.
Method findBump
See also: MerklePathReturns
MerklePath
with level zero hash equal to txid or undefined.
Method findTransactionForSigning
Finds a Transaction in this Beef
and adds any missing input SourceTransactions from this Beef
.
The result is suitable for signing.
See also: TransactionReturns
Transaction with all available input SourceTransaction
s from this Beef.
Argument Details
- txid
- The id of the target transaction.
Method findTxid
See also: BeefTxReturns
BeefTx
in txs
with txid
.
Argument Details
- txid
- of
beefTx
to find
Method fromBinary
Constructs an instance of the Beef class based on the provided binary array
See also: BeefReturns
An instance of the Beef class constructed from the binary data
Argument Details
- bin
- The binary array from which to construct BEEF
Method fromString
Constructs an instance of the Beef class based on the provided string
See also: BeefReturns
An instance of the Beef class constructed from the string
Argument Details
- s
- The string value from which to construct BEEF
- enc
- The encoding of the string value from which BEEF should be constructed
Method getValidTxids
Returns
array of transaction txids that either have a proof or whose inputs chain back to a proven transaction.
Method isValid
Sorts txs
and checks structural validity of beef.
Does NOT verify merkle roots.
Validity requirements: 1. No 'known' txids, unless allowTxidOnly
is true. 2. All transactions have bumps or their inputs chain back to bumps (or are known). 3. Order of transactions satisfies dependencies before dependents. 4. No transactions with duplicate txids.
Argument Details
- allowTxidOnly
- optional. If true, transaction txid only is assumed valid
Method makeTxidOnly
Replaces BeefTx
for this txid with txidOnly.
Replacement is done so that a clone()
can be updated by this method without affecting the original.
Returns
undefined if txid is unknown.
Method mergeBump
Merge a MerklePath that is assumed to be fully valid.
See also: MerklePathReturns
index of merged bump
Method mergeRawTx
Merge a serialized transaction.
Checks that a transaction with the same txid hasn't already been merged.
Replaces existing transaction with same txid.
See also: BeefTxReturns
txid of rawTx
Argument Details
- bumpIndex
- Optional. If a number, must be valid index into bumps array.
Method mergeTransaction
Merge a Transaction
and any referenced merklePath
and sourceTransaction
, recursifely.
Replaces existing transaction with same txid.
Attempts to match an existing bump to the new transaction.
See also: BeefTx, TransactionReturns
txid of tx
Method removeExistingTxid
Removes an existing transaction from the BEEF, given its TXID
Argument Details
- txid
- TXID of the transaction to remove
Method sortTxs
Sort the txs
by input txid dependency order: - Oldest Tx Anchored by Path or txid only - Newer Txs depending on Older parents - Newest Tx
with proof (MerklePath) last, longest chain of dependencies first
sortTxs(): {
missingInputs: string[];
notValid: string[];
valid: string[];
withMissingInputs: string[];
txidOnly: string[];
}
Returns
{ missingInputs, notValid, valid, withMissingInputs }
Method toBinary
Returns a binary array representing the serialized BEEF
Returns
A binary array representing the BEEF
Method toBinaryAtomic
Serialize this Beef as AtomicBEEF.
txid
must exist
after sorting, if txid is not last txid, creates a clone and removes newer txs
Returns
serialized contents of this Beef with AtomicBEEF prefix.
Method toHex
Returns a hex string representing the serialized BEEF
Returns
A hex string representing the BEEF
Method toLogString
Returns
Summary of Beef
contents as multi-line string.
Method toWriter
Serializes this data to writer
Method trimKnownTxids
Ensure that all the txids in knownTxids
are txidOnly
Method verify
Sorts txs
and confirms validity of transaction data contained in beef by validating structure of this beef and confirming computed merkle roots using chainTracker
.
Validity requirements: 1. No 'known' txids, unless allowTxidOnly
is true. 2. All transactions have bumps or their inputs chain back to bumps (or are known). 3. Order of transactions satisfies dependencies before dependents. 4. No transactions with duplicate txids.
Argument Details
- chainTracker
- Used to verify computed merkle path roots for all bump txids.
- allowTxidOnly
- optional. If true, transaction txid is assumed valid
Method verifyValid
Sorts txs
and confirms validity of transaction data contained in beef by validating structure of this beef.
Returns block heights and merkle root values to be confirmed by a chaintracker.
Validity requirements: 1. No 'known' txids, unless allowTxidOnly
is true. 2. All transactions have bumps or their inputs chain back to bumps (or are known). 3. Order of transactions satisfies dependencies before dependents. 4. No transactions with duplicate txids.
Returns
valid
is true iff this Beef is structuraly valid. roots
is a record where keys are block heights and values are the corresponding merkle roots to be validated.
Argument Details
- allowTxidOnly
- optional. If true, transaction txid is assumed valid
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: BeefParty
Extends Beef
that is used to exchange transaction validity data with more than one external party.
Use addKnownTxidsForParty
to keep track of who knows what to reduce re-transmission of potentially large transactions.
Use getTrimmedBeefForParty
to obtain a Beef
trimmed of transaction validity data known to a specific party.
Typical usage scenario:
- Query a wallet storage provider for spendable outputs.
- The provider replies with a Beef validating the returned outputs.
- Construct a new transaction using some of the queried outputs as inputs, including Beef validating all the inputs.
- Receive new valid raw transaction after processing and Beef validating change outputs added to original inputs.
- Return to step 1, continuing to build on old and new spendable outputs.
By default, each Beef is required to be complete and valid: All transactions appear as full serialized bitcoin transactions and each transaction either has a merkle path proof (it has been mined) or all of its input transactions are included.
The size and redundancy of these Beefs becomes a problem when chained transaction creation out-paces the block mining rate.
export class BeefParty extends Beef {
knownTo: Record<string, Record<string, boolean>> = {};
constructor(parties?: string[])
isParty(party: string): boolean
addParty(party: string): void
getKnownTxidsForParty(party: string): string[]
getTrimmedBeefForParty(party: string): Beef
addKnownTxidsForParty(party: string, knownTxids: string[]): void
mergeBeefFromParty(party: string, beef: number[] | Beef): void
}
See also: Beef
Constructor
Argument Details
- parties
- Optional array of initial unique party identifiers.
Property knownTo
keys are party identifiers. values are records of txids with truthy value for which the party already has validity proof.
Method addKnownTxidsForParty
Make note of additional txids "known" to party
.
Argument Details
- party
- unique identifier, added if new.
Method addParty
Adds a new unique party identifier to this BeefParty
.
Method getKnownTxidsForParty
Returns
Array of txids "known" to party
.
Method getTrimmedBeefForParty
See also: BeefReturns
trimmed beef of unknown transactions and proofs for party
Method isParty
Returns
true
if party
has already been added to this BeefParty
.
Method mergeBeefFromParty
Merge a beef
received from a specific party
.
Updates this BeefParty
to track all the txids corresponding to transactions for which party
has raw transaction and validity proof data.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: BeefTx
A single bitcoin transaction associated with a Beef
validity proof set.
Simple case is transaction data included directly, either as raw bytes or fully parsed data, or both.
Supports 'known' transactions which are represented by just their txid. It is assumed that intended consumer of this beef already has validity proof for such a transaction, which they can merge if necessary to create a valid beef.
export default class BeefTx {
_bumpIndex?: number;
_tx?: Transaction;
_rawTx?: number[];
_txid?: string;
inputTxids: string[] = [];
isValid?: boolean = undefined;
get bumpIndex(): number | undefined
set bumpIndex(v: number | undefined)
get hasProof(): boolean
get isTxidOnly(): boolean
get txid(): string
get tx(): Transaction | undefined
get rawTx(): number[] | undefined
constructor(tx: Transaction | number[] | string, bumpIndex?: number)
static fromTx(tx: Transaction, bumpIndex?: number): BeefTx
static fromRawTx(rawTx: number[], bumpIndex?: number): BeefTx
static fromTxid(txid: string, bumpIndex?: number): BeefTx
toWriter(writer: Writer, version: number): void
static fromReader(br: Reader, version: number): BeefTx
}
See also: Reader, Transaction, Writer
Constructor
See also: TransactionArgument Details
- tx
- If string, must be a valid txid. If
number[]
must be a valid serialized transaction. - bumpIndex
- If transaction already has a proof in the beef to which it will be added.
Property isValid
true if hasProof
or all inputs chain to hasProof
.
Typically set by sorting transactions by proven dependency chains.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: FetchHttpClient
Adapter for Node Https module to be used as HttpClient
export class FetchHttpClient implements HttpClient {
constructor(private readonly fetch: Fetch)
async request<D>(url: string, options: HttpClientRequestOptions): Promise<HttpClientResponse<D>>
}
See also: Fetch, HttpClient, HttpClientRequestOptions, HttpClientResponse
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: MerklePath
Represents a Merkle Path, which is used to provide a compact proof of inclusion for a transaction in a block. This class encapsulates all the details required for creating and verifying Merkle Proofs.
Example
// Creating and verifying a Merkle Path
const merklePath = MerklePath.fromHex('...');
const isValid = merklePath.verify(txid, chainTracker);
export default class MerklePath {
blockHeight: number;
path: Array<Array<{
offset: number;
hash?: string;
txid?: boolean;
duplicate?: boolean;
}>>;
static fromHex(hex: string): MerklePath
static fromReader(reader: Reader, legalOffsetsOnly: boolean = true): MerklePath
static fromBinary(bump: number[]): MerklePath
static fromCoinbaseTxidAndHeight(txid: string, height: number): MerklePath
constructor(blockHeight: number, path: Array<Array<{
offset: number;
hash?: string;
txid?: boolean;
duplicate?: boolean;
}>>, legalOffsetsOnly: boolean = true)
toBinary(): number[]
toHex(): string
computeRoot(txid?: string): string
findOrComputeLeaf(height: number, offset: number): MerklePathLeaf | undefined
async verify(txid: string, chainTracker: ChainTracker): Promise<boolean>
combine(other: MerklePath): void
trim(): void
}
See also: ChainTracker, MerklePathLeaf, Reader, toHex, verify
Method combine
Combines this MerklePath with another to create a compound proof.
See also: MerklePathArgument Details
- other
- Another MerklePath to combine with this path.
Throws
- If the paths have different block heights or roots.
Method computeRoot
Computes the Merkle root from the provided transaction ID.
Returns
- The computed Merkle root as a hexadecimal string.
Argument Details
- txid
- The transaction ID to compute the Merkle root for. If not provided, the root will be computed from an unspecified branch, and not all branches will be validated!
Throws
- If the transaction ID is not part of the Merkle Path.
Method findOrComputeLeaf
Find leaf with offset
at height
or compute from level below, recursively.
Does not add computed leaves to path.
See also: MerklePathLeafMethod fromBinary
Creates a MerklePath instance from a binary array.
See also: MerklePathReturns
- A new MerklePath instance.
Argument Details
- bump
- The binary array representation of the Merkle Path.
Method fromCoinbaseTxidAndHeight
See also: MerklePathReturns
- A new MerklePath instance which assumes the tx is in a block with no other transactions.
Argument Details
- txid
- The coinbase txid.
- height
- The height of the block.
Method fromHex
Creates a MerklePath instance from a hexadecimal string.
See also: MerklePathReturns
- A new MerklePath instance.
Argument Details
- hex
- The hexadecimal string representation of the Merkle Path.
Method toBinary
Converts the MerklePath to a binary array format.
Returns
- The binary array representation of the Merkle Path.
Method toHex
Converts the MerklePath to a hexadecimal string format.
Returns
- The hexadecimal string representation of the Merkle Path.
Method trim
Remove all internal nodes that are not required by level zero txid nodes. Assumes that at least all required nodes are present. Leaves all levels sorted by increasing offset.
Method verify
Verifies if the given transaction ID is part of the Merkle tree at the specified block height.
See also: ChainTrackerReturns
- True if the transaction ID is valid within the Merkle Path at the specified block height.
Argument Details
- txid
- The transaction ID to verify.
- chainTracker
- The ChainTracker instance used to verify the Merkle root.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: NodejsHttpClient
Adapter for Node Https module to be used as HttpClient
export class NodejsHttpClient implements HttpClient {
constructor(private readonly https: HttpsNodejs)
async request(url: string, requestOptions: HttpClientRequestOptions): Promise<HttpClientResponse>
}
See also: HttpClient, HttpClientRequestOptions, HttpClientResponse, HttpsNodejs
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: SatoshisPerKilobyte
Represents the "satoshis per kilobyte" transaction fee model.
export default class SatoshisPerKilobyte implements FeeModel {
value: number;
constructor(value: number)
async computeFee(tx: Transaction): Promise<number>
}
See also: FeeModel, Transaction
Constructor
Constructs an instance of the sat/kb fee model.
Argument Details
- value
- The number of satoshis per kilobyte to charge as a fee.
Method computeFee
Computes the fee for a given transaction.
See also: TransactionReturns
The fee in satoshis for the transaction, as a BigNumber.
Argument Details
- tx
- The transaction for which a fee is to be computed.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: Transaction
Represents a complete Bitcoin transaction. This class encapsulates all the details required for creating, signing, and processing a Bitcoin transaction, including inputs, outputs, and various transaction-related methods.
Example
// Creating a new transaction
let tx = new Transaction();
tx.addInput(...);
tx.addOutput(...);
await tx.fee();
await tx.sign();
await tx.broadcast();
export default class Transaction {
version: number;
inputs: TransactionInput[];
outputs: TransactionOutput[];
lockTime: number;
metadata: Record<string, any>;
merklePath?: MerklePath;
static fromBEEF(beef: number[], txid?: string): Transaction
static fromAtomicBEEF(beef: number[]): Transaction
static fromEF(ef: number[]): Transaction
static parseScriptOffsets(bin: number[]): {
inputs: Array<{
vin: number;
offset: number;
length: number;
}>;
outputs: Array<{
vout: number;
offset: number;
length: number;
}>;
}
static fromReader(br: Reader): Transaction
static fromBinary(bin: number[]): Transaction
static fromHex(hex: string): Transaction
static fromHexEF(hex: string): Transaction
static fromHexBEEF(hex: string, txid?: string): Transaction
constructor(version: number = 1, inputs: TransactionInput[] = [], outputs: TransactionOutput[] = [], lockTime: number = 0, metadata: Record<string, any> = new Map(), merklePath?: MerklePath)
addInput(input: TransactionInput): void
addOutput(output: TransactionOutput): void
addP2PKHOutput(address: number[] | string, satoshis?: number): void
updateMetadata(metadata: Record<string, any>): void
async fee(modelOrFee: FeeModel | number = new SatoshisPerKilobyte(1), changeDistribution: "equal" | "random" = "equal"): Promise<void>
getFee(): number
async sign(): Promise<void>
async broadcast(broadcaster: Broadcaster = defaultBroadcaster()): Promise<BroadcastResponse | BroadcastFailure>
toBinary(): number[]
toEF(): number[]
toHexEF(): string
toHex(): string
toHexBEEF(): string
toHexAtomicBEEF(): string
hash(enc?: "hex"): number[] | string
id(): number[];
id(enc: "hex"): string;
id(enc?: "hex"): number[] | string
async verify(chainTracker: ChainTracker | "scripts only" = defaultChainTracker(), feeModel?: FeeModel, memoryLimit?: number): Promise<boolean>
toBEEF(allowPartial?: boolean): number[]
toAtomicBEEF(allowPartial?: boolean): number[]
}
See also: BroadcastFailure, BroadcastResponse, Broadcaster, ChainTracker, FeeModel, MerklePath, Reader, SatoshisPerKilobyte, TransactionInput, TransactionOutput, defaultBroadcaster, defaultChainTracker, sign, toHex, verify
Method addInput
Adds a new input to the transaction.
See also: TransactionInputArgument Details
- input
- The TransactionInput object to add to the transaction.
Throws
- If the input does not have a sourceTXID or sourceTransaction defined.
Method addOutput
Adds a new output to the transaction.
See also: TransactionOutputArgument Details
- output
- The TransactionOutput object to add to the transaction.
Method addP2PKHOutput
Adds a new P2PKH output to the transaction.
Argument Details
- address
- The P2PKH address of the output.
- satoshis
- The number of satoshis to send to the address - if not provided, the output is considered a change output.
Method broadcast
Broadcasts a transaction.
async broadcast(broadcaster: Broadcaster = defaultBroadcaster()): Promise<BroadcastResponse | BroadcastFailure>
Returns
A BroadcastResponse or BroadcastFailure from the Broadcaster
Argument Details
- broadcaster
- The Broadcaster instance wwhere the transaction will be sent
Method fee
Computes fees prior to signing. If no fee model is provided, uses a SatoshisPerKilobyte fee model that pays 1 sat/kb. If fee is a number, the transaction uses that value as fee.
async fee(modelOrFee: FeeModel | number = new SatoshisPerKilobyte(1), changeDistribution: "equal" | "random" = "equal"): Promise<void>
Argument Details
- modelOrFee
- The initialized fee model to use or fixed fee for the transaction
- changeDistribution
- Specifies how the change should be distributed amongst the change outputs
Method fromAtomicBEEF
Creates a new transaction from an Atomic BEEF (BRC-95) structure. Extracts the subject transaction and supporting merkle path and source transactions contained in the BEEF data
See also: TransactionReturns
The subject transaction, linked to its associated inputs populated with merkle paths.
Argument Details
- beef
- A binary representation of an Atomic BEEF structure.
Method fromBEEF
Creates a new transaction, linked to its inputs and their associated merkle paths, from a BEEF V1, V2 or Atomic. Optionally, you can provide a specific TXID to retrieve a particular transaction from the BEEF data. If the TXID is provided but not found in the BEEF data, an error will be thrown. If no TXID is provided, the last transaction in the BEEF data is returned, or the atomic txid.
See also: TransactionReturns
An anchored transaction, linked to its associated inputs populated with merkle paths.
Argument Details
- beef
- A binary representation of transactions in BEEF format.
- txid
- Optional TXID of the transaction to retrieve from the BEEF data.
Method fromBinary
Creates a Transaction instance from a binary array.
See also: TransactionReturns
- A new Transaction instance.
Argument Details
- bin
- The binary array representation of the transaction.
Method fromEF
Creates a new transaction, linked to its inputs and their associated merkle paths, from a EF (BRC-30) structure.
See also: TransactionReturns
An extended transaction, linked to its associated inputs by locking script and satoshis amounts only.
Argument Details
- ef
- A binary representation of a transaction in EF format.
Method fromHex
Creates a Transaction instance from a hexadecimal string.
See also: TransactionReturns
- A new Transaction instance.
Argument Details
- hex
- The hexadecimal string representation of the transaction.
Method fromHexBEEF
Creates a Transaction instance from a hexadecimal string encoded BEEF. Optionally, you can provide a specific TXID to retrieve a particular transaction from the BEEF data. If the TXID is provided but not found in the BEEF data, an error will be thrown. If no TXID is provided, the last transaction in the BEEF data is returned.
See also: TransactionReturns
- A new Transaction instance.
Argument Details
- hex
- The hexadecimal string representation of the transaction BEEF.
- txid
- Optional TXID of the transaction to retrieve from the BEEF data.
Method fromHexEF
Creates a Transaction instance from a hexadecimal string encoded EF.
See also: TransactionReturns
- A new Transaction instance.
Argument Details
- hex
- The hexadecimal string representation of the transaction EF.
Method getFee
Utility method that returns the current fee based on inputs and outputs
Returns
The current transaction fee
Method hash
Calculates the transaction's hash.
Returns
- The hash of the transaction in the specified format.
Argument Details
- enc
- The encoding to use for the hash. If 'hex', returns a hexadecimal string; otherwise returns a binary array.
Method id
Calculates the transaction's ID in binary array.
Returns
- The ID of the transaction in the binary array format.
Method id
Calculates the transaction's ID in hexadecimal format.
Returns
- The ID of the transaction in the hex format.
Argument Details
- enc
- The encoding to use for the ID. If 'hex', returns a hexadecimal string.
Method id
Calculates the transaction's ID.
Returns
- The ID of the transaction in the specified format.
Argument Details
- enc
- The encoding to use for the ID. If 'hex', returns a hexadecimal string; otherwise returns a binary array.
Method parseScriptOffsets
Since the validation of blockchain data is atomically transaction data validation, any application seeking to validate data in output scripts must store the entire transaction as well. Since the transaction data includes the output script data, saving a second copy of potentially large scripts can bloat application storage requirements.
This function efficiently parses binary transaction data to determine the offsets and lengths of each script. This supports the efficient retreival of script data from transaction data.
static parseScriptOffsets(bin: number[]): {
inputs: Array<{
vin: number;
offset: number;
length: number;
}>;
outputs: Array<{
vout: number;
offset: number;
length: number;
}>;
}
Returns
inputs: { vin: number, offset: number, length: number }[] outputs: { vout: number, offset: number, length: number }[] }
Argument Details
- bin
- binary transaction data
Method sign
Signs a transaction, hydrating all its unlocking scripts based on the provided script templates where they are available.
Method toAtomicBEEF
Serializes this transaction and its inputs into the Atomic BEEF (BRC-95) format. The Atomic BEEF format starts with a 4-byte prefix 0x01010101
, followed by the TXID of the subject transaction, and then the BEEF data containing only the subject transaction and its dependencies. This format ensures that the BEEF structure is atomic and contains no unrelated transactions.
Returns
- The serialized Atomic BEEF structure.
Argument Details
- allowPartial
- If true, error will not be thrown if there are any missing sourceTransactions.
Throws
Error if there are any missing sourceTransactions unless allowPartial
is true.
Method toBEEF
Serializes this transaction, together with its inputs and the respective merkle proofs, into the BEEF (BRC-62) format. This enables efficient verification of its compliance with the rules of SPV.
Returns
The serialized BEEF structure
Argument Details
- allowPartial
- If true, error will not be thrown if there are any missing sourceTransactions.
Throws
Error if there are any missing sourceTransactions unless allowPartial
is true.
Method toBinary
Converts the transaction to a binary array format.
Returns
- The binary array representation of the transaction.
Method toEF
Converts the transaction to a BRC-30 EF format.
Returns
- The BRC-30 EF representation of the transaction.
Method toHex
Converts the transaction to a hexadecimal string format.
Returns
- The hexadecimal string representation of the transaction.
Method toHexAtomicBEEF
Converts the transaction to a hexadecimal string Atomic BEEF.
Returns
- The hexadecimal string representation of the transaction Atomic BEEF.
Method toHexBEEF
Converts the transaction to a hexadecimal string BEEF.
Returns
- The hexadecimal string representation of the transaction BEEF.
Method toHexEF
Converts the transaction to a hexadecimal string EF.
Returns
- The hexadecimal string representation of the transaction EF.
Method updateMetadata
Updates the transaction's metadata.
Argument Details
- metadata
- The metadata object to merge into the existing metadata.
Method verify
Verifies the legitimacy of the Bitcoin transaction according to the rules of SPV by ensuring all the input transactions link back to valid block headers, the chain of spends for all inputs are valid, and the sum of inputs is not less than the sum of outputs.
async verify(chainTracker: ChainTracker | "scripts only" = defaultChainTracker(), feeModel?: FeeModel, memoryLimit?: number): Promise<boolean>
Returns
Whether the transaction is valid according to the rules of SPV.
Argument Details
- chainTracker
- An instance of ChainTracker, a Bitcoin block header tracker. If the value is set to 'scripts only', headers will not be verified. If not provided then the default chain tracker will be used.
- feeModel
- An instance of FeeModel, a fee model to use for fee calculation. If not provided then the default fee model will be used.
- memoryLimit
- The maximum memory in bytes usage allowed for script evaluation. If not provided then the default memory limit will be used.
Example
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Class: WhatsOnChain
Represents a chain tracker based on What's On Chain .
export default class WhatsOnChain implements ChainTracker {
readonly network: string;
readonly apiKey: string;
protected readonly URL: string;
protected readonly httpClient: HttpClient;
constructor(network: "main" | "test" | "stn" = "main", config: WhatsOnChainConfig = {})
async isValidRootForHeight(root: string, height: number): Promise<boolean>
async currentHeight(): Promise<number>
protected getHttpHeaders(): Record<string, string>
}
See also: ChainTracker, HttpClient, WhatsOnChainConfig
Constructor
Constructs an instance of the WhatsOnChain ChainTracker.
See also: WhatsOnChainConfigArgument Details
- network
- The BSV network to use when calling the WhatsOnChain API.
- config
- Configuration options for the WhatsOnChain ChainTracker.
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Functions
defaultBroadcaster |
defaultChainTracker |
defaultHttpClient |
isBroadcastFailure |
isBroadcastResponse |
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Function: defaultBroadcaster
See also: ArcConfig, Broadcaster
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Function: defaultChainTracker
See also: ChainTracker
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Function: defaultHttpClient
Returns a default HttpClient implementation based on the environment that it is run on. This method will attempt to use window.fetch
if available (in browser environments). If running in a Node environment, it falls back to using the Node https
module
See also: HttpClient
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Function: isBroadcastFailure
Convenience type guard for response from Broadcaster.broadcast
See also: BroadcastFailure, BroadcastResponse
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Function: isBroadcastResponse
Convenience type guard for response from Broadcaster.broadcast
export function isBroadcastResponse(r: BroadcastResponse | BroadcastFailure): r is BroadcastResponse
See also: BroadcastFailure, BroadcastResponse
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Types
Fetch |
HttpClientResponse |
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Type: Fetch
fetch function interface limited to options needed by ts-sdk
Makes a request to the server.
See also: FetchOptions
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Type: HttpClientResponse
An interface for the response returned by the request method.
export type HttpClientResponse<T = any> = {
data: T;
status: number;
statusText: string;
ok: true;
} | {
data: any;
status: number;
statusText: string;
ok: false;
}
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Enums
Enum: TX_DATA_FORMAT
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Variables
ATOMIC_BEEF |
BEEF_V1 |
BEEF_V2 |
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Variable: ATOMIC_BEEF
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Variable: BEEF_V1
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables
Variable: BEEF_V2
Links: API, Interfaces, Classes, Functions, Types, Enums, Variables