Quickstart

Learn how to transfer STX tokens using Stacks.js.

In this quickstart guide, you will learn how to build a transaction to transfer STX tokens using Stacks.js.

Check out the reference page for @stacks/transactions to learn more about building different types of transactions.


Prerequisites

To follow this quickstart guide, you'll need:

  1. A running instance of the devnet network. You can spin up a devnet instance using clarinet devnet start.

To install clarinet, click here.


Install packages

Add the @stacks/transactions and @stacks/network packages to your project using your preferred package manager.

npm install @stacks/transactions @stacks/network

Build the transaction for a STX transfer

To set up a STX token transfer transaction, use the makeSTXTokenTransfer function. This function requires a senderKey, recipient address, amount to be sent (denominated in uSTX), a network instance, and an anchorMode.

The senderKey is the private key of the sender's wallet.

stx-transfer.ts
import { AnchorMode, makeSTXTokenTransfer, broadcastTransaction } from "@stacks/transactions";
import { StacksDevnet } from "@stacks/network";

const transaction = await makeSTXTokenTransfer({
  recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5",
  amount: 42000000,
  senderKey:
    "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601",
  network: new StacksDevnet(),
  anchorMode: AnchorMode.Any,
});

There are a few optional fields for a STX transfer transaction, including memo, nonce, and fee:

const transaction = await makeSTXTokenTransfer({
  // ...
  memo: "test memo",
  nonce: 0n,
  fee: 200n,
});

You can use memo to add a message as part of the transaction. If you don't want the builder to fetch the nonce and fee from a Stacks node, you can manually set these fields.

Broadcast the transaction

Once you've constructed a valid transaction, you can broadcast it to the network using the broadcastTransaction function.

stx-transfer.ts
import { AnchorMode, makeSTXTokenTransfer, broadcastTransaction } from "@stacks/transactions";
import { StacksDevnet } from "@stacks/network";

const transaction = await makeSTXTokenTransfer({
  recipient: "SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159",
  amount: 12345n,
  senderKey:
    "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601",
  network: new StacksDevnet(),
  anchorMode: AnchorMode.Any,
});

const broadcastResponse = await broadcastTransaction(transaction);
const txId = broadcastResponse.txid;

Upon success, this will return a StacksTransaction object that contains information about the transaction, including the txid.

Next steps