Skip to content

Commit b32602e

Browse files
Create some ethereum types
1 parent 7676581 commit b32602e

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

web3/encoding.nim

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

14+
func encode*(x: EthereumUint32): seq[byte] =
15+
let numTargetBytes = 32 div 8
16+
let paddingBytes = 32 - numTargetBytes
17+
## the Ethereum ABI imposes a 32 byte width for every type
18+
let paddingZeros = newSeq[byte](paddingBytes)
19+
let ret = paddingZeros & @(x.toByteArrayBE())
20+
let retHex = ret.toHex()
21+
ret
22+
1423
func encode*[bits: static[int]](x: StUint[bits]): seq[byte] =
1524
@(x.toBytesBE())
1625

web3/eth_api_types.nim

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
{.push raises: [].}
1111

1212
import
13+
std/[macros, math],
1314
stint,
1415
./primitives
1516

@@ -299,6 +300,37 @@ func payload*(args: TransactionArgs): seq[byte] =
299300
func isEIP4844*(args: TransactionArgs): bool =
300301
args.maxFeePerBlobGas.isSome or args.blobVersionedHashes.isSome
301302

303+
macro makeEthereumTypeEnum(): untyped =
304+
## This macro creates all the various types of Solidity contracts and maps
305+
## them to the type used for their encoding. It also creates an enum to
306+
## identify these types in the contract signatures, along with encoder
307+
## functions used in the generated procedures.
308+
result = newStmtList()
309+
var lastpow2: int
310+
for i in countdown(256, 8, 8):
311+
let
312+
identUint = newIdentNode("EthereumUint" & $i)
313+
identInt = newIdentNode("EthereumInt" & $i)
314+
if ceil(log2(i.float)) == floor(log2(i.float)):
315+
lastpow2 = i
316+
317+
result.add quote do:
318+
type
319+
`identUint`* = StUint[`lastpow2`]
320+
`identInt`* = StInt[`lastpow2`]
321+
322+
let
323+
identUint = ident("EthereumUint")
324+
identInt = ident("EthereumInt")
325+
identBool = ident("EthereumBool")
326+
result.add quote do:
327+
type
328+
`identUint`* = UInt256
329+
`identInt`* = Int256
330+
`identBool`* = distinct Int256
331+
332+
makeEthereumTypeEnum()
333+
302334
# Backwards compatibility
303335

304336
type

0 commit comments

Comments
 (0)