因此,我可以在我的网站上选择“发送”xy 数量的自定义 solana 代币并连接到幻像钱包。这个完全相同的功能在 localhost 中有效,但当我将其上传到我的服务器并通过 ip 地址访问网站时则无效。当此代码在同一浏览器中的客户端执行并且代码相同但使用托管在服务器上的网站时,这怎么可能实现:TypeError:无法读取未定义的属性(读取“摘要”)功能myToken.getOrCreateAssociatedAccountInfo 使用
<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.min.js"></script>
<script src="https://unpkg.com/@solana/spl-token@latest/lib/index.iife.min.js"></script>
在标题中
这是代码:
function sendCOIN(amount){
return new Promise(async(resolve, reject) => {
const publicKey = window.solana._publicKey
const toWallet = new web3.PublicKey("myWalletPublicKey")
const myMint = new web3.PublicKey("myMintAdress");
const myToken = new splToken.Token(
connection,
myMint,
splToken.TOKEN_PROGRAM_ID,
publicKey
);
const createTransferTransaction = async () => {
const fromTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
publicKey
)
const toTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
toWallet
)
let transaction = new web3.Transaction().add(
splToken.Token.createTransferInstruction(
splToken.TOKEN_PROGRAM_ID,
fromTokenAccount.address,
toTokenAccount.address,
publicKey,
[],
web3.LAMPORTS_PER_SOL*amount
)
);
transaction.feePayer = publicKey;
console.log("Getting recent blockhash");
const anyTransaction = transaction;
anyTransaction.recentBlockhash = (
await connection.getRecentBlockhash()
).blockhash;
return transaction;
};
const sendTransaction = async () => {
try {
const transaction = await createTransferTransaction();
if (!transaction) return;
console.log("Sending transaction!")
const { signature } = await window.solana.signAndSendTransaction(transaction);
console.log("Submitted transaction " + signature + ", awaiting confirmation");
await connection.confirmTransaction(signature);
console.log("Transaction " + signature + " confirmed");
return resolve({signature, publicKey: publicKey.toString()})
} catch (err) {
console.warn(err);
console.log("[error] sendTransaction: " + JSON.stringify(err));
return reject(500)
}
};
sendTransaction()
});
}