Calculate Event topic

This commit is contained in:
Mark Spanbroek 2022-02-02 11:51:30 +01:00
parent a2b8daa320
commit 0c3dca0aa1
2 changed files with 16 additions and 3 deletions

View File

@ -8,12 +8,16 @@ export address
export stint export stint
type FunctionSelector* = distinct array[4, byte] type FunctionSelector* = distinct array[4, byte]
type EventTopic* = distinct array[32, byte]
proc toArray*(selector: FunctionSelector): array[4, byte] = proc toArray*(selector: FunctionSelector): array[4, byte] =
array[4, byte](selector) array[4, byte](selector)
proc `$`*(selector: FunctionSelector): string = proc toArray*(topic: EventTopic): array[32, byte] =
"0x" & selector.toArray.toHex array[32, byte](topic)
proc `$`*(value: FunctionSelector | EventTopic): string =
"0x" & value.toArray.toHex
template solidityType(T: type, s: string) = template solidityType(T: type, s: string) =
func solidityType*(_: type T): string = s func solidityType*(_: type T): string = s
@ -64,3 +68,6 @@ func selector*(function: string, parameters: type tuple): FunctionSelector =
var selector: array[4, byte] var selector: array[4, byte]
selector[0..<4] = hash[0..<4] selector[0..<4] = hash[0..<4]
FunctionSelector(selector) FunctionSelector(selector)
func topic*(event: string, parameters: type tuple): EventTopic =
EventTopic(hash(signature(event, parameters)))

View File

@ -1,5 +1,6 @@
import std/unittest import std/unittest
import pkg/contractabi/selector import pkg/stew/byteutils
import pkg/contractabi
suite "function selector": suite "function selector":
@ -29,3 +30,8 @@ suite "function selector":
test "calculates solidity function selector": test "calculates solidity function selector":
check $selector("transfer", (Address, UInt256)) == "0xa9059cbb" check $selector("transfer", (Address, UInt256)) == "0xa9059cbb"
check $selector("transferFrom", (Address, Address, UInt256)) == "0x23b872dd" check $selector("transferFrom", (Address, Address, UInt256)) == "0x23b872dd"
test "calculates solidity event topic":
let expected = "0xddf252ad1be2c89b69c2b068fc378daa" &
"952ba7f163c4a11628f55a4df523b3ef"
check $topic("Transfer", (Address, Address, UInt256)) == expected