You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

window.web3.eth.Contract无法使用,如何替换代码连接合约?

解决方案:用Web3.js结合MetaMask Provider实例化合约

你已经通过CDN引入了最新版Web3.js,只需要先以window.ethereum为Provider初始化Web3实例,再用该实例创建合约对象即可,具体修改如下:

关键修改点

  • 先初始化Web3实例(使用MetaMask提供的window.ethereum作为Provider)
  • 用初始化后的Web3实例创建合约(无需await,合约实例化为同步操作)
  • 注意:如果你的ABI是字符串格式,需要先解析为JSON对象

修改后的完整代码

var account = null;
var contract = null;
// 若ABI为字符串格式,需转为JSON对象,示例:
// const ABI = JSON.parse("your abi string here");
const ABI = "the abi is here"
const ADDRESS = "contract address is here";

async function asyncCall() {
    console.log('async');
    if (window.ethereum) {
      try {
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        account = accounts[0];
        document.getElementById('wallet-address').textContent = account;
        
        // --- 修改部分开始 ---
        // 初始化Web3实例,传入MetaMask的provider
        const web3 = new Web3(window.ethereum);
        // 创建合约实例
        contract = new web3.eth.Contract(ABI, ADDRESS);
        // --- 修改部分结束 ---
        
        var mintButton = document.getElementById('mint');

        mintButton.addEventListener("click", function(){
            console.log('minting');
            // 注意:value字段若为ETH需转为wei,示例:web3.utils.toWei("0.01", "ether")
            contract.methods.mint(account).send({from: account, value: "100"})
                .on('transactionHash', (hash) => console.log('交易哈希:', hash))
                .on('error', (err) => console.error('交易失败:', err));
        });
         
        var totalsupply = await contract.methods.totalsupply().call();
        document.getElementById('ttt').textContent = totalsupply;
      } catch (error) {
        if (error.code === 4001) {
            console.log('用户拒绝了请求');
        }
        console.log(error);
      }
    }
}

asyncCall();

补充说明

  • MetaMask目前不再自动注入window.web3,必须手动用引入的Web3.js库结合window.ethereum初始化Web3实例
  • 调用合约方法时,需确保:
    • ABI格式正确(已解析为JSON对象)
    • value字段单位匹配(ETH需转成wei)
    • 用户钱包的链ID与合约部署链ID一致

内容的提问来源于stack exchange,提问作者David Coleman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:01:01