Broadcast transactions
Prompt users to sign transactions and broadcast them to the Stacks blockchain.
The process of broadcasting transactions is fundamental for interacting with blockchains, whether you're transferring tokens, deploying contracts, or executing contract functions.
In this guide, you will learn how to:
- 1Install the necessary packages
- 2Connect to a user's wallet
- 3Sign and broadcast transactions
- 4Handle transaction results
Setup and installation
Install the required packages to start building and broadcasting transactions:
$npm install @stacks/connect @stacks/transactions
Connect to a user's wallet
Before signing transactions, users need to connect their wallet to your application. Use the connect
function to initiate a wallet connection:
import { connect, isConnected } from '@stacks/connect';async function connectWallet() {if (!isConnected()) {const response = await connect();console.log('Connected with addresses:', response);}}
For more details on wallet connection, see the authentication guide.
Sign and broadcast transactions
There are three types of transactions you can create: STX transfers, contract deployments, and contract calls.
To transfer STX tokens, use the request
method with stx_transferStx
:
import { request } from '@stacks/connect';async function transferStx() {const response = await request('stx_transferStx', {recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV',amount: '100', // in micro-STX (1 STX = 1,000,000 micro-STX)memo: 'Reimbursement', // optional});console.log('Transaction ID:', response.txId);}
Handle transaction results
When a transaction is signed and broadcast, the request
method returns a response object containing information about the transaction:
interface TransactionResponse {txId: string; // The transaction IDtxRaw: string; // The raw transaction hex}
You can use the transaction ID to create a link to view the transaction in the explorer:
async function handleTransaction() {const response = await request('stx_transferStx', {recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV',amount: '100',});const explorerUrl = `https://explorer.stacks.co/txid/${response.txId}`;console.log('View transaction in explorer:', explorerUrl);}