Skip to main content

Create an Account

Before we get started with working with Stellar in code, consider going through the following examples using the Stellar Lab. The lab allows you to create accounts, fund accounts on the Stellar test network, build transactions, run any operation, and inspect responses from Horizon via the Endpoint Explorer.

Accounts are a fundamental building block of Stellar: they hold all your balances, allow you to send and receive payments, and let you place offers to buy and sell assets. Since pretty much everything on Stellar is in some way tied to an account, the first thing you generally need to do when you start developing is create one. This beginner-level tutorial walks through the three building blocks you'll need: generating keys, funding an account, and fetching balances.

Create a Keypair

Stellar uses public key cryptography to secure every transaction: each Stellar account has a keypair consisting of a public key and a secret key. The public key is always safe to share — other people need it to identify your account and verify that you authorized a transaction. It's like an email address. The secret key, however, is private information that proves you own — and gives you access to — your account. It's like a password, and you should never share it with anyone.

Before creating an account, you need to generate your own keypair; we'll learn how in the full example, below.

Create an Account

A valid keypair alone does not make an account. To prevent unused entries from bloating the ledger, Stellar requires every account to hold a minimum balance of 1 XLM before it actually exists.

On the test network you can ask Friendbot — a friendly funding service — to create and fund the account for you. In the SDK examples, below, you'll see that we "discover" the Friendbot endpoint via the RPC's getNetwork call, then issue a funding request.

On the public network, things are a little different. You'd acquire lumens from an exchange or have someone create or sponsor an account on your behalf. This is the purpose of the CreateAccount operation. We'll see in the examples, later, that given a funded account, you can then create a child account on the network with a starting balance.

Fetch Balances

Once your accounts exist you can query their state. On Stellar, assets can be held in a handful of different forms:

  • your native balance is how much XLM you're holding, which is associated directly to your account
  • you can also establish trustlines to various assets to hold your balance; these can be acquired both by simple payment operations and smart contract interactions
  • finally, you can hold custom smart contract tokens which are non-standard assets

You'll learn about these in later tutorials.

Full Example

Let's combine these four concepts into a single cohesive example. Keep in mind that you will always see your USDC balance as zero, since we did not actually receive any of it, but it will be useful in the future when you hold more than just the native token.

For each of these, be sure to follow the installation and setup instructions corresponding to each SDK from their documentation.

import {
Keypair,
BASE_FEE,
Networks,
Operation,
Asset,
humanizeEvents,
TransactionBuilder,
} from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";

// See https://developers.stellar.org/docs/data/apis/api-providers
const server = new Server("https://soroban-testnet.stellar.org");

const testnetUsdc = new Asset(
"USDC",
"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
);

async function main() {
//
// Generating keypairs
//
const parent = Keypair.random();
console.log("Secret:", parent.secret());
console.log("Public:", parent.publicKey());

//
// Account creation via friendbot (does not work on mainnet)
//
const friendbotResponse = await server.requestAirdrop(parent.publicKey());
console.log("SUCCESS! You have a new account:\n", friendbotResponse);

const parentAccount = await server.getAccount(parent.publicKey());
const childAccount = Keypair.random();

//
// Account creation via the CreateAccount operation
//
const createAccountTx = new TransactionBuilder(parentAccount, {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(
Operation.createAccount({
destination: childAccount.publicKey(),
startingBalance: "5",
}),
)
.addOperation(Operation.changeTrust({ asset: testnetUsdc }))
.setTimeout(180)
.build();

createAccountTx.sign(parent);

const sendTxResponse = await server.sendTransaction(createAccountTx);
if (sendTxResponse.status !== "PENDING") {
console.log(`There was an error: ${JSON.stringify(sendTxResponse)}`);
throw sendTxResponse;
}

const txResponse = await server.pollTransaction(sendTxResponse.hash);
if (txResponse.status !== "SUCCESS") {
console.log(
`Transaction status: ${txResponse.status}, events: ${humanizeEvents(
txResponse.diagnosticEvents,
)}`,
);
}

console.log("Created the new account", childAccount.publicKey());

//
// Fetching native and USDC balances
//
const accountEntry = await server.getAccountEntry(parent.publicKey());
console.log("Balance for account: " + parent.publicKey());
console.log("XLM:", accountEntry.balance().toString());

const trustlineEntry = await server.getTrustline(
parent.publicKey(),
testnetUsdc,
);
console.log("USDC:", trustlineEntry.balance().toString());
}

main().catch((err) => console.error(err));

Now that you’ve got an account and check its asset balances, you can start sending and receiving payments, or, if you're ready to hunker down, you can skip ahead and build a wallet or issue a Stellar asset.

Guides in this category: