From b32602e68e1843b6b9601cea20b63ebf96547874 Mon Sep 17 00:00:00 2001 From: Ivan Folgueira Bande Date: Sun, 19 Jan 2025 23:47:10 +0100 Subject: [PATCH] Create some ethereum types --- web3/encoding.nim | 9 +++++++++ web3/eth_api_types.nim | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/web3/encoding.nim b/web3/encoding.nim index 89e07e9..63a273d 100644 --- a/web3/encoding.nim +++ b/web3/encoding.nim @@ -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()) diff --git a/web3/eth_api_types.nim b/web3/eth_api_types.nim index 22e661a..1c83c83 100644 --- a/web3/eth_api_types.nim +++ b/web3/eth_api_types.nim @@ -10,6 +10,7 @@ {.push raises: [].} import + std/[macros, math], stint, ./primitives @@ -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