我试图使Solana NFT事务代码与Typescript & react。
当仅在Typescript中运行此代码时,它可以正常工作。
但在react中,出现了错误。
import { Keypair ,Connection, Transaction, sendAndConfirmTransaction, PublicKey} from "@solana/web3.js";
import Wallet from "@project-serum/sol-wallet-adapter";
import { Token, TOKEN_PROGRAM_ID} from"@solana/spl-token"
const Solana = new Connection("https://api.testnet.solana.com/","confirmed")
import { EventEmitter} from eventemitter3
interface WalletAdapter extends EventEmitter {
publicKey: PublicKey | null;
signTransaction: (transaction: Transaction) => Promise<Transaction>;
connect: () => any;
disconnect: () => any;}
const wallet: WalletAdapter = new Wallet("https://www.sollet.io", "https://api.testnet.solana.com/");
const letsNftTrans = async () => {
const DEMO_FROM_SECRET_KEY = new Uint8Array([
223, 119, 171, 5, 237, 138, 42, 140, 176, 163, 74,
107, 25, 143, 90, 97, 250, 158, 203, 102, 238, 19,
77, 228, 211, 238, 147, 149, 40, 50, 211, 155, 51,
207, 14, 53, 86, 230, 164, 27, 14, 202, 78, 181,
185, 250, 16, 52, 134, 242, 96, 16, 12, 67, 2,
178, 106, 241, 156, 212, 11, 150, 114, 72]);
const DEMO_Keypair = Keypair.fromSecretKey(DEMO_FROM_SECRET_KEY)
let mint;
let myToken;
let toTokenAccount;
mint = await Token.createMint(Solana, DEMO_Keypair, DEMO_Keypair.publicKey, null, 9, TOKEN_PROGRAM_ID)
myToken = await mint.getOrCreateAssociatedAccountInfo(DEMO_Keypair.publicKey)
setTimeout(async function () {
mint = await Token.createMint(Solana, DEMO_Keypair, DEMO_Keypair.publicKey, null, 9, TOKEN_PROGRAM_ID)
console.log('mint public address: ' + mint.publicKey.toBase58());
myToken = await mint.getOrCreateAssociatedAccountInfo(DEMO_Keypair.publicKey)
toTokenAccount = await mint.getOrCreateAssociatedAccountInfo(wallet?.publicKey!)
mint.mintTo(myToken.address, DEMO_Keypair.publicKey,[], 1000000000);
await mint.setAuthority(mint.publicKey, null, "MintTokens", DEMO_Keypair.publicKey, [])
const mintTransaction = new Transaction().add(Token.createTransferInstruction(
TOKEN_PROGRAM_ID,
myToken.address,
toTokenAccount.address,
DEMO_Keypair.publicKey,
[],
1000000000
)
)
const signature = await sendAndConfirmTransaction(
Solana,
mintTransaction,
[DEMO_Keypair],
{commitment:"confirmed"}
)
console.log('SIGNATURE', signature)
}, 20000)}这就是错误发生的地方。
console.log('token public address : '+ myToken.address.toBase58());
toTokenAccount = await mint.getOrCreateAssociatedAccountInfo(wallet?.publicKey!)
console.log('ToTokenAccount :'+toTokenAccount)这是从Chrome控制台窗口输出的错误消息。
浏览器js:47未捕获(in promise)摘要:无法读取未定义的属性(正在读取‘TypeError’)
此外,它在本地和网络环境中的工作方式也不同。本地:http://localhost:port =>无错误。在您的网络上:http://xxx.xxx.xx.xx:port //错误。
我怎么能解决这个问题呢?
发布于 2021-09-20 14:25:08
看起来您的wallet尚未连接,这就是它没有关联publicKey的原因。
一定要连接钱包,以便真正加载一些东西!下面是在sol-wallet-adapter示例中要调用的重要函数:https://github.com/project-serum/sol-wallet-adapter/blob/be3fb1414425dc8ae64d67599d677f9acc09fe4c/example/src/App.tsx#L57
https://stackoverflow.com/questions/69189945
复制相似问题