0%

How Solana really works: programs, accounts, owners and your first token

Programs are chefs, accounts are ingredient boxes, and a token is just a few boxes working together

Most tutorials say "deploy a token in 5 minutes" and never explain why Solana looks so different from Ethereum. Here I do both. First the mental model (programs, accounts, owners, PDAs), then a real token with the CLI and with TypeScript, then an upgrade to Token-2022 with on chain metadata.

You need Node.js 18 or newer, basic JavaScript, and a rough idea of keypairs: a private key signs, and validators check the signature with the public key.

Programs: the chef who remembers nothing

Ethereum added a big idea to blockchains: decentralized state and logic. The chain can run programs and remember what they did. Ethereum calls them smart contracts and Solana calls them programs.

If you know web2, a program is like a server. It has rules, and it changes some state. The difference is where it runs:

HTTP server Program
Runs on One company's machines Thousands of independent validators
Who can change the rules The company Nobody, unless the code allows it
Where the state lives Your database On chain

And the last row is where Solana does something unusual. On Ethereum, a counter's count lives inside the contract. On Solana, programs are stateless. The state lives in separate accounts that you hand to the program on every call. Think of the program as a chef and the accounts as ingredient boxes: the chef never keeps anything, you bring the boxes.

Here is a trimmed Anchor counter that shows it. Notice that count is not inside the program. It is inside a Counter account that gets passed in:

use anchor_lang::prelude::*;
 
#[program]
pub mod counter {
    use super::*;
 
    pub fn increment(ctx: Context<Increment>) -> Result<()> {
        ctx.accounts.counter.count += 1;
        Ok(())
    }
}
 
#[derive(Accounts)]
pub struct Increment<'info> {
    #[account(mut)]
    pub counter: Account<'info, Counter>, // the state, handed in by the caller
}
 
#[account]
pub struct Counter {
    pub count: u64,
}

Accounts: everything lives in a box

An account is Solana's one data structure, and it does three jobs: it stores data, it holds lamports (1 SOL is 1,000,000,000 lamports, used for fees and the rent deposit), and it can hold executable code. A program is simply an account whose executable flag is true.

Field Meaning
lamports Balance in lamports
data Bytes of state, empty for a plain wallet
owner The program that controls this account
executable True if the account holds program code

You can look at any account through the RPC method getAccountInfo. With jsonParsed, the node decodes the data for you. Here is the USDT mint, which has both data and lamports:

curl -X POST https://api.mainnet-beta.solana.com \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getAccountInfo",
    "params": ["Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", {"encoding": "jsonParsed"}]
  }'

A plain wallet comes back with lamports and no data, and the SPL Token Program at TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA comes back with executable set to true. Try both on Solscan.

Setup: CLI, clusters and RPC servers

Install the CLI and check it works:

sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)"
solana -V
solana-keygen new
solana config set -u devnet
solana airdrop 1

solana-keygen new creates your wallet at ~/.config/solana/id.json. The last two lines point the CLI at devnet and give you free test SOL. If the airdrop fails, use the web faucet.

Cluster Purpose Real money?
Mainnet Beta Production Yes
Devnet App developers No, SOL is free
Testnet Validators and core protocol testing No

You never talk to validators directly. You talk to an RPC server: a node that exposes JSON-RPC and WebSocket APIs so apps can submit transactions and read accounts, balances and blocks. It takes no part in consensus, it is built for reads, and public endpoints are rate limited. Wallets, dApps and bots all depend on one, and production apps use a paid provider like Helius or QuickNode.

One shared helper keeps the scripts below short. It connects to devnet and loads your CLI wallet:

// config.ts
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { Connection, Keypair, clusterApiUrl } from "@solana/web3.js";
 
export const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
 
// The wallet created by `solana-keygen new`
const file = path.join(os.homedir(), ".config", "solana", "id.json");
export const payer = Keypair.fromSecretKey(
  new Uint8Array(JSON.parse(fs.readFileSync(file, "utf-8"))),
);

Never paste a raw secret key into source code or commit one to Git. Loading it from the keypair file keeps it out of your repo.

Web2 tables become Solana accounts

In web2 you would keep tokens in two tables. In Solana the same data is spread over many small accounts, all managed by one program:

Web2 Solana
tokens row A mint account (supply, decimals, authorities)
balances row A token account per wallet and mint pair
The server code editing rows The Token Program

So making a token is just create, create, update: create the mint, create a token account for a user, then mint into it. A fair question: where did we give it a name or ticker? Nowhere. A basic mint stores only supply, decimals and authorities. The name, symbol and image are metadata, which we add at the end.

Two kinds of owner

This is the most confusing idea for newcomers, so here is the cute version. Every account has an owner field, and it is always a program, never a person. That program is the only one allowed to change the account's data or take lamports from it. The runtime checks this before any instruction runs, so a buggy program cannot touch accounts that belong to another one.

A token account has a second owner hiding in its data. That one is the wallet that may spend the tokens, and the runtime knows nothing about it. It is an idea defined by the Token Program.

The runtime owner and the data owner of a token account

Here is a small detective script that prints both owners for any token account:

// owners.ts
import { PublicKey } from "@solana/web3.js";
import { connection } from "./config";
 
const [, , address] = process.argv;
if (!address) throw new Error("usage: npx tsx owners.ts TOKEN_ACCOUNT_ADDRESS");
 
const { value } = await connection.getParsedAccountInfo(new PublicKey(address));
if (!value || !("parsed" in value.data)) throw new Error("Not a token account");
 
const info = value.data.parsed.info;
console.log("runtime owner (may write the bytes) :", value.owner.toBase58());
console.log("data owner    (may spend the tokens):", info.owner);
console.log("mint                                :", info.mint);

Run it with npx tsx owners.ts <TOKEN_ACCOUNT>. The first line is the Token Program, and the second is your wallet.

Transactions and instructions

An instruction is one command for one program: the program id, the accounts it will use, and a byte array of input. A transaction bundles one or more instructions with signatures and a recent blockhash, and it is atomic, so if one instruction fails, everything rolls back. Every account is flagged as writable or not, which lets validators run transactions that do not clash in parallel.

Here is a transaction with one instruction that creates a 1,000 byte account. After sending it, the script reads the account back:

// create-account.ts
import { Keypair, SystemProgram, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
import { connection, payer } from "./config";
 
const dataAccount = Keypair.generate();
const space = 1000; // bytes of data
 
const tx = new Transaction().add(
  SystemProgram.createAccount({
    fromPubkey: payer.publicKey,
    newAccountPubkey: dataAccount.publicKey,
    lamports: await connection.getMinimumBalanceForRentExemption(space),
    space,
    programId: SystemProgram.programId, // the runtime owner of the new account
  }),
);
 
// Two signers: the payer funds it, the new keypair proves it controls its address
const signature = await sendAndConfirmTransaction(connection, tx, [payer, dataAccount]);
 
const info = await connection.getAccountInfo(dataAccount.publicKey);
console.log("account :", dataAccount.publicKey.toBase58());
console.log("tx      :", signature);
console.log("bytes   :", info?.data.length); // 1000
console.log("owner   :", info?.owner.toBase58()); // the System Program

A few notes. getMinimumBalanceForRentExemption returns the lamports an account of that size must hold, and the amount grows with the bytes. programId sets the runtime owner. We used the System Program to keep the demo small, but in a real app it would be your own program, so that program can write to the data. And both keys sign: one pays, and the new keypair proves it controls its address.

Make a token with the CLI

The Token Program is maintained by Solana's core engineers. Making a token takes three steps, and the CLI does each in one command:

spl-token create-token
spl-token create-account <MINT>
spl-token mint <MINT> 100
  1. Create a mint, like a bank that is allowed to print coins.
  2. Create a token account for your wallet. You cannot receive a token until you have a place to put it.
  3. Mint 100 tokens into that account.

Check the supply with spl-token supply <MINT>, then open the mint in an explorer on devnet. To see the balance in Phantom, switch it to devnet in its developer settings.

The same token in TypeScript

Everything the CLI does is a client sending requests to an RPC server. Set up a project:

mkdir token-demo && cd token-demo
npm init -y
npm install @solana/web3.js@1 @solana/spl-token @solana/spl-token-metadata
npm install -D typescript tsx @types/node

Save the config.ts file from above, then run this with npx tsx create-token.ts:

// create-token.ts
import {
  createMint,
  getMint,
  getOrCreateAssociatedTokenAccount,
  mintTo,
} from "@solana/spl-token";
import { connection, payer } from "./config";
 
const DECIMALS = 6;
 
// 1. The mint: who may create new supply, and how many decimals
const mint = await createMint(connection, payer, payer.publicKey, null, DECIMALS);
 
// 2. Your balance account for this mint (an associated token account)
const ata = await getOrCreateAssociatedTokenAccount(connection, payer, mint, payer.publicKey);
 
// 3. Mint 100 whole tokens. Libraries want base units, so 100 * 10^6.
await mintTo(connection, payer, mint, ata.address, payer, 100n * 10n ** BigInt(DECIMALS));
 
const info = await getMint(connection, mint);
console.log("mint    :", mint.toBase58());
console.log("account :", ata.address.toBase58());
console.log("supply  :", info.supply, "base units"); // 100000000n

The decimals trap

With 6 decimals, one whole token is 1,000,000 base units. If the script minted 100 instead of 100n * 10n ** 6n, you would get 100 base units, which is only 0.0001 tokens. The CLI's spl-token mint <MINT> 100 takes display units, so it makes 100 whole tokens. Libraries use base units and the CLI uses display units. It is the same integer rule as lamports.

PDAs: a locker with no key

The token account you just made is a PDA (Program Derived Address). A normal address is the public key of a keypair, and whoever has the private key can sign for it. A PDA is worked out from a program id plus some seeds, and it is deliberately placed off the curve, so no private key exists for it. Only the program it came from can sign for it. Picture a locker with no key: only the building manager (the program) can open it.

For a token account, the seeds are your wallet, the Token Program id and the mint. That makes the address predictable (anyone can work out where your balance lives) and unique (one per wallet and mint). Prove it, including the "no private key" part:

// derive-ata.ts
import { PublicKey } from "@solana/web3.js";
import {
  ASSOCIATED_TOKEN_PROGRAM_ID,
  TOKEN_PROGRAM_ID,
  getAssociatedTokenAddressSync,
} from "@solana/spl-token";
 
const [, , walletArg, mintArg] = process.argv;
if (!walletArg || !mintArg) throw new Error("usage: npx tsx derive-ata.ts WALLET MINT");
 
const wallet = new PublicKey(walletArg);
const mint = new PublicKey(mintArg);
 
const [byHand, bump] = PublicKey.findProgramAddressSync(
  [wallet.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],
  ASSOCIATED_TOKEN_PROGRAM_ID,
);
const byLibrary = getAssociatedTokenAddressSync(mint, wallet);
 
console.log("derived by hand :", byHand.toBase58(), "bump", bump);
console.log("derived by lib  :", byLibrary.toBase58());
console.log("same address    :", byHand.equals(byLibrary)); // true
console.log("on the curve    :", PublicKey.isOnCurve(byHand.toBytes())); // false, so no private key exists

The last line prints false. That is the proof that nobody holds a key for this address.

Token-2022: tokens with extras

Token-2022, also called Token Extensions, is a superset of the original program. It does everything the old one does, plus opt-in features like on chain metadata and transfer fees. The two have different ids:

Program Id
Token Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
Token-2022 TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb

Wallets show a token's name, symbol and image by reading metadata. With Token-2022 it lives right inside the mint. The metadata URI should point to a public JSON file:

{
  "name": "Chai Token",
  "symbol": "CHAI",
  "description": "A demo token from my Solana notes",
  "image": "https://example.com/chai.png"
}

This script creates the mint with the metadata extension in one transaction, then reads the name and symbol back from the chain:

// token2022.ts
import { Keypair, SystemProgram, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
import {
  ExtensionType,
  LENGTH_SIZE,
  TOKEN_2022_PROGRAM_ID,
  TYPE_SIZE,
  createInitializeMetadataPointerInstruction,
  createInitializeMintInstruction,
  getMintLen,
  getTokenMetadata,
} from "@solana/spl-token";
import { createInitializeInstruction, pack, type TokenMetadata } from "@solana/spl-token-metadata";
import { connection, payer } from "./config";
 
const mintKeypair = Keypair.generate();
const mint = mintKeypair.publicKey;
 
const metadata: TokenMetadata = {
  mint,
  name: "Chai Token",
  symbol: "CHAI",
  uri: "https://example.com/chai.json", // host your own JSON here
  additionalMetadata: [],
};
 
// The mint needs room for the pointer extension, plus room for the metadata itself
const mintSpace = getMintLen([ExtensionType.MetadataPointer]);
const metadataSpace = TYPE_SIZE + LENGTH_SIZE + pack(metadata).length;
const lamports = await connection.getMinimumBalanceForRentExemption(mintSpace + metadataSpace);
 
const tx = new Transaction().add(
  SystemProgram.createAccount({
    fromPubkey: payer.publicKey,
    newAccountPubkey: mint,
    space: mintSpace,
    lamports,
    programId: TOKEN_2022_PROGRAM_ID,
  }),
  // "The metadata lives in this same account"
  createInitializeMetadataPointerInstruction(mint, payer.publicKey, mint, TOKEN_2022_PROGRAM_ID),
  createInitializeMintInstruction(mint, 6, payer.publicKey, null, TOKEN_2022_PROGRAM_ID),
  createInitializeInstruction({
    programId: TOKEN_2022_PROGRAM_ID,
    metadata: mint,
    updateAuthority: payer.publicKey,
    mint,
    mintAuthority: payer.publicKey,
    name: metadata.name,
    symbol: metadata.symbol,
    uri: metadata.uri,
  }),
);
await sendAndConfirmTransaction(connection, tx, [payer, mintKeypair]);
 
// Read it back straight from the mint account
const onChain = await getTokenMetadata(connection, mint);
console.log("mint   :", mint.toBase58());
console.log("name   :", onChain?.name, "|", onChain?.symbol);

The mint is created with room for the pointer extension, and the rent covers the metadata too. After that, create a token account and mint as before, and the token appears in Phantom on devnet with its name and symbol instead of as "unknown token".

Putting it together

Creating a token in four steps

Idea In one line
Program Stateless code in an account with executable true
Account lamports, data, owner, executable
Runtime owner The program allowed to write the data and debit lamports
Data owner A field inside token account data: the wallet that spends
Transaction Atomic bundle of instructions with signatures
RPC server Your gateway to validators, not part of consensus
Mint and token account The token's definition and one balance per wallet
PDA An address with no private key, derived from seeds
Token-2022 The newer program with opt-in extensions

Try it yourself

  1. Run owners.ts on a token account of yours, and find the runtime owner and the data owner.
  2. Mint 1 base unit instead of 1 whole token, and compare how each looks in Phantom.
  3. Run derive-ata.ts for a friend's wallet and your mint, then send them tokens at that address.
  4. Host your own chai.json and point the Token-2022 script at it.

References


Last updated: October 4, 2026

Enjoyed this? Let's talk

I write about backend, engineering and web3 as I learn them. Always happy to compare notes.

Keep reading