简体   繁体   中英

How to detect an account change in MetaMask using Meteor and web3?

I am creating a DApp using meteor in which a templateVar displays an account address.

Using a web3 function in JavaScript I defined the updateInterface() method as seen below as updateInterface()

However, since the method is a loop I can't seem to trigger the event inside Template.foo.events . The method works as I am able to alert(res) alert the result onto the screen.

Could somebody point me in the right direction? cheers

EDIT: added the template.oncreated function and also the function updateInterface() is placed outside the oncreated , helper and events methods.

Template.foo.onCreated(function fooOnCreated() {
    this.account= new ReactiveVar(0);
});

Template.foo.helpers({
    account() {
        var template = Template.instance();
        myContract = web3.eth.contract(ABIArray).at(contractAddress);

        var result = web3.eth.getCoinbase(function(err, res) {
            TemplateVar.set(template, "person", res);
        });
    },
}); 

Template.foo.events({
      // not sure what to place here
});

var account = web3.eth.accounts[0];
var accountInterval = setInterval(function() {
    if (web3.eth.accounts[0] !== account) {
        account = web3.eth.accounts[0];
        updateInterface();
    }
}, 100);

function updateInterface() {
    var template = Template.instance();
    var result = web3.eth.getCoinbase(function(err, res) {
        alert(res);
        TemplateVar.set(template, "account", res);
    });
}

The problem with events is that it requires an event, whereas the metamask detection function detects a change in account every 100 milliseconds , I am not sure where to place the updateInterface() method.

TemplateVar points here.

<head>
    <body>
        <div id="section">
            {{>foo}}
        </div>
    </body>
</head>

<template name="foo">
    <div id="location">
        <p>Currently logged in as: {{account}} {{TemplateVar.get 
           "account"}} </p>
    </div>
</template>

I think you should put the interval loop inside of the onCreated and instead of checking account !== web3.eth.accounts[0] you should check self.account.get() = web3.eth.accounts[0]

like this

Template.foo.onCreated(function fooOnCreated() {
  this.account= new ReactiveVar(0);
  this.account.set(web3.eth.accounts[0]);
  var self = this;
  var accountInterval = setInterval(function() {
    if (web3.eth.accounts[0] !== self.account.get()) {
      self.account.set(web3.eth.accounts[0]);
    }
  }, 500);
});

and because it is a ReactiveVar you don't have to call the update function. The template should update automatically as the value is used in it.

I have not tested it but I think it should work like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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