Ethereum Engineering: What Tokens does an address own?
One of the more annoying things for newcomers to blockchain is trying to figure out who owns what on the contract. It isn’t exactly straight-forward to figure out as there’s many rabbit holes you can go down largely due to Javascript and the data structures of the RPC being shit.
Let’s look at this Contract.js file
const Web3 = require('web3');
const web3 = new Web3('https://rinkeby.infura.io/v3/<your project>');
let abi = require('./../../config/abi.js');
let contract = new web3.eth.Contract(abi, '0x231ca81721b83353ac4002c10c2d62fcfb7b7272');
let c = {
async getTokens(toAddr) {
let store = {};
let incomingTokenTransferEvents = await contract.getPastEvents('Transfer', {
filter: {'to': toAddr},
fromBlock: 0,
toBlock: 'latest'
});
incomingTokenTransferEvents.forEach((event) => {
if (undefined === store[event.returnValues.tokenId]) {
store[event.returnValues.tokenId] = 0;
}
store[event.returnValues.tokenId]++;
});
let outgoingTokenTransferEvents = await contract.getPastEvents('Transfer', {
filter: {'from': toAddr},
fromBlock: 0,
toBlock: 'latest'
});
outgoingTokenTransferEvents.forEach((event) => {
// console.log(event.returnValues.tokenId);
store[event.returnValues.tokenId]--;
});
return Object.keys(store);
}
}
module.exports = c;
Quick Explainer:
Add your Infuria project key
Configure your ABI.json
Give the function a Ethereum address
Get a list of tokens and the current “number” of tokens (1 for owned, 0 for owned but sold)
How it works
It works like a bank ledger. Transfer Ins minus Transfer Outs. If a person “mints” the token, the originating address will be the null address in the transfer in event; otherwise it’s another Ethereum account. A transfer event has a source and destination and that is how we count the NFTs.
Please subscribe now for more Blockchain Programming Content