From 027b5c37ad71a68c9f6aef389e1adf804955114c Mon Sep 17 00:00:00 2001 From: Eric <5089238+emizzle@users.noreply.github.com> Date: Tue, 21 May 2024 13:10:06 +1000 Subject: [PATCH] fix: deserialize BlockTag from empty string (#73) Allows BlockTag to be deserialized from an empty string --- ethers/blocktag.nim | 7 +++++++ ethers/providers/jsonrpc/conversions.nim | 2 +- testmodule/providers/jsonrpc/testConversions.nim | 11 +++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/ethers/blocktag.nim b/ethers/blocktag.nim index b3b7b7b..0de99c9 100644 --- a/ethers/blocktag.nim +++ b/ethers/blocktag.nim @@ -34,3 +34,10 @@ func `$`*(blockTag: BlockTag): string = blockTag.stringValue of numberBlockTag: "0x" & blockTag.numberValue.toHex + +func `==`*(a, b: BlockTag): bool = + case a.kind + of stringBlockTag: + a.stringValue == b.stringValue + of numberBlockTag: + a.numberValue == b.numberValue diff --git a/ethers/providers/jsonrpc/conversions.nim b/ethers/providers/jsonrpc/conversions.nim index f23de01..f1476fb 100644 --- a/ethers/providers/jsonrpc/conversions.nim +++ b/ethers/providers/jsonrpc/conversions.nim @@ -76,7 +76,7 @@ func `%`*(tag: BlockTag): JsonNode = func fromJson*(_: type BlockTag, json: JsonNode): ?!BlockTag = expectJsonKind(BlockTag, JString, json) let jsonVal = json.getStr - if jsonVal[0..1].toLowerAscii == "0x": + if jsonVal.len >= 2 and jsonVal[0..1].toLowerAscii == "0x": without blkNum =? UInt256.fromHex(jsonVal).catch, error: return BlockTag.failure error.msg return success BlockTag.init(blkNum) diff --git a/testmodule/providers/jsonrpc/testConversions.nim b/testmodule/providers/jsonrpc/testConversions.nim index 4e66491..6017e04 100644 --- a/testmodule/providers/jsonrpc/testConversions.nim +++ b/testmodule/providers/jsonrpc/testConversions.nim @@ -221,3 +221,14 @@ suite "JSON Conversions": "gasPrice": 0x3b9aca07.u256, "gas": 0x52277.u256 } + + test "correctly deserializes BlockTag": + check !BlockTag.fromJson(newJString("earliest")) == BlockTag.earliest + check !BlockTag.fromJson(newJString("latest")) == BlockTag.latest + check !BlockTag.fromJson(newJString("pending")) == BlockTag.pending + check !BlockTag.fromJson(newJString("0x1")) == BlockTag.init(1.u256) + + test "fails to deserialize BlockTag from an empty string": + let res = BlockTag.fromJson(newJString("")) + check res.error of SerializationError + check res.error.msg == "Failed to convert '\"\"' to BlockTag: must be one of 'earliest', 'latest', 'pending'"