Skip to content

Commit

Permalink
Create some ethereum types
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivansete-status committed Jan 20, 2025
1 parent 7676581 commit b32602e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
9 changes: 9 additions & 0 deletions web3/encoding.nim
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ import
std/macros,
stint, ./eth_api_types, stew/[assign2, byteutils]

func encode*(x: EthereumUint32): seq[byte] =
let numTargetBytes = 32 div 8
let paddingBytes = 32 - numTargetBytes
## the Ethereum ABI imposes a 32 byte width for every type
let paddingZeros = newSeq[byte](paddingBytes)
let ret = paddingZeros & @(x.toByteArrayBE())
let retHex = ret.toHex()
ret

func encode*[bits: static[int]](x: StUint[bits]): seq[byte] =
@(x.toBytesBE())

Expand Down
32 changes: 32 additions & 0 deletions web3/eth_api_types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
{.push raises: [].}

import
std/[macros, math],
stint,
./primitives

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

macro makeEthereumTypeEnum(): untyped =
## This macro creates all the various types of Solidity contracts and maps
## them to the type used for their encoding. It also creates an enum to
## identify these types in the contract signatures, along with encoder
## functions used in the generated procedures.
result = newStmtList()
var lastpow2: int
for i in countdown(256, 8, 8):
let
identUint = newIdentNode("EthereumUint" & $i)
identInt = newIdentNode("EthereumInt" & $i)
if ceil(log2(i.float)) == floor(log2(i.float)):
lastpow2 = i

result.add quote do:
type
`identUint`* = StUint[`lastpow2`]
`identInt`* = StInt[`lastpow2`]

let
identUint = ident("EthereumUint")
identInt = ident("EthereumInt")
identBool = ident("EthereumBool")
result.add quote do:
type
`identUint`* = UInt256
`identInt`* = Int256
`identBool`* = distinct Int256

makeEthereumTypeEnum()

# Backwards compatibility

type
Expand Down

0 comments on commit b32602e

Please sign in to comment.