I’ve heard about Foundry being very hyped up right now as the best Environment for developing Contracts on the Blockchain. What’s different and very good about Foundry is that the tests are written in the Solidity language, so you don’t have to learn another language like JS to do your tests. Also it doesn’t make sense to test code with some other language.
What I find a little worrying tho is that the tests do not really run on your blockchain node, they only copy its state. You can read more about that here.
Anyways here is how to set up your Foundry Environemnt for Blockchain Development:
curl -L https://foundry.paradigm.xyz | bash
foundryup
forge init hello_foundry
cd hello_foundry
forge install
Add your HelloWorld.sol
// Hello World contract pragma solidity >=0.4.22 <0.9.0; contract HelloWorld { string public greeting; // Constructor to initialize the greeting message constructor() { greeting = "Hello, World!"; } // Function to get the current greeting message function getGreeting() public view returns (string memory) { return greeting; } // Function to set a new greeting message function setGreeting(string memory _newGreeting) public { greeting = _newGreeting; } }
forge build
forge test
- run
anvil
which will run a local testnet - Get a private key from one of the accounts created by Anvil
forge create HelloWorld --rpc-url http://127.0.0.1:8545 --interactive
When prompted for private key copy paste the one from
Ganache
. This is the result.[⠒] Compiling… No files changed, compilation skipped Enter private key: Deployer: 0x7a97620D02ADA6441d9d6c7CCCC625d8D943D776 Deployed to: 0xd34bad36e60e1BddF87Ec04AA7CAE67642b6831B Transaction hash: 0x085b6a94c4c1f07a2c6e7cf1daca47440b181ff873ce04dbdbfbbf15ee7f9dfd
- You can finally interact with your contract, by calling the functions you’ve defined. Let’s start out by calling a
getGreeting
function which just returns a string stored in a variable.The
0xd34bad36e60e1BddF87Ec04AA7CAE67642b6831B
is the hash of our deployed contract that we got when calling forge createcast call 0xd34bad36e60e1BddF87Ec04AA7CAE67642b6831B "getGreeting()(string memory)" --rpc-url http://127.0.0.1:8545
- To call
setGreeting
, because it’s an operation that changes a blockchain state you have to usecast send
The
0xa870d152929a29ab982c0f8f2803172b23c156f3309bb09a1d30ac40ad6f1290
is our private key from Ganache account.cast send 0xd34bad36e60e1BddF87Ec04AA7CAE67642b6831B --private-key 0xa870d152929a29ab982c0f8f2803172b23c156f3309bb09a1d30ac40ad6f1290 "setGreeting(string)" "Hello" --rpc-url http://127.0.0.1:8545
So that’s it, you’ve successfuly built, deployed and interacted with you contracts on your Local Blockchain. If you prefer using Truffle with Ganache then check out my setup guide here.