如何从React JS访问智能合约功能



我正在制定彩票合同,但当我试图访问我的管理方法时,我在ReactJS中遇到了这个错误。[![在此处输入图像描述][1]][1]请帮我解决这个问题。我已经制定了我的合同,我在将其连接到前端时遇到了问题。

这就是错误。[1] :https://i.stack.imgur.com/QFc2o.png

App.js文件

import detectEthereumProvider from "@metamask/detect-provider";
// import { loadContract } from "./utils/LoadContracts";
import Web3 from "web3";
import lottery from "./lottery";
import {
useEffect,
useState
} from "react";
function App() {
const [balance, setBalance] = useState("");
const [changedAccount, setChangedAccount] = useState([]);
const loader = async() => {
let provider = await detectEthereumProvider();
let web3 = new Web3(provider);
return {
provider,
web3
};
};
useEffect(async() => {
let newLoad = await loader();
let account = await newLoad.web3.eth.getAccounts();
setChangedAccount(account);
}, []);
useEffect(async() => {
let newLoad = await loader();
newLoad.provider.on("accountsChanged", function(accounts) {
let newAccount = accounts;
if (newAccount) {
setChangedAccount(newAccount);
}
});
}, []);
useEffect(async() => {
let newLoad = await loader();
let accountBal =
changedAccount.length > 0 &&
(await newLoad.web3.eth.getBalance(changedAccount[0]));
setBalance(accountBal);
}, [changedAccount]);
useEffect(async() => {
let newLoad = await loader();
let account = await newLoad.web3.eth.getAccounts();
setChangedAccount(account);
const manager = await lottery.methods.manager().call();
}, []);
return ( <
div >
<
p >
Account address {
changedAccount[0]
}, Its balance is: {
balance
} <
/p> <
/div>
);
}
export default App;

lottery.js(包含ABI和合同地址(

import Web3 from "web3";
let web3 = new Web3();
const address = "0xBEbdb8eC68A5803d0f5E93bACe9EB9E4227f5A20";
const abi = [{
inputs: [],
stateMutability: "nonpayable",
type: "constructor"
},
{
inputs: [],
name: "manager",
outputs: [{
internalType: "address",
name: "",
type: "address"
}],
stateMutability: "view",
type: "function",
},
{
inputs: [{
internalType: "uint256",
name: "",
type: "uint256"
}],
name: "players",
outputs: [{
internalType: "address",
name: "",
type: "address"
}],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "enter",
outputs: [],
stateMutability: "payable",
type: "function",
},
{
inputs: [],
name: "getBalance",
outputs: [{
internalType: "uint256",
name: "",
type: "uint256"
}],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "pickWinner",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "getPlayers",
outputs: [{
internalType: "address[]",
name: "",
type: "address[]"
}],
stateMutability: "view",
type: "function",
},
];
export default new web3.eth.Contract(abi, address);

您在这一行的lottery.js中没有提供任何"provider">

let web3 = new Web3();

它没有给你正确的合同实例,因此你无法访问它的方法

相关内容

  • 没有找到相关文章

最新更新