如何将MetaMask与Web3.js 1.2.6版连接?

问题描述 投票:0回答:1

我写了一个智能合约(部署在Ropsten上)和一个网站(node.js,express.js和ejs)

我可以使用Infura API从合同中读取数据,并成功显示在网页上。但是,我想通过Metamask在合同上写数据。目前。我无法将MetaMask与web3.js 1.2.6连接。我已经检查过Web3.givenProvider还返回null。

((我可以通过MyEtherWallet + Meta Mask与我的智能合约进行交互)

详细信息:

开发环境:node.js express.js ejs web3.js(1.2.6)

浏览器:chrome + MetaMask:localhost:3000 / 127.0.0.1:3000

const express = require('express');
const router = express.Router();

const Web3 = require('web3');
//const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/xxxxxxxx"));
const web3 = new Web3(Web3.givenProvider);

const Tx = require('ethereumjs-tx');

let myAddress = '0x3E0980E7cea6804B01BEA49cb70F9B7Cxxxxxxxx';
const abi = [***VERY LONG ABI***];
const address = "0x07cf2ecef130495ea18a25e4f1dfbfc4xxxxxxxx";
const MyContract = new web3.eth.Contract(abi, address);

// define the home page route
router.get('/', (req, res, next) => {
    const resultHome = [];

    MyContract.methods.name().call().then((name) => {
        resultHome.push(name);
        symbol();
    })
    const symbol = () => {
        MyContract.methods.symbol().call().then((symbol) => {
            resultHome.push(symbol);
            totalSupply();
        })
    }
    const totalSupply = () => {
        MyContract.methods.totalSupply().call().then((totalSupply) => {
            resultHome.push(totalSupply);
            home();
        })
    }

    const home = () => {
        res.render('erc20/index', {
            pageTitle: 'ERC-20E Token Standard Enhanced - Info',
            path: 'erc20',
            subPath: 'erc20Info',
            name: resultHome[0],
            symbol: resultHome[1],
            address: address,
            totalSupply: resultHome[2] / 100
        })
    }
})

router.get('/source', (req, res, next) => {
    res.sendFile(__dirname + '/erc20Source.txt');
})

// define the controller route
router.get('/controller', (req, res, next) => {
    let resultController = [];

    MyContract.methods.showRun().call().then((showRun) => {
        resultController.push(showRun);
        controller();
    })

    const controller = () => {
        res.render('erc20/controller', {
            pageTitle: 'ERC-20E Token Standard Enhanced - Controller',
            path: 'erc20',
            subPath: 'erc20Controller',
            showRun: resultController[0]
        })
    }
})

module.exports = router;
node.js express web3 web3js metamask
1个回答
0
投票

自从我将web3放在前端而不是后端后,问题就解决了。

© www.soinside.com 2019 - 2024. All rights reserved.