0

I currently use the code below to extract the ERC721 Token ID from Transfer Event Logs:

txHash := newLog.TxHash.Hex()
hexString := common.BytesToAddress(newLog.Topics[3].Bytes()).Hex()
flowerNum, _ := strconv.ParseUint(hexString, 0, 10)
flowerNumInt := int64(flowerNum)

flowerNumInt is 1023, even though txHash linked below references FLOWER #1133. Moreso, FLOWER #1023 has no transfer events at all, and does not appear in the tx linked below.

https://etherscan.io/tx/0xe330601b05c54116da3b06dd17cf483ab3106fb969989458c8587aac1c34fbf3

Am I doing something wrong during the conversion?

  • 1
    in the tx logs i see 0x000000000000000000000000000000000000000000000000000000000000046d which is 1133. not sure why you're converting the topic bytes to a common.Address type. Just convert it to a big.Int – Miguel Mota Feb 27 at 20:52
1

Here's a full example of decoding the log topic to get the value (in your case the ID as an uint64):

package main

import (
    "context"
    "fmt"
    "log"
    "math/big"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://mainnet.infura.io")
    if err != nil {
        log.Fatal(err)
    }

    txID := common.HexToHash("0xe330601b05c54116da3b06dd17cf483ab3106fb969989458c8587aac1c34fbf3")
    receipt, err := client.TransactionReceipt(context.Background(), txID)
    if err != nil {
        log.Fatal(err)
    }

    logID := "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
    for _, vLog := range receipt.Logs {
        if vLog.Topics[0].Hex() == logID {
            if len(vLog.Topics) > 2 {
                id := new(big.Int)
                id.SetBytes(vLog.Topics[3].Bytes())

                fmt.Println(id.Uint64()) // 1133
            }
        }
    }
}
  • Thanks for the detailed example, this definitely seems like the idiomatic way to do it -- I also realized the error in my code: I'm parsing the hex string incorrectly: flowerNum, _ := strconv.ParseUint(hexString, 0, 10) should be flowerNum, _ := strconv.ParseUint(hexString, 0, 64) – P A S H Feb 28 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.