【发布时间】:2021-12-01 10:19:20
【问题描述】:
我正在使用 Solana 区块链。我正在尝试通过 Phantom 转移 Solana SOL。为此,我使用了下面在 stackoverflow 中使用的代码。 source link
我已经在我的 chrome 浏览器中安装了 Phantom。
当我运行代码时,它显示错误
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'toString')
我认为是这行代码导致了上面的错误
console.log("Public key of the emitter: ",provider.publicKey.toString());
这是代码
import * as web3 from '@solana/web3.js';
import * as splToken from '@solana/spl-token';
const getProvider = async () => {
if ("solana" in window) {
const provider = window.solana;
if (provider.isPhantom) {
console.log("Is Phantom installed? ", provider.isPhantom);
return provider;
}
} else {
window.open("https://www.phantom.app/", "_blank");
}
};
async function transferSOL() {
// Detecing and storing the phantom wallet of the user (creator in this case)
var provider = await getProvider();
console.log("Public key of the emitter: ",provider.publicKey.toString());
// Establishing connection
var connection = new web3.Connection(
web3.clusterApiUrl('devnet'),
);
// I have hardcoded my secondary wallet address here. You can take this address either from user input or your DB or wherever
var recieverWallet = new web3.PublicKey("CkiKLEa9eSEoG6CoTSuaahsF2WqNgArnvoCSbNZjJ7BQ");
// Airdrop some SOL to the sender's wallet, so that it can handle the txn fee
var airdropSignature = await connection.requestAirdrop(
provider.publicKey,
web3.LAMPORTS_PER_SOL,
);
// Confirming that the airdrop went through
await connection.confirmTransaction(airdropSignature);
console.log("Airdropped");
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: web3.LAMPORTS_PER_SOL //Investing 1 SOL. Remember 1 Lamport = 10^-9 SOL.
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Transaction constructor initialized successfully
if(transaction) {
console.log("Txn created successfully");
}
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
// The signature is generated
let signature = await connection.sendRawTransaction(signed.serialize());
// Confirm whether the transaction went through or not
await connection.confirmTransaction(signature);
//Signature chhap diya idhar
console.log("Signature: ", signature);
}
【问题讨论】:
-
不幸的是,该示例不包括连接到外部钱包,例如 Phantom。我建议查看 solana 钱包适配器库,以便轻松连接到各种钱包。它包含一些您在集成应用程序时可以遵循的示例:github.com/solana-labs/wallet-adapter
标签: javascript web3 solana