Skip to content

Instantly share code, notes, and snippets.

@Lebski
Created July 13, 2022 16:39
Show Gist options
  • Save Lebski/4734f45d6a7366db1b8546c604fa77cd to your computer and use it in GitHub Desktop.
Save Lebski/4734f45d6a7366db1b8546c604fa77cd to your computer and use it in GitHub Desktop.
Get Token owner with Moralis API
import fetch from 'node-fetch';
import * as fs from 'fs';
function getUriWithCursor(baseUrl, cursor) {
return baseUrl + "&cursor=" + cursor
}
async function makeMoralisRequest(url) {
try {
const config = {
method: 'GET',
headers: {
'Accept': 'application/json',
'X-API-Key': 'yOurApiKey',
},
}
const response = await fetch(url, config)
const decodedResponse = await response.json()
console.log("Got batch of", decodedResponse.page_size, "of", decodedResponse.total)
return decodedResponse
} catch (error) {
console.log("Error while trying to fetch from moralis", error)
}
}
async function getResults(tokenAddress, tokenId) {
const baseUrl = "https://deep-index.moralis.io/api/v2/nft/" + tokenAddress + "/" + tokenId + "/owners?chain=eth&format=decimal"
let all_entries = []
let response = await makeMoralisRequest(baseUrl)
let result = response.result
let cursor = response.cursor
const total = response.total
all_entries = all_entries.concat(result)
while (total > all_entries.length) {
// Timeout or rate limit from moralis
await new Promise(r => setTimeout(r, 2000));
const urlWithCursor = getUriWithCursor(baseUrl, cursor)
let response = await makeMoralisRequest(urlWithCursor)
result = response.result
cursor = response.cursor
all_entries = all_entries.concat(result)
}
return all_entries
}
async function getAddresses(tokenAddress, tokenId) {
let entries = await getResults(tokenAddress, tokenId)
let all_addresses = []
for (const entry of entries) {
const address = entry.owner_of
for (let index = 0; index < entry.amount; index++) {
all_addresses.push(address)
}
}
await fs.writeFileSync('./completeresponse.json', JSON.stringify(entries));
await fs.writeFileSync('./addresses.json', JSON.stringify(all_addresses));
console.log("Found", entries.length, "entries")
}
async function main() {
const tokenAddress = "0xdeadbeef"
const tokenId = "1"
const addresses = await getAddresses(tokenAddress, tokenId)
}
main()
@Lebski
Copy link
Author

Lebski commented Jul 13, 2022

This allows you to get all holder / owner of any ERC1155 token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment