[英]How to get a user's keypair from their public key only (Solana)?
I'm making a dApp and I want to add a button where a user (the one with their wallet connected) can send exactly 0.01 SOL to another user.我正在制作一个 dApp,我想添加一个按钮,用户(连接钱包的用户)可以将 0.01 SOL 发送给另一个用户。 I already wrote the function in my Rust program and after testing it with
anchor test
it seems to be working when I use my own personal wallet's Keypair to sign the transaction.我已经在我的 Rust 程序中编写了该函数,并且在使用
anchor test
对其进行测试后,当我使用我自己的个人钱包的密钥对来签署交易时,它似乎正在工作。 However, now I am writing the event handler function in my web app's frontend and I'm not sure what to pass for the signers
parameter if I want the user to sign the transaction.但是,现在我正在我的 Web 应用程序的前端编写事件处理程序函数,如果我希望用户签署交易,我不确定要为
signers
参数传递什么。 What do I pass if I don't know their secret key?如果我不知道他们的密钥,我该怎么办? Is there a way that I can generate a user's Keypair from their public key alone or would I need to use the Solana Wallet Adapter for this?
有没有一种方法可以单独从用户的公钥生成用户的密钥对,或者我需要为此使用 Solana 钱包适配器吗? Any help would be appreciated.
任何帮助,将不胜感激。 This is my first time working with Solana!
这是我第一次与 Solana 合作!
This is the function:这是功能:
const tipSol = async (receiverAddress) => {
try {
const provider = getProvider();
const program = new Program(idl, programID, provider);
const lamportsToSend = LAMPORTS_PER_SOL / 100;
const amount = new anchor.BN(lamportsToSend);
await program.rpc.sendSol(amount, {
accounts: {
from: walletAddress,
to: receiverAddress,
systemProgram: SystemProgram.programId,
},
signers: ?
})
console.log('Successfully sent 0.01 SOL!')
window.alert(`You successfully tipped ${receiverAddress} 0.01 SOL!`)
} catch (error) {
console.error('Failed to send SOL:', error);
window.alert('Failed to send SOL:', error);
}
}
Frontends never access private keys .前端从不访问私钥。 Instead the flow is something like:
相反,流程类似于:
You can use the @solana/wallet-adapter
to implement this on your frontend https://github.com/solana-labs/wallet-adapter您可以使用
@solana/wallet-adapter
在您的前端实现此功能https://github.com/solana-labs/wallet-adapter
In practice it would be something like this in your frontend在实践中,你的前端会是这样的
export const Component = () => {
const { connection } = useConnection();
const { sendTransaction } = useWallet();
const handle = async () => {
const ix: TransactionInstruction = await tipSol(receiverKey);
const tx = new Transaction().add(ix);
const sig = await sendTransaction(tx, connection);
};
// ...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.