Skip to content

Commit

Permalink
monorepo: more adjustments related to json and rpc (#3639)
Browse files Browse the repository at this point in the history
* monorepo: more adjustments related to json and rpc

* client: helpRPC casing

* wallet: revert wallet test updates

---------

Co-authored-by: Jochem Brouwer <[email protected]>
  • Loading branch information
gabrocheleau and jochem-brouwer authored Sep 6, 2024
1 parent 1a20b90 commit 4e4082a
Show file tree
Hide file tree
Showing 23 changed files with 72 additions and 69 deletions.
2 changes: 2 additions & 0 deletions config/cspell-ts.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
}
],
"words": [
"!Json",
"!Rpc",
"Hardfork",
"hardfork",
"Chainstart",
Expand Down
4 changes: 2 additions & 2 deletions packages/block/src/block/constructors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,8 @@ export async function createBlockFromExecutionPayload(
}

/**
* Method to retrieve a block from a beacon payload json
* @param payload json of a beacon beacon fetched from beacon apis
* Method to retrieve a block from a beacon payload JSON
* @param payload JSON of a beacon beacon fetched from beacon apis
* @param opts {@link BlockOptions}
* @returns the block constructed block
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/block/src/from-beacon-payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type BeaconConsolidationRequest = {
target_pubkey: PrefixedHexString
}

// Payload json that one gets using the beacon apis
// Payload JSON that one gets using the beacon apis
// curl localhost:5052/eth/v2/beacon/blocks/56610 | jq .data.message.body.execution_payload
export type BeaconPayloadJSON = {
parent_hash: PrefixedHexString
Expand Down
14 changes: 7 additions & 7 deletions packages/block/src/header/header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ export class BlockHeader {
const withdrawalAttr = this.withdrawalsRoot
? { withdrawalsRoot: bytesToHex(this.withdrawalsRoot) }
: {}
const jsonDict: JSONHeader = {
const JSONDict: JSONHeader = {
parentHash: bytesToHex(this.parentHash),
uncleHash: bytesToHex(this.uncleHash),
coinbase: this.coinbase.toString(),
Expand All @@ -759,19 +759,19 @@ export class BlockHeader {
nonce: bytesToHex(this.nonce),
}
if (this.common.isActivatedEIP(1559)) {
jsonDict.baseFeePerGas = bigIntToHex(this.baseFeePerGas!)
JSONDict.baseFeePerGas = bigIntToHex(this.baseFeePerGas!)
}
if (this.common.isActivatedEIP(4844)) {
jsonDict.blobGasUsed = bigIntToHex(this.blobGasUsed!)
jsonDict.excessBlobGas = bigIntToHex(this.excessBlobGas!)
JSONDict.blobGasUsed = bigIntToHex(this.blobGasUsed!)
JSONDict.excessBlobGas = bigIntToHex(this.excessBlobGas!)
}
if (this.common.isActivatedEIP(4788)) {
jsonDict.parentBeaconBlockRoot = bytesToHex(this.parentBeaconBlockRoot!)
JSONDict.parentBeaconBlockRoot = bytesToHex(this.parentBeaconBlockRoot!)
}
if (this.common.isActivatedEIP(7685)) {
jsonDict.requestsRoot = bytesToHex(this.requestsRoot!)
JSONDict.requestsRoot = bytesToHex(this.requestsRoot!)
}
return jsonDict
return JSONDict
}

/**
Expand Down
7 changes: 4 additions & 3 deletions packages/block/test/eip7685block.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
createBlockHeader,
} from '../src/index.js'

import type { JSONRPCBlock } from '../src/index.js'
import type { CLRequest, CLRequestType } from '@ethereumjs/util'

function getRandomDepositRequest(): CLRequest<CLRequestType> {
Expand Down Expand Up @@ -153,9 +154,9 @@ describe('fromRPC tests', () => {
common,
},
)
const jsonBlock = block.toJSON()
const rpcBlock: any = { ...jsonBlock.header, requests: jsonBlock.requests }
const createBlockFromJSON = createBlockFromRPC(rpcBlock, undefined, { common })
const JSONBlock = block.toJSON()
const RPCBlock = { ...JSONBlock.header, requests: JSONBlock.requests }
const createBlockFromJSON = createBlockFromRPC(RPCBlock as JSONRPCBlock, undefined, { common })
assert.deepEqual(block.hash(), createBlockFromJSON.hash())
})
})
4 changes: 2 additions & 2 deletions packages/block/test/from-beacon-payload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('[fromExecutionPayloadJSON]: 4844 devnet 5', () => {
commonJSON.config = { ...commonJSON.config, chainId: 4844001005 }
const network = 'sharding'
common = createCommonFromGethGenesis(commonJSON, { chain: network, customCrypto: { kzg } })
// safely change chainId without modifying underlying json
// safely change chainId without modifying underlying JSON

common.setHardfork(Hardfork.Cancun)
})
Expand Down Expand Up @@ -86,7 +86,7 @@ describe('[fromExecutionPayloadJSON]: 4844 devnet 5', () => {
describe('[fromExecutionPayloadJSON]: kaustinen', () => {
const network = 'kaustinen'

// safely change chainId without modifying underlying json
// safely change chainId without modifying underlying JSON
const common = createCommonFromGethGenesis(testnetVerkleKaustinen, {
chain: network,
eips: [6800],
Expand Down
6 changes: 3 additions & 3 deletions packages/block/test/from-rpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe('[fromRPC]: block #2924874', () => {
})

describe('[fromRPC]:', () => {
it('Should create a block with json data that includes a transaction with value parameter as integer string', () => {
it('Should create a block with JSON data that includes a transaction with value parameter as integer string', () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.London })
const valueAsIntegerString = '1'
const blockDataTransactionValueAsInteger = blockData
Expand All @@ -58,7 +58,7 @@ describe('[fromRPC]:', () => {
)
})

it('Should create a block with json data that includes a transaction with defaults with gasPrice parameter as integer string', () => {
it('Should create a block with JSON data that includes a transaction with defaults with gasPrice parameter as integer string', () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.London })
const gasPriceAsIntegerString = '1'
const blockDataTransactionGasPriceAsInteger = blockData
Expand All @@ -74,7 +74,7 @@ describe('[fromRPC]:', () => {
)
})

it('should create a block given json data that includes a difficulty parameter of type integer string', () => {
it('should create a block given JSON data that includes a difficulty parameter of type integer string', () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.London })
const blockDifficultyAsInteger = createBlockFromRPC(
blockDataDifficultyAsInteger as JSONRPCBlock,
Expand Down
4 changes: 2 additions & 2 deletions packages/client/archive/libp2p/cli-libp2p.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const end = (child: ChildProcessWithoutNullStreams, hasEnded: boolean) => {
assert.ok(res, 'client shut down successfully')
}

describe('[CLI] rpc', () => {
describe('[CLI] RPC', () => {
it('libp2p should start up', () => {
const file = require.resolve('../../dist/bin/cli.js')
const child = spawn(process.execPath, [
Expand All @@ -34,7 +34,7 @@ describe('[CLI] rpc', () => {
assert.ok(true, 'libp2p server started')
const bootnodeAddressArray = message.split(' ')
const bootnodeAddressIndex = bootnodeAddressArray.findIndex((chunk: string) =>
chunk.startsWith('url=')
chunk.startsWith('url='),
)
const bootNodeAddress = bootnodeAddressArray[bootnodeAddressIndex].split('=')[1]
child2 = spawn(process.execPath, [
Expand Down
4 changes: 2 additions & 2 deletions packages/client/bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ import { Event } from '../src/types.js'
import { parseMultiaddrs } from '../src/util/index.js'
import { setupMetrics } from '../src/util/metrics.js'

import { helprpc, startRPCServers } from './startRPC.js'
import { helpRPC, startRPCServers } from './startRPC.js'

import type { Logger } from '../src/logging.js'
import type { FullEthereumService } from '../src/service/index.js'
Expand Down Expand Up @@ -924,7 +924,7 @@ const stopClient = async (
async function run() {
if (args.helpRPC === true) {
// Output RPC help and exit
return helprpc()
return helpRPC()
}

// TODO sharding: Just initialize kzg library now, in future it can be optimized to be
Expand Down
6 changes: 3 additions & 3 deletions packages/client/bin/startRPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function startRPCServers(client: EthereumClient, args: RPCArgs) {

if (rpc) {
rpcHttpServer = createRPCServerListener({
rpcCors,
RPCCors: rpcCors,
server,
withEngineMiddleware:
withEngineMethods && rpcEngineAuth
Expand Down Expand Up @@ -179,7 +179,7 @@ export function startRPCServers(client: EthereumClient, args: RPCArgs) {
})
servers.push(server)
const rpcHttpServer = createRPCServerListener({
rpcCors,
RPCCors: rpcCors,
server,
withEngineMiddleware: rpcEngineAuth
? {
Expand Down Expand Up @@ -228,7 +228,7 @@ export function startRPCServers(client: EthereumClient, args: RPCArgs) {
/**
* Output RPC help and exit
*/
export function helprpc() {
export function helpRPC() {
console.log('-'.repeat(27))
console.log('JSON-RPC: Supported Methods')
console.log('-'.repeat(27))
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/execution/vmexecution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -815,13 +815,13 @@ export class VMExecution extends Execution {
// save the data in spec test compatible manner
const blockNumStr = `${errorBlock.header.number}`
const file = `${this.config.getInvalidPayloadsDir()}/${blockNumStr}.json`
const jsonDump = {
const JSONDump = {
[blockNumStr]: {
parent: headBlock.toExecutionPayload(),
execute: errorBlock.toExecutionPayload(),
},
}
writeFileSync(file, JSON.stringify(jsonDump, null, 2))
writeFileSync(file, JSON.stringify(JSONDump, null, 2))
this.config.logger.warn(`${errorMsg}:\n${error} payload saved to=${file}`)
} else {
this.config.logger.warn(`${errorMsg}:\n${error}`)
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/rpc/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function callWithStackTrace(handler: Function, debug: boolean) {
/**
* Returns tx formatted to the standard JSON-RPC fields
*/
export const jsonRPCTx = (tx: TypedTransaction, block?: Block, txIndex?: number): JSONRPCTx => {
export const toJSONRPCTx = (tx: TypedTransaction, block?: Block, txIndex?: number): JSONRPCTx => {
const txJSON = tx.toJSON()
return {
blockHash: block ? bytesToHex(block.hash()) : null,
Expand Down
28 changes: 14 additions & 14 deletions packages/client/src/rpc/modules/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
} from '@ethereumjs/vm'

import { INTERNAL_ERROR, INVALID_HEX_STRING, INVALID_PARAMS, PARSE_ERROR } from '../error-code.js'
import { callWithStackTrace, getBlockByOption, jsonRPCTx } from '../helpers.js'
import { callWithStackTrace, getBlockByOption, toJSONRPCTx } from '../helpers.js'
import { middleware, validators } from '../validation.js'

import type { Chain } from '../../blockchain/index.js'
Expand Down Expand Up @@ -102,15 +102,15 @@ type JSONRPCLog = {
/**
* Returns block formatted to the standard JSON-RPC fields
*/
const jsonRPCBlock = async (
const toJSONRPCBlock = async (
block: Block,
chain: Chain,
includeTransactions: boolean,
): Promise<JSONRPCBlock> => {
const json = block.toJSON()
const header = json!.header!
const transactions = block.transactions.map((tx, txIndex) =>
includeTransactions ? jsonRPCTx(tx, block, txIndex) : bytesToHex(tx.hash()),
includeTransactions ? toJSONRPCTx(tx, block, txIndex) : bytesToHex(tx.hash()),
)
const withdrawalsAttr =
header.withdrawalsRoot !== undefined
Expand Down Expand Up @@ -154,7 +154,7 @@ const jsonRPCBlock = async (
/**
* Returns log formatted to the standard JSON-RPC fields
*/
const jsonRPCLog = async (
const toJSONRPCLog = async (
log: Log,
block?: Block,
tx?: TypedTransaction,
Expand All @@ -175,7 +175,7 @@ const jsonRPCLog = async (
/**
* Returns receipt formatted to the standard JSON-RPC fields
*/
const jsonRPCReceipt = async (
const toJSONRPCReceipt = async (
receipt: TxReceipt,
gasUsed: bigint,
effectiveGasPrice: bigint,
Expand All @@ -198,7 +198,7 @@ const jsonRPCReceipt = async (
gasUsed: bigIntToHex(gasUsed),
contractAddress: contractAddress?.toString() ?? null,
logs: await Promise.all(
receipt.logs.map((l, i) => jsonRPCLog(l, block, tx, txIndex, logIndex + i)),
receipt.logs.map((l, i) => toJSONRPCLog(l, block, tx, txIndex, logIndex + i)),
),
logsBloom: bytesToHex(receipt.bitvector),
root:
Expand Down Expand Up @@ -680,7 +680,7 @@ export class Eth {

try {
const block = await this._chain.getBlock(hexToBytes(blockHash))
return await jsonRPCBlock(block, this._chain, includeTransactions)
return await toJSONRPCBlock(block, this._chain, includeTransactions)
} catch (error) {
return null
}
Expand All @@ -702,7 +702,7 @@ export class Eth {
}
try {
const block = await getBlockByOption(blockOpt, this._chain)
const response = await jsonRPCBlock(block, this._chain, includeTransactions)
const response = await toJSONRPCBlock(block, this._chain, includeTransactions)
return response
} catch {
return null
Expand Down Expand Up @@ -812,7 +812,7 @@ export class Eth {
}

const tx = block.transactions[txIndex]
return jsonRPCTx(tx, block, txIndex)
return toJSONRPCTx(tx, block, txIndex)
} catch (error: any) {
throw {
code: INVALID_PARAMS,
Expand All @@ -837,7 +837,7 @@ export class Eth {
}

const tx = block.transactions[txIndex]
return jsonRPCTx(tx, block, txIndex)
return toJSONRPCTx(tx, block, txIndex)
} catch (error: any) {
throw {
code: INVALID_PARAMS,
Expand All @@ -859,7 +859,7 @@ export class Eth {
const [_receipt, blockHash, txIndex] = result
const block = await this._chain.getBlock(blockHash)
const tx = block.transactions[txIndex]
return jsonRPCTx(tx, block, txIndex)
return toJSONRPCTx(tx, block, txIndex)
}

/**
Expand Down Expand Up @@ -969,7 +969,7 @@ export class Eth {
block.header.baseFeePerGas!
: (tx as LegacyTx).gasPrice

return jsonRPCReceipt(
return toJSONRPCReceipt(
r,
totalGasSpent,
effectiveGasPrice,
Expand Down Expand Up @@ -1031,7 +1031,7 @@ export class Eth {

const { totalGasSpent, createdAddress } = runBlockResult.results[txIndex]
const { blobGasPrice, blobGasUsed } = runBlockResult.receipts[txIndex] as EIP4844BlobTxReceipt
return jsonRPCReceipt(
return toJSONRPCReceipt(
receipt,
totalGasSpent,
effectiveGasPrice,
Expand Down Expand Up @@ -1130,7 +1130,7 @@ export class Eth {
const logs = await this.receiptsManager.getLogs(from, to, addressBytes, formattedTopics)
return Promise.all(
logs.map(({ log, block, tx, txIndex, logIndex }) =>
jsonRPCLog(log, block, tx, txIndex, logIndex),
toJSONRPCLog(log, block, tx, txIndex, logIndex),
),
)
}
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/rpc/modules/txpool.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { callWithStackTrace, jsonRPCTx } from '../helpers.js'
import { callWithStackTrace, toJSONRPCTx } from '../helpers.js'
import { middleware } from '../validation.js'

import type { EthereumClient } from '../../index.js'
Expand Down Expand Up @@ -37,7 +37,7 @@ export class TxPool {
for (const pool of this._txpool.pool) {
const pendingForAcct = new Map<bigint, any>()
for (const tx of pool[1]) {
pendingForAcct.set(tx.tx.nonce, jsonRPCTx(tx.tx))
pendingForAcct.set(tx.tx.nonce, toJSONRPCTx(tx.tx))
}
if (pendingForAcct.size > 0) pending.set('0x' + pool[0], Object.fromEntries(pendingForAcct))
}
Expand Down
Loading

0 comments on commit 4e4082a

Please sign in to comment.