2

How to implement the below solidity code in golang? especially the abi.encode function?

abi.encode(
    keccak256("delegate(address sender,string amount, string to)"),
    sender,
    amount,
    to
)

2 Answers 2

2
+25

You can make the similar encoding go-ethereum package.

  1. Load the abi file as abi.ABI object:
    abiObject, err := abi.JSON(strings.NewReader("pathToAbiFile"))
    if err != nil {
        return nil, err
    }
  1. Use the pack method of encode them as functioncall:
    pack, err := abiObject.Pack("delegate", sender, amount, to)
        if err != nil {
            return nil, err
        }

ensure that all params being passed are valid go types before being packed.

1

To implement the equivalent of the provided Solidity code in Go, you'll need to use the Ethereum ABI encoding logic. The abi.encode function in Solidity is used for ABI encoding, and in Go, you can use the ethereum/go-ethereum package to achieve the same result

package main

import (
    "fmt"
    "log"
    "strings"

    "github.com/ethereum/go-ethereum/accounts/abi"
    "github.com/ethereum/go-ethereum/crypto"
)

func main() {
    // Replace these values with your actual values
    sender := "0x1234567890123456789012345678901234567890"
    amount := "100"
    to := "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef"

    // Define the function signature using keccak256
    keccak := crypto.Keccak256([]byte("delegate(address,string,string)"))

    // Create an ABI packer
    packer, err := abi.JSONPacker(abi.JSONVersionLatest)
    if err != nil {
        log.Fatal(err)
    }

    // Encode the parameters using the ABI packer
    encodedData, err := packer.Pack(
        "delegate",
        sender,
        amount,
        to,
    )
    if err != nil {
        log.Fatal(err)
    }

    // Concatenate the function signature and encoded data
    finalData := append(keccak[:4], encodedData...)

    // Print the result as a hexadecimal string
    resultHex := fmt.Sprintf("0x%s", strings.ToLower(fmt.Sprintf("%x", finalData)))
    fmt.Println(resultHex)
}

Make sure to replace the placeholder values for sender, amount, and to with your actual values. The example code uses the ethereum/go-ethereum package to perform ABI encoding, and it concatenates the function signature and encoded data to produce the final result

For ethereum/go-ethereum Install go get for dependencies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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