Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add hardhat_getForkedChainId JSON-RPC method #1592

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/guides/mainnet-forking.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,19 @@ await network.provider.request({

This will reset Hardhat Network, starting a new instance in the state described [here](../hardhat-network/README.md#hardhat-network-initial-state).

## Getting the chainId of the original chain

You can query the original chainId of the network that this fork was forked from:

```ts
await network.provider.request({
method: "hardhat_getForkedChainId",
params: [],
)};
```

Returns the chanId of the forked network, or null if this chain is not a fork.

## Troubleshooting

### "Project ID does not have access to archive state"
Expand Down
1 change: 1 addition & 0 deletions docs/hardhat-network/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ To customise it, take a look at [the configuration section](/config/README.md#ha
- `hardhat_dropTransaction` – Remove a transaction from the mempool
- `hardhat_impersonateAccount` – see the [Mainnet Forking guide](../guides/mainnet-forking.md)
- `hardhat_reset` – see the [Mainnet Forking guide](../guides/mainnet-forking.md)
- `hardhat_getForkedChainId` - see the [Mainnet Forking guide](../guides/mainnet-forking.md)
- `hardhat_setBalance` – Modifies the balance of an account.
- `hardhat_setCode` – Modifies the code of an account.
- `hardhat_setLoggingEnabled` – Enable or disable logging in Hardhat Network
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export class JsonRpcClient {
constructor(
private _httpProvider: HttpProvider,
private _networkId: number,
private _chainId: number | undefined,
private _latestBlockNumberOnCreation: number,
private _maxReorg: number,
private _forkCachePath?: string
Expand All @@ -37,6 +38,10 @@ export class JsonRpcClient {
return this._networkId;
}

public getChainId(): number | undefined {
return this._chainId;
}

public async getDebugTraceTransaction(transactionHash: Buffer): Promise<any> {
return this._perform(
"debug_traceTransaction",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ export class HardhatModule {
case "hardhat_reset":
return this._resetAction(...this._resetParams(params));

case "hardhat_getForkedChainId":
return this._getForkedChainIdAction(
...this._getForkedChainIdParams(params)
);

case "hardhat_setLoggingEnabled":
return this._setLoggingEnabledAction(
...this._setLoggingEnabledParams(params)
Expand Down Expand Up @@ -198,6 +203,16 @@ export class HardhatModule {
return true;
}

// hardhat_getForkedChainId

private _getForkedChainIdParams(params: any[]): [] {
return validateParams(params);
}

private async _getForkedChainIdAction(): Promise<number | null> {
return (await this._node.getForkedChainId()) ?? null;
}

// hardhat_setLoggingEnabled

private _setLoggingEnabledParams(params: any[]): [boolean] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ export class HardhatNode extends EventEmitter {
let initialBlockTimeOffset: BN | undefined;

let forkNetworkId: number | undefined;
let forkChainId: number | undefined;

if ("forkConfig" in config) {
const {
Expand All @@ -141,6 +142,7 @@ export class HardhatNode extends EventEmitter {
common = await makeForkCommon(config);

forkNetworkId = forkClient.getNetworkId();
forkChainId = forkClient.getChainId();

this._validateHardforks(
config.forkConfig.blockNumber,
Expand Down Expand Up @@ -200,7 +202,8 @@ export class HardhatNode extends EventEmitter {
initialBlockTimeOffset,
genesisAccounts,
tracingConfig,
forkNetworkId
forkNetworkId,
forkChainId
);

return [common, node];
Expand Down Expand Up @@ -271,7 +274,8 @@ Hardhat Network's forking functionality only works with blocks from at least spu
private _blockTimeOffsetSeconds: BN = new BN(0),
genesisAccounts: GenesisAccount[],
tracingConfig?: TracingConfig,
private _forkNetworkId?: number
private _forkNetworkId?: number,
private _forkChainId?: number
) {
super();

Expand Down Expand Up @@ -1099,6 +1103,10 @@ Hardhat Network's forking functionality only works with blocks from at least spu
);
}

public async getForkedChainId(): Promise<number | undefined> {
return this._forkChainId;
}

private async _addPendingTransaction(tx: TypedTransaction): Promise<string> {
await this._txPool.addTransaction(tx);
await this._notifyPendingTransaction(tx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export async function makeForkClient(
);

const networkId = await getNetworkId(provider);
let chainId;
try {
chainId = await _getChainIdFromEthChainId(provider);
} catch (error) {
chainId = await _getChainIdFromEthNetVersion(provider);
}

const actualMaxReorg = getLargestPossibleReorg(networkId);
const maxReorg = actualMaxReorg ?? FALLBACK_MAX_REORG;

Expand Down Expand Up @@ -86,6 +93,7 @@ Please use block number ${lastSafeBlock} or wait for the block to get ${
const forkClient = new JsonRpcClient(
provider,
networkId,
chainId,
latestBlock,
maxReorg,
cacheToDiskEnabled ? forkCachePath : undefined
Expand All @@ -110,9 +118,32 @@ async function getNetworkId(provider: HttpProvider) {
const networkIdString = (await provider.request({
method: "net_version",
})) as string;

return parseInt(networkIdString, 10);
}

async function _getChainIdFromEthChainId(
provider: HttpProvider
): Promise<number> {
const id = (await provider.request({
method: "eth_chainId",
fvictorio marked this conversation as resolved.
Show resolved Hide resolved
})) as string;

return rpcQuantityToNumber(id);
}

async function _getChainIdFromEthNetVersion(
provider: HttpProvider
): Promise<number> {
const id = (await provider.request({
method: "net_version",
})) as string;

// There's a node returning this as decimal instead of QUANTITY.
// TODO: Document here which node does that
return id.startsWith("0x") ? rpcQuantityToNumber(id) : parseInt(id, 10);
}

async function getLatestBlockNumber(provider: HttpProvider) {
const latestBlockString = (await provider.request({
method: "eth_blockNumber",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
1,
fvictorio marked this conversation as resolved.
Show resolved Hide resolved
3
);

Expand All @@ -88,6 +89,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3
);

Expand All @@ -102,6 +104,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3
);

Expand All @@ -122,6 +125,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3,
this.tmpDir
);
Expand Down Expand Up @@ -149,6 +153,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3,
this.tmpDir
);
Expand Down Expand Up @@ -183,6 +188,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3
);

Expand Down Expand Up @@ -213,6 +219,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3
);

Expand Down Expand Up @@ -242,6 +249,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3
);
await assert.isRejected(
Expand Down Expand Up @@ -270,6 +278,7 @@ describe("JsonRpcClient", () => {
fakeProvider as any,
1,
123,
undefined,
3
);
await assert.isRejected(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,19 @@ describe("Hardhat module", function () {
}
});

describe("hardhat_getForkedChainId", function () {
it("gets correct chainId", async function () {
const hardhatChainId = await this.provider.send(
"hardhat_getForkedChainId"
);
if (isFork) {
assert.equal(hardhatChainId, 1);
} else {
assert.isNull(hardhatChainId);
}
});
});

describe("hardhat_setBalance", function () {
it("should reject an invalid address", async function () {
await assertInvalidArgumentsError(
Expand Down