error messages for custom errors

This commit is contained in:
Mark Spanbroek 2024-03-20 12:58:17 +01:00 committed by markspanbroek
parent 955ac2d58f
commit ce63c375f7
2 changed files with 7 additions and 4 deletions

View File

@ -27,11 +27,13 @@ func decode*[E: SolidityError](_: type E, data: seq[byte]): ?!(ref E) =
when compiles(E.arguments):
without arguments =? E.decodeArguments(data), error:
return failure "unable to decode " & $E & ": " & error.msg
success (ref E)(arguments: arguments)
let message = "EVM reverted: " & $E & $arguments
success (ref E)(msg: message, arguments: arguments)
else:
if data.len > 4:
return failure "unable to decode " & $E & ": unread trailing bytes found"
success (ref E)()
let message = "EVM reverted: " & $E & "()"
success (ref E)(msg: message)
func encode*[E: SolidityError](_: type AbiEncoder, error: ref E): seq[byte] =
result = @(E.selector.toArray)

View File

@ -1,4 +1,5 @@
import std/unittest
import std/strutils
import pkg/questionable/results
import pkg/contractabi
import pkg/ethers/errors
@ -14,7 +15,7 @@ suite "Decoding of custom errors":
let decoded = SimpleError.decode(@[0xc2'u8, 0xbb, 0x94, 0x7c])
check decoded is ?!(ref SimpleError)
check decoded.isSuccess
check (!decoded) != nil
check (!decoded).msg.contains("SimpleError()")
test "decodes error with arguments":
let expected = (ref ErrorWithArguments)(arguments: (1.u256, true))
@ -23,6 +24,7 @@ suite "Decoding of custom errors":
check decoded.isSuccess
check (!decoded).arguments.one == 1.u256
check (!decoded).arguments.two == true
check (!decoded).msg.contains("ErrorWithArguments(one: 1, two: true)")
test "returns failure when decoding fails":
let invalid = @[0xc2'u8, 0xbb, 0x94, 0x0] # last byte is wrong
@ -51,4 +53,3 @@ suite "Decoding of custom errors":
const works = compiles:
InvalidError.decode(@[0x1'u8, 0x2, 0x3, 0x4])
check not works