简体   繁体   English

如何将web3.js 1.0.x连接到Metamsk

[英]How to connect web3.js 1.0.x to Metamsk

I am using web3.js 1.0.0-beta.36 to connect to the blockchain. 我正在使用web3.js 1.0.0-beta.36连接到区块链。

But unfortunately this code cannot connect to Metamask, if it has been enabled. 但是不幸的是,如果启用了此代码,则它无法连接到Metamask。

var metamask = false;
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    metamask = true; 
    web3.eth.defaultAccount = web3.eth.accounts[0];
} else {
    web3 = new Web3(new
    Web3.providers.HttpProvider(infuraUrl));
    var address = web3.eth.accounts.create().address;
}
myContract = new web3.eth.Contract(abi,contractAddress);
myContract.methods.Register((Name,Id).send({},function(error,result){
    if (! error)
        console.log(result);
    else
        console.log(error);
});

When we run this program with Metamsk it displays this error: 当我们使用Metamsk运行该程序时,它将显示以下错误:

Error: Returned error: Error: MetaMask Tx Signature: User denied transaction signature.

but when I mention a fixed address it works: 但是当我提到固定地址时,它起作用:

myContract.methods.Register((Name,Id).send({from: '0x...'},function(error,result){
        if (! error)
            console.log(result);
        else
            console.log(error);
    });

For some reasons I can't bring the address itself in the source code and I want it to get the address from Metamask. 由于某些原因,我无法将地址本身包含在源代码中,而是希望它从Metamask中获取地址。 What should I do? 我该怎么办?

Eureka!!! 尤里卡! (without special Archimedes style!) (没有特殊的阿基米德风格!)

Finally I found. 终于我找到了。

window.addEventListener('load', async () => {
    // Modern dapp browsers...
    if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        try {
            await ethereum.enable();
            var accounts= await web3.eth.getAccounts();
            var option={from: accounts[0] };
            var myContract = new web3.eth.Contract(abi,contractAddress);
            myContract.methods.RegisterInstructor('11','Ali')
            .send(option,function(error,result){
                if (! error)
                    console.log(result);
                else
                    console.log(error);
            });
        } catch (error) {
            // User denied account access...
        }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        // Acccounts always exposed
        web3.eth.sendTransaction({/* ... */});
    }
    // Non-dapp browsers...
    else {
        console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
    }
});

This connects to Metamask properly. 这将正确连接到Metamask。 Main problem was that our browsers are supermodern!!! 主要问题是我们的浏览器是超现代的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM