发送多个相关事务的最佳实践 [solana] [web3js]

Mir*_*ono 3 web3js solana

在 Solana 中发送多个相关交易的最佳实践是什么?假设我想发送 2 笔交易,每笔交易都是相关的。

如果第二个失败,那么我必须要求用户发送第一笔和第二笔交易。但实际上我可以实现这样当第二个 trx 失败时,它只会要求用户重试第二个。

有人可以在这件事上为我指出正确的方向吗?

谢谢

Jac*_*ech 7

有两种方法可以做到这一点。

  1. 将指令打包到单个事务中

如果您不受事务限制(最大 1232 字节、最多 30 条指令、最多 18 个公钥、最多 1.4m 计算)的约束,您可以将指令打包到单个事务中,并且任何失败都会导致整个事务失败。

例子:

const Transaction = new Transaction().add(
  SystemProgram.createAccount({
      fromPubkey: publicKey,
      newAccountPubkey: mintKeypair.publicKey,
      space: MINT_SIZE,
      lamports: lamports,
      programId: TOKEN_PROGRAM_ID,
  }),
  createInitializeMintInstruction(
    mintKeypair.publicKey, 
    form.decimals, 
    publicKey, 
    publicKey, 
    TOKEN_PROGRAM_ID)
);
Run Code Online (Sandbox Code Playgroud)

如果是以上,createInitializeMintInstruction则要看createAccount第一个。将两者打包在一个事务中,如果其中任何一个指令失败,则整个事务失败。

  1. 在 UI 上管理事务重试

由于限制,您可以将每笔交易分开,但最终会相互依赖。

const transaction1 = new Transaction().add(
  SystemProgram.createAccount({
      fromPubkey: publicKey,
      newAccountPubkey: mintKeypair.publicKey,
      space: MINT_SIZE,
      lamports: lamports,
      programId: TOKEN_PROGRAM_ID,
  })
);
const transaction2 = new Transaction().add(
  createInitializeMintInstruction(
    mintKeypair.publicKey, 
    form.decimals, 
    publicKey, 
    publicKey, 
    TOKEN_PROGRAM_ID)
);

const signature1 = await connection.sendTransaction(transaction1, [mintKeypair, payerKeypair])
const signature2 = await connection.sendTransaction(transaction2, [mintKeyPair, payerKeypair])
Run Code Online (Sandbox Code Playgroud)

使用上述内容,您可以connection.confirmTransaction与签名一起使用来验证哪些签名实际得到确认,哪些签名失败。这将允许您根据网络上确认的交易随意切换 UI。