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.
У токенов нет адресов контрактов, только адреса минта
В Ethereum каждый токен однозначно идентифицируется своим адресом контракта. В Solana каждый токен однозначно идентифицируется адресом минта. Базовая идея аналогична: это ончейн-указатель на конкретный токен. Но поскольку Token Program Solana является универсальным, вам не нужно развертывать отдельный «адрес контракта». Вместо этого вы предоставляете среде выполнения Solana новый 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 разработчиков
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.)
| Шаг | Ethereum (ERC-20) | Solana (SPL Token) |
|---|---|---|
| 1. Подготовка кода токена | Обычно используется OpenZeppelin. Вы создаете файл Solidity (например, MyToken.sol). | Пользовательский контракт не требуется. Token Program уже развернут. Вы просто создаете mint account. |
| 2. Компиляция и развертывание | Компиляция и развертывание с помощью Hardhat/Truffle (например, npx hardhat run deploy.js --network ...). | Используйте spl-token create-token. Отдельное развертывание контракта не требуется. Процесс завершается одним RPC-вызовом. |
| 3. Первичный минтинг | Вызовите конструктор контракта или функцию mint(). Включает комиссии за газ, которые могут варьироваться. | Выполните spl-token mint <MINT_ADDRESS> <AMOUNT>. Обычно очень низкие комиссии за транзакции. |
| 4. Создание получателя | Обычно это просто обычный адрес Ethereum. Пользователи должны вручную добавить адрес контракта в кошельки. | Associated token account (ATA) автоматически распознается кошельками, такими как Phantom или Solflare. |
| 5. Проверка результатов | Просмотр в Etherscan. Пользователи часто вручную добавляют адрес контракта в свой кошелек. | Выполните solana balance <ADDRESS> или spl-token accounts. Вы также можете искать по адресу минта в Solana Explorer. |
| 6. Обновление кода | Для крупных обновлений вы можете использовать паттерн прокси или повторно развернуть контракт. | Token Program фиксирован. Вы можете включить расширения или написать отдельную ончейн-программу для более сложной логики. |
| 7. Требования к аудиту | Каждый контракт обычно требует аудита, особенно если вы добавляете пользовательскую логику. | Основной Token Program уже прошел несколько аудитов. Для чистого минтинга токенов дополнительные аудиты редко необходимы. |
Хотите выпустить собственный токен на Solana? Ознакомьтесь с этим руководством!
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 useВы можете проверить количество десятичных знаков с помощью getTokenSupply из @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 tokensМы можем проверить количество десятичных знаков с помощью getTokenSupply из @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 Сначала рассмотрим этот код для понимания логики:
В Solana каждый токен идентифицируется уникальным адресом Mint, а пользователи хранят свои балансы в Associated Token Account (ATA). В транзакции адрес ATA используется в качестве отправителя или получателя при переводе токенов. В отличие от Ethereum, где вы напрямую вызываете контракт ERC-20, Solana обрабатывает логику перевода токенов через нативную системную программу.
Мы можем создать инструкцию перевода для транзакции через createTransferCheckedInstruction и отправить её через sendTransaction из @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