我如何 "unwrap SOL" 使用 web3 sdk?

How do I "unwrap SOL" using the web3 sdk?

我需要使用 web3 sdk 解包一些 SOL。我想知道,这只是从包装账户到 SOL 账户的简单转账,还是比这更复杂?下面是我设置的一些示例代码。

const emptyWSolAccount = async (amount:any) => {
  const wsolAddress = await Token.getAssociatedTokenAddress(
    ASSOCIATED_TOKEN_PROGRAM_ID,
    TOKEN_PROGRAM_ID,
    new PublicKey("So11111111111111111111111111111111111111112"),
    wallet.publicKey
  );

  const wsolAccount = await connection.getAccountInfo(wsolAddress);

  if (wsolAccount) {
    const transaction = new Transaction({
      feePayer: wallet.publicKey,
    });
    const instructions = [];

    const lamports = amount * LAMPORTS_PER_SOL;
    
    instructions.push(
      SystemProgram.transfer({
        fromPubkey: wsolAddress,
        toPubkey: wallet.publicKey,
        lamports: lamports, // 1 sol
      })
    );

    transaction.add(...instructions);
    transaction.recentBlockhash = await (
      await connection.getRecentBlockhash()
    ).blockhash;
    transaction.partialSign(wallet.payer);
    const result = await connection.sendTransaction(transaction, [
      wallet.payer,
    ]);
    console.log({ result });
    return { result };
  }

  return ;
};

这在任何地方都没有真正解释,但解包 SOL 实际上意味着关闭已包装的 SOL 帐户。

所以不用 SystemProgram.transfer 指令,你会做:

    instructions.push(
      splToken.instructions.createCloseAccountInstruction(
        wsolAddress,
        wallet.publicKey,
        wallet.publicKey,
      )
    );

这将关闭 wsolAddress 并将内容发送到 wallet,假设 wallet 是所有者。

您可以在 https://github.com/solana-labs/solana-program-library/blob/3db53e278b543a040d3c970797b6be6f9ea5aef9/token/cli/src/main.rs#L1139-L1194

查看 CLI 实现