Skip to content

Commit

Permalink
Wire ForkedChainRef to graphql and rpc_utils (#2936)
Browse files Browse the repository at this point in the history
* fixes

* Wire ForkedChainRef to graphql and rpc_utils
  • Loading branch information
jangko authored Dec 13, 2024
1 parent a7ab984 commit 650fec5
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 28 deletions.
27 changes: 15 additions & 12 deletions nimbus/graphql/ethapi.nim
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import
".."/[transaction, evm/state, config, constants],
../transaction/call_evm,
../core/[tx_pool, tx_pool/tx_item],
../core/chain/forked_chain,
../common/common,
web3/eth_api_types

Expand Down Expand Up @@ -75,6 +76,7 @@ type
chainDB: CoreDbRef
ethNode: EthereumNode
txPool: TxPoolRef
chain: ForkedChainRef

{.push gcsafe, raises: [].}
{.pragma: apiRaises, raises: [].}
Expand Down Expand Up @@ -154,28 +156,28 @@ proc getStateDB(com: CommonRef, header: Header): LedgerRef {.deprecated: "Ledge

proc getBlockByNumber(ctx: GraphqlContextRef, number: Node): RespResult =
try:
let header = ?ctx.chainDB.getBlockHeader(toBlockNumber(number))
let header = ?ctx.chain.headerByNumber(toBlockNumber(number))
ok(headerNode(ctx, header))
except ValueError as exc:
err(exc.msg)

proc getBlockByNumber(ctx: GraphqlContextRef, number: base.BlockNumber): RespResult =
let header = ?ctx.chainDB.getBlockHeader(number)
let header = ?ctx.chain.headerByNumber(number)
ok(headerNode(ctx, header))

proc getBlockByHash(ctx: GraphqlContextRef, hash: Node): RespResult =
try:
let header = ?ctx.chainDB.getBlockHeader(toHash(hash))
let header = ?ctx.chain.headerByHash(toHash(hash))
ok(headerNode(ctx, header))
except ValueError as exc:
err(exc.msg)

proc getBlockByHash(ctx: GraphqlContextRef, hash: Hash32): RespResult =
let header = ?ctx.chainDB.getBlockHeader(hash)
let header = ?ctx.chain.headerByHash(hash)
ok(headerNode(ctx, header))

proc getLatestBlock(ctx: GraphqlContextRef): RespResult =
let header = ?ctx.chainDB.getCanonicalHead()
let header = ctx.chain.latestHeader
ok(headerNode(ctx, header))

proc getTxCount(ctx: GraphqlContextRef, txRoot: Hash32): RespResult =
Expand Down Expand Up @@ -1295,7 +1297,7 @@ proc queryLogs(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.
proc queryGasPrice(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} =
let ctx = GraphqlContextRef(ud)
try:
bigIntNode(calculateMedianGasPrice(ctx.chainDB))
bigIntNode(calculateMedianGasPrice(ctx.chain))
except CatchableError as em:
err("can't get gasPrice: " & em.msg)

Expand Down Expand Up @@ -1420,23 +1422,24 @@ proc initEthApi(ctx: GraphqlContextRef) =
echo res.error
quit(QuitFailure)

proc setupGraphqlContext*(com: CommonRef,
proc setupGraphqlContext*(chain: ForkedChainRef,
ethNode: EthereumNode,
txPool: TxPoolRef): GraphqlContextRef =
let ctx = GraphqlContextRef(
chainDB: com.db,
com : com,
chainDB: chain.com.db,
com : chain.com,
ethNode: ethNode,
txPool : txPool
txPool : txPool,
chain : chain,
)
graphql.init(ctx)
ctx.initEthApi()
ctx

proc setupGraphqlHttpHandler*(com: CommonRef,
proc setupGraphqlHttpHandler*(chain: ForkedChainRef,
ethNode: EthereumNode,
txPool: TxPoolRef): GraphqlHttpHandlerRef =
let ctx = setupGraphqlContext(com, ethNode, txPool)
let ctx = setupGraphqlContext(chain, ethNode, txPool)
GraphqlHttpHandlerRef.new(ctx)

{.pop.}
4 changes: 2 additions & 2 deletions nimbus/rpc.nim
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ proc addHttpServices(handlers: var seq[RpcHandlerProc],
# json-rpc have no reliable identification

if conf.graphqlEnabled:
let ctx = setupGraphqlContext(com, nimbus.ethNode, nimbus.txPool)
let ctx = setupGraphqlContext(nimbus.chainRef, nimbus.ethNode, nimbus.txPool)
let server = GraphqlHttpHandlerRef.new(ctx)
handlers.addHandler(server)
info "GraphQL API enabled", url = "http://" & $address
Expand Down Expand Up @@ -196,7 +196,7 @@ proc addServices(handlers: var seq[RpcHandlerProc],
# The order is important: graphql, ws, rpc

if conf.graphqlEnabled:
let ctx = setupGraphqlContext(com, nimbus.ethNode, nimbus.txPool)
let ctx = setupGraphqlContext(nimbus.chainRef, nimbus.ethNode, nimbus.txPool)
let server = GraphqlHttpHandlerRef.new(ctx)
handlers.addHandler(server)
info "GraphQL API enabled", url = "http://" & $address
Expand Down
17 changes: 8 additions & 9 deletions nimbus/rpc/rpc_utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ import
std/[sequtils, algorithm],
./rpc_types,
./params,
../db/core_db,
../db/ledger,
../constants, stint,
../utils/utils,
../transaction,
../transaction/call_evm,
../core/eip4844,
../core/chain/forked_chain,
../evm/types,
../evm/state,
../evm/precompiles,
Expand All @@ -29,13 +29,11 @@ import
../common/common,
web3/eth_api_types

proc calculateMedianGasPrice*(chain: CoreDbRef): GasInt {.raises: [RlpError].} =
proc calculateMedianGasPrice*(chain: ForkedChainRef): GasInt =
const minGasPrice = 30_000_000_000.GasInt
var prices = newSeqOfCap[GasInt](64)
let header = chain.getCanonicalHead().valueOr:
return minGasPrice
for encodedTx in chain.getBlockTransactionData(header.txRoot):
let tx = decodeTx(encodedTx)
let blk = chain.latestBlock
for tx in blk.transactions:
prices.add(tx.gasPrice)

if prices.len > 0:
Expand All @@ -57,9 +55,10 @@ proc calculateMedianGasPrice*(chain: CoreDbRef): GasInt {.raises: [RlpError].} =
# re-enable the "query.gasPrice" test case (remove `skip = true`).
result = max(result, minGasPrice)

proc unsignedTx*(tx: TransactionArgs, chain: CoreDbRef, defaultNonce: AccountNonce, chainId: ChainId): Transaction
{.gcsafe, raises: [CatchableError].} =

proc unsignedTx*(tx: TransactionArgs,
chain: ForkedChainRef,
defaultNonce: AccountNonce,
chainId: ChainId): Transaction =
var res: Transaction

if tx.to.isSome:
Expand Down
8 changes: 4 additions & 4 deletions nimbus/rpc/server_api.nim
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ proc ledgerFromTag(api: ServerAPIRef, blockTag: BlockTag): Result[LedgerRef, str
let header = ?api.headerFromTag(blockTag)
if not api.chain.stateReady(header):
api.chain.replaySegment(header.blockHash)

ok(LedgerRef.init(api.com.db))

proc blockFromTag(api: ServerAPIRef, blockTag: BlockTag): Result[Block, string] =
Expand Down Expand Up @@ -389,7 +389,7 @@ proc setupServerAPI*(api: ServerAPIRef, server: RpcServer, ctx: EthContext) =

server.rpc("eth_gasPrice") do() -> Web3Quantity:
## Returns an integer of the current gas price in wei.
w3Qty(calculateMedianGasPrice(api.com.db).uint64)
w3Qty(calculateMedianGasPrice(api.chain).uint64)

server.rpc("eth_accounts") do() -> seq[eth_types.Address]:
## Returns a list of addresses owned by client.
Expand Down Expand Up @@ -474,7 +474,7 @@ proc setupServerAPI*(api: ServerAPIRef, server: RpcServer, ctx: EthContext) =
let
accDB = api.ledgerFromTag(blockId("latest")).valueOr:
raise newException(ValueError, "Latest Block not found")
tx = unsignedTx(data, api.chain.db, accDB.getNonce(address) + 1, api.com.chainId)
tx = unsignedTx(data, api.chain, accDB.getNonce(address) + 1, api.com.chainId)
eip155 = api.com.isEIP155(api.chain.latestNumber)
signedTx = signTransaction(tx, acc.privateKey, eip155)
return rlp.encode(signedTx)
Expand All @@ -495,7 +495,7 @@ proc setupServerAPI*(api: ServerAPIRef, server: RpcServer, ctx: EthContext) =
let
accDB = api.ledgerFromTag(blockId("latest")).valueOr:
raise newException(ValueError, "Latest Block not found")
tx = unsignedTx(data, api.chain.db, accDB.getNonce(address) + 1, api.com.chainId)
tx = unsignedTx(data, api.chain, accDB.getNonce(address) + 1, api.com.chainId)
eip155 = api.com.isEIP155(api.chain.latestNumber)
signedTx = signTransaction(tx, acc.privateKey, eip155)
networkPayload =
Expand Down
2 changes: 1 addition & 1 deletion tests/test_graphql.nim
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ proc graphqlMain*() =
chain = setupChain()
txPool = TxPoolRef.new(chain)

let ctx = setupGraphqlContext(chain.com, ethNode, txPool)
let ctx = setupGraphqlContext(chain, ethNode, txPool)
when isMainModule:
ctx.main(caseFolder, purgeSchema = false)
else:
Expand Down

0 comments on commit 650fec5

Please sign in to comment.