Use rocketh with Foundry

This page takes a Foundry project, made by forge init, and adds rocketh to it: deploy scripts that deploy and configure your contracts, typed against what forge build compiled, and a forge test and a forge script that find what those scripts deployed by name, typed (deployer.Counter() returns a Counter). It does it in an order you can follow in a terminal, and ends with what is not supported yet.

A first release: please try it and tell us what breaks

Foundry support is new: @rocketh/forge 0.1.0 is its first release. It is tested, but it has not met many real projects yet, so we would love you to try it on yours. Bugs, rough edges, missing pieces, or "I expected it to work like this": open an issue on GitHub, at wighawag/rocketh. Feedback now shapes what comes next.

How the pieces fit

  • Deploy scripts stay TypeScript, run by rocketh. They are the same scripts a Hardhat project runs with hardhat-deploy, and they deploy anywhere rocketh does: a local node, a fork, a live network, a test.
  • forge compiles. rocketh-forge artifacts turns forge's out/ into typed artifacts, so a deploy script's constructor arguments and function calls are checked against your contracts' ABIs.
  • Solidity reads, it never deploys. rocketh-forge solidity runs your deploy scripts on a fresh chain and generates Solidity through which a forge test or a forge script reads the result: on a plain forge test, a fixture made by your deploy scripts; against a network or a fork, the deployments rocketh recorded there.

So setUp() does not redeploy your system by hand: your tests run against what your deploy scripts actually produce, proxies, libraries and post-deploy calls included.

You need Foundry (forge and anvil on the PATH) and Node.js 22 or later, with pnpm or npm.

A forge project

Start from any forge project. This page makes a new one:

# set the current directory
forge init my-project
cd my-project

forge init writes src/Counter.sol (a Counter with number, setNumber and increment), a test, a script and foundry.toml, and installs forge-std in lib/. rocketh adds a package.json beside them, which makes the folder an ES module package:

file: package.json

{
	"name": "my-project",
	"version": "0.0.0",
	"type": "module"
}

Then install rocketh, its command line (@rocketh/node), the two extensions most projects use (deploy, and read / execute), and @rocketh/forge:

pnpm add -D rocketh @rocketh/node @rocketh/deploy @rocketh/read-execute @rocketh/forge --allow-build=esbuild --allow-build=@parcel/watcher

The --allow-build flags answer a question pnpm 11 asks about those two packages' build scripts; Get started without Hardhat explains it.

foundry.toml

Two settings to add to the one forge init wrote:

file: foundry.toml

[profile.default]
src = "src"
out = "out"
libs = ["lib"]
# put the sources in the solc metadata, which rocketh records with each deployment and verification needs
use_literal_content = true
# the Solidity rocketh-forge generates reads the fixture and the deployment records at test time
fs_permissions = [{access = "read", path = "./generated"}, {access = "read", path = "./deployments"}]
  • use_literal_content = true, before you deploy anything. By default forge's solc metadata lists each source by hash and URL only. rocketh records that metadata with each deployment, and a block explorer needs the sources themselves, so without this setting rocketh-verify cannot verify. A deployment keeps the metadata it was made with (rocketh reuses it while the bytecode is unchanged), so setting it later only helps new deployments. rocketh-forge artifacts warns when it is missing.
  • fs_permissions lets the generated Solidity read generated/ (the fixture) and deployments/ (what rocketh deployed on each network). Without it, a test fails with forge's own error naming the path it may not read, and rocketh-forge solidity tells you so too.

Everything rocketh-forge writes goes to generated/, rebuilt from your build and your deployments, so keep it out of git, with node_modules:

printf 'node_modules\ngenerated\n' >> .gitignore

deployments/ is different: it is the record of what is deployed on each network, so commit it (a local node's folder, deployments/localhost, you may want to ignore).

The rocketh folder

rocketh needs two folders: rocketh for its configuration, and deploy for the deploy scripts.

mkdir rocketh deploy

rocketh reads its configuration from rocketh/config.ts: the named accounts your scripts use, the environments they deploy to, and the extensions they call.

file: rocketh/config.ts

import type {UserConfig} from 'rocketh/types';

export const config = {
	accounts: {
		deployer: {default: 0},
	},
	environments: {
		// the node `anvil` starts
		localhost: {chain: 31337},
	},
	data: {},
} as const satisfies UserConfig;

import * as deployExtension from '@rocketh/deploy';
import * as readExecuteExtension from '@rocketh/read-execute';

const extensions = {...deployExtension, ...readExecuteExtension};
export {extensions};

type Extensions = typeof extensions;
type Accounts = typeof config.accounts;
type Data = typeof config.data;
export type {Extensions, Accounts, Data};

deployer: {default: 0} is the node's first account, the one anvil holds the key for. On a live network you give rocketh a key or another signer instead: see Named accounts and signers and Environments and chains.

The file your deploy scripts import binds deployScript to those extensions and re-exports the typed artifacts:

file: rocketh/deploy.ts

import {type Accounts, type Data, type Extensions, extensions} from './config.js';
import {setupDeployScripts} from 'rocketh';

// generated by `rocketh-forge artifacts`, after `forge build`
export * as artifacts from '../generated/artifacts/index.js';

export const {deployScript} = setupDeployScripts<Extensions, Accounts, Data>(extensions);

A deploy script

Deploy scripts live in deploy/ and run in order. This one deploys Counter and then configures it:

file: deploy/001_deploy_counter.ts

import {deployScript, artifacts} from '../rocketh/deploy.js';

export default deployScript(
	async ({deploy, execute, namedAccounts}) => {
		const {deployer} = namedAccounts;

		const counter = await deploy('Counter', {
			account: deployer,
			artifact: artifacts.Counter,
		});

		// typed against Counter's ABI: a misspelled function or a wrong argument fails to compile
		await execute(counter, {account: deployer, functionName: 'setNumber', args: [42n]});
	},
	{tags: ['Counter']},
);

See Deploy scripts, tags and dependencies for how scripts are ordered and selected, and Deploy contracts, proxies, diamonds and deterministic addresses for what they can deploy.

Typed artifacts

forge build
npx rocketh-forge artifacts

rocketh-forge artifacts reads foundry.toml (its active profile: FOUNDRY_PROFILE, else default) for src and out, and writes generated/artifacts/ with one typed export per contract of src/, the same module hardhat-deploy generates for a Hardhat project. Test (.t.sol) and script (.s.sol) contracts, and libraries in lib/ such as forge-std, are left out; --sources names the folders or files to generate instead (to include a proxy from lib/, say). Run it after every forge build: it rewrites only what changed.

Deployments in forge tests

npx rocketh-forge solidity

It starts a fresh anvil (chain 31337), runs your deploy scripts on it, saves the resulting state, and writes generated/solidity/:

  • Deployments.g.sol: the Deployer type, getDeployer(), and one typed accessor per deployment (deployer.Counter()), plus has, getAddress and get by name, as forge-deploy has them;
  • DeploymentInterfaces.g.sol: an interface for each deployment that has no contract type to return (a diamond, a contract not in your build);
  • fixture/: the chain's state after your scripts ran, and their deployment records.

Now replace the test forge init wrote, which deploys its own Counter, with one that tests the Counter your deploy script deployed:

file: test/Counter.t.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {Test} from "forge-std/Test.sol";
import {Deployer, getDeployer} from "../generated/solidity/Deployments.g.sol";
import {Counter} from "../src/Counter.sol";

contract CounterTest is Test {
    Deployer deployer;

    function setUp() public {
        deployer = getDeployer();
    }

    function test_SetByTheDeployScript() public view {
        // a compile error if the deployment "Counter" is renamed or removed
        Counter counter = deployer.Counter();
        assertEq(counter.number(), 42);
    }

    function test_Increment() public {
        Counter counter = deployer.Counter();
        counter.increment();
        assertEq(counter.number(), 43);
    }

    function test_IncrementFromAnyone() public {
        vm.prank(makeAddr("alice"));
        deployer.Counter().increment();
        assertEq(deployer.Counter().number(), 43);
    }
}

and replace the script, which deployed a Counter too, with one that acts on the deployed one (it is used below):

file: script/Counter.s.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {Script} from "forge-std/Script.sol";
import {getDeployer} from "../generated/solidity/Deployments.g.sol";

contract IncrementCounter is Script {
    function run() public {
        vm.startBroadcast();
        getDeployer().Counter().increment();
        vm.stopBroadcast();
    }
}
forge test
Ran 3 tests for test/Counter.t.sol:CounterTest
[PASS] test_Increment() (gas: 26177)
[PASS] test_IncrementFromAnyone() (gas: 38589)
[PASS] test_SetByTheDeployScript() (gas: 22505)
Suite result: ok. 3 passed; 0 failed; 0 skipped

On chain 31337, which is what a plain forge test runs on, getDeployer() loads the fixture (with vm.loadAllocs, and the fixture's block number and timestamp), so each test starts from the state your deploy scripts left, setNumber(42) included. Nothing is redeployed per test, and the generated code needs nothing installed, not even forge-std.

The accessors read the records with cheatcodes, never with a call, so a cheatcode that applies to the next call applies to the call you make on what they return: vm.prank(alice); deployer.Counter().increment(); sends increment from alice, and vm.expectRevert(...) before deployer.Counter().something() expects that call to revert.

What an accessor returns:

  • the contract the deployment was made from, when forge builds it (deployer.Counter() returns a Counter);
  • for a proxy, the implementation's contract at the proxy's address;
  • for a diamond, an interface generated from the merged ABI of its facets;
  • for a library, its address, since Solidity cannot use a library as a type;
  • for a contract that is not in your build, or that a different solc version compiled, an interface generated from its ABI. rocketh-forge solidity says which contracts get one, and why.

Keeping it up to date

The generated files are a snapshot of your build and your deployments:

  • A contract changed since the fixture was made: setUp() fails with the command to run, the rocketh-forge commands as you last ran them.
  • A deploy script changed (a new step, another argument): run rocketh-forge solidity again, or the fixture is still the old run.
  • A new deployment name needs rocketh-forge solidity again, for its accessor. A network deployed after it ran is found without it, since each environment's chain is read at test time.
  • A fresh clone (and CI) has no generated/ yet, and every test file that imports it fails to compile, so build without tests and scripts first:
forge build --skip test --skip script
npx rocketh-forge artifacts
npx rocketh-forge solidity
forge test

A package.json script ("generate": "forge build --skip test --skip script && rocketh-forge artifacts && rocketh-forge solidity") saves typing it.

Deploy, and a forge script

Start a local node, in a terminal of its own since it keeps running:

async: anvil keeps running, in a terminal of its own

anvil

and deploy to it with rocketh:

npx rocketh -e localhost --skip-prompts

rocketh runs every script in deploy/ and records what it deployed in deployments/localhost/. Run it again and it finds Counter deployed with the same code and does not redeploy it. On a local node it asks nothing, so --skip-prompts is not needed there; on a live network it shows the gas price and waits for you to confirm, which is what you want (see Asking before a run).

A forge script

The script written above reads Counter by name. On a network, getDeployer() reads the deployments rocketh recorded for that network's chain. A local node on chain 31337 is the one exception: chain 31337 means the fixture, which is not that node's state, so a script that broadcasts there must name the environment:

ROCKETH_ENVIRONMENT=localhost forge script script/Counter.s.sol --rpc-url http://127.0.0.1:8545 --broadcast --unlocked --sender 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266

--unlocked --sender uses the account anvil holds the key for; on a live network use your usual forge signer (--account, --private-key, --ledger). getDeployer() makes no transaction, so it may be called before or after vm.startBroadcast(): the script broadcasts only its own calls. Without --rpc-url, forge script runs against the fixture, as a test does.

Which deployments getDeployer() reads

In order:

  1. ROCKETH_ENVIRONMENT=<name>: the records rocketh -e <name> saved in deployments/<name>/, and a test or script on another chain than theirs is refused. ROCKETH_ENVIRONMENT=fixture names the fixture.
  2. On chain 31337 (a plain forge test): the fixture.
  3. Otherwise, the environment whose records were made on the current chain. So forge test --fork-url <a mainnet RPC> reads what rocketh deployed on mainnet, and the same tests run against the fixture and against the real deployments. If two environments are on that chain, set ROCKETH_ENVIRONMENT to choose.
# the same tests, against what is deployed on Sepolia (the records in deployments/sepolia)
forge test --fork-url $SEPOLIA_RPC_URL

rocketh-forge solidity -e sepolia,mainnet restricts the environments it reads, and so the ones selected by chain.

forge coverage

forge coverage --no-match-coverage generated

forge coverage builds without the optimizer, so it never has the bytecode the fixture deployed: under it, the "contract changed" check is skipped and the tests run against the fixture's code. The generated files would appear in coverage's table and lower the totals; --no-match-coverage generated leaves them out (forge has no foundry.toml setting for it).

Verifying and exporting

Verification, export to a frontend, and generated documentation all work from the deployment records, exactly as for any rocketh project: see Export, verify and document. With use_literal_content = true set before you deployed, rocketh-verify has every source it needs.

Known limits

This is a first release; these are the limits we know of. If you hit one that matters to you, or one that is not here, open an issue: it helps decide what comes next.

  • Deploy scripts are TypeScript only. There are no Solidity deploy scripts (as forge-deploy has): Solidity reads deployments, it does not make them. Typed deploy calls from Solidity remain a possible later step.
  • A fresh clone needs the generation steps before forge test compiles, as above. A cheaper step meant to run on install is being considered.
  • The fixture needs anvil on the PATH. It is made by a run of your scripts in an environment named memory, as in any run without an environment, so a script that branches on the environment's name or tags sees memory.
  • Named accounts and a deployment's linkedData are not readable from Solidity yet. A test that needs the admin address has to know it.
  • Foundry's keystore is not a rocketh signer yet: rocketh cannot use an account imported with cast wallet import. Give rocketh its keys as Named accounts and signers describes; forge script keeps using its own.
  • rocketh-forge solidity reads every folder of deployments/, including a local one (deployments/localhost) you may not commit, so the generated accessors can differ between machines. -e restricts it.
  • forge script --broadcast can set too low a gas limit on a live network: forge takes it from its own local simulation, not from the node, and a transaction can be mined and fail out of gas. --skip-simulation makes forge ask the node; --gas-estimate-multiplier raises forge's estimate. Deploys made by rocketh ask the node and are not affected.
  • hardhat test solidity is not supported: rocketh-forge solidity reads forge's build and has only been run under forge.

Next

Search
Search the documentation