You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Solana Web3 TS/JS库实现SOL的包装与解包并生成交易指令

使用Solana Web3 TS实现SOL的包装与解包

SOL 包装(Wrap)实现

包装SOL为WSOL需要先确保用户拥有对应的WSOL关联账户,再执行包装指令。以下是完整的指令生成代码:

import { Connection, PublicKey, TransactionInstruction } from '@solana/web3.js';
import { createAssociatedTokenAccountInstruction, createWrapNativeAccountInstruction, getAssociatedTokenAddress } from '@solana/spl-token';

// 基础配置
const connection = new Connection('https://api.devnet.solana.com');
const userPubkey = new PublicKey('替换为用户公钥');
const wsolMint = new PublicKey('So11111111111111111111111111111111111111112'); // WSOL标准mint地址
const wrapAmount = 1 * 10**9; // 要包装的SOL数量,单位lamports(1 SOL = 1e9 lamports)

// 获取用户的WSOL关联账户地址
const userWsolAccount = await getAssociatedTokenAddress(wsolMint, userPubkey);

// 初始化指令数组
const wrapInstructions: TransactionInstruction[] = [];

// 检查关联账户是否存在,不存在则创建
const accountExists = !!(await connection.getAccountInfo(userWsolAccount));
if (!accountExists) {
  const createAtaIx = createAssociatedTokenAccountInstruction(
    userPubkey,    // 支付账户(承担创建账户的手续费)
    userWsolAccount, // 要创建的关联账户地址
    userPubkey,    // 关联账户的所有者
    wsolMint       // WSOL的mint地址
  );
  wrapInstructions.push(createAtaIx);
}

// 生成包装指令
const wrapIx = createWrapNativeAccountInstruction(
  userPubkey,      // 转出SOL的用户账户
  userWsolAccount, // 接收WSOL的关联账户
  userPubkey,      // 账户所有者
  wrapAmount       // 要包装的lamports数量
);
wrapInstructions.push(wrapIx);

// wrapInstructions数组可直接加入交易提交执行

SOL 解包(Unwrap)实现

解包WSOL为SOL只需生成解包指令,直接将WSOL转换为SOL转回用户账户:

import { Connection, PublicKey, TransactionInstruction } from '@solana/web3.js';
import { createUnwrapNativeAccountInstruction, getAssociatedTokenAddress } from '@solana/spl-token';

// 基础配置
const connection = new Connection('https://api.devnet.solana.com');
const userPubkey = new PublicKey('替换为用户公钥');
const wsolMint = new PublicKey('So11111111111111111111111111111111111111112');
const unwrapAmount = 1 * 10**9; // 要解包的WSOL数量,单位lamports

// 获取用户的WSOL关联账户地址
const userWsolAccount = await getAssociatedTokenAddress(wsolMint, userPubkey);

// 生成解包指令
const unwrapIx = createUnwrapNativeAccountInstruction(
  userWsolAccount, // 持有WSOL的关联账户
  userPubkey,      // 接收SOL的用户账户
  userPubkey,      // 账户所有者
  unwrapAmount     // 要解包的lamports数量
);

// 将unwrapIx加入交易即可执行解包操作

注意事项

  • 需安装与@solana/web3.js@0.30.8兼容的@solana/spl-token版本,推荐0.1.8。
  • 执行交易前需确保用户账户有足够SOL支付手续费,且WSOL账户余额满足解包需求。
  • 可通过connection.getTokenAccountBalance(userWsolAccount)验证包装/解包后的余额变化。

内容的提问来源于stack exchange,提问作者GarouDan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:35:40