Solana 是一个高性能的区块链平台,支持快速、低成本的交易。本文将详细介绍如何在 Solana 上连接 Phantom 钱包、转账 SOL 和 SPL 代币(如 USDT),以及如何铸造 SPL 代币。如何通过设置优先费用来优化交易确认速度。
1. 环境准备
1.1 安装依赖
首先,安装所需的库:
npm install @solana/web3.js @solana/spl-token @solana/wallet-adapter-phantom bs58 buffer
1.2 引入库
在代码中引入以下库:
import bs58 from 'bs58';
import { Buffer } from 'buffer';
import * as splToken from '@solana/spl-token';
import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';
import {
clusterApiUrl,
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
Transaction,
} from '@solana/web3.js';
2. 连接 Phantom 钱包
2.1 初始化钱包和连接
constructor() {
this.wallet = new PhantomWalletAdapter();
this.connection = new Connection(
"https://sleek-xxx-star.solana-xxx.quiknode.xxx/xxxxxxxxxxxxxxxxxxxx",
// 连接是 solana rpc节点 自己搭建或者去 QuickNode 购买,
// 或者使用 clusterApiUrl("mainnet-beta")
// testnet 测试网 devnet 开发网 mainnet-beta 主网
"confirmed"
);
}
2.2 连接钱包
async connectWallet(): Promise<string> {
try {
await this.wallet.connect();
const publicKey = this.wallet.publicKey.toString();
console.log("Connected with public key:", publicKey);
return publicKey;
} catch (error) {
console.error("Error connecting to Phantom Wallet:", error);
}
}
2.3 断开钱包连接
async disconnectWallet(): Promise<string> {
if (this.wallet) {
try {
await this.wallet.disconnect();
console.log("Disconnected from the Phantom wallet");
} catch (error) {
console.error("Error disconnecting from Phantom Wallet:", error);
}
} else {
alert("Phantom wallet not found!");
}
}
3. 转账 SOL 和 SPL 代币
3.1 转账 SOL
async transferSOL(receiverPublicKey, amount) {
if (!this.wallet.connected) {
await this.wallet.connect();
}
const senderPublicKey = this.wallet.publicKey;
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: senderPublicKey,
toPubkey: new PublicKey(receiverPublicKey),
lamports: amount * LAMPORTS_PER_SOL,
})
);
const { blockhash } = await this.connection.getRecentBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = senderPublicKey;
const signedTransaction = await this.wallet.signTransaction(transaction);
const signature = await this.connection.sendRawTransaction(signedTransaction.serialize());
console.log("Transaction signature:", signature);
return signature;
}
3.2 转账 SPL 代币(如 USDT)
async transferUSDT(receiverPublicKey, amount) {
if (!this.wallet.connected) {
await this.wallet.connect();
}
const senderPublicKey = this.wallet.publicKey;
const usdtMintAddress = new PublicKey("代币的地址");
// 如USDT:Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB
const fromTokenAccount = await splToken.getOrCreateAssociatedTokenAccount(
this.connection,
senderPublicKey,
usdtMintAddress,
senderPublicKey
).then(ata => ata.address);
const toTokenAccount = await splToken.getOrCreateAssociatedTokenAccount(
this.connection,
senderPublicKey,
usdtMintAddress,
new PublicKey(receiverPublicKey)
).then(ata => ata.address);
const transaction = new Transaction().add(
splToken.createTransferInstruction(
fromTokenAccount,
toTokenAccount,
senderPublicKey,
amount * Math.pow(10, 6) // USDT 有 6 位小数
)
);
const { blockhash } = await this.connection.getRecentBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = senderPublicKey;
const signedTransaction = await this.wallet.signTransaction(transaction);
const signature = await this.connection.sendRawTransaction(signedTransaction.serialize());
console.log("Transaction signature:", signature);
return signature;
}
4. 铸造 SPL 代币
4.1 创建代币
async createMint() {
const feePayer = Keypair.fromSecretKey(
bs58.decode("your_secret_key_here")
);
const mintPubkey = await splToken.createMint(
this.connection,
feePayer,
feePayer.publicKey,
feePayer.publicKey,
8 // 代币小数位
);
console.log(`Mint created: ${mintPubkey.toBase58()}`);
return mintPubkey;
}
4.2 铸造代币
async mintTokens(mintPubkey, amount) {
const feePayer = Keypair.fromSecretKey(
bs58.decode("your_secret_key_here")
);
const tokenAccount = await splToken.createAssociatedTokenAccount(
this.connection,
feePayer,
mintPubkey,
feePayer.publicKey
);
const txhash = await splToken.mintToChecked(
this.connection,
feePayer,
mintPubkey,
tokenAccount,
feePayer,
amount * Math.pow(10, 8), // 假设代币有 8 位小数
8
);
console.log(`Tokens minted: ${txhash}`);
return txhash;
}
5. 优化交易确认速度
通过设置优先费用,可以加快交易确认速度:
const { ComputeBudgetProgram } = require('@solana/web3.js');
const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
units: 10000,
});
const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
microLamports: 100000,
});
const transaction = new Transaction()
.add(modifyComputeUnits)
.add(addPriorityFee)
.add(
splToken.createTransferInstruction(
fromTokenAccount,
toTokenAccount,
senderPublicKey,
amount * Math.pow(10, 6)
)
);