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
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.
Los tokens no tienen direcciones de contrato, solo direcciones de mint
En Ethereum, cada token se identifica de forma única por su dirección de contrato. En Solana, cada token se identifica de forma única por una dirección de mint. La idea subyacente es similar: es el puntero onchain de ese token específico. Pero como el Token Program de Solana es universal, no despliegas una “dirección de contrato” independiente. En su lugar, proporcionas al runtime de Solana un nuevo mint account.
No Approval Flow Needed
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.
What Does A Solana Token Program Look Like?
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.
Where’s the Token Metadata?
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.
Tradeoffs of Each Approach
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
- Good for interfaces
- Flexibility on each smart contract
- Hard to index all tokens
- Requires approval flow for transferring tokens
- New smart contract deployment required for each token
SPL-Token
- Single smart contract means you know what to expect from the code
- New tokens are created with transactions
- Indexing the tokens is simple
- Newer token standards require a new smart contract
- Reusable by developers
High-Level Comparison
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.)
| Paso | Ethereum (ERC-20) | Solana (SPL Token) |
|---|---|---|
| 1. Preparar Código del Token | Usualmente utiliza OpenZeppelin. Creas un archivo Solidity (p. ej., MyToken.sol). | No se necesita un contrato personalizado. El Token Program ya está desplegado. Solo creas una Cuenta de Acuñación (Mint Account). |
| 2. Compilar y Desplegar | Compilar y desplegar usando Hardhat/Truffle (p. ej., npx hardhat run deploy.js --network ...). | Usar spl-token create-token. No hay despliegue de contrato separado. Una única llamada RPC completa el proceso. |
| 3. Acuñación Inicial | Llamar al constructor del contrato o función mint(). Implica tarifas de gas que pueden variar. | Ejecutar spl-token mint <MINT_ADDRESS> <AMOUNT>. Normalmente tarifas de transacción muy bajas. |
| 4. Crear Destinatario | Típicamente solo una dirección regular de Ethereum. Los usuarios deben agregar manualmente la dirección del contrato en las carteras. | Una Cuenta de Token Asociada (ATA por sus siglas en inglés) es reconocida automáticamente por carteras como Phantom o Solflare. |
| 5. Verificar Resultados | Ver en Etherscan. Los usuarios a menudo agregan la dirección del contrato manualmente a su cartera. | Ejecutar solana balance <ADDRESS> o spl-token accounts. También puedes buscar por dirección de acuñación en Solana Explorer. |
| 6. Actualizaciones de Código | Para actualizaciones importantes, podrías usar un patrón proxy o volver a desplegar el contrato. | El Token Program es fijo. Puedes habilitar extensiones o escribir un programa separado en cadena para lógica más compleja. |
| 7. Requisitos de Auditoría | Cada contrato típicamente requiere una auditoría, especialmente si agregas lógica personalizada. | El Token Program principal ya ha sido sometido a múltiples auditorías. Para acuñar tokens únicamente, raramente son necesarias auditorías adicionales. |
¿Quieres acuñar tu propio token en Solana? Consulta esta guía.
How to do ERC20 on Solana
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.
How to do 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 a token’s metadata (name, symbol, and URI) 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);
});
How to do 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);
});
How to do decimals()
function decimals() public view returns (uint8) // Returns the number of decimals the token usePuedes verificar los decimales usando getTokenSupply de @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);
});How to do 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
How to do totalSupply()
function totalSupply() public view returns (uint256) // Returns the total issuance of tokensPodemos verificar los decimales usando getTokenSupply de @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);
});How to do transfer()
function transfer(address _to, uint256 _value) public returns (bool success) // Moves a value amount of tokens from the caller’s account to _to Primero, analicemos este código para entender la lógica:
En Solana, cada token se identifica por su dirección de Mint única, y los usuarios almacenan sus saldos en un Associated Token Account (ATA). En una transacción, la dirección del ATA se utiliza como emisor o receptor para transferir tokens. A diferencia de Ethereum, donde llamas directamente a un contrato ERC-20, Solana gestiona la lógica de transferencia de tokens a través de su sistema program nativo.
Podemos crear la instrucción de transferencia de una transacción mediante createTransferCheckedInstruction y enviarla mediante sendTransaction de @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!
Node storing all data and participating in consensus
- Ethereum: Archive Node
- Solana: [n/a]
Node storing some data and participating in consensus
- Ethereum: Full Node
- Solana: Consensus Node
Node storing some data and not participating in consensus
- Ethereum: Light Node
- Solana: RPC Node