github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/encoding/web3hex/encoder.go (about) 1 package web3hex 2 3 import ( 4 bin "encoding/binary" 5 "math/big" 6 "strings" 7 8 "github.com/hyperledger/burrow/crypto" 9 "github.com/tmthrgd/go-hex" 10 ) 11 12 type encoder struct { 13 } 14 15 var Encoder = new(encoder) 16 17 func (e *encoder) Bytes(bs []byte) string { 18 return "0x" + hex.EncodeToString(bs) 19 } 20 21 func (e *encoder) BytesTrim(bs []byte) string { 22 if len(bs) == 0 { 23 return "" 24 } 25 str := hex.EncodeToString(bs) 26 // Ethereum expects leading zeros to be removed from RLP encodings (SMH) 27 str = strings.TrimLeft(str, "0") 28 if len(str) == 0 { 29 // Special case for zero 30 return "0x0" 31 } 32 return "0x" + str 33 } 34 35 func (e *encoder) BigInt(x *big.Int) string { 36 return e.BytesTrim(x.Bytes()) 37 } 38 39 func (e *encoder) Uint64OmitEmpty(x uint64) string { 40 if x == 0 { 41 return "" 42 } 43 return e.Uint64(x) 44 } 45 46 func (e *encoder) Uint64(x uint64) string { 47 bs := make([]byte, 8) 48 bin.BigEndian.PutUint64(bs, x) 49 return e.BytesTrim(bs) 50 } 51 52 func (e *encoder) Address(address crypto.Address) string { 53 return e.BytesTrim(address.Bytes()) 54 }