我写了一个智能合约(在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:本地主机: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;
答案 0 :(得分:0)
自从我将web3放在前端而不是后端之后,问题就解决了。