0%

solana programs, owners and token accounts

the system program, the token program and the little factory that connects them

most people learn solana by copying a "create token" snippet and moving on. it works, but you never learn why a token needs two different accounts, why your wallet does not own your own usdc balance, or which program is actually moving the lamports. this post fixes that.

we will meet the three programs that matter most (system, token and associated token account), see who owns what, and then run real scripts on devnet to watch it happen.

what is a program?

a program is a smart contract: executable code on the chain that receives instructions and changes state. the key design choice is that programs are stateless. a program never keeps data inside itself. it reads and writes separate accounts that are passed in with every instruction. on ethereum a contract owns its storage, while here the code sits in one account and the data sits in many others.

programs are mostly written in rust, compiled to bytecode that the runtime executes. most developers use the anchor framework, which hides the boilerplate behind macros. there are three kinds:

kind examples notes
native system, stake, vote built into the validator software
spl token, associated token account, token-2022 the solana program library, standard programs anyone can use
user deployed your app, a dex, a lending market deployed by anyone

the spl library has more than tokens. it also holds governance, token lending and a naming service (the thing behind names like alice.sol).

owners: the idea everything else depends on

every account has an owner field, and the owner is always a program, never a person. that program is the only one allowed to change the account's data or take lamports out of it. anyone can read any account, but only the owner can write. the runtime checks this before every instruction, which is why a buggy program cannot corrupt another program's accounts.

there is a second, separate use of the word "owner", and it causes most of the confusion:

layer field meaning enforced by
runtime account.owner the program allowed to write this account the solana runtime
application owner inside a token account's data the wallet that controls the tokens the token program's own logic

here is the cute part: even programs have owners. a program account is owned by a loader (like the bpf loader), the program whose job is to run it. you will see that in a script later.

setup

install the cli, make a wallet, and get free devnet sol:

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

if the airdrop is rate limited, use the web faucet. then set up a small typescript project. the scripts use the v1 line of @solana/web3.js, so pin it, because a newer major version has a different api:

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

two tiny helper files keep every script short. the first connects to devnet and loads the wallet the cli already made, so no secret key is ever pasted into code:

// 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"))),
);

the second turns long program ids into friendly names, so the output of the later scripts reads like english:

// names.ts
export const NAMES: Record<string, string> = {
  "11111111111111111111111111111111": "System Program",
  TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA: "Token Program",
  TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb: "Token-2022 Program",
  ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL: "Associated Token Account Program",
  BPFLoaderUpgradeab1e11111111111111111111111: "BPF Loader (upgradeable)",
  NativeLoader1111111111111111111111111111111: "Native Loader",
  MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr: "Memo Program",
};
 
export const nameOf = (id: string) => NAMES[id] ?? id;

never commit a secret key to git or paste one into a chat or screenshot. whoever holds it controls the wallet.

the system program: four jobs

the system program lives at 11111111111111111111111111111111 (thirty two ones). it is the most basic native program, and it owns every ordinary wallet. it has four jobs:

job instruction who must sign
create an account createAccount the funder and the new account
move sol transfer the sender
change the owner assign the account being reassigned
add data space allocate the account being resized

instead of four separate scripts, here is one tour that does all four to the same account and prints the account after every step:

// system-tour.ts
import {
  Keypair,
  PublicKey,
  SystemProgram,
  Transaction,
  sendAndConfirmTransaction,
  type TransactionInstruction,
} from "@solana/web3.js";
import { connection, payer } from "./config";
import { nameOf } from "./names";
 
const box = Keypair.generate();
const SPACE = 100;
const MEMO = new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr");
 
async function send(ix: TransactionInstruction, signers: Keypair[]) {
  await sendAndConfirmTransaction(connection, new Transaction().add(ix), signers);
}
 
async function show(step: string) {
  const info = await connection.getAccountInfo(box.publicKey);
  console.log(
    step.padEnd(9),
    "| lamports", String(info?.lamports).padEnd(8),
    "| bytes", String(info?.data.length).padEnd(4),
    "| owner", nameOf(info!.owner.toBase58()),
  );
}
 
// 1. CREATE: a brand new account, funded to stay rent exempt at 100 bytes
const rent = await connection.getMinimumBalanceForRentExemption(SPACE);
await send(
  SystemProgram.createAccount({
    fromPubkey: payer.publicKey,
    newAccountPubkey: box.publicKey,
    lamports: rent,
    space: 0,
    programId: SystemProgram.programId,
  }),
  [payer, box],
);
await show("create");
 
// 2. TRANSFER: top it up with 0.001 SOL
await send(
  SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: box.publicKey, lamports: 1_000_000 }),
  [payer],
);
await show("transfer");
 
// 3. ALLOCATE: give it 100 bytes (it must still be owned by the System Program)
await send(SystemProgram.allocate({ accountPubkey: box.publicKey, space: SPACE }), [payer, box]);
await show("allocate");
 
// 4. ASSIGN: hand it to another program. This is one way: devnet only, please.
await send(SystemProgram.assign({ accountPubkey: box.publicKey, programId: MEMO }), [payer, box]);
await show("assign");
 
// Proof that the System Program lost control: this transfer must fail
try {
  await send(
    SystemProgram.transfer({ fromPubkey: box.publicKey, toPubkey: payer.publicKey, lamports: 1_000 }),
    [payer, box],
  );
  console.log("unexpected: the transfer worked");
} catch {
  console.log("transfer out failed, as expected: the System Program no longer owns this account");
}

run it with npx tsx system-tour.ts. you should see the owner change from the system program to the memo program at the last step, and the final transfer fail. that failure is the point of the demo: after assign, the system program really has lost control. a few things to know:

  • allocating does not add lamports. the account must already hold enough to be rent exempt at its new size, which is why step 1 funds it for 100 bytes.
  • assign is one way. the memo program has no instruction to send lamports back, so the small amount in that account is stuck. that is fine on devnet, but never try it with real money.
  • rent numbers: 0 bytes needs 890,880 lamports (about 0.00089 sol), 100 bytes needs 1,586,880, and a 165 byte token account needs 2,039,280.

the token program

the token program is one of the spl programs. its source is at solana-program/token. it lets users create a new token (a mint), mint new supply, transfer tokens, and let an authority freeze token accounts.

here is the picture to hold in your head. the system program owns plain wallets. the token program owns the accounts that hold data about tokens: the mints, and every balance.

which program owns which account

every balance is its own account

look at any wallet app. it shows sol, usdc and a few other tokens. sol is the native token, so it sits in the lamports field of your wallet account. every other token is different: for each token you hold, there is a separate address on chain storing your balance of it.

so who should own one of those balance accounts? the token program. it has to, because every transfer, mint or burn changes the number stored there, and only the owner program may write to it. your wallet is recorded inside the account's data as the application level owner, which is how the token program knows you are the one allowed to spend.

an owner map for real accounts

this script asks mainnet who owns a few well known addresses, and prints the owner by name. you can add your own addresses on the command line:

// owner-map.ts
import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js";
import { nameOf } from "./names";
 
const mainnet = new Connection(clusterApiUrl("mainnet-beta"), "confirmed");
 
const SAMPLES: [label: string, address: string][] = [
  ["USDC mint", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"],
  ["Token Program", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"],
  ["Associated Token Account Program", "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"],
  ["System Program", "11111111111111111111111111111111"],
];
 
// Add your own addresses on the command line: npx tsx owner-map.ts ADDRESS ADDRESS
const extra = process.argv.slice(2).map((a): [string, string] => [a.slice(0, 8) + "...", a]);
 
for (const [label, address] of [...SAMPLES, ...extra]) {
  const info = await mainnet.getAccountInfo(new PublicKey(address));
  if (!info) {
    console.log(label.padEnd(34), "| nothing on chain here");
    continue;
  }
  console.log(
    label.padEnd(34),
    "| owner:", nameOf(info.owner.toBase58()).padEnd(26),
    "| executable:", String(info.executable).padEnd(5),
    "| bytes:", info.data.length,
  );
}

the usdc mint is owned by the token program. the token program itself is owned by a loader, and the system program by the native loader. programs have owners too.

the associated token account program

so who creates all those balance accounts? the associated token account (ata) program. it has a create function that makes a deterministic account for one wallet and one mint. deterministic means anyone can work out the address without asking. it is a pda (program derived address) computed from three seeds:

seeds   = [ wallet address, token program id, mint address ]
program = associated token account program

a pda is deliberately generated off the ed25519 curve, so it has no private key, and only the program it came from can sign for it. the result is that every wallet and mint pair has exactly one canonical balance address. that is why a friend can send you usdc just by knowing your wallet address.

creating an ata is a little chain of calls, and three programs touch the same account:

how an associated token account is created in four steps

do not take my word for it. this script creates an ata for a brand new wallet, then reads the transaction back from the chain and lists every program the ata program called:

// ata-trace.ts
import { Keypair, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
import {
  createAssociatedTokenAccountInstruction,
  createMint,
  getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import { connection, payer } from "./config";
import { nameOf } from "./names";
 
// A fresh mint and a fresh wallet, so the token account really has to be created
const mint = await createMint(connection, payer, payer.publicKey, null, 6);
const friend = Keypair.generate();
const ata = getAssociatedTokenAddressSync(mint, friend.publicKey);
 
const tx = new Transaction().add(
  createAssociatedTokenAccountInstruction(payer.publicKey, ata, friend.publicKey, mint),
);
const signature = await sendAndConfirmTransaction(connection, tx, [payer]);
 
// Read the transaction back and list every program the ATA program called
const parsed = await connection.getParsedTransaction(signature, {
  commitment: "confirmed",
  maxSupportedTransactionVersion: 0,
});
 
console.log("new token account:", ata.toBase58());
console.log("outer call       :", nameOf(parsed!.transaction.message.instructions[0].programId.toBase58()));
 
for (const group of parsed!.meta?.innerInstructions ?? []) {
  for (const ix of group.instructions) {
    const type = "parsed" in ix ? ix.parsed.type : "(not decoded)";
    console.log("  inner call     :", nameOf(ix.programId.toBase58()).padEnd(18), "->", type);
  }
}

you should see the outer call go to the associated token account program, and inner calls to the system program and the token program. the exact list of inner instructions can vary between versions, but those are the programs you will meet.

make a token

to make your own token you need three steps:

  1. create a mint. think of it as a bank that may print more coins. it can also hold a freeze authority.
  2. create an associated token account for that mint and a specific wallet. you cannot receive a token until this account exists.
  3. mint tokens into that account.

with the cli

spl-token create-token
spl-token supply <MINT>
spl-token create-account <MINT>
spl-token mint <MINT> 100
spl-token balance <MINT>
spl-token accounts

create-token prints the mint address, and you use that same address in every later command. then open the mint in solana explorer on devnet and call getAccountInfo on it to see its data and lamports.

with typescript

the same flow in code, which also reads the result back so you can see both kinds of owner:

// make-token.ts
import { TOKEN_PROGRAM_ID, createMint, getAccount, getMint, getOrCreateAssociatedTokenAccount, mintTo } from "@solana/spl-token";
import { connection, payer } from "./config";
 
const DECIMALS = 6;
 
// 1. The mint. The payer is both the mint authority and the freeze authority.
const mint = await createMint(connection, payer, payer.publicKey, payer.publicKey, DECIMALS);
 
// 2. Your balance account for this mint
const ata = await getOrCreateAssociatedTokenAccount(connection, payer, mint, payer.publicKey);
 
// 3. Mint 100 whole tokens (libraries speak base units)
await mintTo(connection, payer, mint, ata.address, payer, 100n * 10n ** BigInt(DECIMALS));
 
// 4. Read it back
const supply = (await getMint(connection, mint)).supply;
const account = await getAccount(connection, ata.address);
const raw = await connection.getAccountInfo(ata.address);
 
console.log("mint                    :", mint.toBase58());
console.log("supply (base units)     :", supply); // 100000000n
console.log("runtime owner           :", raw!.owner.equals(TOKEN_PROGRAM_ID) ? "Token Program" : "?");
console.log("data owner is my wallet :", account.owner.equals(payer.publicKey)); // true

the last two lines are the whole lesson of this post. the runtime owner is the token program, which controls who may write the bytes. the data owner is your wallet, which controls who may spend the tokens.

the decimals trap

this mint has 6 decimals, so one whole token is 1,000,000 base units. libraries always work in base units, so mintTo(..., 100n) would mint only 0.0001 tokens. the cli is different: spl-token mint <MINT> 100 takes display units and makes 100 whole tokens. it is the same integer rule as lamports. also remember that a basic mint stores no name or ticker. that comes from metadata, which token-2022 can keep inside the mint.

cheat sheet

idea in one line
program stateless code in an account marked executable
account owner the program that may write the data and debit lamports
system program owns wallets, creates accounts, moves sol, assigns owners, allocates space
token program owns every mint and every token balance
mint defines a token: supply, decimals, mint and freeze authority
token account one per wallet per token, holds the balance
ata program the factory for the deterministic token account
pda an address derived from seeds, with no private key
runtime owner a program, enforced by the runtime
data owner the wallet inside a token account, enforced by the token program

try it yourself

  1. in system-tour.ts, call allocate a second time on the same account and read the error.
  2. lower the funding in step 1 below the rent minimum for 100 bytes and watch the allocation fail.
  3. run owner-map.ts with the address of your own wallet and your own mint. what owns each?
  4. run ata-trace.ts twice. why does the second run still create a new account?

references


Last updated: October 9, 2026

Enjoyed this? Let's talk

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

Keep reading