尝试记录 Remix 合约时旧版本的 Web3 出错

时间:2021-05-01 23:35:56

标签: web3 remix

我正在尝试从一个简单的 Remix 合同中获取记录在浏览器控制台上的详细信息。 但是,当我尝试以下 html 时,我收到一条错误消息:

<块引用>

web3.eth.contract 不是函数

查看文档,我看到了变化:

var RemixContract = web3.eth.contract([

为此:

var RemixContract = new web3.eth.Contract([

至少允许分配合约变量,但随后我无法使用 RemixContract.at 函数调用智能合约数据。 我相信这与旧的 Web3 版本有冲突,但我无法弄清楚如何将数据带入浏览器控制台。

所需的输出是:能够在浏览器控制台上看到我的合同的详细信息。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Deploy a Remix Contract</title>

    <link rel="stylesheet" type="text/css" href="main.css">
    <!--The following line contains the source of web3 in case it is not on the directory-->
    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>

<body>
    <div>
        <h1>Deploy a Remix Contract</h1>
    </div>

    <script>

        // Connect to the web3 provider
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
        }

        // Set a default account
        web3.eth.defaultAccount = web3.eth.accounts[0];

        // Get the contract abi
        // To get the contract ABI from Remix, go to the Compile tab and grab the ABI
        var RemixContract = web3.eth.contract([
    {
        "constant": false,
        "inputs": [
            {
                "name": "x",
                "type": "string"
            }
        ],
        "name": "setMessage",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "getMessage",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
]);

        // Get the contract address
        var myMessage = RemixContract.at('0xd9145CCE52D386f254917e481eB44e9943F39138')

        console.log(myMessage);

    </script>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

找到答案,我使用的是旧的 web3 语法,我应该替换它:

// Get the contract address
var RemixContract = web3.eth.contract(CONTRACT-ABI-HERE);
// Get the contract abi
var myMessage = RemixContract.at('CONTRACT ADDRESS HERE');
console.log(myMessage);

这样:

var RemixContract = new web3.eth.Contract(CONTRACT-ABI, CONTRACT ADDRESS);
console.log(RemixContract)