Skip to content

Commit

Permalink
fix: deserialize BlockTag from empty string (#73)
Browse files Browse the repository at this point in the history
Allows BlockTag to be deserialized from an empty string
  • Loading branch information
emizzle authored May 21, 2024
1 parent 958d7b4 commit 027b5c3
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
7 changes: 7 additions & 0 deletions ethers/blocktag.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion ethers/providers/jsonrpc/conversions.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions testmodule/providers/jsonrpc/testConversions.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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'"

0 comments on commit 027b5c3

Please sign in to comment.