Skip to content

Get Started Using Go Library

This tutorial walks you through the basics of building an XRP Ledger-connected application using xrpl-go, a pure Go library built to interact with the XRP Ledger.

This tutorial is intended for beginners and should take no longer than 30 minutes to complete.

Goals

In this tutorial, you'll learn:

  • The basic building blocks of XRP Ledger-based applications.
  • How to connect to the XRP Ledger using xrpl-go.
  • How to get an account on the Testnet using xrpl-go.
  • How to use the xrpl-go library to look up information about an account on the XRP Ledger.
  • How to put these steps together to create a Go app.

Prerequisites

To complete this tutorial, you should meet the following guidelines:

  • Have a basic understanding of Go.
  • Have installed Go version 1.25.13 or later.

Source Code

Click Download on the top right of the code preview panel to download the source code.

Steps

Follow the steps to create a simple application with xrpl-go.

1. Install Dependencies

The xrpl-go library is available on pkg.go.dev.

Start a new project by creating an empty folder, then move into that folder and install the xrpl-go library via Go modules:

# Initialize your module (if you haven't already)
go mod init your-module-name

# Fetch the latest version of xrpl-go and all of its packages
go get github.com/Peersyst/xrpl-go/...@latest

In your project folder, create a get-acct-info folder with a main.go file inside it. As you work through the following steps, add the code shown in the code panel to this file.

Alternatively, if you're using the downloaded source code, you can install the dependencies listed in the go.mod file:

go mod tidy

2. Connect to the XRP Ledger

Connect to the XRP Ledger Testnet

To make queries and submit transactions, you need to connect to the XRP Ledger. To do this with xrpl-go, create a client from the websocket package and call its Connect() method. The sample code also attaches a Testnet faucet provider to the client so that you can fund a new account in the next step. This tutorial uses the WebSocket client because it can also subscribe to events.

The sample code shows you how to connect to the Testnet, which is one of the available parallel networks.

(Optional) Connect Using JSON-RPC

xrpl-go also provides a JSON-RPC client in the rpc package. The get-acct-info-rpc/main.go file in the code panel shows the same application using the JSON-RPC client. You create the client from a config that takes the server URL and the faucet provider. Because JSON-RPC sends one HTTP request per call, there is no connection to open or close.

Connect to the XRP Ledger Mainnet

The sample code in the previous section shows you how to connect to the Testnet, which is a parallel network for testing where the money has no real value. When you're ready to integrate with the production XRP Ledger, you'll need to connect to the Mainnet. You can do that in two ways:

  • By installing the core server (xrpld) and running a node yourself. The core server connects to the Mainnet by default, but you can change the configuration to use Testnet or Devnet. There are good reasons to run your own core server. If you run your own server, you can connect to it like so:

    import "github.com/Peersyst/xrpl-go/xrpl/websocket"
    
    const MY_SERVER = "ws://localhost:6006/"
    
    func main() {
      client := websocket.NewClient(websocket.NewClientConfig().WithHost(MY_SERVER))
    
      // ... custom code goes here
    }

    See the example core server config file for more information about default values.

  • By using one of the available public servers:

    import "github.com/Peersyst/xrpl-go/xrpl/websocket"
    
    const PUBLIC_SERVER = "wss://xrplcluster.com/"
    
    func main() {
      client := websocket.NewClient(websocket.NewClientConfig().WithHost(PUBLIC_SERVER))
    
      // ... custom code goes here
    }

3. Get Account

Create and Fund a Wallet

In xrpl-go, account creation and key management live in the wallet package, and on Testnet you can use the built-in faucet provider on your client to fund a brand-new account immediately. On Testnet, you can fund a new ED25519 account as shown in the example.

The wallet.New constructor returns a Go Wallet value with the following fields:

type Wallet struct {
    PublicKey      string          // the hex-encoded public key
    PrivateKey     string          // the hex-encoded private key
    ClassicAddress types.Address   // the XRPL “r…” address
    Seed           string          // the base58 seed
}

(Optional) Use Your Own Wallet Seed

If you already have a seed encoded in base58, you can make a Wallet instance from it with wallet.FromSeed, as shown in the commented-out line of the example.

4. Query the XRP Ledger

You can query the XRP Ledger to get information about a specific account, a specific transaction, the state of a current or a historical ledger, and the XRP Ledger's decentralized exchange. You need to make these queries, among other reasons, to look up account info to follow best practices for reliable transaction submission.

Use the client's GetAccountInfo() method to look up information about the account you got in the previous step. The websocket and rpc packages provide typed getter methods like this for common queries. To call any other method of the XRP Ledger's WebSocket API, use the client's Request() method.

5. Listen for Events

You can set up handlers for various types of events in xrpl-go, such as whenever the XRP Ledger's consensus process produces a new ledger version. To do that, first attach an event handler using the client's OnLedgerClosed() method, then call the Subscribe() method with the subscribe method request for the type of events you want.

6. Disconnect

Call the Disconnect() method so the program can end. The example code waits 10 seconds before disconnecting to allow time for the ledger event listener to receive and display events.

7. Run the Application

Finally, in your terminal, run the application from the folder that contains the go.mod file like so:

go run ./get-acct-info

You should see output similar to the following:

Connected to Testnet

Creating a new wallet and funding it with Testnet XRP...
Wallet: rLpGGFQhU1JJB2YnHgQ5bcpph9CxNsREKb
Account Testnet Explorer URL:
  https://testnet.xrpl.org/accounts/rLpGGFQhU1JJB2YnHgQ5bcpph9CxNsREKb

Getting account info...
{
  "account_data": {
    "index": "E02B88187332A044320B0CE553B2962FF593E00C42A3C2D5D59FBD80A551217B",
    "Flags": 0,
    "LedgerEntryType": "AccountRoot",
    "Account": "rLpGGFQhU1JJB2YnHgQ5bcpph9CxNsREKb",
    "Balance": "100000000",
    "OwnerCount": 0,
    "PreviousTxnID": "538931DECCE783C08991B7BB242A84ED14397FF1DAD40BD9366F97F34FD8144C",
    "PreviousTxnLgrSeq": 22090474,
    "Sequence": 22090474
  },
  "ledger_index": 22090474,
  "validated": true
}

Listening for ledger close events...
Ledger #22090475 validated with 27 transactions!
Ledger #22090476 validated with 28 transactions!

Disconnected

To run the JSON-RPC version of the application instead, use go run ./get-acct-info-rpc. It prints the same wallet and account info, then exits without listening for events.

See Also

package main

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/Peersyst/xrpl-go/pkg/crypto"
	"github.com/Peersyst/xrpl-go/xrpl/faucet"
	"github.com/Peersyst/xrpl-go/xrpl/queries/account"
	"github.com/Peersyst/xrpl-go/xrpl/queries/common"
	subscribe "github.com/Peersyst/xrpl-go/xrpl/queries/subscription"
	streamtypes "github.com/Peersyst/xrpl-go/xrpl/queries/subscription/types"
	"github.com/Peersyst/xrpl-go/xrpl/wallet"
	"github.com/Peersyst/xrpl-go/xrpl/websocket"
)


func main() {
	// Define the network client with a faucet provider
	client := websocket.NewClient(
		websocket.NewClientConfig().
			WithHost("wss://s.altnet.rippletest.net:51233").
			WithFaucetProvider(faucet.NewTestnetFaucetProvider()),
	)

	// Connect to the network
	if err := client.Connect(); err != nil {
		panic(err)
	}
	fmt.Println("Connected to Testnet")

	// Create a wallet and fund it with the Testnet faucet:
	fmt.Println("\nCreating a new wallet and funding it with Testnet XRP...")
	testWallet, err := wallet.New(crypto.ED25519())
	if err != nil {
		panic(err)
	}
	if err := client.FundWallet(&testWallet); err != nil {
		panic(err)
	}
	fmt.Println("Wallet:", testWallet.ClassicAddress)
	fmt.Println("Account Testnet Explorer URL:")
	fmt.Printf("  https://testnet.xrpl.org/accounts/%s\n", testWallet.ClassicAddress)

	// To provide your own seed, replace the testWallet value with the below
	// testWallet, err := wallet.FromSeed("your-seed-key", "")

	// Get info from the ledger about the address we just funded
	fmt.Println("\nGetting account info...")
	accountInfo, err := client.GetAccountInfo(&account.InfoRequest{
		Account:     testWallet.GetAddress(),
		LedgerIndex: common.Validated,
	})
	if err != nil {
		panic(err)
	}
	accountInfoJSON, err := json.MarshalIndent(accountInfo, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(accountInfoJSON))

	// Listen to ledger close events
	fmt.Println("\nListening for ledger close events...")
	client.OnLedgerClosed(func(ledger *streamtypes.LedgerStream) {
		fmt.Printf("Ledger #%d validated with %d transactions!\n",
			ledger.LedgerIndex, ledger.TxnCount)
	})
	if _, err := client.Subscribe(&subscribe.Request{
		Streams: []string{"ledger"},
	}); err != nil {
		panic(err)
	}

	// Disconnect when done so the program can end.
	// Wait 10 seconds to give the ledger event listener time to receive
	// and display some ledger events.
	time.Sleep(10 * time.Second)
	if err := client.Disconnect(); err != nil {
		panic(err)
	}
	fmt.Println("\nDisconnected")
}