From 987d6f40282862fbf9af22269e70b820240a7e08 Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Wed, 1 Dec 2021 17:26:35 +0100 Subject: [PATCH] Fail gracefully when decoding enum fails --- contractabi/decoding.nim | 6 +++++- tests/contractabi/testDecoding.nim | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/contractabi/decoding.nim b/contractabi/decoding.nim index bc1a234..e4a6651 100644 --- a/contractabi/decoding.nim +++ b/contractabi/decoding.nim @@ -94,7 +94,11 @@ func decode(decoder: var AbiDecoder, T: type bool): ?!T = else: failure "invalid boolean value" func decode(decoder: var AbiDecoder, T: type enum): ?!T = - success T(?decoder.read(uint64)) + let value = ?decoder.read(uint64) + if value in T.low.uint64..T.high.uint64: + success T(value) + else: + failure "invalid enum value" func decode[I](decoder: var AbiDecoder, T: type array[I, byte]): ?!T = var arr: T diff --git a/tests/contractabi/testDecoding.nim b/tests/contractabi/testDecoding.nim index 1ba9dbd..916479f 100644 --- a/tests/contractabi/testDecoding.nim +++ b/tests/contractabi/testDecoding.nim @@ -65,7 +65,12 @@ suite "ABI decoding": checkDecode(one) checkDecode(two) - # TODO: failure to decode when invalid enum value + test "fails to decode enum when encountering invalid value": + type SomeEnum = enum + one = 1 + two = 2 + let encoded = AbiEncoder.encode(3'u8) + check AbiDecoder.decode(encoded, SomeEnum).error.msg == "invalid enum value" test "decodes stints": checkDecode(UInt128)