Skip to content

Instantly share code, notes, and snippets.

@RareSkills
Created November 8, 2023 10:57
Show Gist options
  • Save RareSkills/5d60ad42cdd81b6e136605a832ba59ee to your computer and use it in GitHub Desktop.
Save RareSkills/5d60ad42cdd81b6e136605a832ba59ee to your computer and use it in GitHub Desktop.
const Web3 = require('web3');
// Initialize web3 instance
const web3 = new Web3('your rpc endpoint');
async function getNFTsOwnedByAddress(contractAddress, ownerAddress) {
// Create a new contract instance
const contract = new web3.eth.Contract([
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "address"
},
{
"indexed": true,
"name": "to",
"type": "address"
},
{
"indexed": true,
"name": "tokenId",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
}
], contractAddress);
// THESE FILTERS QUERY FROM BLOCK 0 WHICH IS NOT EFFICIENT
// Get past Transfer events for incoming transfers
const incomingEvents = await contract.getPastEvents('Transfer', {
filter: { to: ownerAddress },
fromBlock: 0,
toBlock: 'latest'
});
// Get past Transfer events for outgoing transfers
const outgoingEvents = await contract.getPastEvents('Transfer', {
filter: { from: ownerAddress },
fromBlock: 0,
toBlock: 'latest'
});
// Extract tokenIds from the events
const incomingTokenIds = new Set(incomingEvents.map(event => event.returnValues.tokenId));
const outgoingTokenIds = new Set(outgoingEvents.map(event => event.returnValues.tokenId));
// Filter out the tokens that were transferred away
const ownedTokenIds = [...incomingTokenIds].filter(tokenId => !outgoingTokenIds.has(tokenId));
return ownedTokenIds;
}
// Usage
getNFTsOwnedByAddress('YOUR_CONTRACT_ADDRESS', 'TARGET_OWNER_ADDRESS')
.then(tokenIds => console.log(tokenIds))
.catch(err => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment