diff --git a/ethers.nimble b/ethers.nimble index cb1f5a3..25dc9c5 100644 --- a/ethers.nimble +++ b/ethers.nimble @@ -5,6 +5,8 @@ license = "MIT" requires "chronos >= 3.0.0 & < 4.0.0" requires "contractabi >= 0.4.0 & < 0.5.0" +requires "questionable >= 0.10.2 & < 0.11.0" +requires "stew" task test, "Run the test suite": exec "nimble install -d -y" diff --git a/ethers/address.nim b/ethers/address.nim new file mode 100644 index 0000000..16322aa --- /dev/null +++ b/ethers/address.nim @@ -0,0 +1,23 @@ +import pkg/stew/byteutils +import pkg/questionable + +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/testmodule/test.nim b/testmodule/test.nim index f405430..ae6d0fc 100644 --- a/testmodule/test.nim +++ b/testmodule/test.nim @@ -1 +1,4 @@ +import ./testAddress +import ./testJsonRpcProvider + {.warning[UnusedImport]:off.} diff --git a/testmodule/testAddress.nim b/testmodule/testAddress.nim new file mode 100644 index 0000000..a3e23b5 --- /dev/null +++ b/testmodule/testAddress.nim @@ -0,0 +1,25 @@ +import std/unittest +import pkg/ethers/address +import pkg/questionable + +suite "Address": + + let address = Address.init [ + 0x1'u8, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, + 0x1 , 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa + ] + + test "can be converted to string": + check $address == "0x0102030405060708090a0102030405060708090a" + + test "can be parsed from string": + check: + Address.init("0x0102030405060708090a0102030405060708090a") == some address + + test "parsing fails when string does not contain proper hex": + check: + Address.init("0xfoo2030405060708090a0102030405060708090a") == none Address + + test "parsing fails when string does not contain 20 bytes": + check: + Address.init("0x0102030405060708090a010203040506070809") == none Address