Sending Raw Transaction (Hex)
The sendRawTransaction
method allows you to broadcast a raw Bitcoin transaction to the OP_NET network. You can send fully signed transactions in hex format or partially signed transactions in PSBT format.
Method
sendRawTransaction(tx: string, psbt: boolean): Promise<BroadcastedTransaction>;
-
Parameters:
tx: string
: The raw transaction in hexadecimal format.psbt: boolean
:true
: Indicates the transaction is in Partially Signed Bitcoin Transaction (PSBT) format.false
: Indicates the transaction is a fully signed raw transaction in hex format.
-
Returns:
Promise<BroadcastedTransaction>
: An object containing details about the broadcast operation.
Object Definitions
BroadcastedTransaction
ObjectField | Type | Description |
---|---|---|
success | boolean | Indicates whether the transaction was successfully broadcast. |
result | string | (Optional) Transaction ID if the broadcast was successful. |
error | string | (Optional) Error message if the broadcast failed. |
peers | number | (Optional) Number of peers that accepted the transaction. |
identifier | bigint | string | Unique identifier for the transaction, which could be the transaction ID or another reference. |
Example Usage
Sending a Fully Signed Raw Transaction
const rawTransactionHex = "fce09cbe03..."; // Replace with your raw transaction hex
try {
const result = await provider.sendRawTransaction(rawTransactionHex, false);
if (result.success) {
console.log("Transaction Broadcasted Successfully:");
console.log("Transaction ID:", result.result);
console.log("Peers Accepted:", result.peers);
} else {
console.error("Broadcast Failed:", result.error);
}
} catch (error) {
console.error("Error Sending Transaction:", error.message);
}
Sending a PSBT
const psbtHex = "70736274ff0100..."; // Replace with your PSBT in hex format
try {
const result = await provider.sendRawTransaction(psbtHex, true);
if (result.success) {
console.log("PSBT Broadcasted Successfully:");
console.log("Transaction ID:", result.result);
console.log("Peers Accepted:", result.peers);
} else {
console.error("Broadcast Failed:", result.error);
}
} catch (error) {
console.error("Error Sending PSBT:", error.message);
}
Best Practices
- Ensure the
tx
parameter is correctly formatted:- Use raw hex for fully signed transactions.
- Use PSBT format when
psbt: true
.
- Always validate the transaction locally before broadcasting to avoid unnecessary errors.
- Handle network errors and failures gracefully.
What’s Next?
After broadcasting a transaction, you can: