Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ParseTopicsIntoMap method for abi utilities #110

Open
ciricc opened this issue Oct 25, 2023 · 1 comment
Open

Add ParseTopicsIntoMap method for abi utilities #110

ciricc opened this issue Oct 25, 2023 · 1 comment

Comments

@ciricc
Copy link
Contributor

ciricc commented Oct 25, 2023

Now we have only one way to parse event log inputs - through ethereum's MapTopicsIntoMap function with type convertations after.
What about this?

func convertEthereumAddressToTronAddress(
	addr eCommon.Address,
) address.Address {
	addrBytes := make([]byte, 1+len(addr.Bytes()))
	copy(addrBytes[:1], []byte{address.TronBytePrefix})
	copy(addrBytes[1:], addr.Bytes())
	return addrBytes
}

func ParseTopicsIntoMap(out map[string]interface{}, values eABI.Arguments, topics [][]byte) error {
	if out == nil {
		return fmt.Errorf("out is nil")
	}

	ethTopics := make([]eCommon.Hash, len(topics))
	for i, v := range topics {
		ethTopics[i] = eCommon.Hash(v)
	}

	err := eABI.ParseTopicsIntoMap(out, values, ethTopics)
	if err != nil {
		return err
	}

	for k, v := range out {
		switch tV := v.(type) {
		case eCommon.Address:
			out[k] = convertEthereumAddressToTronAddress(tV)
		}
	}

	return nil
}
@ciricc
Copy link
Contributor Author

ciricc commented Oct 25, 2023

For the most comfortable usage, added one more function to get events parser:

func GetEventFromABI(ABI *core.SmartContract_ABI, eventName string) (*eABI.Event, error) {
	arguments, err := abi.GetInputsParser(ABI, eventName)
	if err != nil {
		return nil, err
	}

	for _, entry := range ABI.Entrys {
		if entry.Type == core.SmartContract_ABI_Entry_Event && entry.Name == eventName {
			eventParser := eABI.NewEvent(entry.Name, entry.Name, entry.Anonymous, arguments)

			return &eventParser, nil
		}
	}

	return nil, fmt.Errorf("event entry not found")
}

And usage now is:

contractAbi, err := tronNode.GetContractABI(nftContractAddress)
if err != nil {
	panic(err)
}

txInfo, err := tronNode.GetTransactionInfoByID(hex.EncodeToString(tx.Txid))
if err != nil {
	panic(err)
}

eventsParser, err := GetEventFromABI(contractAbi, "Transfer")
if err != nil {
	panic(err)
}

for _, eventLog := range txInfo.Log {
	values := map[string]interface{}{}
        // skip signature topic
	err := ParseTopicsIntoMap(values, eventsParser.Inputs, eventLog.Topics[1:])
	if err != nil {
		panic(err)
	}

	toAddress := values["to"]
	log.Println("toAddress: ", toAddress)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant