fix: deserialize BlockTag from empty string (#73)

Allows BlockTag to be deserialized from an empty string
This commit is contained in:
Eric 2024-05-21 13:10:06 +10:00 committed by GitHub
parent 958d7b45d1
commit 027b5c37ad
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 19 additions and 1 deletions

View File

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

View File

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

View File

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