If you’re coming from the EVM ecosystem, one thing you know well is ERC20. Tokens are the heart of almost any smart contract and they’re usually one of the first things you learn how to deploy. On Solana, what is the ERC20 equivalent and how does it differ?
ERC20 sets a standard for Fungible Tokens, which means that each token is the same as another token (both in type and value). For example, an ERC20 Token works similarly to the ETH token, where 1 Token is always equal to any other Token.
The Token Program on Solana is the single smart contract that is used for most token operations. This is different from Ethereum, where you deploy a new smart contract for every token. Why is there only one main smart contract for tokens on Solana?
The Solana Account Model separates the state from execution logic on Solana, making interfaces very difficult to create like ERC20 does on Ethereum. Instead of multiple smart contracts, the single Token Program handles tokens in separate “accounts” known as “mint accounts”, while user tokens are stored in individual “token accounts”. The account model gives a significant benefit in program reusability and predetermined definition, avoiding unknown side effects of anyone being able to write their own ERC20 token functions.
Di Ethereum, setiap token diidentifikasi secara unik oleh Contract Address-nya. Di Solana, setiap token diidentifikasi secara unik oleh Mint Address. Ide dasarnya serupa—ini adalah penunjuk onchain untuk token spesifik tersebut. Namun karena Token Program Solana bersifat universal, Anda tidak perlu men-deploy "contract address" terpisah. Sebaliknya, Anda menyediakan runtime Solana dengan mint account baru.
On Ethereum, transferring ERC20 tokens between two addresses often requires approve + transferFrom if you're doing it on behalf of a user. On Solana, each user already has an ATA (Associated token accounts) recognized by the Token Program. A single Solana transaction can atomically call multiple instructions, so no separate approval step is required. You can directly transfer from one user’s token account to another in one go.
A very rough translation of the Solana Token Program would look like this:
// SPDX-License-Identifier: MIT license
pragma solidity =0.8.28;
struct Mint {
uint8 decimals;
uint256 supply;
address mintAuthority;
address freezeAuthority;
address mintAddress;
}
struct TokenAccount {
address mintAddress;
address owner;
uint256 balance;
bool isFrozen;
}
contract Spl20 {
mapping(address => Mint) public mints;
mapping(address => TokenAccount) public tokenAccounts;
mapping(address => bool) public mintAddresses;
mapping(address => bool) public tokenAddresses;
function initializeMint(uint8 decimals, address mintAuthority, address freezeAuthority, address mintAddress)
public
returns (Mint memory)
{
require(mintAddresses[mintAddress] == false, "Mint already exists");
mints[mintAddress] = Mint(decimals, 0, mintAuthority, freezeAuthority, mintAddress);
mintAddresses[mintAddress] = true;
return Mint(decimals, 0, mintAuthority, freezeAuthority, mintAddress);
}
function mintTokens(address toMintTokens, address mintAddress, uint256 amount) public {
require(mints[mintAddress].mintAuthority == msg.sender, "Only the mint authority can mint tokens");
require(mints[mintAddress].mintAddress != address(0), "Token does not exist");
require(mints[mintAddress].supply + amount <= type(uint256).max, "Supply overflow");
mints[mintAddress].supply += amount;
address tokenAddress = address(uint160(uint256(keccak256(abi.encodePacked(toMintTokens, mintAddress)))));
if (tokenAccounts[tokenAddress].mintAddress == address(0)) {
tokenAccounts[tokenAddress] = TokenAccount(mintAddress, toMintTokens, 0, false);
tokenAddresses[tokenAddress] = true;
}
tokenAccounts[tokenAddress].balance += amount;
tokenAccounts[tokenAddress].owner = toMintTokens;
}
function transfer(address to, address mintAddress, uint256 amount) public {
address toTokenAddress = address(uint160(uint256(keccak256(abi.encodePacked(to, mintAddress)))));
address fromTokenAddress = address(uint160(uint256(keccak256(abi.encodePacked(msg.sender, mintAddress)))));
require(tokenAccounts[fromTokenAddress].balance >= amount, "Insufficient balance");
require(tokenAccounts[toTokenAddress].balance + amount <= type(uint256).max, "Supply overflow");
require(tokenAccounts[fromTokenAddress].owner == msg.sender, "fromToken owner is not msg.sender");
require(tokenAccounts[fromTokenAddress].isFrozen == false, "fromToken is frozen");
require(tokenAccounts[toTokenAddress].isFrozen == false, "toToken is frozen");
if (tokenAccounts[toTokenAddress].mintAddress == address(0)) {
tokenAccounts[toTokenAddress] = TokenAccount(mintAddress, to, 0, false);
tokenAddresses[toTokenAddress] = true;
}
tokenAccounts[fromTokenAddress].balance -= amount;
tokenAccounts[toTokenAddress].balance += amount;
}
function getMint(address token) public view returns (Mint memory) {
return mints[token];
}
function getTokenAccount(address owner, address token) public view returns (TokenAccount memory) {
return tokenAccounts[address(uint160(uint256(keccak256(abi.encodePacked(owner, token)))))];
}
}As you can see in the contract, instead of an approval flow, there is only a transfer function to move tokens. On Solana, a single transaction can call multiple smart contract functions atomically, removing the need for the approval flow. Another difference is that everything is stored in a token account on Solana, keeping the details of the owner’s tokens separate from the other state.
One thing you may have noticed in the code is that there wasn’t any token metadata in the smart contract itself. Today this metadata is handled by the Token Metadata Program on Solana, allowing metadata to be extended as people wish to have more fields associated with their token. This does mean there’s a separate function to add to a transaction(remember, SVM can handle multiple in order function calls in a single transaction) to add name, symbol, description and other fields to your Token.
Now that you have a general idea of how the token program on Solana works, let’s go through some of the tradeoffs of each token standard.
ERC20
SPL-Token
Below is a table comparing the basic steps of deploying an ERC-20 token on Ethereum vs. creating an SPL token on Solana. (On Solana, you can freely mint SPL tokens by using the spl-token command in the command-line tool.)
| Langkah | Ethereum (ERC-20) | Solana (SPL Token) |
|---|---|---|
| 1. Persiapkan Kode Token | Biasanya menggunakan OpenZeppelin. Anda membuat file Solidity (misalnya, MyToken.sol). | Tidak perlu kontrak kustom. Token Program sudah di-deploy. Anda hanya perlu membuat Mint Account. |
| 2. Kompilasi & Deploy | Kompilasi dan deploy menggunakan Hardhat/Truffle (misalnya, npx hardhat run deploy.js --network ...). | Gunakan spl-token create-token. Tidak ada deployment kontrak terpisah. Satu panggilan RPC menyelesaikan proses. |
| 3. Minting Awal | Panggil constructor kontrak atau fungsi mint(). Melibatkan biaya gas yang bisa bervariasi. | Jalankan spl-token mint <MINT_ADDRESS> <AMOUNT>. Biaya transaksi biasanya sangat rendah. |
| 4. Buat Penerima | Biasanya hanya alamat Ethereum biasa. Pengguna harus menambahkan contract address secara manual di wallet. | Associated Token Account (ATA) secara otomatis dikenali oleh wallet seperti Phantom atau Solflare. |
| 5. Periksa Hasil | Lihat di Etherscan. Pengguna sering menambahkan contract address secara manual ke wallet mereka. | Jalankan solana balance <ADDRESS> atau spl-token accounts. Anda juga dapat mencari berdasarkan mint address di Solana Explorer. |
| 6. Pembaruan Kode | Untuk upgrade besar, Anda mungkin menggunakan pola proxy atau men-deploy ulang kontrak. | Token Program bersifat tetap. Anda dapat mengaktifkan ekstensi atau menulis program onchain terpisah untuk logika yang lebih kompleks. |
| 7. Persyaratan Audit | Setiap kontrak biasanya memerlukan audit, terutama jika Anda menambahkan logika kustom. | Token Program utama telah menjalani beberapa audit. Untuk minting token murni, audit tambahan jarang diperlukan. |
Want to mint your own token on Solana? Check out this guide!
Let's explore how to replicate key ERC20-like functions on Solana, using the Token Program and @solana/web3.js.
On Solana, tokens are identified by a Mint Address rather than a custom contract address. You can query the token’s metadata, supply, decimals, and other information using various RPC endpoints and libraries, as shown in the examples below.
name()function name() public view returns (string) // Returns the name of the tokenYou can use @metaplex-foundation/umi-bundle-defaults and @metaplex-foundation/mpl-token-metadata to fetch and parse an NFT’s off-chain metadata from its mint address.
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
import { fetchDigitalAsset, mplTokenMetadata } from "@metaplex-foundation/mpl-token-metadata";
import { PublicKey } from "@metaplex-foundation/js";
const mintAddress = new PublicKey("Token Address");
async function name() {
try {
const umi = createUmi("https://api.devnet.solana.com");
umi.use(mplTokenMetadata());
const digitalAsset = await fetchDigitalAsset(umi, mintAddress);
return digitalAsset.metadata.name;
} catch (error) {
console.error("Error fetching token name:", error);
return null;
}
}
name().then(name => {
console.log("token Name:", name);
})
.catch(error => {
console.error("Error:", error);
});
symbol()function symbol() public view returns (string) // Returns the symbol of the tokenYou can also retrieve the symbol in the same way as name(), using @metaplex-foundation/umi-bundle-defaults and @metaplex-foundation/mpl-token-metadata.
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
import { fetchDigitalAsset, mplTokenMetadata } from "@metaplex-foundation/mpl-token-metadata";
import { PublicKey } from "@metaplex-foundation/js";
const mintAddress = new PublicKey("Token Address");
async function symbol() {
try {
const umi = createUmi("https://api.devnet.solana.com");
umi.use(mplTokenMetadata());
const asset = await fetchDigitalAsset(umi, mintAddress);
return asset.metadata.symbol;
} catch (error) {
console.error("Error fetching NFT symbol:", error);
return null;
}
}
symbol().then(symbol => {
console.log("Symbol:", symbol);
}).catch(error => {
console.error("Error:", error);
});
decimals()function decimals() public view returns (uint8) // Returns the number of decimals the token useYou can check decimals using getTokenSupply from @solana/web3.js
import { Connection, PublicKey } from "@solana/web3.js";
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
const mintAddress = new PublicKey("Token Address");
async function decimals() {
let response = await connection.getTokenSupply(mintAddress);
return response.value.decimals;
}
decimals().then(decimals => {
console.log(decimals);
}).catch(error => {
console.error("Error:", error);
});balanceOf()function balanceOf(address _owner) public view returns (uint256 balance) // Returns the number of tokens in owner's accountimport { Connection, PublicKey } from "@solana/web3.js";
import { AccountLayout }from "@solana/spl-token";
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
const mintAddress = new PublicKey("Token Address");
const ownerAddress = new PublicKey("Your Wallet Address");
async function balanceOf(_owner){
let response = await connection.getTokenAccountsByOwner(_owner, { mint: mintAddress });
const accountInfo = AccountLayout.decode(response.value[0].account.data);
return accountInfo.amount;
}
balanceOf(ownerAddress).then(balance => {
console.log(balance); // need to multiply the result by the decimal precision to get the correct value.
}).catch(error => {
console.error("Error:", error);
});We can check the balance of the requested account using getTokenAccountsByOwner from @solana/spl-token
totalSupply()function totalSupply() public view returns (uint256) // Returns the total issuance of tokensWe can check decimals using getTokenSupply from @solana/web3.js
import { Connection, PublicKey } from "@solana/web3.js";
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
const mintAddress = new PublicKey("Token Address");
async function totalSupply() {
let response = await connection.getTokenSupply(mintAddress);
return response.value.amount;
}
totalSupply().then(supply => {
console.log(supply); // need to multiply the result by the decimal precision to get the correct value
}).catch(error => {
console.error("Error:", error);
});transfer()function transfer(address _to, uint256 _value) public returns (bool success) // Moves a value amount of tokens from the caller’s account to _to First, Let’s look at this code for understanding logic:
On Solana, each token is identified by its unique Mint address, and users store their balances in an Associated Token Account (ATA). In a transaction, the ATA address is used as the sender or receiver for transferring tokens. Unlike on Ethereum, where you directly call an ERC-20 contract, Solana handles token transfer logic through its native system program.
We can make a transaction’s transfer instruction through createTransferCheckedInstruction and send it through sendTransaction from @solana/spl-token.
import { Keypair, Transaction, Connection, PublicKey } from "@solana/web3.js";
import { createTransferCheckedInstruction } from "@solana/spl-token";
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
// Must contain your private key as a Uint8Array
const ownerSecretkey = [];
const ownerPrivatekeypair = Keypair.fromSecretKey(new Uint8Array(ownerSecretkey));
const receiverAddress = new PublicKey("Receiver's Wallet Address");
const mintAddress = new PublicKey("Token Address");
const ownerTokenAccount = new PublicKey("Your Associated Token Account Address");
const receiverTokenAccount = new PublicKey("Receiver's Associated Token Account Address");
// For a token with 9 decimals, transferring 1 => 1 * 10^9
const amount = 1;
async function transfer(_to, _value) {
try {
// Create a transaction with the transfer instruction
const tx = new Transaction().add(
createTransferCheckedInstruction(
ownerTokenAccount,
mintAddress,
receiverTokenAccount,
ownerPrivatekeypair.publicKey,
_value * Math.pow(10, 9), // Decimal correction
9 // decimals
)
);
// Send the transaction (simplified, no explicit blockhash or feePayer set)
await connection.sendTransaction(tx, [ownerPrivatekeypair]);
return true;
} catch (error) {
console.error("Error in transfer:", error);
return false;
}
}
transfer(receiverAddress, amount)
.then(result => {
console.log(result);
})
.catch(error => {
console.error("Error:", error);
});
How we can check receiverTokenAddress through receiverAddress? We can use getOrCreateAssociatedTokenAccount. It will retrieve the associated token account, or create it if it doesn't exist.
import { Keypair, Transaction, Connection, PublicKey } from "@solana/web3.js";
import { createTransferCheckedInstruction, getOrCreateAssociatedTokenAccount } from "@solana/spl-token";
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
// Must contain your private key as a Uint8Array
const ownerSecretkey = [];
const ownerPrivatekeypair = Keypair.fromSecretKey(new Uint8Array(ownerSecretkey));
const receiverAddress = new PublicKey("Receiver's Wallet Address");
const mintAddress = new PublicKey("Token Address");
const amount = 1; // Amount to transfer
async function transfer(_to, _value) {
try {
// Get or create the sender's ATA
const ownerTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
ownerPrivatekeypair, // Fee payer
mintAddress,
ownerPrivatekeypair.publicKey
);
// Get or create the receiver's ATA
const receiverTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
ownerPrivatekeypair, // Fee payer
mintAddress,
_to
);
// Build the transaction
const tx = new Transaction().add(
createTransferCheckedInstruction(
ownerTokenAccount.address,
mintAddress,
receiverTokenAccount.address,
ownerPrivatekeypair.publicKey,
_value * Math.pow(10, 9), // Decimal correction (9 decimals)
9 // decimals
)
);
// Send the transaction (simple version)
await connection.sendTransaction(tx, [ownerPrivatekeypair]);
return true;
} catch (error) {
console.error("Error in transfer:", error);
return false;
}
}
// Execute the transfer function
transfer(receiverAddress, amount)
.then(result => {
console.log("Transaction result:", result);
})
.catch(error => {
console.error("Error:", error);
});
Want to explore more features? Check out this guide!