# Send a Single Account Batch Transaction

A [Batch transaction](/docs/references/protocol/transactions/types/batch) allows you to group multiple transactions together and execute them as a single atomic operation.

This tutorial shows you how to create a `Batch` transaction where a single account submits multiple transactions that either all succeed together or all fail together.

## Goals

By the end of this tutorial, you will be able to:

- Create a `Batch` transaction with multiple inner transactions, signed and submitted by a single account.
- Configure the `Batch` transaction to ensure atomicity, so that either all inner transactions succeed or they all fail.


## Prerequisites

To complete this tutorial, you should:

- Have a basic understanding of the XRP Ledger.
- Have an [XRP Ledger client library](/ja/docs/references/client-libraries) installed. This page provides examples for the following:
  - **JavaScript** with the [xrpl.js library](https://github.com/XRPLF/xrpl.js). See [Get Started Using JavaScript](/docs/tutorials/get-started/get-started-javascript) for setup steps.
  - **Python** with the [xrpl-py library](https://github.com/XRPLF/xrpl-py). See [Get Started Using Python](/docs/tutorials/get-started/get-started-python) for setup steps.
  - **Go** with the [xrpl-go library](https://github.com/XRPLF/xrpl-go). See [Get Started Using Go](/docs/tutorials/get-started/get-started-go) for setup steps.


## Source Code

You can find the complete source code for this tutorial's examples in the code samples section of this website's repository.

## Steps

The example in this tutorial demonstrates a scenario where an account sends multiple payments that must be processed atomically in one `Batch` transaction.

### 1. Install dependencies

JavaScript
From the code sample folder, use `npm` to install dependencies:

```bash
npm install
```

Python
From the code sample folder, set up a virtual environment and use `pip` to install dependencies:

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

Go
From the code sample folder, use `go` to install dependencies:

```bash
go mod tidy
```

### 2. Set up client and accounts

To get started, import the client library and instantiate a client to connect to the XRPL. For this tutorial you need a funded account for the `Batch` transaction **sender**, and two other accounts to **receive** the payments.

JavaScript
```js
import xrpl from "xrpl"

// Connect to the network ----------------------
const client = new xrpl.Client("wss://s.altnet.rippletest.net:51233/")
await client.connect()

// Create and fund wallets
console.log("=== Funding new wallets from faucet... ===");
const [{ wallet: sender }, { wallet: wallet1 }, { wallet: wallet2 }] =
  await Promise.all([
    client.fundWallet(),
    client.fundWallet(),
    client.fundWallet(),
  ]);

console.log(`Sender: ${sender.address}, Balance: ${await client.getXrpBalance(sender.address)} XRP`)
console.log(`Wallet1: ${wallet1.address}, Balance: ${await client.getXrpBalance(wallet1.address)} XRP`)
console.log(`Wallet2: ${wallet2.address}, Balance: ${await client.getXrpBalance(wallet2.address)} XRP`)
```

Python
```py
import json
import sys

from xrpl.account import get_balance
from xrpl.clients import JsonRpcClient
from xrpl.models import Batch, Payment, Transaction, Tx
from xrpl.models.transactions.batch import BatchFlag
from xrpl.models.transactions.transaction import TransactionFlag
from xrpl.transaction import submit_and_wait
from xrpl.utils import drops_to_xrp, xrp_to_drops
from xrpl.wallet import generate_faucet_wallet

# Set up client ----------------------
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Create and fund wallets
print("=== Funding new wallets from faucet... ===")
sender = generate_faucet_wallet(client)
wallet1 = generate_faucet_wallet(client)
wallet2 = generate_faucet_wallet(client)

print(f"Sender: {sender.address}, Balance: {drops_to_xrp(str(get_balance(sender.address, client)))} XRP")
print(f"Wallet1: {wallet1.address}, Balance: {drops_to_xrp(str(get_balance(wallet1.address, client)))} XRP")
print(f"Wallet2: {wallet2.address}, Balance: {drops_to_xrp(str(get_balance(wallet2.address, client)))} XRP")
```

Go
```go
package main

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/Peersyst/xrpl-go/pkg/crypto"
	"github.com/Peersyst/xrpl-go/xrpl/faucet"
	"github.com/Peersyst/xrpl-go/xrpl/hash"
	"github.com/Peersyst/xrpl-go/xrpl/queries/transactions"
	"github.com/Peersyst/xrpl-go/xrpl/transaction"
	"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
	"github.com/Peersyst/xrpl-go/xrpl/wallet"
	"github.com/Peersyst/xrpl-go/xrpl/websocket"
	wstypes "github.com/Peersyst/xrpl-go/xrpl/websocket/types"
)

func main() {
	// Connect to the network ----------------------
	client := websocket.NewClient(
		websocket.NewClientConfig().
			WithHost("wss://s.altnet.rippletest.net:51233").
			WithFaucetProvider(faucet.NewTestnetFaucetProvider()),
	)
	defer client.Disconnect()

	if err := client.Connect(); err != nil {
		panic(err)
	}

	// Create and fund wallets
	fmt.Println("=== Funding new wallets from faucet... ===")
	createAndFund := func() wallet.Wallet {
		w, err := wallet.New(crypto.ED25519())
		if err != nil {
			panic(err)
		}
		if err := client.FundWallet(&w); err != nil {
			panic(err)
		}
		return w
	}
	sender := createAndFund()
	wallet1 := createAndFund()
	wallet2 := createAndFund()

	printBalances := func() {
		for _, w := range []struct {
			label  string
			wallet wallet.Wallet
		}{
			{"Sender", sender},
			{"Wallet1", wallet1},
			{"Wallet2", wallet2},
		} {
			balance, err := client.GetXrpBalance(w.wallet.GetAddress())
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s: %s, Balance: %s XRP\n", w.label, w.wallet.GetAddress(), balance)
		}
	}
	printBalances()
```

### 3. Prepare inner transactions

Next, prepare the inner transactions that will be included in the batch.

JavaScript
```js
// Create inner transactions ----------------------
// REQUIRED: Inner transactions MUST have the tfInnerBatchTxn flag (0x40000000).
// This marks them as part of a batch (requires Fee: 0 and empty SigningPubKey).

// Transaction 1
const payment1 = {
  TransactionType: "Payment",
  Account: sender.address,
  Destination: wallet1.address,
  Amount: xrpl.xrpToDrops(2),
  Flags: xrpl.GlobalFlags.tfInnerBatchTxn // THIS IS REQUIRED
}

// Transaction 2
const payment2 = {
  TransactionType: "Payment",
  Account: sender.address,
  Destination: wallet2.address,
  Amount: xrpl.xrpToDrops(5),
  Flags: xrpl.GlobalFlags.tfInnerBatchTxn // THIS IS REQUIRED
}
```

Python
```py
# Create inner transactions ----------------------
# REQUIRED: Inner transactions MUST have the TF_INNER_BATCH_TXN flag (0x40000000).
# This marks them as part of a batch (requires Fee: 0 and empty SigningPubKey).

# Transaction 1
payment1 = Payment(
    account=sender.address,
    destination=wallet1.address,
    amount=xrp_to_drops(2),
    flags=TransactionFlag.TF_INNER_BATCH_TXN,  # THIS IS REQUIRED
)

# Transaction 2
payment2 = Payment(
    account=sender.address,
    destination=wallet2.address,
    amount=xrp_to_drops(5),
    flags=TransactionFlag.TF_INNER_BATCH_TXN,  # THIS IS REQUIRED
)
```

Go
```go
	// Create inner transactions ----------------------
	// REQUIRED: Inner transactions MUST have the TfInnerBatchTxn flag (0x40000000).
	// This marks them as part of a batch (requires Fee: 0 and empty SigningPubKey).

	// Transaction 1
	payment1 := transaction.Payment{
		BaseTx: transaction.BaseTx{
			Account: sender.GetAddress(),
			Flags:   types.TfInnerBatchTxn, // THIS IS REQUIRED
		},
		Destination: wallet1.GetAddress(),
		Amount:      types.XRPCurrencyAmount(2000000), // 2 XRP
	}

	// Transaction 2
	payment2 := transaction.Payment{
		BaseTx: transaction.BaseTx{
			Account: sender.GetAddress(),
			Flags:   types.TfInnerBatchTxn, // THIS IS REQUIRED
		},
		Destination: wallet2.GetAddress(),
		Amount:      types.XRPCurrencyAmount(5000000), // 5 XRP
	}
```

The first transaction sends a payment of 2 XRP from the sender to `wallet1`, and the second transaction sends 5 XRP from the sender to `wallet2`. Both transactions must include the `tfInnerBatchTxn` (0x40000000) flag to indicate that they are inner transactions of a batch.

Inner transactions must have a Fee of **0** and an empty string for the `SigningPubKey`. The outer `Batch` transaction handles the overall fee and signing for all inner transactions.

Note
The `Fee` and `SigningPubKey` fields are omitted as the client library's *autofill* functionality automatically populates these when submitting the `Batch` transaction.

You typically don't need to set these manually, but if you do, ensure `Fee` is set to 0 and `SigningPubKey` is an empty string.

### 4. Prepare Batch transaction

Create the `Batch` transaction and provide the inner transactions. The key fields to note are:

| Field | Value |
|  --- | --- |
| TransactionType | The type of transaction, in this case `Batch`. |
| Account | The wallet address of the account that is sending the `Batch` transaction. |
| Flags | The flags for the `Batch` transaction. For this example the transaction is configured with the `tfAllOrNothing` (0x00010000) flag to ensure that either all inner transactions succeed or they all fail atomically. See [Batch Flags](/ja/docs/references/protocol/transactions/types/batch#batch-flags) for other options. |
| RawTransactions | Contains the list of inner transactions to be applied. Must include a minimum of **2** transactions and a maximum of **8** transactions. These transactions can come from one account or multiple accounts. |


JavaScript
```js
// Prepare Batch transaction ----------------------
console.log("\n=== Creating Batch transaction... ===")
const batchTx = {
  TransactionType: "Batch",
  Account: sender.address,
  Flags: xrpl.BatchFlags.tfAllOrNothing, // tfAllOrNothing: All inner transactions must succeed
  // Must include a minimum of 2 transactions and a maximum of 8 transactions.
  RawTransactions: [
    { RawTransaction: payment1 }, 
    { RawTransaction: payment2 }
  ]
}
console.log(JSON.stringify(batchTx, null, 2))

// Validate the transaction structure before submitting
xrpl.validate(batchTx)
```

Python
```py
# Prepare Batch transaction ----------------------
print("\n=== Creating Batch transaction... ===")
batch_tx = Batch(
    account=sender.address,
    flags=BatchFlag.TF_ALL_OR_NOTHING,  # TF_ALL_OR_NOTHING: All inner transactions must succeed
    # Must include a minimum of 2 transactions and a maximum of 8 transactions.
    raw_transactions=[payment1, payment2],
)
print(json.dumps(batch_tx.to_xrpl(), indent=2))
```

Go
```go
	// Prepare Batch transaction ----------------------
	fmt.Printf("\n=== Creating Batch transaction... ===\n")
	batchTx := transaction.Batch{
		BaseTx: transaction.BaseTx{
			Account: sender.GetAddress(),
		},
		// Must include a minimum of 2 transactions and a maximum of 8 transactions.
		RawTransactions: []types.RawTransaction{
			{RawTransaction: payment1.Flatten()},
			{RawTransaction: payment2.Flatten()},
		},
	}
	// tfAllOrNothing: All inner transactions must succeed
	batchTx.SetAllOrNothingFlag()

	// Flatten() converts the struct to a map and adds the TransactionType field
	flatBatchTx := batchTx.Flatten()
	batchTxJSON, _ := json.MarshalIndent(flatBatchTx, "", "  ")
	fmt.Printf("%s\n", string(batchTxJSON))
```

### 5. Submit Batch transaction

Now the sender can submit the `Batch` transaction:

JavaScript
```js
// Submit and wait for validation ----------------------
console.log("\n=== Submitting Batch transaction... ===")
const submitResponse = await client.submitAndWait(batchTx, {
  wallet: sender,
  // "autofill" will automatically add Fee: "0" and SigningPubKey: "" to inner transactions.
  autofill: true
})
```

Python
```py
# Submit and wait for validation ----------------------
print("\n=== Submitting Batch transaction... ===")
# "autofill" (on by default in submit_and_wait) will automatically add Fee: "0" and SigningPubKey: "" to inner transactions.
submit_response = submit_and_wait(batch_tx, client, sender)
```

Go
```go
	// Submit and wait for validation ----------------------
	fmt.Printf("\n=== Submitting Batch transaction... ===\n")
	// "Autofill" will automatically add Fee: "0" and SigningPubKey: "" to inner transactions.
	submitResponse, err := client.SubmitTxAndWait(flatBatchTx, &wstypes.SubmitOptions{
		Autofill: true,
		Wallet:   &sender,
	})
	if err != nil {
		panic(err)
	}
```

Because `autofill` is enabled, the client library automatically fills in any missing fields, like the `Fee` and `SigningPubKey`, before submitting the batch.

### 6. Check Batch transaction result

To check the result of the `Batch` transaction submission:

JavaScript
```js
// Check Batch transaction result ----------------------
if (submitResponse.result.meta.TransactionResult !== "tesSUCCESS") {
  const resultCode = submitResponse.result.meta.TransactionResult
  console.warn(`\nTransaction failed with result code ${resultCode}`)
  await client.disconnect()
  process.exit(1)
}
console.log("\nBatch transaction submitted successfully!")
console.log("Result:\n", JSON.stringify(submitResponse.result, null, 2))
// View the batch transaction on the XRPL Explorer
console.log(`\nBatch transaction URL:\nhttps://testnet.xrpl.org/transactions/${submitResponse.result.hash}`)
```

Python
```py
# Check Batch transaction result ----------------------
if submit_response.result["meta"]["TransactionResult"] != "tesSUCCESS":
    result_code = submit_response.result["meta"]["TransactionResult"]
    print(f"\nTransaction failed with result code {result_code}")
    sys.exit(1)
print("\nBatch transaction submitted successfully!")
print("Result:\n", json.dumps(submit_response.result, indent=2))
# View the batch transaction on the XRPL Explorer
print(f"\nBatch transaction URL:\nhttps://testnet.xrpl.org/transactions/{submit_response.result['hash']}")
```

Go
```go
	// Check Batch transaction result ----------------------
	if submitResponse.Meta.TransactionResult != "tesSUCCESS" {
		fmt.Printf("\nTransaction failed with result code %s\n", submitResponse.Meta.TransactionResult)
		os.Exit(1)
	}
	fmt.Printf("\nBatch transaction submitted successfully!\n")
	resultJSON, _ := json.MarshalIndent(submitResponse, "", "  ")
	fmt.Printf("Result:\n%s\n", string(resultJSON))
	// View the batch transaction on the XRPL Explorer
	fmt.Printf("\nBatch transaction URL:\nhttps://testnet.xrpl.org/transactions/%s\n", submitResponse.Hash)
```

The code checks for a `tesSUCCESS` result and displays the response details.

Warning
A `tesSUCCESS` result indicates that the `Batch` transaction was processed successfully, but does not guarantee the inner transactions succeeded. For example, see the [following transaction on the XRPL Explorer](https://livenet.xrpl.org/transactions/31A944F359D18C1C9DB3ACFC17BBFF5750E71B3CF2D9158701D8F477B81E63C4).

Because the `Batch` transaction is configured with a `tfAllOrNothing` flag, if any inner transaction fails, **all** inner transactions will fail, and only the `Batch` transaction fee is deducted from the **sender**.

### 7. Verify inner transactions

Since there is no way to check the status of inner transactions in the `Batch` transaction result, you need to calculate the inner transaction hashes and look them up on the ledger:

JavaScript
```js
// Calculate and verify inner transaction hashes ----------------------
console.log("\n=== Verifying inner transactions... ===")
const rawTransactions = submitResponse.result.tx_json.RawTransactions
let hasFailure = false

for (let i = 0; i < rawTransactions.length; i++) {
  const innerTx = rawTransactions[i].RawTransaction
  const hash = xrpl.hashes.hashSignedTx(innerTx)
  console.log(`\nTransaction ${i + 1} hash: ${hash}`)

  try {
    const tx = await client.request({ command: 'tx', transaction: hash })
    const status = tx.result.meta?.TransactionResult
    console.log(` - Status: ${status} (Ledger ${tx.result.ledger_index})`)
    console.log(` - Transaction URL: https://testnet.xrpl.org/transactions/${hash}`)
  } catch (error) {
    hasFailure = true
    console.log(` - Transaction not found: ${error}`)
  }
}
if (hasFailure) {
  console.error("\n--- Error: One or more inner transactions failed. ---")
  await client.disconnect()
  process.exit(1)
}
```

Python
```py
# Calculate and verify inner transaction hashes ----------------------
print("\n=== Verifying inner transactions... ===")
raw_transactions = submit_response.result["tx_json"]["RawTransactions"]
has_failure = False

for i, raw_tx in enumerate(raw_transactions):
    inner_tx = Transaction.from_xrpl(raw_tx["RawTransaction"])
    tx_hash = inner_tx.get_hash()
    print(f"\nTransaction {i + 1} hash: {tx_hash}")

    tx_response = client.request(Tx(transaction=tx_hash))
    if tx_response.is_successful():
        status = tx_response.result["meta"]["TransactionResult"]
        print(f" - Status: {status} (Ledger {tx_response.result['ledger_index']})")
        print(f" - Transaction URL: https://testnet.xrpl.org/transactions/{tx_hash}")
    else:
        has_failure = True
        print(f" - Transaction not found: {tx_response.result['error']}")

if has_failure:
    print("\n--- Error: One or more inner transactions failed. ---")
    sys.exit(1)
```

Go
```go
	// Calculate and verify inner transaction hashes ----------------------
	fmt.Printf("\n=== Verifying inner transactions... ===\n")
	rawTransactions := submitResponse.TxJSON["RawTransactions"].([]any)
	hasFailure := false

	for i, rawTx := range rawTransactions {
		innerTx := rawTx.(map[string]any)["RawTransaction"].(map[string]any)
		txHash, err := hash.SignTx(innerTx)
		if err != nil {
			panic(err)
		}
		fmt.Printf("\nTransaction %d hash: %s\n", i+1, txHash)

		txResponse, err := client.Request(&transactions.TxRequest{Transaction: txHash})
		if err != nil {
			hasFailure = true
			fmt.Printf(" - Transaction not found: %s\n", err)
			continue
		}
		var tx transactions.TxResponse
		if err := txResponse.GetResult(&tx); err != nil {
			panic(err)
		}
		fmt.Printf(" - Status: %s (Ledger %d)\n", tx.Meta.TransactionResult, tx.LedgerIndex)
		fmt.Printf(" - Transaction URL: https://testnet.xrpl.org/transactions/%s\n", txHash)
	}
	if hasFailure {
		fmt.Printf("\n--- Error: One or more inner transactions failed. ---\n")
		os.Exit(1)
	}
```

The code extracts the actual inner transactions from the batch response, calculates the hash of each inner transaction and looks up each transaction on the ledger using its hash.

### 8. Verify balances

You can also verify that the inner transactions executed successfully by checking the account balances to confirm the expected changes.

JavaScript
```js
// Verify balances after transaction
console.log("\n=== Final balances ===")
console.log(`Sender: ${sender.address}, Balance: ${await client.getXrpBalance(sender.address)} XRP`)
console.log(`Wallet1: ${wallet1.address}, Balance: ${await client.getXrpBalance(wallet1.address)} XRP`)
console.log(`Wallet2: ${wallet2.address}, Balance: ${await client.getXrpBalance(wallet2.address)} XRP`)

await client.disconnect()
```

Python
```py
# Verify balances after transaction
print("\n=== Final balances ===")
print(f"Sender: {sender.address}, Balance: {drops_to_xrp(str(get_balance(sender.address, client)))} XRP")
print(f"Wallet1: {wallet1.address}, Balance: {drops_to_xrp(str(get_balance(wallet1.address, client)))} XRP")
print(f"Wallet2: {wallet2.address}, Balance: {drops_to_xrp(str(get_balance(wallet2.address, client)))} XRP")
```

Go
```go
	// Verify balances after transaction
	fmt.Printf("\n=== Final balances ===\n")
	printBalances()
}
```

## See Also

- **Concepts**:
  - [Batch Transactions](/ja/docs/concepts/transactions/batch-transactions)
- **Tutorials**:
  - [Send a Multi-Account Batch Transaction](/ja/docs/tutorials/best-practices/transaction-sending/send-a-multi-account-batch-transaction)
- **References**:
  - [Batch Transaction](/docs/references/protocol/transactions/types/batch)