@solana/web3.js 2.0:Solana 转账全流程解析

@solana/web3.js2.0:Solana转账全流程解析Solana区块链以高吞吐量和低交易成本,已成为开发者的热门选择。而@solana/web3.js2.0作为最新一代JavaScript库,为与Solana网络交互提供了更高效、模块化的工具。本文将深入剖析如何使

@solana/web3.js 2.0:Solana 转账全流程解析

Solana 区块链以高吞吐量和低交易成本,已成为开发者的热门选择。而 @solana /web3.js 2.0 作为最新一代 JavaScript 库,为与 Solana 网络交互提供了更高效、模块化的工具。本文将深入剖析如何使用 @solana /web3.js 2.0 实现 Solana 区块链上的转账操作,从环境配置到代码实现,再到本地测试验证,旨在为开发者提供一个实用的全流程指南。无论你是 Solana 新手还是资深开发者,都能从中获得丰富的实践洞察。

本文通过一个完整的转账示例,系统解析了 @solana /web3.js 2.0 在 Solana 开发中的核心应用。内容涵盖:环境变量与密钥配置、RPC 客户端连接、签名者生成、交易消息构建,以及 0.5 SOL 的转账逻辑,并在本地测试验证器上验证结果。代码实现基于 TypeScript 的 solana_transfer.ts,配合 package.json 配置,展示了从开发到验证的全流程最佳实践。文章旨在为开发者提供可复现的参考,助力高效掌握 Solana 开发。

实操

代码实现与解析 以下是实现 Solana 转账的核心代码,我们将逐步拆解其功能和作用。这段代码展示了如何利用 @solana /web3.js 2.0 从一个账户向另一个账户转账 0.5 SOL。

solann_transfer 文件

import {
    createKeyPairSignerFromBytes,
    createSolanaRpc,
    createSolanaRpcSubscriptions,
    lamports,
    getBase58Encoder,
    sendAndConfirmTransactionFactory,
    pipe,
    createTransactionMessage,
    setTransactionMessageFeePayer,
    setTransactionMessageLifetimeUsingBlockhash,
    appendTransactionMessageInstruction,
    signTransactionMessageWithSigners,
    getSignatureFromTransaction,
    address,
} from "@solana/web3.js";
import { getTransferSolInstruction } from "@solana-program/system";
// 导入 dotenv
import dotenv from "dotenv";

// 加载 .env 文件中的变量
dotenv.config();
import fs from "fs";

// 访问环境变量
const encoded_data = process.env.ENCODED_DATA;
const private_key = process.env.PRIVATE_KEY;
const user1 = process.env.SOL_ADDRESS1;
const user2 = process.env.SOL_ADDRESS2;
const httpProvider = process.env.SOL_RPC_URL;
const wssProvider = process.env.WSS_PROVIDER;

console.log(`encoded_data: ${encoded_data}`);
if (
    !private_key ||
    !wssProvider ||
    !encoded_data ||
    !user1 ||
    !user2 ||
    !httpProvider
) {
    console.error("Missing environment variables.");
    process.exit(1);
}

const user1Address = address(user1);
const user2Address = address(user2);

// 1 - 创建一个 Solana RPC 客户端
const rpc = createSolanaRpc(httpProvider);
const rpcSubscriptions = createSolanaRpcSubscriptions(wssProvider);
console.log(`✅ - 已建立与 ${httpProvider} 的连接`);

const LAMPORTS_PER_SOL = BigInt(1_000_000_000);

async function main() {
    const encoded_data = [4, 230, 246];
    // const keypairBytes = JSON.parse(fs.readFileSync("../keys/KeykETTNzif4hHZ8dzqM3xNigyAQ4Z3XXyU9yBbM3y9.json").toString())
    // const signer = await createKeyPairSignerFromBytes(new Uint8Array(keypairBytes as number[]));

    const secretKey = private_key as string;
    const signer = await createKeyPairSignerFromBytes(
        getBase58Encoder().encode(secretKey)
    );

    // const seed = new Uint8Array(encoded_data);
    // const signer = await createKeyPairSignerFromBytes(seed);

    // 创建转账交易
    const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();

    const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }), // 初始化新的交易消息。版本为 0
        (tx) => setTransactionMessageFeePayer(user1Address, tx), // 设置交易的手续费支付者
        (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), // 设置交易的生命周期 使用最近的区块哈希设置交易的生命周期
        (tx) =>
            appendTransactionMessageInstruction(
                // 添加转账指令 将转账指令添加到交易中
                getTransferSolInstruction({
                    amount: lamports(LAMPORTS_PER_SOL / BigInt(2)),
                    destination: user2Address,
                    source: signer,
                }),
                tx
            )
    );
    // 5 - 签名并发送交易
    const signedTransaction = await signTransactionMessageWithSigners(
        transactionMessage
    );
    const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({
        rpc,
        rpcSubscriptions,
    });

    try {
        await sendAndConfirmTransaction(signedTransaction, {
            commitment: "confirmed",
            skipPreflight: true,
        });
        const signature = getSignatureFromTransaction(signedTransaction);
        console.log("✅ - 转账交易:", signature);
    } catch (e) {
        console.error("转账失败:", e);
    }
}

main();

/**
 * 
Web3_wallet/solana-demo on  master [✘?] is 📦 1.0.0 via ⬢ v22.1.0 via 🅒 base 
➜ ts-node solana_transfer.ts
✅ - 已建立与 https://solana-devnet.g.alchemy.com/v2/YLgbp9I-spejSR_9EHp_-UYDrIYdrwE1 的连接
(node:65790) ExperimentalWarning: The Ed25519 Web Crypto API algorithm is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:65790) [UNDICI-WS] Warning: WebSockets are experimental, expect them to change at any time.
✅ - 转账交易: 5BZMYyU1a7ZHtf6q62nkrvrRfc7ee4pLHyiuUk6sPWHkurpNy4obvD4hGmTwFQpjyhtbstConhXbf4EdUQhba6fu

➜ ts-node solana_transfer.ts
✅ - 已建立与 https://solana-devnet.g.alchemy.com/v2/YLgbp9I-spejSR_9EHp_-UYDrIYdrwE1 的连接
(node:75521) ExperimentalWarning: The Ed25519 Web Crypto API algorithm is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:75521) [UNDICI-WS] Warning: WebSockets are experimental, expect them to change at any time.
✅ - 转账交易: 5TX6QHZz9BoXdAourteREavDM2q6ZuSc7FyAE69KemrjZZrfJqhML4YqgHeayMAGQEDNJ68HwDymo7D1miHZqcQX

// https://github.com/anamansari062/test-2.0/blob/main/src/index.js
 */

代码解析

  1. 导入模块

从 @solana/web3.js 导入了一系列核心函数,用于构建和发送交易:

  • createKeyPairSignerFromBytes:从私钥生成签名者。
  • createSolanaRpc 和 createSolanaRpcSubscriptions:创建与 Solana 网络交互的 HTTP 和 WebSocket 客户端。
  • lamports:将 SOL 转换为最小单位 Lamports(1 SOL = 10亿 Lamports)。
  • pipe:函数式编程工具,用于链式处理交易消息。
  • createTransactionMessage、setTransactionMessageFeePayer 等:构建交易的步骤。
  • getTransferSolInstruction:从 @solana-program/system 获取转账指令。
    1. 环境配置

使用 dotenv 加载 .env 文件中的变量(如私钥、地址、RPC URL),并进行校验。如果缺少关键变量,程序会退出,确保安全性。

  1. RPC 客户端初始化

    const rpc = createSolanaRpc(httpProvider);
    const rpcSubscriptions = createSolanaRpcSubscriptions(wssProvider);

    通过 HTTP 和 WebSocket 协议连接 Solana 网络,分别用于发送请求和订阅事件。

  2. 签名者生成

    const signer = await createKeyPairSignerFromBytes(getBase58Encoder().encode(secretKey));

    使用 Base58 编码的私钥生成签名者,用于签署交易。

  3. 构建交易消息

使用 pipe 函数链式处理:

  • 初始化交易(版本 0)。
  • 设置手续费支付者(user1Address)。
  • 使用最新区块哈希(latestBlockhash)设置交易有效期。
  • 添加转账指令,转账金额为 0.5 SOL(LAMPORTS_PER_SOL / BigInt(2))。
  1. 签名与发送

    const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
    await sendAndConfirmTransaction(signedTransaction, { commitment: "confirmed", skipPreflight: true });

    使用签名者签署交易,并通过工厂函数发送到网络,等待确认。skipPreflight: true 跳过预检查以加快速度。

  2. 运行结果

示例输出表明交易成功:

✅ - 转账交易: 5BZMYyU1a7ZHtf6q62nkrvrRfc7ee4pLHyiuUk6sPWHkurpNy4obvD4hGmTwFQpjyhtbstConhXbf4EdUQhba6fu

执行与验证

运行 ts-node solana_transfer.ts,完成 0.5 SOL 的转账,并返回交易签名,可通过 Solana Explorer 查看详情。

package.json 文件

{
  "name": "solana-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@solana-program/system": "^0.6.2",
    "@solana/web3.js": "2",
    "dotenv": "^16.4.7",
    "ed25519-hd-key": "^1.3.0",
    "bs58": "^6.0.0",
    "bip39": "3.1.0"
  },
  "devDependencies": {
    "@types/node": "^22.13.4"
  }
}

本地测试

# Solana

```bash
➜ solana-test-validator -r

Ledger location: test-ledger
Log: test-ledger/validator.log
⠄ Initializing...                                                                                                        Waiting for fees to stabilize 1...
Identity: AvV5zuhWHPCNRhq8qyPrfA4yjLqiFPySFxyYt7NuHicE
Genesis Hash: EQ6H4aqK3RbAP2eYtvrMFHK3SrbKT9NHJ4MtT2hrVCKB
Version: 2.0.15
Shred Version: 290
Gossip Address: 127.0.0.1:1024
TPU Address: 127.0.0.1:1027
JSON RPC URL: http://127.0.0.1:8899
WebSocket PubSub URL: ws://127.0.0.1:8900
⠁ 00:03:00 | Processed Slot: 382 | Confirmed Slot: 382 | Finalized Slot: 351

➜ ts-node transfer.ts

✅ - 已建立与 http://127.0.0.1:8899 的连接
(node:4171) ExperimentalWarning: The Ed25519 Web Crypto API algorithm is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
✅ - 新的 user1 地址已创建:3ziUaeQ1zZwbQf1FYHGYrKQkifEWSG5K47WKPQFzXVpp
✅ - 从文件生成 user2 地址:Sq7vmiewuLGcQArLUhny1iXtXPqrnC1EWGt5SJ89aS5
✅ - user1 使用 RPC 方法空投 1 SOL
✅ - tx1: 36RRUnQQbPYrXjSTcpw5Aqf9KYW1aBEp8GH9akBAgqfypeyxtWSLx9Ss3e7tqQ83sgwpdhtfaUTXbHBspk58z6dP
(node:4171) [UNDICI-WS] Warning: WebSockets are experimental, expect them to change at any time.
✅ - user2 使用工厂函数空投 1 SOL
✅ - tx2: 2YFtea2ez4XuDdgKn6Zj9L6ogdt9eFwu4CfSb4Ekgd7kbmUQJEU6frkvVKvCBjBL1fZWM3yaxoKetQyTLZjzsCnj
✅ - 转账交易: 3Wqnj7Whghqyg9xVXEBkFbTJvCjBJ83eHQ91FPoJ69KzBmWSSppYnvuz7kC9n2uJotVg4eB1ARBbgUQt6SbiHfxe


## 总结
通过对 @solana
/web3.js 2.0 的全流程解析,我们成功实现了 Solana 区块链上的转账功能。从环境搭建到交易签名,再到本地测试验证,整个过程展示了该库在性能和易用性上的优势。借助 @solana
/web3.js 2.0 的模块化设计,开发者可以极大简化开发复杂度,专注于业务逻辑而非底层细节。本文提供的示例可作为起点,开发者还可进一步扩展到更复杂的应用场景(如批量交易或跨程序调用),解锁 Solana 生态的更多可能。

## 参考

- https://www.solanazh.com/
- https://github.com/solana-labs
- https://github.com/anza-xyz/kit
- https://www.jsonrpc.org/specification
- https://www.anchor-lang.com/docs
- https://solana.com/zh/docs
- https://solanacookbook.com/zh/
- https://solscan.io/
- https://github.com/yihau/anchor-auction/blob/main/programs/auction/src/lib.rs
- https://www.solar.team/116d1d99211c81b7b4e3e77e93f231f9
- https://explorer.solana.com/
- https://websocketking.com/
- https://attractive-spade-1e3.notion.site/Solana-fca856aad4e5441f80f28cc4e015ca98
- https://github.com/anamansari062/test-2.0/blob/main/src/index.js
点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
寻月隐君
寻月隐君
0x89EE...a439
不要放弃,如果你喜欢这件事,就不要放弃。如果你不喜欢,那这也不好,因为一个人不应该做自己不喜欢的事。