总结Solana 开发指南:连接 Phantom 钱包、转账 SOL 和 SPL 代币

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)
    )
  );
在Python中监控Solana链上的SPL代币变化,可以使用Solana官方提供的PySolana库,它是一个Python SDK,可以帮助我们连接Solana网络并获取交易数据。以下是基本步骤: 1. **安装PySolana**: 首先需要安装`pysolana`库,你可以使用pip来安装: ``` pip install pysolana ``` 2. **创建索拉纳客户端**: 导入必要的模块,并通过`WalletProvider`获取钱包密钥,用于连接Solana节点: ```python from solana.publickey import PublicKey from solana.keypair import Keypair from solana.client import Client # 替换为你的公钥私钥 keypair = Keypair.from_secret_key("YOUR_SECRET_KEY") url = "https://api.mainnet-beta.solana.com" # 使用主网或测试网地址 client = Client(url, wallet=keypair) ``` 3. **订阅账户**: 获取你要监控的SPL代币的账户地址,然后订阅这个地址的变化: ```python token_address = PublicKey("TOKEN_ADDRESS") # 替换为实际的SPL代币地址 def handle_events(event): print(f"Event: {event}") client.on_message += handle_events subscription = client.stream_account_history(token_address) ``` 4. **处理事件**: `subscription`将返回一个生成器,每次有新的交易发生时,会触发回调函数`handle_events`。你需要在这里处理具体的事件,比如余额变动。 5. **长期运行**: 通常你会在无限循环中接收处理新事件,直到你选择停止监控。注意这可能会消耗一定的资源,所以可以选择设定定时任务或者限制监控的时间范围。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值