ERC20は代替可能トークン(Fungible Tokens)の標準を定めたもので、各トークンは他のトークンと(種類も価値も)同一です。たとえば、ERC20トークンはETHトークンと同様に機能し、1トークンは常に他のどの1トークンとも等価です。
Token Program
SolanaのToken Programは、ほとんどのトークン操作に使用される唯一のスマートコントラクトです。これは、トークンごとに新しいスマートコントラクトをデプロイするEthereumとは異なります。なぜSolanaにはトークン用のメインのスマートコントラクトが1つしかないのでしょうか?
SolanaアカウントモデルはSolanaにおいて状態と実行ロジックを分離しているため、EthereumのERC20のようなインターフェースを作成するのは非常に困難です。複数のスマートコントラクトの代わりに、単一のToken Programが「mintアカウント」と呼ばれる別個の「アカウント」でトークンを扱い、ユーザーのトークンは個別の「token account」に保管されます。アカウントモデルにより、プログラムの再利用性と事前に定められた定義という大きな利点が得られ、誰でも独自のERC20トークン関数を書けることによる未知の副作用を避けられます。
トークンにはコントラクトアドレスはなく、ミントアドレスのみ
Ethereumでは、各トークンはコントラクトアドレスによって一意に識別されます。Solanaでは、各トークンはミントアドレスによって一意に識別されます。基本的な考え方は似ており、特定のトークンを指すオンチェーン上のポインターです。ただし、Solana Token Programは汎用的であるため、個別の「コントラクトアドレス」をデプロイすることはありません。代わりに、新しいmint accountをSolanaランタイムに提供します。
承認フローは不要
Ethereumでは、ユーザーに代わってERC20トークンを2つのアドレス間で転送する場合、approve + transferFromが必要になることがよくあります。Solanaでは、各ユーザーはToken Programが認識するATA(Associated token accounts)をすでに持っています。1つのSolanaトランザクションで複数のinstructionsをアトミックに呼び出せるため、別途承認ステップは不要です。あるユーザーのtoken accountから別のユーザーのtoken accountへ、一度に直接転送できます。
SolanaのToken Programはどのような形をしている?
SolanaのToken Programをごく大まかに置き換えると、次のようになります:
// 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)))))];
}
}コントラクトからわかるように、承認フローの代わりに、トークンを移動するための転送関数だけが存在します。Solanaでは、1つのトランザクションで複数のスマートコントラクト関数をアトミックに呼び出せるため、承認フローが不要になります。もう1つの違いは、Solanaではすべてがtoken accountに保存され、所有者のトークンの詳細が他の状態から分離されている点です。
トークンメタデータはどこにある?
コードを見て、スマートコントラクト自体にトークンメタデータがないことにお気づきかもしれません。現在、このメタデータはSolana上のToken Metadata Programによって処理されており、トークンにより多くのフィールドを関連付けたい場合に、メタデータを拡張できます。つまり、トークンに名前、シンボル、説明などのフィールドを追加するには、トランザクションに追加する別の関数が必要になります(SVMは1つのトランザクション内で複数の関数呼び出しを順番に処理できることを思い出してください)。
各アプローチのトレードオフ
Solanaのトークンプログラムがどのように動作するかの概要がわかったところで、各トークン標準のトレードオフを見ていきましょう。
ERC20
- インターフェースに適している
- 各スマートコントラクトで柔軟に対応できる
- すべてのトークンのインデックス化が難しい
- トークンの転送に承認フローが必要
- トークンごとに新しいスマートコントラクトのデプロイが必要
SPL-Token
- 単一のスマートコントラクトのため、コードから何が期待できるかがわかる
- 新しいトークンはトランザクションで作成される
- トークンのインデックス化が簡単
- 新しいトークン標準には新しいスマートコントラクトが必要
- 開発者が再利用できる
概要比較
以下は、EthereumでのERC-20トークンのデプロイと、SolanaでのSPLトークンの作成における基本的な手順を比較した表です。(Solanaでは、コマンドラインツールのspl-tokenコマンドを使って、SPLトークンを自由にミントできます。)
| ステップ | Ethereum(ERC-20) | Solana(SPLトークン) |
|---|---|---|
| 1. トークンコードの準備 | 通常はOpenZeppelinを使用。Solidityファイル(例:MyToken.sol)を作成します。 | カスタムコントラクトは不要。Token Programは既にデプロイ済み。Mint Accountを作成するだけです。 |
| 2. コンパイルとデプロイ | HardhatやTruffleを使用してコンパイルとデプロイ(例:npx hardhat run deploy.js --network ...)。 | spl-token create-tokenを使用。個別のコントラクトデプロイは不要。1回のRPC呼び出しでプロセスが完了します。 |
| 3. 初期Mint | コントラクトのコンストラクタまたは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でmintアドレスによる検索も可能です。 |
| 6. コードの更新 | 大規模なアップグレードには、プロキシパターンを使用するか、コントラクトを再デプロイする場合があります。 | Token Programは固定。拡張機能を有効にするか、より複雑なロジックのために別のオンチェーンプログラムを作成できます。 |
| 7. 監査要件 | 各コントラクトには通常、監査が必要です。特にカスタムロジックを追加する場合。 | メインのToken Programは既に複数の監査を受けています。純粋にトークンをミントするだけであれば、追加の監査はほとんど不要です。 |
Solanaで独自トークンをミントしたいですか?このガイドをご覧ください!
SolanaでERC20を実現する方法
Token Programと@solana/web3.jsを使って、ERC20のような主要な機能をSolanaで再現する方法を見てみましょう。
Solanaでは、トークンは独自のコントラクトアドレスではなくMint Addressで識別されます。以下の例のように、さまざまなRPCエンドポイントやライブラリを使って、トークンのメタデータ、供給量、小数点以下の桁数などの情報を照会できます。
name()の実装方法
function name() public view returns (string) // Returns the name of the token@metaplex-foundation/umi-bundle-defaultsと@metaplex-foundation/mpl-token-metadataを使用すると、Mintアドレスからトークンのメタデータ(名前、シンボル、URI)を取得して解析できます。
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 tokenname()と同様に、@metaplex-foundation/umi-bundle-defaultsと@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 use@solana/web3.jsのgetTokenSupplyを使って小数点以下の桁数を確認できます。
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);
});@solana/spl-tokenのgetTokenAccountsByOwnerを使って、指定したアカウントの残高を確認できます。
totalSupply()の実装方法
function totalSupply() public view returns (uint256) // Returns the total issuance of tokens@solana/web3.jsのgetTokenSupplyを使って総供給量を確認できます。
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 まず、ロジックを理解するためにこのコードを見てみましょう:
Solanaでは、各トークンは固有のMintアドレスで識別され、ユーザーはAssociated Token Account(ATA)に残高を保管します。トランザクションでは、ATAアドレスがトークン送受信の送信元または受信先として使用されます。ERC-20コントラクトを直接呼び出すEthereumとは異なり、Solanaは共有のToken Programを通じてトークン転送を処理します。
createTransferCheckedInstructionでトランザクションの転送instructionsを作成し、@solana/spl-tokenのsendTransactionで送信できます。
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);
});
receiverAddress から receiverTokenAddress を確認するにはどうすればよいでしょうか?getOrCreateAssociatedTokenAccount を使用できます。associated token account を取得し、存在しない場合は作成します。
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);
});
その他の機能を探索したいですか?こちらのガイドをご覧ください!
すべてのデータを保存し、コンセンサスに参加するノード
- Ethereum: アーカイブノード
- Solana: [該当なし]
一部のデータを保存し、コンセンサスに参加するノード
- Ethereum: フルノード
- Solana: コンセンサスノード
一部のデータを保存し、コンセンサスに参加しないノード
- Ethereum: ライトノード
- Solana: RPCノード