Metamask
Web3 的 Transfer() 方法我得到錯誤並且沒有傳輸
我試著在we3上做一個按鈕,點擊它,傳輸方法應該在5分鐘後開始。當我首先點擊我的按鈕時,元遮罩顯示給我這個
我的堅固程式碼:
address payable public tenant = payable(0x6eC9Ce7Db83035a69e60d2407e5d5fcc1e6411A6); address payable public landlord = payable(0x16125Aa47cc309988Cf774d8001b614527203A4E); uint256 public lastRun; function myFunction() payable public { require(block.timestamp - lastRun > 5 minutes, 'Need to wait 5 minutes'); //require(msg.value == rent, "Please pay the proper rent."); landlord.transfer(1); lastRun = block.timestamp; }
我的 App.js 程式碼:
import React, { Component } from 'react'; import detectEthereumProvider from '@metamask/detect-provider'; import Web3 from 'web3'; import './App.css'; import { useEffect } from 'react'; import { useState } from 'react'; function App() { const [web3Api,setWeb3Api]= useState({ provider:null, web3:null, }) useEffect( ()=>{ const loadProvider = async()=>{ const provider = await detectEthereumProvider(); if(provider){ setWeb3Api({ provider, web3:new Web3(provider) }) console.log(provider); } else { window.alert("Please install Metamask"); } } loadProvider()},[]) const [account, setAccount] = useState(null) useEffect( ()=>{ const loadAccounts = async ()=>{ const accounts = await web3Api.web3.eth.getAccounts() console.log(accounts); setAccount(accounts[0]) } web3Api.web3 && loadAccounts() },[web3Api.web3]) //Load Contract const [contract, setContract] = useState() useEffect(()=>{ const loadContract = async()=>{ const contractFile = await fetch('/abis/Properties.json'); const convertTpJson = await contractFile.json(); //Find the abi const abi = convertTpJson.abi; const networkId = await web3Api.web3.eth.net.getId(); const contractAddress = convertTpJson.networks[networkId].address; const depolyedContract = await new web3Api.web3.eth.Contract(abi, contractAddress); setContract(depolyedContract) console.log(depolyedContract.methods); } web3Api.web3 && loadContract(); },[web3Api.web3]) const sendTx = async() => { await contract.methods.myFunction().send({from:account}); }; setInterval('sendTx', 5 * 1000 * 60); return ( <div className="App"> <button onClick={sendTx}>Click Here</button> </div> ); } export default App;
該錯誤消息通常是由未預期的輸出引起的。例如,如果它期望一個“uint”,但契約會恢復。可能的原因是地址無效、abi 無效、功能恢復
查看
myFunction
可能的原因是require
條件失敗:
require(block.timestamp - lastRun > 5 minutes, 'Need to wait 5 minutes')
上一次執行後至少需要 5 分鐘landlord.transfer(1)
至少需要 1 wei,並且房東地址能夠接收乙太幣(非合約地址,或具有receive
功能的合約)。該
sendTx
函式不發送任何金額,因此如果合約餘額為零,則轉賬將失敗。如果您想要函式呼叫的金額,則必須使用參數value
。例如:await contract.methods.myFunction().send({ from: account, value: "1000", });