Author

Topic: code snippet: how to get NFT ownerOf (Read 37 times)

sr. member
Activity: 309
Merit: 290
March 05, 2022, 04:38:54 AM
#1
Is this the right topic for a quick code example?

I had need to find ownerOf on a private Ethereum test network. The library being using was missing the call. A workaround was far less complex than fixing the library. It's a quick hack but it may help others in the same situation. Plenty of other examples were found to modify to get here, thanks other random devs.
 
Needs - geth

First, you need to define an ABI. The Ethereum Application Binary Interface (ABI) lets you specify how to interact with a contract and return data in a format you’re expecting. I only care about ownerOf.

Add a new file, ownerof.abi :

Code:
abi = [{ "constant":true,"inputs":[{"name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"name":"owner","type"
:"address"}], "type":"function" }]

Then a quick script with two passed arguments the NFT contract address and the tokenID of the NFT you are querying for ownership: NFTcheck.sh

Code:
!/bin/sh
/home/geth/geth -attach << EOF | grep "ADDRESS:" | sed "s/ADDRESS: //"
loadScript("/home/geth/ownerof.abi");
caddr = "$1";
c = web3.eth.contract(abi).at(caddr);
d = c.ownerOf.getData($2);
var addy = web3.eth.call({to: caddr, data: d});
console.log("ADDRESS: " + addy);
EOF

Then run this command like so ./NFTcheck.sh

You can run the script from any other language/script, for example PHP would use exec().

Note, the address returned is a byte32 and all lower case. You will need to slice the last 40 characters and use a checksum address to get the proper upper and lowercase of the actual address. For comparison against a known address it works fine.

The web3 that comes with geth is 0.20.1 so you can't use toChecksumAddress() on the return.


If there are better ways feel free to post.
Jump to: