Last active
August 19, 2023 06:22
-
-
Save miguelmota/bc4304bb21a8f4cc0a37a0f9347b8bbb to your computer and use it in GitHub Desktop.
Golang Solidity "abi.encodePacked" example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/hex" | |
"fmt" | |
"math/big" | |
"github.com/ethereum/go-ethereum/common/math" | |
) | |
func main() { | |
// bytes32 stateRoots | |
stateRoots := "3a53dc4890241dbe03e486e785761577d1c369548f6b09aa38017828dcdf5c27" | |
// uint256[2] calldata signatures | |
signatures := []string{ | |
"3402053321874964899321528271743396700217057178612185975187363512030360053932", | |
"1235124644010117237054094970590473241953434069965207718920579820322861537001", | |
} | |
// uint256 feeReceivers, | |
feeReceivers := "0" | |
// bytes calldata txss | |
txss := "000000000000000100010000" | |
result := encodePacked( | |
encodeBytesString(stateRoots), | |
encodeUint256Array(signatures), | |
encodeUint256(feeReceivers), | |
encodeBytesString(txss), | |
) | |
got := hex.EncodeToString(result) | |
want := "3a53dc4890241dbe03e486e785761577d1c369548f6b09aa38017828dcdf5c2707857e73108d077c5b7ef89540d6493f70d940f1763a9d34c9d98418a39d28ac02bb0e4743a7d0586711ee3dd6311256579ab7abcd53c9c76f040bfde4d6d6e90000000000000000000000000000000000000000000000000000000000000000000000000000000100010000" | |
fmt.Println(got == want) // true | |
} | |
func encodePacked(input ...[]byte) []byte { | |
return bytes.Join(input, nil) | |
} | |
func encodeBytesString(v string) []byte { | |
decoded, err := hex.DecodeString(v) | |
if err != nil { | |
panic(err) | |
} | |
return decoded | |
} | |
func encodeUint256(v string) []byte { | |
bn := new(big.Int) | |
bn.SetString(v, 10) | |
return math.U256Bytes(bn) | |
} | |
func encodeUint256Array(arr []string) []byte { | |
var res [][]byte | |
for _, v := range arr { | |
b := encodeUint256(v) | |
res = append(res, b) | |
} | |
return bytes.Join(res, nil) | |
} |
manishkumar5464
commented
May 18, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment