Skip to content

Commit 027b5c3

Browse files
authored
fix: deserialize BlockTag from empty string (#73)
Allows BlockTag to be deserialized from an empty string
1 parent 958d7b4 commit 027b5c3

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

ethers/blocktag.nim

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,10 @@ func `$`*(blockTag: BlockTag): string =
3434
blockTag.stringValue
3535
of numberBlockTag:
3636
"0x" & blockTag.numberValue.toHex
37+
38+
func `==`*(a, b: BlockTag): bool =
39+
case a.kind
40+
of stringBlockTag:
41+
a.stringValue == b.stringValue
42+
of numberBlockTag:
43+
a.numberValue == b.numberValue

ethers/providers/jsonrpc/conversions.nim

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ func `%`*(tag: BlockTag): JsonNode =
7676
func fromJson*(_: type BlockTag, json: JsonNode): ?!BlockTag =
7777
expectJsonKind(BlockTag, JString, json)
7878
let jsonVal = json.getStr
79-
if jsonVal[0..1].toLowerAscii == "0x":
79+
if jsonVal.len >= 2 and jsonVal[0..1].toLowerAscii == "0x":
8080
without blkNum =? UInt256.fromHex(jsonVal).catch, error:
8181
return BlockTag.failure error.msg
8282
return success BlockTag.init(blkNum)

testmodule/providers/jsonrpc/testConversions.nim

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,14 @@ suite "JSON Conversions":
221221
"gasPrice": 0x3b9aca07.u256,
222222
"gas": 0x52277.u256
223223
}
224+
225+
test "correctly deserializes BlockTag":
226+
check !BlockTag.fromJson(newJString("earliest")) == BlockTag.earliest
227+
check !BlockTag.fromJson(newJString("latest")) == BlockTag.latest
228+
check !BlockTag.fromJson(newJString("pending")) == BlockTag.pending
229+
check !BlockTag.fromJson(newJString("0x1")) == BlockTag.init(1.u256)
230+
231+
test "fails to deserialize BlockTag from an empty string":
232+
let res = BlockTag.fromJson(newJString(""))
233+
check res.error of SerializationError
234+
check res.error.msg == "Failed to convert '\"\"' to BlockTag: must be one of 'earliest', 'latest', 'pending'"

0 commit comments

Comments
 (0)