From e3c9aa436867b02e66f81c52c7dabc913ce74b52 Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Wed, 19 Jan 2022 09:16:22 +0100 Subject: [PATCH] Add support for Ethereum addresses --- contractabi/address.nim | 26 ++++++++++++++++++++++++++ contractabi/decoding.nim | 9 +++++++++ contractabi/encoding.nim | 5 +++++ tests/contractabi/examples.nim | 4 ++++ tests/contractabi/testAddress.nim | 25 +++++++++++++++++++++++++ tests/contractabi/testDecoding.nim | 3 +++ tests/contractabi/testEncoding.nim | 4 ++++ tests/testAll.nim | 1 + 8 files changed, 77 insertions(+) create mode 100644 contractabi/address.nim create mode 100644 tests/contractabi/testAddress.nim diff --git a/contractabi/address.nim b/contractabi/address.nim new file mode 100644 index 0000000..30fb6f6 --- /dev/null +++ b/contractabi/address.nim @@ -0,0 +1,26 @@ +import pkg/stew/byteutils +import pkg/questionable +import pkg/upraises + +push: {.upraises: [].} + +type + Address* = distinct array[20, byte] + +func init*(_: type Address, bytes: array[20, byte]): Address = + Address(bytes) + +func init*(_: type Address, hex: string): ?Address = + try: + let bytes = array[20, byte].fromHex(hex) + some Address.init(bytes) + except ValueError: + none Address + +func toArray*(address: Address): array[20, byte] = + array[20, byte](address) + +func `$`*(address: Address): string = + "0x" & toHex(address.toArray) + +func `==`*(a, b: Address): bool {.borrow.} diff --git a/contractabi/decoding.nim b/contractabi/decoding.nim index f4123b3..ba4375c 100644 --- a/contractabi/decoding.nim +++ b/contractabi/decoding.nim @@ -5,6 +5,10 @@ import pkg/questionable/results import pkg/upraises import ./encoding import ./integers +import ./address + +export stint +export address push: {.upraises:[].} @@ -114,6 +118,11 @@ func decode(decoder: var AbiDecoder, T: type enum): ?!T = else: failure "invalid enum value" +func decode(decoder: var AbiDecoder, T: type Address): ?!T = + var bytes: array[20, byte] + bytes[0..<20] =(?decoder.read(20))[0..<20] + success T.init(bytes) + func decode[I](decoder: var AbiDecoder, T: type array[I, byte]): ?!T = var arr: T arr[0..