nim-ethers/testmodule/testEvents.nim

79 lines
2.2 KiB
Nim
Raw Normal View History

2022-02-01 14:49:36 +00:00
import pkg/asynctest
import pkg/ethers
import pkg/contractabi
import ./examples
suite "Events":
type
SimpleEvent = object of Event
a: UInt256
b: Address
IndexedEvent = object of Event
a: UInt256
b {.indexed.}: Address
c: Address
d {.indexed.}: UInt256
ComplexIndexedEvent = object of Event
a {.indexed.}: array[42, UInt256]
b {.indexed.}: seq[UInt256]
c {.indexed.}: string
d {.indexed.}: seq[byte]
e {.indexed.}: (Address, UInt256)
proc example(_: type SimpleEvent): SimpleEvent =
SimpleEvent(
a: UInt256.example,
b: Address.example
)
proc example(_: type IndexedEvent): IndexedEvent =
IndexedEvent(
a: UInt256.example,
b: Address.example,
c: Address.example,
d: UInt256.example
)
func encode[T](_: type Topic, value: T): Topic =
let encoded = AbiEncoder.encode(value)
result[0..<Topic.len] = encoded[0..<Topic.len]
test "decodes event fields":
let event = SimpleEvent.example
let data = AbiEncoder.encode( (event.a, event.b) )
check SimpleEvent.decode(data, @[]) == success event
test "decodes indexed fields":
let event = IndexedEvent.example
var topics: seq[Topic]
topics.add Topic.default
topics.add Topic.encode(event.b)
topics.add Topic.encode(event.d)
let data = AbiEncoder.encode( (event.a, event.c) )
check IndexedEvent.decode(data, topics) == success event
test "fails when data is incomplete":
let event = SimpleEvent.example
let invalid = AbiEncoder.encode( (event.a,) )
check SimpleEvent.decode(invalid, @[]).isFailure
test "fails when topics are incomplete":
let event = IndexedEvent.example
var invalid: seq[Topic]
invalid.add Topic.default
invalid.add Topic.encode(event.b)
let data = AbiEncoder.encode( (event.a, event.c) )
check IndexedEvent.decode(data, invalid).isFailure
test "ignores indexed complex arguments":
let topics = @[
Topic.default,
Topic.example,
Topic.example,
Topic.example,
Topic.example,
Topic.example
]
check ComplexIndexedEvent.decode(@[], topics) == success ComplexIndexedEvent()