我已经使用 Remix 部署了这个简单的智能合约
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract Counter {
uint256 private count = 0;
function setCount(uint256 val) external payable {
count = val;
}
function viewCount() external view returns (uint256) {
return count;
}
}
我使用 evm 版本部署了此合约:paris。代码已成功部署并且在 Remix IDE 上运行良好。
我正在尝试在我的下一个应用程序中使用 web3.js 进行交互,使用 metamask 的方式如下
const loadWeb3 = async () => {
if (window.ethereum) {
const web = new Web3(window.ethereum);
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
console.log("Accounts requested from MetaMask RPC: ", accounts);
try {
const contract = new web.eth.Contract(abi,contract-address);
const transactionReceipt = await contract.methods
.setCount(10)
.send({ from: accounts[0], gas: 3000000 });
console.log(transaction);
} catch (err) {
console.log(`error: ${err}`);
}
} else {
console.log("Please install metamask");
}
};
我原以为交易会成功,但我在交易收据中收到了此消息
error: TransactionRevertedWithoutReasonError: Transaction has been reverted by the EVM:
{"blockHash":"0x6138b0cdd3a047486419f066ef056aab7b28c11bbaea82b5812c095f96cf86c7","blockNumber":"1382940","cumulativeGasUsed":"21046","from":"0x9ded1ae475bd50a15dde12bbc34b7ea04969cd0b","gasUsed":"21046","logs":[],"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","status":"0","to":"0xb69254cc37d818fdbcff6501acff400913147c1c","transactionHash":"0x6d3a2d51bae3746069db1cc778b357b92a6348a37d157181943c894cfbfc0d76","transactionIndex":"1"}
无法弄清楚为什么会发生此错误。
经过3个小时的探索,我似乎找到了答案。当尝试以以下方式执行代码时,代码按预期运行 -
const contract = new web.eth.Contract(ABI, address);
const gasEstimate = await contract.methods
.setCount("10")
.estimateGas({ from: accounts[0] });
console.log(gasEstimate);
const encode = await contract.methods.setCount(10).encodeABI();
const tx = await web.eth.sendTransaction({
from: accounts[0],
to: address,
gas: gasEstimate,
data: encode,
});
使用此方法执行交易时获得所需的输出。