Solana Web3.js 2.0 极速入门:从安装到首笔链上转账

·

Web3.js 是连接 JavaScript 世界与 Solana 区块链的桥梁。2024 年底发布的 2.0 版本带来了更小的包体积、更快的加密运算以及灵活的 TypeScript 支持,让开发者能轻松写出高性能的 DApp。本篇教程将带你完成以下任务:

关键词:Solana、Web3.js 2.0、交易发送、优先级费用、tree-shakable、TypeScript 客户端、lamport 转账、计算单元、迁移指南、加密性能


为什么选择 Web3.js 2.0?

性能飞跃

极致精简

代码支持 tree-shaking;只打包你真正用到的模块,最终产物体积可缩减 70% 以上

更强可定制性

👉 想立刻体验飞快签署的 Solana 交易流程?点击实战!


项目准备一步到位

环境要求

1 分钟初始化

npm init -y
mkdir src && touch src/index.js
npm install @solana/web3.js@2 @solana-program/system @solana-program/compute-budget

生成的 package.json 已锁定 2.x 版本,后续升级可直接 npm update.


构建转账脚本

1. 配置地址与密钥

import {
  address,
  createKeyPairSignerFromBytes,
  getBase58Encoder
} from '@solana/web3.js';

const destinationAddress = address('收款者公钥');
const secretKeyUint8 = getBase58Encoder().encode('你的私钥');
const sourceKeypair = await createKeyPairSignerFromBytes(secretKeyUint8);

2. 建立 RPC & WebSocket 连接

import {
  createSolanaRpc,
  createSolanaRpcSubscriptions,
  sendAndConfirmTransactionFactory
} from '@solana/web3.js';

const rpc     = createSolanaRpc('https://mainnet.helius-rpc.com/?api-key=YOUR_KEY');
const rpcSub  = createSolanaRpcSubscriptions('wss://mainnet.helius-rpc.com/?api-key=YOUR_KEY');
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions: rpcSub });

3. 构造转账指令

import { lamports } from '@solana/web3.js';
import { getTransferSolInstruction } from '@solana-program/system';

const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();

const instruction = getTransferSolInstruction({
  amount: lamports(1000000), // 0.001 SOL
  source: sourceKeypair,
  destination: destinationAddress
});

4. 使用函数式管道拼装交易

import {
  pipe,
  createTransactionMessage,
  setTransactionMessageFeePayer,
  setTransactionMessageLifetimeUsingBlockhash,
  appendTransactionMessageInstruction
} from '@solana/web3.js';

let txMsg = pipe(
  createTransactionMessage({ version: 0 }),
  m => setTransactionMessageFeePayer(sourceKeypair.address, m),
  m => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
  m => appendTransactionMessageInstruction(instruction, m)
);

5. 签名

import { signTransactionMessageWithSigners } from '@solana/web3.js';
const signedTx = await signTransactionMessageWithSigners(txMsg);

精准估算优先费用与计算单元

根据已签名交易拉取优先费用

用 Base64 把交易序列化后交给 Helius API,即可返回 micro-lamports 级的建议值。
import { getBase64EncodedWireTransaction } from '@solana/web3.js';

const base64Tx = getBase64EncodedWireTransaction(signedTx);
const { result } = await fetch(rpc, {/* 调用 getPriorityFeeEstimate 获取 `priorityFeeEstimate` */});
const priorityFee = result.priorityFeeEstimate;

计算单元 = 实际需求 × 1.1

import { getComputeUnitEstimateForTransactionMessageFactory } from '@solana/web3.js';

const getEstimate = getComputeUnitEstimateForTransactionMessageFactory({ rpc });
let cuEstimate = await getEstimate(txMsg);
cuEstimate = Math.max(1000, Math.ceil(cuEstimate * 1.1));

最终:重构、再签、发送

import {
  appendTransactionMessageInstructions,
  getSetComputeUnitPriceInstruction,
  getSetComputeUnitLimitInstruction
} from '@solana/web3.js';

const { value: finalBlockhash } = await rpc.getLatestBlockhash().send();

txMsg = appendTransactionMessageInstructions([
  getSetComputeUnitPriceInstruction({ microLamports: priorityFee }),
  getSetComputeUnitLimitInstruction({ units: cuEstimate })
], txMsg);

txMsg = setTransactionMessageLifetimeUsingBlockhash(finalBlockhash, txMsg);
const finalSignedTx = await signTransactionMessageWithSigners(txMsg);

const sig = await sendAndConfirm(finalSignedTx, {
  commitment: 'confirmed',
  maxRetries: 0,
  skipPreflight: true
});
console.log('转账完成!TxID:', sig);

运行项目:

node src/index.js

常见问题 FAQ

Q1:1.x 与 2.x API 差异大,我的旧代码怎么办?
A:仍在生产环境运行的项目可以继续锁版本:npm install @solana/web3.js@^1。新项目建议直接拥抱 2.x,收益巨大。

Q2:新 SDK 的类型定义是否向后兼容?
A:不兼容,但官方提供了 @solana-program/* 自动生成的 TypeScript 客户端,导入字段、方法命名更语义化。

Q3:如何确认交易真的上链了?
A:使用 sendAndConfirmTransaction 并把 commitment 设为 confirmedfinalized。你可以监听 onAccountChangegetSignatureStatus 进行二次验证。

Q4:skipPreflighttrue 会不会不安全?
A:适合已充分测试的交易;若需长时间调试应保持默认 false,让预检帮你捕获常见错误。

Q5:生手如何估算优先费用更加准确?
A:先调用 Helius 官方推荐的 API;高并发场景可叠加 动态滑动窗口 机制,根据网络拥堵实时调整。
👉 查看最新优先费用波动,把握最佳提交时机!


写在最后

Web3.js 2.0 以模块化、高性能、零依赖三大革新,重新定义了 Solana 开发体验。只需十几行代码,你就能在飞速确认的主网上完成一次性命中的转账。
下一段旅程,试着把上面的逻辑封装进一个 React Native 模块,或替换成你自己的 RPC 集群——你会发现,2.0 的抽象边界让一切都能“插拔”。祝你编码愉快!