Foundry
Using Foundry to Deploy To Phron
Introduction
Foundry is an Ethereum development environment written in Rust that helps developers manage dependencies, compile projects, run tests, deploy contracts, and interact with blockchains from the command line. Foundry can directly interact with Phron's Ethereum API so it can be used to deploy smart contracts into Phron.
Four tools make up Foundry:
Forge - compiles, tests, and deploys contracts
Cast - a command line interface for interacting with contracts
Anvil - a local TestNet node for development purposes that can fork preexisting networks
Chisel - a Solidity REPL for quickly testing Solidity snippets
This guide will cover how to use Foundry to compile, deploy, and debug Ethereum smart contracts on the Phron TestNet.
Checking Prerequisites
To get started, you will need the following:
Have an account with funds. You can get DEV tokens for testing on Phron once every 24 hours from the Phron Faucet
To test out the examples in this guide on Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers
Have Foundry installed
Creating a Foundry Project
You will need to create a Foundry project if you don't already have one. You can create one by completing the following steps:
Install Foundry if you haven't already. If on Linux or MacOS, you can run these commands:
If on Windows, you'll have to install Rust and then build Foundry from source:
Create the project, which will create a folder with three folders within it, and open it:
With the default project created, you should see three folders.
lib
- all of the project's dependencies in the form of git submodulessrc
- where to put your smart contracts (with functionality)test
- where to put the forge tests for your project, which are written in Solidity
In addition to these three folders, a git project will also be created along with a prewritten .gitignore
file with relevant file types and folders ignored.
The Source Folder
The src
folder may already contain Counter.sol
, a minimal Solidity contract. Feel free to delete it. To avoid errors, you should also delete the Counter.s.sol
file in the scripts
folder and the Counter.t.sol
file in the test
folder. In the following steps, you will be deploying an ERC-20 contract. In the contracts directory, you can create the MyToken.sol
file:
Open the file and add the following contract to it:
Before you attempt to compile, install OpenZeppelin contracts as a dependency. You may have to commit previous changes to git beforehand. By default, Foundry uses git submodules instead of npm packages, so the traditional npm import path and command are not used. Instead, use the name of OpenZeppelin's GitHub repository:
Compiling Solidity
Once all dependencies have been installed, you can compile the contract:
After compilation, two folders will be created: out
and cache
. The ABI and bytecode for your contracts will be contained within the out
folder. These two folders are already ignored by the .gitignore
included in the default Foundry project initialization.
Deploying the Contract
There are two primary ways to deploy contracts using Foundry. The first is the straightforward command forge create
. There's also the more flexible and powerful option of foundry scripting, which runs simulations before any deployments. In the following sections, forge create
and foundry scripting will both be covered.
Using Forge Create
Deploying the contract with forge create
takes a single command, but you must include an RPC endpoint, a funded private key, and constructor arguments. MyToken.sol
asks for an initial supply of tokens in its constructor, so each of the following commands includes 100 as a constructor argument. You can deploy the MyToken.sol
contract using the following command for the correct network:
After you've deployed the contract and a few seconds have passed, you should see the address in the terminal.
Congratulations! Your contract is live! Save the address, as you will use it to interact with this contract instance in the next step.
Deploying via Solidity Scripting
Solidity scripting is a more powerful and flexible way to deploy contracts than forge create
. Writing a Solidity script is identical to writing a typical Solidity smart contract, though you won't ever deploy this contract.
You can tailor the behavior of forge script
with various parameters. All components are optional except for local simulation, which is a required part of every run. The forge script
command will attempt to execute all applicable steps in the following order:
Local simulation - simulate the transaction(s) in a local EVM
Onchain simulation - simulate the transaction(s) via the provided RPC URL
Broadcasting - when the
--broadcast
flag is provided, and simulations succeed, the transaction(s) are dispatchedVerification - API-based smart contract verification when the
--verify
flag and a valid API key are provided
Now, go ahead and write the script. In the script folder, create a file named MyToken.s.sol
. Copy and paste the contents of the below file.
Notice that even though the above script is not being deployed, it still requires all the typical formatting for a Solidity contract, such as the pragma statement.
You can deploy the MyToken.sol
contract with the below command. Remember that it will execute all relevant steps in order. For this example, Foundry will first attempt a local simulation and a simulation against the provided RPC before deploying the contract. Foundry won't proceed with the deployment if any of the simulations fail.
If your script's execution succeeds, your terminal should resemble the output below.
And that's it! For more information about Solidity scripting with Foundry, be sure to check out Foundry's documentation site.
Interacting with the Contract
Foundry includes cast, a CLI for performing Ethereum RPC calls.
Try to retrieve your token's name using Cast, where INSERT_YOUR_CONTRACT_ADDRESS
is the address of the contract that you deployed in the previous section:
You should get this data in hexadecimal format:
This is far from readable, but you can use Cast to convert it into your desired format. In this case, the data is text, so you can convert it into ASCII characters to see "My Token":
You can also mutate data with cast as well. Try burning tokens by sending them to the zero address.
The transaction will be signed by your Phron account and be broadcast to the network. The output should look similar to:
Congratulations, you have successfully deployed and interacted with a contract using Foundry!
Forking with Anvil
As previously mentioned, Anvil is a local TestNet node for development purposes that can fork preexisting networks. Forking Phron allows you to interact with live contracts deployed on the network.
There are some limitations to be aware of when forking with Anvil. Since Anvil is based on an EVM implementation, you cannot interact with any of the Phron precompiled contracts and their functions. Precompiles are a part of the Substrate implementation and therefore cannot be replicated in the simulated EVM environment. This prohibits you from interacting with cross-chain assets on Phron and Substrate-based functionality such as staking and governance.
To fork Phron, you will need to have your own endpoint and API key which you can get from one of the supported Endpoint Providers.
To fork Phron from the command line, you can run the following command from within your Foundry project directory:
Your forked instance will have 10 development accounts that are pre-funded with 10,000 test tokens. The forked instance is available at http://127.0.0.1:8545/
. The output in your terminal should resemble the following:
To verify you have forked the network, you can query the latest block number:
If you convert the result
from hex to decimal, you should get the latest block number from the time you forked the network. You can cross reference the block number using a block explorer.
From here you can deploy new contracts to your forked instance of Phron or interact with contracts already deployed. Building off of the previous example in this guide, you can make a call using Cast to check the balance of the minted MYTOK tokens in the account you deployed the contract with:
Using Chisel
Chisel is a Solidity REPL or shell. It allows a developer to write Solidity directly in the console for testing small snippets of code, letting developers skip the project setup and contract deployment steps for what should be a quick process.
Since Chisel is mainly useful for quick testing, it can be used outside of a Foundry project. But, if executed within a Foundry project, it will keep the configurations within foundry.toml
when running.
For this example, you will be testing out some of the features of abi
within Solidity because it is complex enough to demonstrate how Chisel could be useful. To get started using Chisel, run the following in the command line to start the shell:
In the shell, you can write Solidity code as if it were running within a function:
Let's say you were interested in how abi
encoded data because you're looking into how to most efficiently store data on the blockchain and thus save gas. To view how the myData
is stored in memory, you can use the following command while in the Chisel shell:
memdump
will dump all of the data in your current session. You'll likely see something like this below. If you aren't good at reading hexadecimal or if you don't know how ABI encoding works, then you might not be able to find where the myData
variable has been stored.
Fortunately, Chisel lets you easily figure out where this information is stored. Using the !rawstack
command, you can find the location in the stack where the value of a variable:
In this situation, since bytes is over 32 bytes in length, the memory pointer is displayed instead. But that's exactly what's needed since you already know the entirety of the stack from the !memdump
command.
The !rawstack
command shows that the myData
variable is stored at 0x80
, so when comparing this with the memory dump retrieved from the !memdump
command, it looks like myData
is stored like this:
At first glance, this makes sense, since 0xa0
has a value of 0x64
which is equal to 100, and 0xc0
has a value of 0x01
which is equal to true. If you want to learn more about how ABI-encoding works, the Solidity documentation for ABI is helpful. In this case, there are a lot of zeros in this method of data packing, so as a smart contract developer you might instead try to use structs or pack the data together more efficiently with bitwise code.
Since you're done with this code, you can clear the state of Chisel so that it doesn't mess with any future logic that you want to try out (while running the same instance of Chisel):
There's an even easier way to test with Chisel. When writing code that ends with a semicolon (;
), Chisel will run it as a statement, storing its value in Chisel's runtime state. But if you only needed to see how the ABI-encoded data was represented, then you could get away with running the code as an expression. To try this out with the same abi
example, write the following in the Chisel shell:
You should see something like the following:
While it doesn't display the data in the same way, you still get the contents of the data, and it also further breaks down how the information is coded, such as letting you know that the 0xa0
value defines the length of the data.
By default, when you leave the Chisel shell, none of the data is persisted. But you can instruct chisel to do so. For example, you can take the following steps to store a variable:
Store a
uint256
in ChiselStore the session with
!save
. For this example, you can use the number1
as a save IDQuit the session
Then to view and interact with your stored Chisel states, you can take the following steps:
View a list of saved Chisel states
Load your stored states
View the
uint256
saved in Chisel from the previous set of steps
You can even fork networks while using Chisel:
Then, for example, you can query the balance of one of Phron's collators:
If you want to learn more about Chisel, download Foundry and refer to its official reference page.
Foundry With Hardhat
Often, there will be the case where a project that you wish to integrate with has all of its setup within Hardhat, making it an arduous task to convert the entirety of the project into Foundry. This additional work is avoidable by creating a hybrid project that uses both Hardhat and Foundry features together. This is possible with Hardhat's hardhat-foundry plugin.
To convert your preexisting Foundry project to a hybrid project, you will essentially have to install a Hardhat project into the same folder:
For more information, please refer to our documentation on Creating a Hardhat Project.
After initializing the new Hardhat project, a few new folders and files should appear: contracts
, hardhat.config.js
, scripts
, and test/Lock.js
. You'll need to make a few modifications to create a hybrid project:
Edit the
hardhat.config.js
file within your repository. Open it up, and at the top, add the following:After adding the
hardhat-foundry
plugin, the typicalcontracts
folders for Hardhat will not work because now Hardhat expects all smart contracts to be stored within Foundry'ssrc
folderMove all smart contracts within the
contracts
folder into thesrc
folder, and then delete thecontracts
folderEdit the
foundry.toml
file to ensure that dependencies installed via Git submodules and npm can be compiled by the Forge tool. Edit theprofile.default
to ensure that thelibs
entry has bothlib
andnode_modules
:
Now both forge build
and npx hardhat compile
should work regardless of the dependencies.
Both forge test
and npx hardhat test
should now be able to access all smart contracts and dependencies. forge test
will only test the Solidity tests, whereas npx hardhat test
will only test the JavaScript tests. If you would like to use them in conjunction, then you can create a new script within your package.json
file:
You can run this command with:
Finally, while not necessary, it could be worthwhile to move all JavaScript scripts from the scripts
folder into Foundry's script
folder and delete the scripts
folder so that you don't have two folders that serve the same purpose.
This tutorial is for educational purposes only. As such, any contracts or code created in this tutorial should not be used in production.The information presented herein has been provided by third parties and is made available solely for general information purposes. Phron does not endorse any project listed and described on the Phron Doc Website (https://docs.Phron.ai/). Phron does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Phron disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Phron. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Phron has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Phron harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.
Last updated