Foundry - testing and deployment
Testing and deploying smart contracts using Foundry
- Use
foundryup
toolchain installer
curl -L https://foundry.paradigm.xyz | bash
This will install foundryup
, then simply follow the instructions on-screen, which will make the foundryup command available in your CLI.
Running foundryup
by itself will install the latest precompiled binaries: forge
, cast
, anvil
, and chisel
. See foundryup --help
for more options.
-
Once installed, create a project. Let’s name it
hello_subspace
.To initialize the project, run
forge init hello_subspace
cd into
hello_subspace
directory and let’s have a look at the project’s structure. -
All the necessary repo structure was created automatically, so we can start writing and testing our smart contracts right away. As you can see, there are separate directories for storing smart contracts (src) and testing smart contracts (test). Let’s have a look at the
Counter.sol
smart contract and add a few more functions to the standard behavior. Our smart contract will have three functions:setNumber()
that sets the uint256 number to the provided value,increment()
which increases the value by 1 anddecrement()
which decreases the value by 1.// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
contract Counter {
uint256 public number;
function setNumber(uint256 newNumber) public {
number = newNumber;
}
function increment() public {
number++;
}
function decrement() public {
number--;
}
} -
Let’s make sure that all functions are working properly by adding a couple of tests to the
Counter.t.sol
test file and check if they pass.// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import "../src/Counter.sol";
contract CounterTest is Test {
Counter public counter;
function setUp() public {
counter = new Counter();
counter.setNumber(2);
}
function testIncrement() public {
counter.increment();
assertEq(counter.number(), 3);
}
function testSetNumber(uint256 x) public {
counter.setNumber(x);
assertEq(counter.number(), x);
}
function testDecrement() public {
counter.decrement();
assertEq(counter.number(), 1);
}
} -
In our tests, we first set the initial value of number to two, then check if function
increment()
increases the value by 1 and ifdecrement()
decreases the value by 1. Let’s build a project by running:forge build
and ensure that tests are working as expected by running
forge test