0

Disclaimer: Terrible at Javascript

I am trying to loop through events and store the block number, to and from accounts in a Javascript object. I am not sure what I am doing wrong, but it isnt working as planned. I would appreciate any pointers on this.

const Web3 = require('web3')
const web3 = new Web3(new Web3(`https://mainnet.infura.io/v3/{SOME_PROJECT_ID}}`));

var contract = new web3.eth.Contract(contractAbi, contractAddress);
var accounts = {};


// Crawl the Chain from the Contract Deployment Date till the latest block
contract.getPastEvents(
    'Transfer',
    {
      fromBlock: 8437000,
      toBlock: 'latest'
    },(error, events) => { 

    if (!error){
      var obj=JSON.parse(JSON.stringify(events));
      var array = Object.keys(obj)

    //   Looping through returned array and adding to the account{} JavaScript Object
      for (var i = 0; i < array.length; i++) {
        accounts[obj[array[i].blockNumber]] = obj[array[i]].blockNumber; 
        accounts[obj[array[i]._from]] = obj[array[i]].returnValues._from; 
        accounts[obj[array[i]._to]] = obj[array[i]].returnValues._to; 
    }
    }
    else {
      console.log(error)
}

// This prints nothing
for (var i = 0; i < accounts.length; i++) {
    console.log(accounts[i].blockNumber);
}
// The result of this is `[ [ 'undefined', '0x811573775614C5290690E9788c373111c1543D7A' ] ]` which is just one item.
console.log(Object.entries(accounts));
})

1 Answer 1

0

Change this:

for (var i = 0; i < array.length; i++) {
    accounts[obj[array[i].blockNumber]] = obj[array[i]].blockNumber; 
    accounts[obj[array[i]._from]] = obj[array[i]].returnValues._from; 
    accounts[obj[array[i]._to]] = obj[array[i]].returnValues._to; 
}

To this:

for (var i = 0; i < array.length; i++) {
    accounts[obj[array[i]] = {
        blockNumber: obj[array[i]].blockNumber,
        _from: obj[array[i]].returnValues._from,
        _to: obj[array[i]].returnValues._to
    };
}

Or better yet, to this:

for (const [key, val] of Object.entries(obj)) {
    accounts[key] = {
        blockNumber: val.blockNumber,
        _from: val.returnValues._from,
        _to: val.returnValues._to
    };
}
2
  • Thanks for this. I have gone with the second option, . I need to add a closing bracket ] to it , but now when i run the code, i get an empty bracket i.e. []
    – 0xsegfault
    Aug 28, 2019 at 18:03
  • the third option works
    – 0xsegfault
    Aug 28, 2019 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.