EVM -> Solana

ERC20 trên Solana là gì?

Nếu bạn đến từ hệ sinh thái EVM, có một điều bạn chắc chắn đã biết rõ là ERC20. Token là trái tim của hầu hết mọi hợp đồng thông minh và thường là một trong những thứ đầu tiên bạn học cách triển khai. Trên Solana, đâu là thứ tương đương với ERC20 và nó khác biệt như thế nào?

ERC20 đặt ra một tiêu chuẩn cho các token có thể thay thế (Fungible Token), nghĩa là mỗi token đều giống với một token khác (cả về loại lẫn giá trị). Ví dụ, một token ERC20 hoạt động tương tự như token ETH, trong đó 1 token luôn bằng với bất kỳ token nào khác.

Token Program

Token Program trên Solana là hợp đồng thông minh duy nhất được dùng cho hầu hết các thao tác với token. Điều này khác với Ethereum, nơi bạn triển khai một hợp đồng thông minh mới cho mỗi token. Vậy tại sao trên Solana chỉ có một hợp đồng thông minh chính cho token?

Mô hình tài khoản Solana tách biệt trạng thái khỏi logic thực thi trên Solana, khiến việc tạo các interface như ERC20 trên Ethereum trở nên rất khó khăn. Thay vì nhiều hợp đồng thông minh, một Token Program duy nhất xử lý token trong các “tài khoản” riêng biệt gọi là “mint account”, trong khi token của người dùng được lưu trong các token account riêng lẻ. Mô hình tài khoản mang lại lợi ích đáng kể về khả năng tái sử dụng chương trình và định nghĩa được xác định trước, tránh các tác dụng phụ không lường trước khi bất kỳ ai cũng có thể tự viết các hàm token ERC20 của riêng mình.

Token không có địa chỉ hợp đồng, chỉ có địa chỉ mint

Trên Ethereum, mỗi token được xác định duy nhất bằng Contract Address (địa chỉ hợp đồng). Trên Solana, mỗi token được xác định duy nhất bằng Mint Address (địa chỉ mint). Ý tưởng cơ bản tương tự nhau: đây là con trỏ onchain cho token cụ thể đó. Nhưng vì Token Program của Solana là chung cho mọi token, bạn không triển khai một “địa chỉ hợp đồng” riêng. Thay vào đó, bạn cung cấp cho runtime của Solana một mint account mới.

Không cần quy trình phê duyệt

Trên Ethereum, việc chuyển token ERC20 giữa hai địa chỉ thường yêu cầu approve + transferFrom nếu bạn thực hiện thay mặt người dùng. Trên Solana, mỗi người dùng đã có sẵn một ATA (Associated token account) được Token Program nhận diện. Một giao dịch Solana duy nhất có thể gọi nhiều lệnh theo cách nguyên tử (atomic), nên không cần bước phê duyệt riêng. Bạn có thể chuyển trực tiếp từ token account của người dùng này sang người dùng khác chỉ trong một lần.

Token Program của Solana trông như thế nào?

Một bản chuyển đổi rất sơ lược của Token Program trên Solana sẽ trông như sau:

Solidity
// 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)))))];
    }
}

Như bạn có thể thấy trong hợp đồng, thay vì quy trình phê duyệt, chỉ có một hàm transfer để di chuyển token. Trên Solana, một giao dịch duy nhất có thể gọi nhiều hàm hợp đồng thông minh theo cách nguyên tử, loại bỏ nhu cầu về quy trình phê duyệt. Một khác biệt nữa là mọi thứ đều được lưu trong một token account trên Solana, giúp tách biệt thông tin token của chủ sở hữu khỏi các trạng thái khác.

Metadata của token nằm ở đâu?

Một điều bạn có thể đã nhận thấy trong đoạn code là không có bất kỳ metadata token nào trong chính hợp đồng thông minh. Hiện nay, metadata này được xử lý bởi Token Metadata Program trên Solana, cho phép mở rộng metadata khi mọi người muốn gắn thêm nhiều trường hơn cho token của mình. Điều này đồng nghĩa với việc có một hàm riêng cần thêm vào giao dịch (hãy nhớ rằng SVM có thể xử lý nhiều lệnh gọi hàm theo thứ tự trong một giao dịch duy nhất) để thêm tên, ký hiệu, mô tả và các trường khác cho token của bạn.

Đánh đổi của từng cách tiếp cận

Giờ bạn đã có ý niệm chung về cách token program trên Solana hoạt động, hãy cùng xem qua một số đánh đổi của từng tiêu chuẩn token.

ERC20

  • Phù hợp cho các interface
  • Linh hoạt trên từng hợp đồng thông minh
  • Khó lập chỉ mục tất cả token
  • Yêu cầu quy trình phê duyệt để chuyển token
  • Cần triển khai hợp đồng thông minh mới cho mỗi token

SPL-Token

  • Chỉ một hợp đồng thông minh duy nhất nên bạn biết rõ cần kỳ vọng gì từ code
  • Token mới được tạo bằng các giao dịch
  • Việc lập chỉ mục token rất đơn giản
  • Các tiêu chuẩn token mới hơn yêu cầu một hợp đồng thông minh mới
  • Nhà phát triển có thể tái sử dụng

So sánh tổng quan

Dưới đây là bảng so sánh các bước cơ bản để triển khai token ERC-20 trên Ethereum với việc tạo token SPL trên Solana. (Trên Solana, bạn có thể tự do mint token SPL bằng lệnh spl-token trong công cụ dòng lệnh.)

BướcEthereum (ERC-20)Solana (SPL Token)
1. Chuẩn bị mã TokenThường sử dụng OpenZeppelin. Bạn tạo một tệp Solidity (ví dụ: MyToken.sol).Không cần hợp đồng tùy chỉnh. Token Program đã được triển khai sẵn. Bạn chỉ cần tạo một Mint Account.
2. Biên dịch & Triển khaiBiên dịch và triển khai bằng Hardhat/Truffle (ví dụ: npx hardhat run deploy.js --network ...).Sử dụng spl-token create-token. Không cần triển khai hợp đồng riêng. Một lệnh gọi RPC duy nhất hoàn tất quy trình.
3. Mint ban đầuGọi constructor của hợp đồng hoặc hàm mint(). Liên quan đến phí gas có thể thay đổi.Chạy spl-token mint <MINT_ADDRESS> <AMOUNT>. Thường có phí giao dịch rất thấp.
4. Tạo người nhậnThường chỉ là một địa chỉ Ethereum thông thường. Người dùng phải thêm địa chỉ hợp đồng thủ công vào ví.Một Associated Token Account (ATA) được ví như Phantom hoặc Solflare tự động nhận diện.
5. Kiểm tra kết quảXem trên Etherscan. Người dùng thường phải thêm địa chỉ hợp đồng thủ công vào ví của họ.Chạy solana balance <ADDRESS> hoặc spl-token accounts. Bạn cũng có thể tìm kiếm theo địa chỉ mint trên Solana Explorer.
6. Cập nhật mãĐối với nâng cấp lớn, bạn có thể sử dụng mô hình proxy hoặc triển khai lại hợp đồng.Token Program là cố định. Bạn có thể bật các tiện ích mở rộng hoặc viết một chương trình trên chuỗi riêng cho logic phức tạp hơn.
7. Yêu cầu kiểm toánMỗi hợp đồng thường yêu cầu kiểm toán, đặc biệt nếu bạn thêm logic tùy chỉnh.Token Program chính đã trải qua nhiều cuộc kiểm toán. Đối với việc mint token đơn thuần, hiếm khi cần kiểm toán bổ sung.

Bạn muốn mint token của riêng mình trên Solana? Hãy xem hướng dẫn này!

Cách thực hiện ERC20 trên Solana

Hãy cùng khám phá cách tái tạo các hàm chính giống ERC20 trên Solana, bằng cách sử dụng Token Program và @solana/web3.js.

Trên Solana, token được xác định bằng Mint Address thay vì địa chỉ hợp đồng tùy chỉnh. Bạn có thể truy vấn metadata, nguồn cung, decimals và các thông tin khác của token bằng nhiều RPC endpoint và thư viện khác nhau, như minh họa trong các ví dụ bên dưới.

Cách thực hiện name()

Bash
function name() public view returns (string) // Returns the name of the token

Bạn có thể sử dụng @metaplex-foundation/umi-bundle-defaults và @metaplex-foundation/mpl-token-metadata để lấy và phân tích metadata của token (tên, ký hiệu và URI) từ mint address của nó.

JSX
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);
  });

Cách thực hiện symbol()

Bash
function symbol() public view returns (string) // Returns the symbol of the token

Bạn cũng có thể lấy ký hiệu theo cách tương tự như name(), bằng cách sử dụng @metaplex-foundation/umi-bundle-defaults và @metaplex-foundation/mpl-token-metadata.

JSX
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);
});

Cách thực hiện decimals()

Bash
function decimals() public view returns (uint8) // Returns the number of decimals the token use

Bạn có thể kiểm tra decimals bằng cách sử dụng getTokenSupply từ @solana/web3.js

JSX
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);
});

Cách thực hiện balanceOf()

Bash
function balanceOf(address _owner) public view returns (uint256 balance) // Returns the number of tokens in owner's account
JSX
import { 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);
});

Chúng ta có thể kiểm tra số dư của tài khoản được yêu cầu bằng cách sử dụng getTokenAccountsByOwner từ @solana/spl-token

Cách thực hiện totalSupply()

Bash
function totalSupply() public view returns (uint256) // Returns the total issuance of tokens

Chúng ta có thể kiểm tra tổng nguồn cung bằng cách sử dụng getTokenSupply từ @solana/web3.js

JSX
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);
});

Cách thực hiện transfer()

Solidity
function transfer(address _to, uint256 _value) public returns (bool success) // Moves a value amount of tokens from the caller’s account to _to 

Đầu tiên, hãy xem đoạn code này để hiểu logic:

Trên Solana, mỗi token được xác định bởi địa chỉ Mint duy nhất của nó, và người dùng lưu trữ số dư của họ trong một Associated Token Account (ATA). Trong một giao dịch, địa chỉ ATA được sử dụng làm người gửi hoặc người nhận khi chuyển token. Không giống như trên Ethereum, nơi bạn gọi trực tiếp hợp đồng ERC-20, Solana xử lý việc chuyển token thông qua Token Program dùng chung.

Chúng ta có thể tạo lệnh chuyển trong giao dịch thông qua createTransferCheckedInstruction và gửi nó qua sendTransaction từ @solana/spl-token.

JSX
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);
  });

Làm thế nào để kiểm tra receiverTokenAddress thông qua receiverAddress? Chúng ta có thể dùng getOrCreateAssociatedTokenAccount. Hàm này sẽ truy xuất associated token account, hoặc tạo mới nếu chưa tồn tại.

JSX
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);
  });

Muốn khám phá thêm các tính năng? Hãy xem hướng dẫn này!

Node lưu trữ toàn bộ dữ liệu và tham gia đồng thuận

  • Ethereum: Archive Node
  • Solana: [không có]

Node lưu trữ một phần dữ liệu và tham gia đồng thuận

  • Ethereum: Full Node
  • Solana: Consensus Node

Node lưu trữ một phần dữ liệu và không tham gia đồng thuận

  • Ethereum: Light Node
  • Solana: RPC Node

Keep Learning

Tìm hiểu về tài khoản trên Solana

Xem tài khoản khác nhau như thế nào khi xây dựng trên Ethereum và Solana

Explore
ERC20 trên Solana là gì? | Solana