Introduce Address type
This commit is contained in:
parent
898bf8f16f
commit
fe688bde79
|
@ -5,6 +5,8 @@ license = "MIT"
|
||||||
|
|
||||||
requires "chronos >= 3.0.0 & < 4.0.0"
|
requires "chronos >= 3.0.0 & < 4.0.0"
|
||||||
requires "contractabi >= 0.4.0 & < 0.5.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":
|
task test, "Run the test suite":
|
||||||
exec "nimble install -d -y"
|
exec "nimble install -d -y"
|
||||||
|
|
|
@ -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.}
|
|
@ -1 +1,4 @@
|
||||||
|
import ./testAddress
|
||||||
|
import ./testJsonRpcProvider
|
||||||
|
|
||||||
{.warning[UnusedImport]:off.}
|
{.warning[UnusedImport]:off.}
|
||||||
|
|
|
@ -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
|
Loading…
Reference in New Issue