From b0a5d923aa910c0dfecde2a401a5c1f233b39e1b Mon Sep 17 00:00:00 2001 From: jangko Date: Mon, 10 Jun 2024 16:28:02 +0700 Subject: [PATCH] Replace std.Option with results.Opt --- tests/helpers/handlers.nim | 2 +- tests/helpers/utils.nim | 10 +-- tests/test_contracts.nim | 7 +- tests/test_deposit_contract.nim | 5 +- tests/test_execution_types.nim | 48 ++++++------- tests/test_json_marshalling.nim | 10 ++- tests/test_logs.nim | 5 +- tests/test_signed_tx.nim | 30 ++++---- web3.nim | 84 +++++++++++----------- web3.nimble | 1 + web3/contract_dsl.nim | 6 +- web3/conversions.nim | 3 +- web3/engine_api.nim | 33 +++++---- web3/engine_api_types.nim | 19 ++--- web3/eth_api.nim | 5 +- web3/eth_api_types.nim | 120 ++++++++++++++++---------------- web3/execution_types.nim | 100 +++++++++++++------------- web3/primitives.nim | 10 ++- web3/transaction_signing.nim | 12 ++-- 19 files changed, 264 insertions(+), 246 deletions(-) diff --git a/tests/helpers/handlers.nim b/tests/helpers/handlers.nim index 6c2f7d4..6dbf56a 100644 --- a/tests/helpers/handlers.nim +++ b/tests/helpers/handlers.nim @@ -102,7 +102,7 @@ proc installHandlers*(server: RpcServer) = if x != "-1".JsonString: result = decodeFromString(x, UInt256) - server.rpc("eth_feeHistory") do(x: JsonString, blockCount: Quantity, newestBlock: RtBlockIdentifier, rewardPercentiles: Option[seq[float64]]) -> FeeHistoryResult: + server.rpc("eth_feeHistory") do(x: JsonString, blockCount: Quantity, newestBlock: RtBlockIdentifier, rewardPercentiles: Opt[seq[float64]]) -> FeeHistoryResult: var fh: FeeHistoryResult if x != "-1".JsonString: fh = decodeFromString(x, FeeHistoryResult) diff --git a/tests/helpers/utils.nim b/tests/helpers/utils.nim index a90ab59..232c9fe 100644 --- a/tests/helpers/utils.nim +++ b/tests/helpers/utils.nim @@ -1,5 +1,5 @@ import - std/options, + results, chronos, stew/byteutils, ../../web3, @@ -8,11 +8,11 @@ import proc deployContract*(web3: Web3, code: string, gasPrice = 0): Future[ReceiptObject] {.async.} = var code = code var tr: TransactionArgs - tr.`from` = some(web3.defaultAccount) - tr.data = some(hexToSeqByte(code)) - tr.gas = Quantity(3000000).some + tr.`from` = Opt.some(web3.defaultAccount) + tr.data = Opt.some(hexToSeqByte(code)) + tr.gas = Opt.some Quantity(3000000) if gasPrice != 0: - tr.gasPrice = some(gasPrice.Quantity) + tr.gasPrice = Opt.some(gasPrice.Quantity) let r = await web3.send(tr) return await web3.getMinedTransactionReceipt(r) diff --git a/tests/test_contracts.nim b/tests/test_contracts.nim index 307b262..27f6b25 100644 --- a/tests/test_contracts.nim +++ b/tests/test_contracts.nim @@ -8,9 +8,10 @@ # those terms. import - std/[options, json], + std/json, pkg/unittest2, chronos, stint, + results, ../web3, ./helpers/utils @@ -265,8 +266,8 @@ suite "Contracts": echo "transfers: ", await ns.getJsonLogs( Transfer, - fromBlock = some(blockId(deployedAtBlock)), - toBlock = some(blockId(1000.BlockNumber))) + fromBlock = Opt.some(blockId(deployedAtBlock)), + toBlock = Opt.some(blockId(1000.BlockNumber))) await notifFut await s.unsubscribe() diff --git a/tests/test_deposit_contract.nim b/tests/test_deposit_contract.nim index abd2676..52d4034 100644 --- a/tests/test_deposit_contract.nim +++ b/tests/test_deposit_contract.nim @@ -8,9 +8,10 @@ # those terms. import - std/[options, json], + std/json, pkg/unittest2, chronos, stint, + results, ../web3, ./helpers/utils, ./helpers/primitives_utils, @@ -43,7 +44,7 @@ suite "Deposit contract": var fut = newFuture[void]() - let options = FilterOptions(fromBlock: some(blockId(0.BlockNumber))) + let options = FilterOptions(fromBlock: Opt.some(blockId(0.BlockNumber))) let s = await ns.subscribe(DepositEvent, options) do ( pubkey: DynamicBytes[0, 48], withdrawalCredentials: DynamicBytes[0, 32], amount: DynamicBytes[0, 8], signature: DynamicBytes[0, 96], merkleTreeIndex: DynamicBytes[0, 8]) {.raises: [], gcsafe.}: diff --git a/tests/test_execution_types.nim b/tests/test_execution_types.nim index c64b0f2..4ebbb7d 100644 --- a/tests/test_execution_types.nim +++ b/tests/test_execution_types.nim @@ -38,17 +38,17 @@ suite "Execution types tests": baseFeePerGas: 12.u256, blockHash: h256(13), transactions: @[TypedTransaction.conv(14)], - withdrawals: some(@[wd]), - blobGasUsed: some(15.Quantity), - excessBlobGas: some(16.Quantity), + withdrawals: Opt.some(@[wd]), + blobGasUsed: Opt.some(15.Quantity), + excessBlobGas: Opt.some(16.Quantity), ) attr = PayloadAttributes( timestamp: 1.Quantity, prevRandao: h256(2), suggestedFeeRecipient: address(3), - withdrawals: some(@[wd]), - parentBeaconBlockRoot: some(h256(4)), + withdrawals: Opt.some(@[wd]), + parentBeaconBlockRoot: Opt.some(h256(4)), ) blobs = BlobsBundleV1( @@ -59,9 +59,9 @@ suite "Execution types tests": response = GetPayloadResponse( executionPayload: payload, - blockValue: some(1.u256), - blobsBundle: some(blobs), - shouldOverrideBuilder: some(false), + blockValue: Opt.some(1.u256), + blobsBundle: Opt.some(blobs), + shouldOverrideBuilder: Opt.some(false), ) deposit = DepositReceiptV1( @@ -79,14 +79,14 @@ suite "Execution types tests": test "payload version": var badv31 = payload - badv31.blobGasUsed = none(Quantity) + badv31.blobGasUsed = Opt.none(Quantity) var badv32 = payload - badv32.excessBlobGas = none(Quantity) + badv32.excessBlobGas = Opt.none(Quantity) var v2 = payload - v2.blobGasUsed = none(Quantity) - v2.excessBlobGas = none(Quantity) + v2.blobGasUsed = Opt.none(Quantity) + v2.excessBlobGas = Opt.none(Quantity) var v1 = v2 - v1.withdrawals = none(seq[WithdrawalV1]) + v1.withdrawals = Opt.none(seq[WithdrawalV1]) check badv31.version == Version.V3 check badv32.version == Version.V3 check v2.version == Version.V2 @@ -104,23 +104,23 @@ suite "Execution types tests": test "attr version": var v2 = attr - v2.parentBeaconBlockRoot = none(Hash256) + v2.parentBeaconBlockRoot = Opt.none(Hash256) var v1 = v2 - v1.withdrawals = none(seq[WithdrawalV1]) + v1.withdrawals = Opt.none(seq[WithdrawalV1]) check attr.version == Version.V3 check v2.version == Version.V2 check v1.version == Version.V1 test "response version": var badv31 = response - badv31.blobsBundle = none(BlobsBundleV1) + badv31.blobsBundle = Opt.none(BlobsBundleV1) var badv32 = response - badv32.shouldOverrideBuilder = none(bool) + badv32.shouldOverrideBuilder = Opt.none(bool) var v2 = response - v2.blobsBundle = none(BlobsBundleV1) - v2.shouldOverrideBuilder = none(bool) + v2.blobsBundle = Opt.none(BlobsBundleV1) + v2.shouldOverrideBuilder = Opt.none(bool) var v1 = v2 - v1.blockValue = none(UInt256) + v1.blockValue = Opt.none(UInt256) check badv31.version == Version.V3 check badv32.version == Version.V3 check v2.version == Version.V2 @@ -167,16 +167,16 @@ suite "Execution types tests": test "payload version 4": var v4 = payload - v4.depositReceipts = some(@[deposit]) - v4.exits = some(@[exit]) + v4.depositReceipts = Opt.some(@[deposit]) + v4.exits = Opt.some(@[exit]) check v4.version == Version.V4 var bad41 = v4 - bad41.depositReceipts = none(seq[DepositReceiptV1]) + bad41.depositReceipts = Opt.none(seq[DepositReceiptV1]) check bad41.version == Version.V4 var bad42 = v4 - bad42.exits = none(seq[WithdrawalRequestV1]) + bad42.exits = Opt.none(seq[WithdrawalRequestV1]) check bad42.version == Version.V4 let v41 = bad41.V4 diff --git a/tests/test_json_marshalling.nim b/tests/test_json_marshalling.nim index bd09412..d7f4dbf 100644 --- a/tests/test_json_marshalling.nim +++ b/tests/test_json_marshalling.nim @@ -79,6 +79,14 @@ proc rand[T](_: type seq[T]): seq[T] = proc rand[T](_: type SingleOrList[T]): SingleOrList[T] = SingleOrList[T](kind: slkSingle, single: rand(T)) +proc rand[X](T: type Opt[X]): T = + var x: array[1, byte] + discard randomBytes(x) + if x[0] > 127: + result = Opt.some(rand(X)) + else: + result = Opt.none(X) + proc rand[X: object](T: type X): T = result = T() for field in fields(result): @@ -237,7 +245,7 @@ suite "JSON-RPC Quantity": test "AccessListResult with error": let z = AccessListResult( - error: some("error") + error: Opt.some("error") ) let w = JrpcConv.encode(z) check w == """{"accessList":[],"error":"error","gasUsed":"0x0"}""" diff --git a/tests/test_logs.nim b/tests/test_logs.nim index 3718a26..fb1262f 100644 --- a/tests/test_logs.nim +++ b/tests/test_logs.nim @@ -8,10 +8,11 @@ # those terms. import - std/[options, json, random], + std/[json, random], pkg/unittest2, ../web3, chronos, stint, + results, ./helpers/utils #[ Contract LoggerContract @@ -74,7 +75,7 @@ suite "Logs": let notifFut = newFuture[void]() var notificationsReceived = 0 - let options = FilterOptions(fromBlock: some(blockId(0.BlockNumber))) + let options = FilterOptions(fromBlock: Opt.some(blockId(0.BlockNumber))) let s = await ns.subscribe(MyEvent, options) do ( sender: Address, value: UInt256) {.raises: [], gcsafe.}: diff --git a/tests/test_signed_tx.nim b/tests/test_signed_tx.nim index b308ff1..8f8dbb8 100644 --- a/tests/test_signed_tx.nim +++ b/tests/test_signed_tx.nim @@ -8,9 +8,9 @@ # those terms. import - std/[options], pkg/unittest2, chronos, stint, + results, eth/keys, eth/common/eth_types, stew/byteutils, @@ -47,12 +47,12 @@ suite "Signed transactions": publicKey = privateKey.toPublicKey() address = publicKey.toCanonicalAddress() var tx: TransactionArgs - tx.nonce = some(Quantity(9)) - tx.`from` = some(Address(address)) - tx.value = some(1000000000000000000.u256) - tx.to = some(Address(hexToByteArray[20]("0x3535353535353535353535353535353535353535"))) - tx.gas = some(Quantity(21000'u64)) - tx.gasPrice = some(Quantity(20000000000'i64)) + tx.nonce = Opt.some(Quantity(9)) + tx.`from` = Opt.some(Address(address)) + tx.value = Opt.some(1000000000000000000.u256) + tx.to = Opt.some(Address(hexToByteArray[20]("0x3535353535353535353535353535353535353535"))) + tx.gas = Opt.some(Quantity(21000'u64)) + tx.gasPrice = Opt.some(Quantity(20000000000'i64)) let txBytes = encodeTransaction(tx, privateKey, ChainId(1)) let txHex = "0x" & txBytes.toHex @@ -71,10 +71,10 @@ suite "Signed transactions": let acc = Address(toCanonicalAddress(pk.toPublicKey())) var tx: TransactionArgs - tx.`from` = some(accounts[0]) - tx.value = some(ethToWei(10.u256)) - tx.to = some(acc) - tx.gasPrice = some(gasPrice) + tx.`from` = Opt.some(accounts[0]) + tx.value = Opt.some(ethToWei(10.u256)) + tx.to = Opt.some(acc) + tx.gasPrice = Opt.some(gasPrice) # Send 10 eth to acc discard await web3.send(tx) @@ -82,10 +82,10 @@ suite "Signed transactions": assert(balance == ethToWei(10.u256)) # Send 5 eth back - web3.privateKey = some(pk) - tx.value = some(ethToWei(5.u256)) - tx.to = some(accounts[0]) - tx.gas = some(Quantity(3000000)) + web3.privateKey = Opt.some(pk) + tx.value = Opt.some(ethToWei(5.u256)) + tx.to = Opt.some(accounts[0]) + tx.gas = Opt.some(Quantity(3000000)) discard await web3.send(tx) balance = await web3.provider.eth_getBalance(acc, "latest") diff --git a/web3.nim b/web3.nim index a450a05..bb864b7 100644 --- a/web3.nim +++ b/web3.nim @@ -8,8 +8,9 @@ # those terms. import - std/[options, json, tables, uri, macros], + std/[json, tables, uri, macros], stint, httputils, chronos, + results, json_rpc/[rpcclient, jsonmarshal], json_rpc/private/jrpc_sys, eth/keys, @@ -34,8 +35,8 @@ type provider*: RpcClient subscriptions*: Table[string, Subscription] defaultAccount*: Address - privateKey*: Option[PrivateKey] - lastKnownNonce*: Option[Quantity] + privateKey*: Opt[PrivateKey] + lastKnownNonce*: Opt[Quantity] onDisconnect*: proc() {.gcsafe, raises: [].} Web3SenderImpl = ref object @@ -49,7 +50,7 @@ type value*: UInt256 gas*: uint64 gasPrice*: int - chainId*: Option[ChainId] + chainId*: Opt[ChainId] blockNumber*: BlockNumber Sender*[T] = ContractInstance[T, Web3SenderImpl] @@ -182,7 +183,7 @@ proc getHistoricalEvents(s: Subscription, options: FilterOptions) {.async.} = echo "Caught exception in getHistoricalEvents: ", e.msg echo e.getStackTrace() -proc subscribe*(w: Web3, name: string, options: Option[FilterOptions], +proc subscribe*(w: Web3, name: string, options: Opt[FilterOptions], eventHandler: SubscriptionEventHandler, errorHandler: SubscriptionErrorHandler): Future[Subscription] {.async.} = @@ -215,7 +216,7 @@ proc subscribeForLogs*(w: Web3, options: FilterOptions, errorHandler: SubscriptionErrorHandler, withHistoricEvents = true): Future[Subscription] {.async.} = - result = await subscribe(w, "logs", some(options), logsHandler, errorHandler) + result = await subscribe(w, "logs", Opt.some(options), logsHandler, errorHandler) if withHistoricEvents: discard getHistoricalEvents(result, options) else: @@ -249,7 +250,7 @@ proc subscribeForBlockHeaders*(w: Web3, # `nil` options so that we skip sending an empty `{}` object as an extra argument # to geth for `newHeads`: https://github.com/ethereum/go-ethereum/issues/21588 - result = await subscribe(w, "newHeads", none(FilterOptions), eventHandler, errorHandler) + result = await subscribe(w, "newHeads", Opt.none(FilterOptions), eventHandler, errorHandler) result.historicalEventsProcessed = true proc unsubscribe*(s: Subscription): Future[void] {.async.} = @@ -258,9 +259,9 @@ proc unsubscribe*(s: Subscription): Future[void] {.async.} = discard await s.web3.provider.eth_unsubscribe(s.id) proc getJsonLogs(s: Web3SenderImpl, topic: Topic, - fromBlock = none(RtBlockIdentifier), - toBlock = none(RtBlockIdentifier), - blockHash = none(BlockHash)): Future[seq[JsonString]] = + fromBlock = Opt.none(RtBlockIdentifier), + toBlock = Opt.none(RtBlockIdentifier), + blockHash = Opt.none(BlockHash)): Future[seq[JsonString]] = var options = FilterOptions( address: AddressOrList(kind: slkSingle, single: s.contractAddress), @@ -279,9 +280,9 @@ proc getJsonLogs(s: Web3SenderImpl, topic: Topic, proc getJsonLogs*[TContract](s: Sender[TContract], EventName: type, - fromBlock = none(RtBlockIdentifier), - toBlock = none(RtBlockIdentifier), - blockHash = none(BlockHash)): Future[seq[JsonString]] {.inline.} = + fromBlock = Opt.none(RtBlockIdentifier), + toBlock = Opt.none(RtBlockIdentifier), + blockHash = Opt.none(BlockHash)): Future[seq[JsonString]] {.inline.} = mixin eventTopic getJsonLogs(s.sender, eventTopic(EventName), fromBlock, toBlock, blockHash) @@ -292,13 +293,13 @@ proc nextNonce*(web3: Web3): Future[Quantity] {.async.} = else: let fromAddress = web3.privateKey.get().toPublicKey().toCanonicalAddress.Address result = await web3.provider.eth_getTransactionCount(fromAddress, "latest") - web3.lastKnownNonce = some result + web3.lastKnownNonce = Opt.some result proc send*(web3: Web3, c: TransactionArgs): Future[TxHash] {.async.} = if web3.privateKey.isSome(): var cc = c if cc.nonce.isNone: - cc.nonce = some(await web3.nextNonce()) + cc.nonce = Opt.some(await web3.nextNonce()) let t = encodeTransaction(cc, web3.privateKey.get()) return await web3.provider.eth_sendRawTransaction(t) else: @@ -308,7 +309,7 @@ proc send*(web3: Web3, c: TransactionArgs, chainId: ChainId): Future[TxHash] {.d doAssert(web3.privateKey.isSome()) var cc = c if cc.nonce.isNone: - cc.nonce = some(await web3.nextNonce()) + cc.nonce = Opt.some(await web3.nextNonce()) let t = encodeTransaction(cc, web3.privateKey.get(), chainId) return await web3.provider.eth_sendRawTransaction(t) @@ -319,21 +320,21 @@ proc sendData(web3: Web3, value: UInt256, gas: uint64, gasPrice: int, - chainId = none(ChainId)): Future[TxHash] {.async.} = + chainId = Opt.none(ChainId)): Future[TxHash] {.async.} = let - gasPrice = if web3.privateKey.isSome() or gasPrice != 0: some(gasPrice.Quantity) - else: none(Quantity) - nonce = if web3.privateKey.isSome(): some(await web3.nextNonce()) - else: none(Quantity) - chainId = if chainId.isSome(): some(Quantity(chainId.get)) - else: none(Quantity) + gasPrice = if web3.privateKey.isSome() or gasPrice != 0: Opt.some(gasPrice.Quantity) + else: Opt.none(Quantity) + nonce = if web3.privateKey.isSome(): Opt.some(await web3.nextNonce()) + else: Opt.none(Quantity) + chainId = if chainId.isSome(): Opt.some(Quantity(chainId.get)) + else: Opt.none(Quantity) cc = TransactionArgs( - data: some(data), - `from`: some(defaultAccount), - to: some(contractAddress), - gas: some(Quantity(gas)), - value: some(value), + data: Opt.some(data), + `from`: Opt.some(defaultAccount), + to: Opt.some(contractAddress), + gas: Opt.some(Quantity(gas)), + value: Opt.some(value), nonce: nonce, gasPrice: gasPrice, chainId: chainId @@ -345,14 +346,16 @@ proc send*[T](c: ContractInvocation[T, Web3SenderImpl], value = 0.u256, gas = 3000000'u64, gasPrice = 0): Future[TxHash] = - sendData(c.sender.web3, c.sender.contractAddress, c.sender.web3.defaultAccount, c.data, value, gas, gasPrice) + sendData(c.sender.web3, c.sender.contractAddress, + c.sender.web3.defaultAccount, c.data, value, gas, gasPrice) proc send*[T](c: ContractInvocation[T, Web3SenderImpl], chainId: ChainId, value = 0.u256, gas = 3000000'u64, gasPrice = 0): Future[TxHash] = - sendData(c.sender.web3, c.sender.contractAddress, c.sender.web3.defaultAccount, c.data, value, gas, gasPrice, some(chainId)) + sendData(c.sender.web3, c.sender.contractAddress, + c.sender.web3.defaultAccount, c.data, value, gas, gasPrice, some(chainId)) proc callAux( web3: Web3, @@ -363,11 +366,11 @@ proc callAux( gas = 3000000'u64, blockNumber = high(BlockNumber)): Future[seq[byte]] {.async.} = var cc: TransactionArgs - cc.data = some(data) - cc.source = some(defaultAccount) - cc.to = some(contractAddress) - cc.gas = some(Quantity(gas)) - cc.value = some(value) + cc.data = Opt.some(data) + cc.source = Opt.some(defaultAccount) + cc.to = Opt.some(contractAddress) + cc.gas = Opt.some(Quantity(gas)) + cc.value = Opt.some(value) result = if blockNumber != high(BlockNumber): await web3.provider.eth_call(cc, blockId(blockNumber)) @@ -379,7 +382,8 @@ proc call*[T]( value = 0.u256, gas = 3000000'u64, blockNumber = high(BlockNumber)): Future[T] {.async.} = - let response = await callAux(c.sender.web3, c.sender.contractAddress, c.sender.web3.defaultAccount, c.data, value, gas, blockNumber) + let response = await callAux(c.sender.web3, c.sender.contractAddress, + c.sender.web3.defaultAccount, c.data, value, gas, blockNumber) if response.len > 0: discard decode(response, 0, 0, result) else: @@ -468,11 +472,11 @@ proc createImmutableContractInvocation*( proc deployContractAux(web3: Web3, data: seq[byte], gasPrice = 0): Future[Address] {.async.} = var tr: TransactionArgs - tr.`from` = some(web3.defaultAccount) - tr.data = some(data) - tr.gas = Quantity(30000000).some + tr.`from` = Opt.some(web3.defaultAccount) + tr.data = Opt.some(data) + tr.gas = Opt.some Quantity(30000000) if gasPrice != 0: - tr.gasPrice = some(gasPrice.Quantity) + tr.gasPrice = Opt.some(gasPrice.Quantity) let h = await web3.send(tr) let r = await web3.getMinedTransactionReceipt(h) diff --git a/web3.nimble b/web3.nimble index 66a3a35..1d8be60 100644 --- a/web3.nimble +++ b/web3.nimble @@ -25,6 +25,7 @@ requires "json_serialization" requires "nimcrypto" requires "stew" requires "stint" +requires "results" ### Helper functions proc test(args, path: string) = diff --git a/web3/contract_dsl.nim b/web3/contract_dsl.nim index 0d7de65..fefd3b9 100644 --- a/web3/contract_dsl.nim +++ b/web3/contract_dsl.nim @@ -1,5 +1,5 @@ import - std/[macros, strutils, options], + std/[macros, strutils], nimcrypto/keccak, json_serialization, ./[encoding, eth_api_types], @@ -114,7 +114,7 @@ proc parseContract(body: NimNode): seq[InterfaceObject] = result.add EventInput(name: $arg, typ: typ) var - constructor: Option[ConstructorObject] + constructor: Opt[ConstructorObject] functions: seq[FunctionObject] events: seq[EventObject] for procdef in body: @@ -137,7 +137,7 @@ proc parseContract(body: NimNode): seq[InterfaceObject] = doAssert(not ((ispure or isview) and ispayable), "can't be both `pure` or `view` while being `payable`") if isconstructor: - constructor = some(ConstructorObject( + constructor = Opt.some(ConstructorObject( stateMutability: if ispure: pure elif isview: view elif ispayable: payable else: nonpayable, inputs: parseInputs(procdef[3]), outputs: parseOutputs(procdef[3][0]) diff --git a/web3/conversions.nim b/web3/conversions.nim index a3fb5bd..fea282c 100644 --- a/web3/conversions.nim +++ b/web3/conversions.nim @@ -13,7 +13,6 @@ import stew/byteutils, faststreams/textio, json_rpc/jsonmarshal, - json_serialization/std/options, json_serialization/stew/results, json_serialization, ./primitives, @@ -22,7 +21,7 @@ import ./execution_types export - options, + results, json_serialization, jsonmarshal diff --git a/web3/engine_api.nim b/web3/engine_api.nim index ec69314..eeefaa3 100644 --- a/web3/engine_api.nim +++ b/web3/engine_api.nim @@ -8,7 +8,7 @@ # those terms. import - json_serialization/std/[options], + json_serialization/stew/results, serialization/errors, json_rpc/client, ./conversions, @@ -29,17 +29,17 @@ createRpcSigsFromNim(RpcClient): proc engine_newPayloadV2(payload: ExecutionPayloadV2): PayloadStatusV1 proc engine_newPayloadV3(payload: ExecutionPayloadV3, expectedBlobVersionedHashes: seq[VersionedHash], parentBeaconBlockRoot: FixedBytes[32]): PayloadStatusV1 proc engine_newPayloadV4(payload: ExecutionPayloadV4, expectedBlobVersionedHashes: seq[VersionedHash], parentBeaconBlockRoot: FixedBytes[32]): PayloadStatusV1 - proc engine_forkchoiceUpdatedV1(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Option[PayloadAttributesV1]): ForkchoiceUpdatedResponse - proc engine_forkchoiceUpdatedV2(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Option[PayloadAttributesV2]): ForkchoiceUpdatedResponse - proc engine_forkchoiceUpdatedV3(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Option[PayloadAttributesV3]): ForkchoiceUpdatedResponse + proc engine_forkchoiceUpdatedV1(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Opt[PayloadAttributesV1]): ForkchoiceUpdatedResponse + proc engine_forkchoiceUpdatedV2(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Opt[PayloadAttributesV2]): ForkchoiceUpdatedResponse + proc engine_forkchoiceUpdatedV3(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Opt[PayloadAttributesV3]): ForkchoiceUpdatedResponse proc engine_getPayloadV1(payloadId: PayloadID): ExecutionPayloadV1 proc engine_getPayloadV2(payloadId: PayloadID): GetPayloadV2Response proc engine_getPayloadV2_exact(payloadId: PayloadID): GetPayloadV2ResponseExact proc engine_getPayloadV3(payloadId: PayloadID): GetPayloadV3Response proc engine_getPayloadV4(payloadId: PayloadID): GetPayloadV4Response proc engine_exchangeTransitionConfigurationV1(transitionConfiguration: TransitionConfigurationV1): TransitionConfigurationV1 - proc engine_getPayloadBodiesByHashV1(hashes: seq[BlockHash]): seq[Option[ExecutionPayloadBodyV1]] - proc engine_getPayloadBodiesByRangeV1(start: Quantity, count: Quantity): seq[Option[ExecutionPayloadBodyV1]] + proc engine_getPayloadBodiesByHashV1(hashes: seq[BlockHash]): seq[Opt[ExecutionPayloadBodyV1]] + proc engine_getPayloadBodiesByRangeV1(start: Quantity, count: Quantity): seq[Opt[ExecutionPayloadBodyV1]] # https://github.com/ethereum/execution-apis/blob/9301c0697e4c7566f0929147112f6d91f65180f6/src/engine/common.md proc engine_exchangeCapabilities(methods: seq[string]): seq[string] @@ -52,30 +52,30 @@ createRpcSigsFromNim(RpcClient): proc engine_newPayloadV2(payload: ExecutionPayload): PayloadStatusV1 proc engine_newPayloadV2(payload: ExecutionPayloadV1OrV2): PayloadStatusV1 proc engine_newPayloadV3(payload: ExecutionPayload, - expectedBlobVersionedHashes: Option[seq[VersionedHash]], - parentBeaconBlockRoot: Option[FixedBytes[32]]): PayloadStatusV1 + expectedBlobVersionedHashes: Opt[seq[VersionedHash]], + parentBeaconBlockRoot: Opt[FixedBytes[32]]): PayloadStatusV1 proc engine_newPayloadV4(payload: ExecutionPayload, - expectedBlobVersionedHashes: Option[seq[VersionedHash]], - parentBeaconBlockRoot: Option[FixedBytes[32]]): PayloadStatusV1 - proc engine_forkchoiceUpdatedV2(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Option[PayloadAttributes]): ForkchoiceUpdatedResponse - proc engine_forkchoiceUpdatedV3(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Option[PayloadAttributes]): ForkchoiceUpdatedResponse + expectedBlobVersionedHashes: Opt[seq[VersionedHash]], + parentBeaconBlockRoot: Opt[FixedBytes[32]]): PayloadStatusV1 + proc engine_forkchoiceUpdatedV2(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Opt[PayloadAttributes]): ForkchoiceUpdatedResponse + proc engine_forkchoiceUpdatedV3(forkchoiceState: ForkchoiceStateV1, payloadAttributes: Opt[PayloadAttributes]): ForkchoiceUpdatedResponse template forkchoiceUpdated*( rpcClient: RpcClient, forkchoiceState: ForkchoiceStateV1, - payloadAttributes: Option[PayloadAttributesV1]): Future[ForkchoiceUpdatedResponse] = + payloadAttributes: Opt[PayloadAttributesV1]): Future[ForkchoiceUpdatedResponse] = engine_forkchoiceUpdatedV1(rpcClient, forkchoiceState, payloadAttributes) template forkchoiceUpdated*( rpcClient: RpcClient, forkchoiceState: ForkchoiceStateV1, - payloadAttributes: Option[PayloadAttributesV2]): Future[ForkchoiceUpdatedResponse] = + payloadAttributes: Opt[PayloadAttributesV2]): Future[ForkchoiceUpdatedResponse] = engine_forkchoiceUpdatedV2(rpcClient, forkchoiceState, payloadAttributes) template forkchoiceUpdated*( rpcClient: RpcClient, forkchoiceState: ForkchoiceStateV1, - payloadAttributes: Option[PayloadAttributesV3]): Future[ForkchoiceUpdatedResponse] = + payloadAttributes: Opt[PayloadAttributesV3]): Future[ForkchoiceUpdatedResponse] = engine_forkchoiceUpdatedV3(rpcClient, forkchoiceState, payloadAttributes) template getPayload*( @@ -138,9 +138,8 @@ template exchangeCapabilities*( rpcClient: RpcClient, methods: seq[string]): Future[seq[string]] = engine_exchangeCapabilities(rpcClient, methods) - + template getClientVersion*( rpcClient: RpcClient, version: ClientVersionV1): Future[seq[ClientVersionV1]] = engine_getClientVersionV1(rpcClient, version) - \ No newline at end of file diff --git a/web3/engine_api_types.nim b/web3/engine_api_types.nim index 2f75ef9..93a78fc 100644 --- a/web3/engine_api_types.nim +++ b/web3/engine_api_types.nim @@ -8,12 +8,13 @@ # those terms. import - std/[options, typetraits], + std/typetraits, stint, - primitives + primitives, + results export - options, stint, primitives + results, stint, primitives type TypedTransaction* = distinct seq[byte] @@ -102,7 +103,7 @@ type baseFeePerGas*: UInt256 blockHash*: BlockHash transactions*: seq[TypedTransaction] - withdrawals*: Option[seq[WithdrawalV1]] + withdrawals*: Opt[seq[WithdrawalV1]] # https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/cancun.md#executionpayloadv3 ExecutionPayloadV3* = object @@ -169,7 +170,7 @@ type # https://github.com/ethereum/execution-apis/blob/main/src/engine/shanghai.md#engine_getpayloadbodiesbyrangev1 ExecutionPayloadBodyV1* = object transactions*: seq[TypedTransaction] - withdrawals*: Option[seq[WithdrawalV1]] + withdrawals*: Opt[seq[WithdrawalV1]] # https://github.com/ethereum/execution-apis/blob/v1.0.0-beta.3/src/engine/paris.md#payloadattributesv1 PayloadAttributesV1* = object @@ -197,7 +198,7 @@ type timestamp*: Quantity prevRandao*: FixedBytes[32] suggestedFeeRecipient*: Address - withdrawals*: Option[seq[WithdrawalV1]] + withdrawals*: Opt[seq[WithdrawalV1]] SomePayloadAttributes* = PayloadAttributesV1 | @@ -214,8 +215,8 @@ type PayloadStatusV1* = object status*: PayloadExecutionStatus - latestValidHash*: Option[BlockHash] - validationError*: Option[string] + latestValidHash*: Opt[BlockHash] + validationError*: Opt[string] # https://github.com/ethereum/execution-apis/blob/v1.0.0-beta.3/src/engine/paris.md#forkchoicestatev1 ForkchoiceStateV1* = object @@ -228,7 +229,7 @@ type ForkchoiceUpdatedResponse* = object payloadStatus*: PayloadStatusV1 - payloadId*: Option[PayloadID] + payloadId*: Opt[PayloadID] # https://github.com/ethereum/execution-apis/blob/v1.0.0-beta.3/src/engine/paris.md#transitionconfigurationv1 TransitionConfigurationV1* = object diff --git a/web3/eth_api.nim b/web3/eth_api.nim index 9c96722..0382496 100644 --- a/web3/eth_api.nim +++ b/web3/eth_api.nim @@ -9,8 +9,7 @@ # according to those terms. import - std/[json, options], - json_serialization/std/[options], + std/json, json_serialization/stew/results, json_rpc/[client, jsonmarshal], stint, @@ -99,7 +98,7 @@ createRpcSigsFromNim(RpcClient): proc eth_feeHistory( blockCount: Quantity, newestBlock: BlockIdentifier, - rewardPercentiles: Option[seq[float64]]): FeeHistoryResult + rewardPercentiles: Opt[seq[float64]]): FeeHistoryResult proc debug_getRawBlock(blockId: BlockIdentifier): RlpEncodedBytes proc debug_getRawHeader(blockId: BlockIdentifier): RlpEncodedBytes diff --git a/web3/eth_api_types.nim b/web3/eth_api_types.nim index 33f19e7..3347587 100644 --- a/web3/eth_api_types.nim +++ b/web3/eth_api_types.nim @@ -32,33 +32,33 @@ type ## expected to do this on their own. TransactionArgs* = object - `from`*: Option[Address] # (optional) The address the transaction is sent from. - to*: Option[Address] # The address the transaction is directed to. - gas*: Option[Quantity] # (optional) Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions. - gasPrice*: Option[Quantity] # (optional) Integer of the gasPrice used for each paid gas. - maxFeePerGas*: Option[Quantity] # (optional) MaxFeePerGas is the maximum fee per gas offered, in wei. - maxPriorityFeePerGas*: Option[Quantity] # (optional) MaxPriorityFeePerGas is the maximum miner tip per gas offered, in wei. - value*: Option[UInt256] # (optional) Integer of the value sent with this transaction. - nonce*: Option[Quantity] # (optional) integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce + `from`*: Opt[Address] # (optional) The address the transaction is sent from. + to*: Opt[Address] # The address the transaction is directed to. + gas*: Opt[Quantity] # (optional) Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions. + gasPrice*: Opt[Quantity] # (optional) Integer of the gasPrice used for each paid gas. + maxFeePerGas*: Opt[Quantity] # (optional) MaxFeePerGas is the maximum fee per gas offered, in wei. + maxPriorityFeePerGas*: Opt[Quantity] # (optional) MaxPriorityFeePerGas is the maximum miner tip per gas offered, in wei. + value*: Opt[UInt256] # (optional) Integer of the value sent with this transaction. + nonce*: Opt[Quantity] # (optional) integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce # We accept "data" and "input" for backwards-compatibility reasons. # "input" is the newer name and should be preferred by clients. # Issue detail: https://github.com/ethereum/go-ethereum/issues/15628 - data*: Option[seq[byte]] # (optional) Hash of the method signature and encoded parameters. For details see Ethereum Contract ABI. - input*: Option[seq[byte]] + data*: Opt[seq[byte]] # (optional) Hash of the method signature and encoded parameters. For details see Ethereum Contract ABI. + input*: Opt[seq[byte]] # Introduced by EIP-2930. - accessList*: Option[seq[AccessTuple]] - chainId*: Option[Quantity] + accessList*: Opt[seq[AccessTuple]] + chainId*: Opt[Quantity] # EIP-4844 - maxFeePerBlobGas*: Option[UInt256] - blobVersionedHashes*: Option[seq[Hash256]] + maxFeePerBlobGas*: Opt[UInt256] + blobVersionedHashes*: Opt[seq[Hash256]] # EIP-4844 blob sidecars - blobs*: Option[seq[Blob]] - commitments*: Option[seq[KZGCommitment]] - proofs*: Option[seq[KZGProof]] + blobs*: Opt[seq[Blob]] + commitments*: Opt[seq[KZGCommitment]] + proofs*: Opt[seq[KZGProof]] ## A block header object BlockHeader* = ref object @@ -78,11 +78,11 @@ type timestamp*: Quantity nonce*: FixedBytes[8] mixHash*: Hash256 - baseFeePerGas*: Option[UInt256] # EIP-1559 - withdrawalsRoot*: Option[Hash256] # EIP-4895 - blobGasUsed*: Option[Quantity] # EIP-4844 - excessBlobGas*: Option[Quantity] # EIP-4844 - parentBeaconBlockRoot*: Option[Hash256] # EIP-4788 + baseFeePerGas*: Opt[UInt256] # EIP-1559 + withdrawalsRoot*: Opt[Hash256] # EIP-4895 + blobGasUsed*: Opt[Quantity] # EIP-4844 + excessBlobGas*: Opt[Quantity] # EIP-4844 + parentBeaconBlockRoot*: Opt[Hash256] # EIP-4788 WithdrawalObject* = object index*: Quantity @@ -106,18 +106,18 @@ type gasLimit*: Quantity # the maximum gas allowed in this block. gasUsed*: Quantity # the total used gas by all transactions in this block. timestamp*: Quantity # the unix timestamp for when the block was collated. - nonce*: Option[FixedBytes[8]] # hash of the generated proof-of-work. null when its pending block. + nonce*: Opt[FixedBytes[8]] # hash of the generated proof-of-work. null when its pending block. mixHash*: Hash256 size*: Quantity # integer the size of this block in bytes. totalDifficulty*: UInt256 # integer of the total difficulty of the chain until this block. transactions*: seq[TxOrHash] # list of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter. uncles*: seq[Hash256] # list of uncle hashes. - baseFeePerGas*: Option[UInt256] # EIP-1559 - withdrawals*: Option[seq[WithdrawalObject]] # EIP-4895 - withdrawalsRoot*: Option[Hash256] # EIP-4895 - blobGasUsed*: Option[Quantity] # EIP-4844 - excessBlobGas*: Option[Quantity] # EIP-4844 - parentBeaconBlockRoot*: Option[Hash256] # EIP-4788 + baseFeePerGas*: Opt[UInt256] # EIP-1559 + withdrawals*: Opt[seq[WithdrawalObject]] # EIP-4895 + withdrawalsRoot*: Opt[Hash256] # EIP-4895 + blobGasUsed*: Opt[Quantity] # EIP-4844 + excessBlobGas*: Opt[Quantity] # EIP-4844 + parentBeaconBlockRoot*: Opt[Hash256] # EIP-4788 TxOrHashKind* = enum tohHash @@ -136,17 +136,17 @@ type AccessListResult* = object accessList*: seq[AccessTuple] - error*: Option[string] + error*: Opt[string] gasUsed*: Quantity TransactionObject* = ref object # A transaction object, or null when no transaction was found: hash*: TxHash # hash of the transaction. nonce*: Quantity # TODO: Is int? the number of transactions made by the sender prior to this one. - blockHash*: Option[BlockHash] # hash of the block where this transaction was in. null when its pending. - blockNumber*: Option[BlockNumber] # block number where this transaction was in. null when its pending. - transactionIndex*: Option[Quantity] # integer of the transactions index position in the block. null when its pending. + blockHash*: Opt[BlockHash] # hash of the block where this transaction was in. null when its pending. + blockNumber*: Opt[BlockNumber] # block number where this transaction was in. null when its pending. + transactionIndex*: Opt[Quantity] # integer of the transactions index position in the block. null when its pending. `from`*: Address # address of the sender. - to*: Option[Address] # address of the receiver. null when its a contract creation transaction. + to*: Opt[Address] # address of the receiver. null when its a contract creation transaction. value*: UInt256 # value transferred in Wei. gasPrice*: Quantity # gas price provided by the sender in Wei. gas*: Quantity # gas provided by the sender. @@ -154,14 +154,14 @@ type v*: Quantity # ECDSA recovery id r*: UInt256 # ECDSA signature r s*: UInt256 # ECDSA signature s - yParity*: Option[Quantity] # ECDSA y parity, none for Legacy, same as v for >= Tx2930 - `type`*: Option[Quantity] # EIP-2718, with 0x0 for Legacy - chainId*: Option[Quantity] # EIP-159 - accessList*: Option[seq[AccessTuple]] # EIP-2930 - maxFeePerGas*: Option[Quantity] # EIP-1559 - maxPriorityFeePerGas*: Option[Quantity] # EIP-1559 - maxFeePerBlobGas*: Option[UInt256] # EIP-4844 - blobVersionedHashes*: Option[seq[VersionedHash]] # EIP-4844 + yParity*: Opt[Quantity] # ECDSA y parity, none for Legacy, same as v for >= Tx2930 + `type`*: Opt[Quantity] # EIP-2718, with 0x0 for Legacy + chainId*: Opt[Quantity] # EIP-159 + accessList*: Opt[seq[AccessTuple]] # EIP-2930 + maxFeePerGas*: Opt[Quantity] # EIP-1559 + maxPriorityFeePerGas*: Opt[Quantity] # EIP-1559 + maxFeePerBlobGas*: Opt[UInt256] # EIP-4844 + blobVersionedHashes*: Opt[seq[VersionedHash]] # EIP-4844 ReceiptObject* = ref object # A transaction receipt object, or null when no receipt was found: transactionHash*: TxHash # hash of the transaction. @@ -169,18 +169,18 @@ type blockHash*: BlockHash # hash of the block where this transaction was in. blockNumber*: BlockNumber # block number where this transaction was in. `from`*: Address # address of the sender. - to*: Option[Address] # address of the receiver. null when its a contract creation transaction. + to*: Opt[Address] # address of the receiver. null when its a contract creation transaction. cumulativeGasUsed*: Quantity # the total amount of gas used when this transaction was executed in the block. effectiveGasPrice*: Quantity # The sum of the base fee and tip paid per unit of gas. gasUsed*: Quantity # the amount of gas used by this specific transaction alone. - contractAddress*: Option[Address] # the contract address created, if the transaction was a contract creation, otherwise null. + contractAddress*: Opt[Address] # the contract address created, if the transaction was a contract creation, otherwise null. logs*: seq[LogObject] # TODO: See Wiki for details. list of log objects, which this transaction generated. logsBloom*: FixedBytes[256] # bloom filter for light clients to quickly retrieve related logs. - `type`*: Option[Quantity] # integer of the transaction type, 0x0 for legacy transactions, 0x1 for access list types, 0x2 for dynamic fees. - root*: Option[Hash256] # 32 bytes of post-transaction stateroot (pre Byzantium) - status*: Option[Quantity] # either 1 (success) or 0 (failure) - blobGasUsed*: Option[Quantity] # uint64 - blobGasPrice*: Option[UInt256] # UInt256 + `type`*: Opt[Quantity] # integer of the transaction type, 0x0 for legacy transactions, 0x1 for access list types, 0x2 for dynamic fees. + root*: Opt[Hash256] # 32 bytes of post-transaction stateroot (pre Byzantium) + status*: Opt[Quantity] # either 1 (success) or 0 (failure) + blobGasUsed*: Opt[Quantity] # uint64 + blobGasPrice*: Opt[UInt256] # UInt256 Topic* = FixedBytes[32] @@ -199,20 +199,20 @@ type AddressOrList* = SingleOrList[Address] FilterOptions* = object - fromBlock*: Option[RtBlockIdentifier] # (optional, default: "latest") integer block number, or "latest" for the last mined block or "pending", "earliest" for not yet mined transactions. - toBlock*: Option[RtBlockIdentifier] # (optional, default: "latest") integer block number, or "latest" for the last mined block or "pending", "earliest" for not yet mined transactions. + fromBlock*: Opt[RtBlockIdentifier] # (optional, default: "latest") integer block number, or "latest" for the last mined block or "pending", "earliest" for not yet mined transactions. + toBlock*: Opt[RtBlockIdentifier] # (optional, default: "latest") integer block number, or "latest" for the last mined block or "pending", "earliest" for not yet mined transactions. # TODO: address as optional list of address or optional address address*: AddressOrList # (optional) contract address or a list of addresses from which logs should originate. topics*: seq[TopicOrList] # (optional) list of DATA topics. Topics are order-dependent. Each topic can also be a list of DATA with "or" options. - blockHash*: Option[BlockHash] # (optional) hash of the block. If its present, fromBlock and toBlock, should be none. Introduced in EIP234 + blockHash*: Opt[BlockHash] # (optional) hash of the block. If its present, fromBlock and toBlock, should be none. Introduced in EIP234 LogObject* = object removed*: bool # true when the log was removed, due to a chain reorganization. false if its a valid log. - logIndex*: Option[Quantity] # integer of the log index position in the block. null when its pending log. - transactionIndex*: Option[Quantity] # integer of the transactions index position log was created from. null when its pending log. - transactionHash*: Option[TxHash] # hash of the transactions this log was created from. null when its pending log. - blockHash*: Option[BlockHash] # hash of the block where this log was in. null when its pending. null when its pending log. - blockNumber*: Option[BlockNumber] # the block number where this log was in. null when its pending. null when its pending log. + logIndex*: Opt[Quantity] # integer of the log index position in the block. null when its pending log. + transactionIndex*: Opt[Quantity] # integer of the transactions index position log was created from. null when its pending log. + transactionHash*: Opt[TxHash] # hash of the transactions this log was created from. null when its pending log. + blockHash*: Opt[BlockHash] # hash of the block where this log was in. null when its pending. null when its pending log. + blockNumber*: Opt[BlockNumber] # the block number where this log was in. null when its pending. null when its pending log. address*: Address # address from which this log originated. data*: seq[byte] # contains one or more 32 Bytes non-indexed arguments of the log. topics*: seq[Topic] # array of 0 to 4 32 Bytes DATA of indexed log arguments. @@ -257,7 +257,7 @@ type baseFeePerBlobGas*: seq[UInt256] gasUsedRatio*: seq[float64] blobGasUsedRatio*: seq[float64] - reward*: Option[seq[FeeHistoryReward]] + reward*: Opt[seq[FeeHistoryReward]] {.push raises: [].} @@ -279,10 +279,10 @@ func txOrHash*(hash: TxHash): TxOrHash = func txOrHash*(tx: TransactionObject): TxOrHash = TxOrHash(kind: tohTx, tx: tx) -proc `source=`*(c: var TransactionArgs, a: Option[Address]) = +proc `source=`*(c: var TransactionArgs, a: Opt[Address]) = c.`from` = a -func source*(c: TransactionArgs): Option[Address] = +func source*(c: TransactionArgs): Opt[Address] = c.`from` template `==`*(a, b: RlpEncodedBytes): bool = diff --git a/web3/execution_types.nim b/web3/execution_types.nim index d2cdc7c..dab800a 100644 --- a/web3/execution_types.nim +++ b/web3/execution_types.nim @@ -31,29 +31,29 @@ type baseFeePerGas*: UInt256 blockHash*: Hash256 transactions*: seq[TypedTransaction] - withdrawals*: Option[seq[WithdrawalV1]] - blobGasUsed*: Option[Quantity] - excessBlobGas*: Option[Quantity] - depositReceipts*: Option[seq[DepositReceiptV1]] - exits*: Option[seq[WithdrawalRequestV1]] + withdrawals*: Opt[seq[WithdrawalV1]] + blobGasUsed*: Opt[Quantity] + excessBlobGas*: Opt[Quantity] + depositReceipts*: Opt[seq[DepositReceiptV1]] + exits*: Opt[seq[WithdrawalRequestV1]] PayloadAttributes* = object timestamp*: Quantity prevRandao*: FixedBytes[32] suggestedFeeRecipient*: Address - withdrawals*: Option[seq[WithdrawalV1]] - parentBeaconBlockRoot*: Option[FixedBytes[32]] + withdrawals*: Opt[seq[WithdrawalV1]] + parentBeaconBlockRoot*: Opt[FixedBytes[32]] SomeOptionalPayloadAttributes* = - Option[PayloadAttributesV1] | - Option[PayloadAttributesV2] | - Option[PayloadAttributesV3] + Opt[PayloadAttributesV1] | + Opt[PayloadAttributesV2] | + Opt[PayloadAttributesV3] GetPayloadResponse* = object executionPayload*: ExecutionPayload - blockValue*: Option[UInt256] - blobsBundle*: Option[BlobsBundleV1] - shouldOverrideBuilder*: Option[bool] + blockValue*: Opt[UInt256] + blobsBundle*: Opt[BlobsBundleV1] + shouldOverrideBuilder*: Opt[bool] Version* {.pure.} = enum V1 @@ -125,20 +125,20 @@ func V3*(attr: PayloadAttributes): PayloadAttributesV3 = parentBeaconBlockRoot: attr.parentBeaconBlockRoot.get ) -func V1*(attr: Option[PayloadAttributes]): Option[PayloadAttributesV1] = +func V1*(attr: Opt[PayloadAttributes]): Opt[PayloadAttributesV1] = if attr.isNone: - return none(PayloadAttributesV1) - some(attr.get.V1) + return Opt.none(PayloadAttributesV1) + Opt.some(attr.get.V1) -func V2*(attr: Option[PayloadAttributes]): Option[PayloadAttributesV2] = +func V2*(attr: Opt[PayloadAttributes]): Opt[PayloadAttributesV2] = if attr.isNone: - return none(PayloadAttributesV2) - some(attr.get.V2) + return Opt.none(PayloadAttributesV2) + Opt.some(attr.get.V2) -func V3*(attr: Option[PayloadAttributes]): Option[PayloadAttributesV3] = +func V3*(attr: Opt[PayloadAttributes]): Opt[PayloadAttributesV3] = if attr.isNone: - return none(PayloadAttributesV3) - some(attr.get.V3) + return Opt.none(PayloadAttributesV3) + Opt.some(attr.get.V3) func payloadAttributes*(attr: PayloadAttributesV1): PayloadAttributes = PayloadAttributes( @@ -152,7 +152,7 @@ func payloadAttributes*(attr: PayloadAttributesV2): PayloadAttributes = timestamp: attr.timestamp, prevRandao: attr.prevRandao, suggestedFeeRecipient: attr.suggestedFeeRecipient, - withdrawals: some(attr.withdrawals) + withdrawals: Opt.some(attr.withdrawals) ) func payloadAttributes*(attr: PayloadAttributesV3): PayloadAttributes = @@ -160,21 +160,21 @@ func payloadAttributes*(attr: PayloadAttributesV3): PayloadAttributes = timestamp: attr.timestamp, prevRandao: attr.prevRandao, suggestedFeeRecipient: attr.suggestedFeeRecipient, - withdrawals: some(attr.withdrawals), - parentBeaconBlockRoot: some(attr.parentBeaconBlockRoot) + withdrawals: Opt.some(attr.withdrawals), + parentBeaconBlockRoot: Opt.some(attr.parentBeaconBlockRoot) ) -func payloadAttributes*(x: Option[PayloadAttributesV1]): Option[PayloadAttributes] = - if x.isNone: none(PayloadAttributes) - else: some(payloadAttributes x.get) +func payloadAttributes*(x: Opt[PayloadAttributesV1]): Opt[PayloadAttributes] = + if x.isNone: Opt.none(PayloadAttributes) + else: Opt.some(payloadAttributes x.get) -func payloadAttributes*(x: Option[PayloadAttributesV2]): Option[PayloadAttributes] = - if x.isNone: none(PayloadAttributes) - else: some(payloadAttributes x.get) +func payloadAttributes*(x: Opt[PayloadAttributesV2]): Opt[PayloadAttributes] = + if x.isNone: Opt.none(PayloadAttributes) + else: Opt.some(payloadAttributes x.get) -func payloadAttributes*(x: Option[PayloadAttributesV3]): Option[PayloadAttributes] = - if x.isNone: none(PayloadAttributes) - else: some(payloadAttributes x.get) +func payloadAttributes*(x: Opt[PayloadAttributesV3]): Opt[PayloadAttributes] = + if x.isNone: Opt.none(PayloadAttributes) + else: Opt.some(payloadAttributes x.get) func V1V2*(p: ExecutionPayload): ExecutionPayloadV1OrV2 = ExecutionPayloadV1OrV2( @@ -347,7 +347,7 @@ func executionPayload*(p: ExecutionPayloadV2): ExecutionPayload = baseFeePerGas: p.baseFeePerGas, blockHash: p.blockHash, transactions: p.transactions, - withdrawals: some(p.withdrawals) + withdrawals: Opt.some(p.withdrawals) ) func executionPayload*(p: ExecutionPayloadV3): ExecutionPayload = @@ -366,9 +366,9 @@ func executionPayload*(p: ExecutionPayloadV3): ExecutionPayload = baseFeePerGas: p.baseFeePerGas, blockHash: p.blockHash, transactions: p.transactions, - withdrawals: some(p.withdrawals), - blobGasUsed: some(p.blobGasUsed), - excessBlobGas: some(p.excessBlobGas) + withdrawals: Opt.some(p.withdrawals), + blobGasUsed: Opt.some(p.blobGasUsed), + excessBlobGas: Opt.some(p.excessBlobGas) ) func executionPayload*(p: ExecutionPayloadV4): ExecutionPayload = @@ -387,11 +387,11 @@ func executionPayload*(p: ExecutionPayloadV4): ExecutionPayload = baseFeePerGas: p.baseFeePerGas, blockHash: p.blockHash, transactions: p.transactions, - withdrawals: some(p.withdrawals), - blobGasUsed: some(p.blobGasUsed), - excessBlobGas: some(p.excessBlobGas), - depositReceipts: some(p.depositRequests), - exits: some(p.withdrawalRequests) + withdrawals: Opt.some(p.withdrawals), + blobGasUsed: Opt.some(p.blobGasUsed), + excessBlobGas: Opt.some(p.excessBlobGas), + depositReceipts: Opt.some(p.depositRequests), + exits: Opt.some(p.withdrawalRequests) ) func executionPayload*(p: ExecutionPayloadV1OrV2): ExecutionPayload = @@ -444,21 +444,21 @@ func getPayloadResponse*(x: ExecutionPayloadV1): GetPayloadResponse = func getPayloadResponse*(x: GetPayloadV2Response): GetPayloadResponse = GetPayloadResponse( executionPayload: x.executionPayload.executionPayload, - blockValue: some(x.blockValue) + blockValue: Opt.some(x.blockValue) ) func getPayloadResponse*(x: GetPayloadV3Response): GetPayloadResponse = GetPayloadResponse( executionPayload: x.executionPayload.executionPayload, - blockValue: some(x.blockValue), - blobsBundle: some(x.blobsBundle), - shouldOverrideBuilder: some(x.shouldOverrideBuilder) + blockValue: Opt.some(x.blockValue), + blobsBundle: Opt.some(x.blobsBundle), + shouldOverrideBuilder: Opt.some(x.shouldOverrideBuilder) ) func getPayloadResponse*(x: GetPayloadV4Response): GetPayloadResponse = GetPayloadResponse( executionPayload: x.executionPayload.executionPayload, - blockValue: some(x.blockValue), - blobsBundle: some(x.blobsBundle), - shouldOverrideBuilder: some(x.shouldOverrideBuilder) + blockValue: Opt.some(x.blockValue), + blobsBundle: Opt.some(x.blobsBundle), + shouldOverrideBuilder: Opt.some(x.shouldOverrideBuilder) ) \ No newline at end of file diff --git a/web3/primitives.nim b/web3/primitives.nim index dd2fdcd..62ba783 100644 --- a/web3/primitives.nim +++ b/web3/primitives.nim @@ -8,11 +8,15 @@ # those terms. import - std/[options, hashes, typetraits], - stint, stew/[byteutils, results] + std/[hashes, typetraits], + stint, + stew/byteutils, + results export - hashes, options, typetraits + hashes, + typetraits, + results const # https://github.com/ethereum/execution-apis/blob/c4089414bbbe975bbc4bf1ccf0a3d31f76feb3e1/src/engine/cancun.md#blobsbundlev1 diff --git a/web3/transaction_signing.nim b/web3/transaction_signing.nim index 143f55c..ef856e5 100644 --- a/web3/transaction_signing.nim +++ b/web3/transaction_signing.nim @@ -8,7 +8,7 @@ # those terms. import - options, + results, eth_api_types, stint, eth/[common, keys, rlp], eth/common/transaction @@ -22,11 +22,11 @@ func signTransaction(tr: var Transaction, pk: PrivateKey) = tr.R = fromBytesBE(UInt256, r.toOpenArray(0, 31)) tr.S = fromBytesBE(UInt256, r.toOpenArray(32, 63)) - tr.V = int64(v) + 27 # TODO! Complete this + tr.V = uint64(v) + 27 # TODO! Complete this func signTransactionEip155(tr: var Transaction, pk: PrivateKey) = let chainId = tr.chainId - tr.V = int64(chainId) * 2 + 35 + tr.V = uint64(chainId) * 2 + 35 let h = tr.txHashNoSignature let s = sign(pk, SkMessage(h.data)) @@ -37,14 +37,14 @@ func signTransactionEip155(tr: var Transaction, pk: PrivateKey) = tr.R = fromBytesBE(UInt256, r.toOpenArray(0, 31)) tr.S = fromBytesBE(UInt256, r.toOpenArray(32, 63)) - tr.V = int64(v) + int64(chainId) * 2 + 35 + tr.V = uint64(v) + uint64(chainId) * 2 + 35 func encodeTransaction*(s: TransactionArgs, pk: PrivateKey): seq[byte] = var tr = Transaction(txType: TxLegacy) tr.gasLimit = s.gas.get.GasInt tr.gasPrice = s.gasPrice.get.GasInt if s.to.isSome: - tr.to = some(EthAddress(s.to.get)) + tr.to = Opt.some(EthAddress(s.to.get)) if s.value.isSome: tr.value = s.value.get @@ -62,7 +62,7 @@ func encodeTransaction*(s: TransactionArgs, pk: PrivateKey, chainId: ChainId): s tr.gasLimit = s.gas.get.GasInt tr.gasPrice = s.gasPrice.get.GasInt if s.to.isSome: - tr.to = some(EthAddress(s.to.get)) + tr.to = Opt.some(EthAddress(s.to.get)) if s.value.isSome: tr.value = s.value.get