我正在使用本教程(https://youtu.be/Wn_Kb3MR_cU)构建一个web3应用程序。此应用程序连接到metamask,然后您可以发送以太坊并随交易附上gif。
下面是我的TransactionContext.jsx
这是控制台错误的截图
这是TransactionContext.jsx的全部代码。我尝试了几乎所有的方法,但无法解决这个错误。
import React, { useEffect, useState, } from 'react';
import { ethers } from 'ethers';
import { contractABI, contractAddress } from '../utils/constants';
export const TransactionContext = React.createContext();
const { ethereum } = window;
const getEthereumContract = () => {
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const transactionContract = new ethers.Contract(contractAddress, contractABI, signer);
return transactionContract;
}
export const TransactionProvider = ({ children }) => {
const [currentAccount, setCurrentAccount] = useState("");
const [formData, setFormData] = useState({ addressTo: '', amount: '', keyword: '', message: '' });
const [isLoading, setIsLoading] = useState(false);
const [transactionCount, setTransactionCount] = useState(localStorage.getItem('transactionCount'));
const [transactions, setTransactions] = useState([]);
const handleChange = (e, name) => {
setFormData((prevState) => ({ ...prevState, [name]: e.target.value }));
}
const getAllTransactions = async () => {
try {
if (!ethereum) return alert("Please install metamask");
const transactionContract = getEthereumContract();
const availableTransactions = await transactionContract.getAllTransactions();
const structuredTransactions = availableTransactions.map((transaction) => ({
addressTo: transaction.receiver,
addressFrom: transaction.sender,
timestamp: new Date(transaction.timestamp.toNumber() * 1000).toLocaleString(),
message: transaction.message,
keyword: transaction.keyword,
amount: parseInt(transaction.amount._hex) / (10 ** 18)
}))
setTransactions(structuredTransactions);
console.log(structuredTransactions);
} catch (error) {
console.log(error);
}
}
const checkIfWalletIsConnected = async () => {
try {
if (!ethereum) return alert("Please Install Metamask");
const accounts = await ethereum.request({ method: 'eth_accounts' });
if (accounts.length) {
setCurrentAccount(accounts[0]);
getAllTransactions();
}
else {
console.log('No accounts found');
}
} catch (error) {
console.log(error);
throw new Error("No Ethereum Object.")
}
}
const checkIfTransactionsExist = async () => {
try {
if (ethereum) {
const transactionContract = getEthereumContract();
const transactionCount = await transactionContract.getTransactionCount();
window.localStorage.setItem("transactionCount", transactionCount);
}
} catch (error) {
console.log(error);
throw new Error("No Ethereum Object.");
}
}
const connectWallet = async () => {
try {
if (!ethereum) return alert("Please Install Metamask");
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
setCurrentAccount(accounts[0]);
window.location.reload();
}
catch (error) {
console.log(error);
throw new Error("No Ethereum Object.");
}
}
const sendTransaction = async () => {
try {
if (!ethereum) return alert("Please Install Metamask");
const { addressTo, amount, keyword, message } = formData;
const transactionContract = getEthereumContract();
const parsedAmount = ethers.utils.parseEther(amount);
await ethereum.request({
method: 'eth_sendTransaction',
params: [{
from: currentAccount,
to: addressTo,
gas: '0x5208', //21000 Gwei
value: parsedAmount._hex, //0.00001
}],
});
const transactionHash = await transactionContract.addToBlockchain(addressTo, parsedAmount, message, keyword);
setIsLoading(true);
console.log(`Loading - ${transactionHash.hash}`);
await transactionHash.wait();
setIsLoading(false);
console.log(`Success - ${transactionHash.hash}`);
const transactionCount = await transactionContract.getTransactionCount();
setTransactionCount(transactionCount.toNumber());
window.location.reload();
} catch (error) {
throw new Error("Connect Wallet");
}
}
useEffect(() => {
checkIfWalletIsConnected();
checkIfTransactionsExist();
}, [transactionCount]);
return (
<TransactionContext.Provider value={{ connectWallet, currentAccount, formData, setFormData, handleChange, sendTransaction, transactions, isLoading }}>
{children}
</TransactionContext.Provider>
);
};
1条答案
按热度按时间7vux5j2d1#
你好,我有同样的错误。当我降级ethers版本时,它被修复了,如下所示:-npm uninstall ethers -npm i -S ethers@5.7.2参考:https://ethereum.stackexchange.com/questions/144315/nextjs-13-and-ethers-properties-of-undefined-reading-web3provider
祝你好运!