Skip to content

Commit c74d9fc

Browse files
encoding.nim: recover makeTypeEnum macro
1 parent dd78dee commit c74d9fc

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

web3/encoding.nim

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,65 @@ import
1111
std/macros,
1212
stint, ./eth_api_types, stew/[assign2, byteutils]
1313

14+
macro makeTypeEnum(): untyped =
15+
## This macro creates all the various types of Solidity contracts and maps
16+
## them to the type used for their encoding. It also creates an enum to
17+
## identify these types in the contract signatures, along with encoder
18+
## functions used in the generated procedures.
19+
result = newStmtList()
20+
var lastpow2: int
21+
for i in countdown(256, 8, 8):
22+
let
23+
identUint = newIdentNode("Uint" & $i)
24+
identInt = newIdentNode("Int" & $i)
25+
if ceil(log2(i.float)) == floor(log2(i.float)):
26+
lastpow2 = i
27+
if i notin [256, 125]: # Int/UInt256/128 are already defined in stint. No need to repeat.
28+
result.add quote do:
29+
type
30+
`identUint`* = StUint[`lastpow2`]
31+
`identInt`* = StInt[`lastpow2`]
32+
let
33+
identUint = ident("Uint")
34+
identInt = ident("Int")
35+
identBool = ident("Bool")
36+
result.add quote do:
37+
type
38+
`identUint`* = UInt256
39+
`identInt`* = Int256
40+
`identBool`* = distinct Int256
41+
42+
for m in countup(8, 256, 8):
43+
let
44+
identInt = ident("Int" & $m)
45+
identUint = ident("Uint" & $m)
46+
identFixed = ident "Fixed" & $m
47+
identUfixed = ident "Ufixed" & $m
48+
identT = ident "T"
49+
result.add quote do:
50+
# Fixed stuff is not actually implemented yet, these procedures don't
51+
# do what they are supposed to.
52+
type
53+
`identFixed`*[N: static[int]] = distinct `identInt`
54+
`identUfixed`*[N: static[int]] = distinct `identUint`
55+
56+
let
57+
identFixed = ident("Fixed")
58+
identUfixed = ident("Ufixed")
59+
result.add quote do:
60+
type
61+
`identFixed`* = distinct Int128
62+
`identUfixed`* = distinct UInt128
63+
for i in 1..256:
64+
let
65+
identBytes = ident("Bytes" & $i)
66+
identResult = ident "result"
67+
result.add quote do:
68+
type
69+
`identBytes`* = FixedBytes[`i`]
70+
71+
makeTypeEnum()
72+
1473
func encode*[bits: static[int]](x: StUint[bits]): seq[byte] =
1574
@(x.toByteArrayBE())
1675

0 commit comments

Comments
 (0)