用HTML去测试部署好的web3 helloworld

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web3.js Example</title>
    <script src="https://cdn.jsdelivr.net/npm/web3@1.3.6/dist/web3.min.js"></script>
</head>

<body>
    <h1>Web3.js Example</h1>
    <p id="result"></p>

    <script>
        
        const API_URL = 'https://sepolia.infura.io/v3/写你自己的地址';
         // 合约地址
        const contractAddress = '写你合约部署后生成的提示里contract adress后面的内容'; // 替换为您的智能合约地址
        // 初始化Web3
        if (typeof web3 !== 'undefined') {
            var web3 = new Web3(web3.currentProvider);
        } else {
            // 如果没有安装MetaMask或其他钱包,这里将无法连接到以太坊网络
            var web3 = new Web3(new Web3.providers.HttpProvider(API_URL));
        }

        // 合约地址和ABI   我的ABI就是一个sayHello函数 ,这个是合约编译后生成的json文件中截取的
        const abi = [
            {
                "inputs": [],
                "name": "sayHello",
                "outputs": [
                    {
                        "internalType": "string",
                        "name": "",
                        "type": "string"
                    }
                ],
                "stateMutability": "pure",
                "type": "function",
                "constant": true
            }
        ];

       


        // 创建合约实例
        var contract = new web3.eth.Contract(abi, contractAddress);

        // 调用合约的只读函数
        contract.methods.sayHello().call()
            .then(function (result) {
                document.getElementById('result').innerText = result;
            })
            .catch(function (error) {
                console.error(error);
            });
    </script>
</body>

</html>

上面是我的测试代码,需要改动的有4点

  1. 你的应用地址API_URL,到infura网站上去查
  2. contract adress 合约地址,truffle部署成功后,会有提示,提示里包含了这个信息,一定要存好。
  3. abi 是你的合约代码编译后生成的build/contracts/YourSol.json文件里的一部分,直接打开拷贝。譬如我的合约是HelloWorld,文件就是HelloWorld.json
  4. 我的函数是sayHello你的不一定是,看需求改
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容