Bitcoin Forum
May 05, 2024, 03:22:53 AM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: code snippet: how to get NFT ownerOf  (Read 22 times)
linenoise (OP)
Sr. Member
****
Offline Offline

Activity: 304
Merit: 290


View Profile WWW
March 05, 2022, 09: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 <contract> <tokenID>

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.
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!