Building a Custom Transaction Broadcast Client
Overview
Getting Started
import { Transaction, BroadcastResponse, BroadcastFailure, Broadcaster } from '@bsv/sdk'import { Transaction } from '@bsv/sdk'
import type { Broadcaster } from '@bsv/sdk/src/transaction/Broadcaster'
/**
* Represents an WOC transaction broadcaster.
*/
export default class WOC implements Broadcaster {
network: 'main' | 'test'
URL: string
/**
* Constructs an instance of the WOC broadcaster.
*
* @param {string} network - which network to use (testnet or mainnet)
*/
constructor(network: 'main' | 'test') {
this.network = network
this.URL = `https://api.whatsonchain.com/v1/bsv/${network}/tx/raw`
}
/**
* Broadcasts a transaction via WOC.
* This method will assume that window.fetch is available
*
* @param {Transaction} tx - The transaction to be broadcasted.
* @returns {Promise<BroadcastResponse | BroadcastFailure>} A promise that resolves to either a success or failure response.
*/
async broadcast(tx: Transaction): Promise<BroadcastResponse | BroadcastFailure> {
const txhex = tx.toHex()
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ txhex })
}
try {
let data: any = {}
// Use fetch in a browser environment
const response = await window.fetch(`${this.URL}`, requestOptions)
data = await response.json()
if (data.txid as boolean || response.ok as boolean || response.status === 200) {
return {
status: 'success',
txid: data?.txid,
message: data?.messages
}
}
} catch (e) {
// TODO: Implement error handling as needed
}
}
}Last updated
Was this helpful?

