Support encoding of strings

This commit is contained in:
Mark Spanbroek 2021-11-29 10:39:13 +01:00
parent abd66679ad
commit 662c0fb4b8
3 changed files with 9 additions and 0 deletions

View File

@ -4,4 +4,5 @@ description = "ABI Encoding for Ethereum contracts"
license = "MIT" license = "MIT"
requires "stint" requires "stint"
requires "stew"
requires "upraises >= 0.1.0 & < 0.2.0" requires "upraises >= 0.1.0 & < 0.2.0"

View File

@ -1,5 +1,6 @@
import pkg/stint import pkg/stint
import pkg/upraises import pkg/upraises
import pkg/stew/byteutils
export stint export stint
@ -110,6 +111,9 @@ func encode[T](encoder: var AbiEncoder, value: seq[T]) =
encoder.finishTuple() encoder.finishTuple()
encoder.setDynamic() encoder.setDynamic()
func encode(encoder: var AbiEncoder, value: string) =
encoder.encode(value.toBytes)
func write*[T](encoder: var AbiEncoder, value: T) = func write*[T](encoder: var AbiEncoder, value: T) =
var writer = AbiEncoder.init() var writer = AbiEncoder.init()
writer.encode(value) writer.encode(value)

View File

@ -1,6 +1,7 @@
import std/unittest import std/unittest
import pkg/stint import pkg/stint
import pkg/stew/byteutils
import contractabi import contractabi
import ./examples import ./examples
@ -154,5 +155,8 @@ suite "ABI encoding":
AbiEncoder.encode(32'u8) & # offset in tuple AbiEncoder.encode(32'u8) & # offset in tuple
AbiEncoder.encode(a) AbiEncoder.encode(a)
test "encodes strings as UTF-8 byte sequence":
check AbiEncoder.encode("hello!☺") == AbiEncoder.encode("hello!☺".toBytes)
# https://medium.com/b2expand/abi-encoding-explanation-4f470927092d # https://medium.com/b2expand/abi-encoding-explanation-4f470927092d
# https://docs.soliditylang.org/en/v0.8.1/abi-spec.html#formal-specification-of-the-encoding # https://docs.soliditylang.org/en/v0.8.1/abi-spec.html#formal-specification-of-the-encoding