Introduce Address type

This commit is contained in:
Mark Spanbroek 2022-01-18 11:40:07 +01:00
parent 898bf8f16f
commit fe688bde79
4 changed files with 53 additions and 0 deletions

View File

@ -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"

23
ethers/address.nim Normal file
View File

@ -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.}

View File

@ -1 +1,4 @@
import ./testAddress
import ./testJsonRpcProvider
{.warning[UnusedImport]:off.}

View File

@ -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