我将 SOL/Lamports 转移到 PDA 帐户,但无法从 PDA 中提取 SOL。
Transfer SOL to PDA
我从下面给出的代码生成 PDA 帐户。
const GREETING_SEED = 'Hello';
greetedPubkey = await PublicKey.createWithSeed(
payer.publicKey,
GREETING_SEED,
programId,
);
const transaction = new Transaction().add(
SystemProgram.createAccountWithSeed({
fromPubkey: payer.publicKey,
basePubkey: payer.publicKey,
seed: GREETING_SEED,
newAccountPubkey: greetedPubkey,
lamports,
space: GREETING_SIZE,
programId,
}),
);
await sendAndConfirmTransaction(connection, transaction, [payer]);
使用以下代码片段进行 Sol 交易:
transaction.add(
SystemProgram.transfer({
fromPubkey:toaccount.publicKey,
toPubkey: greetedPubkey,
lamports: LAMPORTS_PER_SOL/100,
programId: programId,
}),
);
const signature=await sendAndConfirmTransaction(connection, transaction, [toaccount]);
上面的代码工作正常。
Withdraw SOL from PDA
但我无法从 PDA 帐户中提取 SOL。
transaction.add(
SystemProgram.transfer({
fromPubkey: greetedPubKey,
toPubkey: toaccount.publicKey,
lamports: LAMPORTS_PER_SOL/100,
programId: programId,
}),
);
const signature=await sendAndConfirmTransaction(connection, transaction, [greetedPubKey]);
我尽一切努力去做。但无法使用 PDA 地址签署交易。如果我犯了任何错误,还有其他方法或要点
最佳答案
分配给程序的帐户,例如greetedPubkey
,在执行createAccountWithSeed
之后,只能由程序本身更改其数据或扣除内存。以下是文档的摘录:
A created account is initialized to be owned by a built-in program called the System program and is called a system account aptly. An account includes "owner" metadata. The owner is a program id. The runtime grants the program write access to the account if its id matches the owner. For the case of the System program, the runtime allows clients to transfer lamports and importantly assign account ownership, meaning changing the owner to a different program id. If an account is not owned by a program, the program is only permitted to read its data and credit the account.
https://docs.solana.com/developing/programming-model/accounts#ownership-and-assignment-to-programs
为了将 lamports 转移回来,您必须让您的程序处理一条指令,将 lamports 从 greetedPubkey
移回您的帐户,例如,通过执行以下操作:
**from_account.try_borrow_mut_lamports()? -= amount_of_lamports;
**to_account.try_borrow_mut_lamports()? += amount_of_lamports;
您可以在https://solanacookbook.com/references/programs.html#how-to-transfer-sol-in-a-program找到完整的示例。
这不是您问题的一部分,但作为附录,使用 createAccountWithSeed
创建的帐户不是 PDA,因此您的程序将无法签名为了它。
关于reactjs - 如何在 solana 中从 PDA 中提取 sol/lamports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71709062/