18 min read
Overview
Welcome to lesson 4 of Quicknode's DeFi DEX course! This lesson, we're diving into testing and deploying the DEX contracts we have built over the past two lessons. Testing is crucial to ensure the proper functioning of your smart contracts. Before we get started with our actual testing and deployment to the Ethereum Sepolia testnet, let us take a few minutes to discuss the current best practices and standards for developing and maintaining smart contract code today. Afterward, we will discuss some more technical testing methods and then get into creating tests for our DEX smart contracts using Foundry.
Best Practices for Smart Contract Development
- Start Simple: Simpler is often better. Ensure your smart contracts do only what they need to do, and no more.
- Modular Design: Write modular code to improve readability, reusability, and maintainability. For example, logic used more than once can be seperated into utility functions to reusability.
- Code Comments: Solidity supports comments. Use them to describe the purpose and functionality of functions, especially public ones.
- Reentrancy Guard: Prevent recursive calls from external contracts using mechanisms like the Checks-Effects-Interactions pattern and using tools like reentrancyGuard.
- Regular Audits: Have your code audited by third-party experts? especially before any mainnet release.
- Use Established Libraries: Leverage well-vetted libraries like OpenZeppelin, which provide implementations for standard functionalities (e.g., ERC20, ERC721).
- Gas Optimization: Always be mindful of gas costs. Avoid unnecessary storage operations, use appropriate data types, and prune unnecessary code.
- Error Handling: Make use of require, assert, and revert to handle unexpected situations.
- Access Control: Ensure only authorized entities can access certain functions using tools like Ownable or Role-based access control.
- Timelocks: For critical governance decisions or contract upgrades, implement a delay before any changes take effect, giving users time to react.
- Pause Mechanism: Implement a mechanism to pause contract functionalities in case of detected vulnerabilities.
Smart Contract Testing Environments
Local Blockchain Environment
This is one way to test your smart contracts without having to worry about deploying them onto a public blockchain. It involves creating a copy (or "fork") of a blockchain locally so developers can deploy and experiment with their contracts locally without risking real funds on mainnet or needing to deploy and test on a testnet blockchain. In local blockchain development, you can use both automated and manual testing methods.
Testnet Blockchain Environment
Testnets are separate blockchain environments that operate just like mainnet but are meant for a testing environment. Some benefits of using a testnet as compared to locally include, more realistic interactions since you are conducting activity on a public blockchain. This may come at the downside of having to maintain testnet tokens to test with or longer testing cycles (since testnet blockchains generally slower than your local one).
Smart Contract Testing
When testing smart contracts using Foundry or any other testing framework, it is essential to ensure consistent behavior and security of your smart contracts. As you know, deploying a smart contract on the blockchain is immutable. Therefore, you'll need to be confident your smart contract is free from vulnerabilities, or you won't be able to change the code (unless you re-deploy or have an upgradeable contract). Additionally, since our smart contracts will be public and decentralized (as it has no admin privileges), we need to be confident the functionality works as expected, or it can lead to bad actors taking advantage of the smart contracts.
Types of Automated Testing
Automated testing refers to using tools that will automatically check and evaluate the functionalities of your smart contract. These automated tests are built using scripts written in languages like Solidity, JavaScript, and Python. The result of using a script to test enables us to run tests as often as we'd like, save time, minimize human error (compared to manual testing), and carry out tasks faster than we would manually.
Unit Testing
Another form of automated testing refers to Unit testing. This testing refers to the practice of testing individual sections of your code to ensure they work correctly. For example, in a smart contract, you might test the functions that handle exchanging tokens to ensure they work as expected. This will help catch errors early in the development process.
Positive and Negative Tests
- Positive Tests: Things that the code should handle. Double-checking the start/end state changes from each test. For example, making sure that liquidity can be added to the exchange pool and that liquidity tokens are minted correctly.
- Negative Tests: Things that the code should not handle. For example, creating an exchange for a token that already has an associated exchange should fail.
Other Testing Methods
- Fuzz Testing: Fuzz testing involves throwing a lot of random data at your software to see how it reacts. It's a way to uncover unexpected errors or vulnerabilities in your code.
- Invariant Testing: Invariant testing checks for things in your code that should always be true. For example, in a smart contract, you might have an invariant that the total amount of tokens should never decrease. Invariant testing ensures that your code always adheres to these rules.
- Differential Testing: Differential testing compares the outcomes of two different systems or versions of code that are supposed to do the same thing (we won't use this, but it's good to know).
Manual Testing
After completing automated tests, manual testing should be next in the development cycle. This type of testing determines if the smart contract functions per the technical specifications of the "product" (in our case, the DEX). This type of testing is extremely valuable when you are testing the smart contracts through your frontend to make sure the DEX and frontend work as expected.
Audits & Bug Bounties
To further increase the chance of finding an issue in your smart contracts, you can get an independent audit by a reputable private third party or start a bug bounty campaign. Audits usually include automated testing and a full analysis of your codebase. Audits are most useful for finding security issues and poor development standards.
Alternatively, you can start a bug bounty campaign and allow users from the community to submit feedback and win a reward if any vulnerabilities or other weak security standards are found.
Compiling the DEX Contracts
Now that we have a basic understanding of smart contract testing standards and the different test types, let us move on to compiling and testing our DEX smart contracts. In your main directory (e.g., defi_dex) within your terminal window, run the following forge command in your terminal to compile the smart contracts.
forge build
You should see an output like this:
[⠆] Compiling...
[⠒] Compiling 17 files with Solc 0.8.20
[⠰] Solc 0.8.20 finished in 888.40ms
Compiler run successful!
Compiling our contracts converts them to bytecode, which is what the EVM can understand.
Given that your compilation was successful, let's now move on to testing.
Building Tests for the Factory Contract
In your test folder, create another file called Factory.t.sol and input the following code:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "forge-std/Test.sol";
import "../src/Factory.sol";
import "../src/Exchange.sol";
import "../src/ERC20.sol";
contract FactoryTest is Test {
Factory public factory;
MyToken public token;
address tokenOwner = makeAddr("owner");
function setUp() public {
token = new MyToken(tokenOwner);
factory = new Factory();
}
function testInitialState() public view {
assertEq(factory.tokenCount(), 0);
assertEq(factory.getExchange(address(token)), address(0));
assertEq(factory.getToken(address(1)), address(0));
assertEq(factory.getTokenWithId(0), address(0));
assertEq(factory.getTokenWithId(1), address(0));
}
function testCreateNewExchange() public {
address tokenExchangeAddress = factory.createNewExchange(address(token));
assertEq(factory.getExchange(address(token)), tokenExchangeAddress, "Exchange address does not match");
assertTrue(tokenExchangeAddress != address(0), "Exchange address should not be 0x0");
assertGt(tokenExchangeAddress.code.length, 0, "Exchange should be deployed");
assertEq(factory.tokenToExchange(address(token)), tokenExchangeAddress);
assertEq(factory.getToken(tokenExchangeAddress), address(token));
assertEq(factory.exchangeToToken(tokenExchangeAddress), address(token));
assertEq(factory.tokenCount(), 1);
assertEq(factory.getTokenWithId(1), address(token));
assertEq(factory.idToToken(1), address(token));
assertEq(address(factory.exchangeArray(0)), tokenExchangeAddress);
assertEq(factory.getTokenWithId(0), address(0));
}
function testCreateMultipleExchanges() public {
MyToken secondToken = new MyToken(tokenOwner);
address firstExchange = factory.createNewExchange(address(token));
address secondExchange = factory.createNewExchange(address(secondToken));
assertTrue(firstExchange != secondExchange);
assertEq(factory.tokenCount(), 2);
assertEq(factory.getExchange(address(token)), firstExchange);
assertEq(factory.getExchange(address(secondToken)), secondExchange);
assertEq(factory.getToken(firstExchange), address(token));
assertEq(factory.getToken(secondExchange), address(secondToken));
assertEq(factory.getTokenWithId(1), address(token));
assertEq(factory.getTokenWithId(2), address(secondToken));
assertEq(address(factory.exchangeArray(0)), firstExchange);
assertEq(address(factory.exchangeArray(1)), secondExchange);
assertEq(factory.getTokenWithId(3), address(0));
}
function testCreateExchangeForExistingTokenReverts() public {
address tokenExchangeAddress = factory.createNewExchange(address(token));
vm.expectRevert(bytes("exchange already exists"));
factory.createNewExchange(address(token));
assertEq(factory.tokenCount(), 1);
assertEq(factory.getExchange(address(token)), tokenExchangeAddress);
assertEq(factory.getTokenWithId(2), address(0));
}
function testCreateExchangeForZeroAddressReverts() public {
vm.expectRevert(bytes("Invalid token address"));
factory.createNewExchange(address(0));
assertEq(factory.tokenCount(), 0);
assertEq(factory.getTokenWithId(1), address(0));
}
}
Remember to save the file! Let's now recap the code.
The setUp function deploys a token and a fresh Factory before each test. The tests check the initial empty registry, exchange deployment, both directions of the token-exchange mappings, sequential token IDs, and exchangeArray. They also verify that zero addresses and duplicate tokens revert without increasing tokenCount. Token IDs start at 1; array indices start at 0.
Use vm.expectRevert immediately before a call that should fail. Foundry 1.0 and later no longer support the legacy testFail naming convention.
Building Tests for the Exchange Contract
The Exchange contract has a lot of logic, so we won't be building out tests for every function but for the main ones that users use to add and remove liquidity, get quote prices for swaps and swap tokens.
In your test folder, create another file called Exchange.t.sol and input the following code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../src/Exchange.sol";
import "../src/ERC20.sol";
import "forge-std/Test.sol";
contract ExchangeTest is Test {
Exchange exchange;
MyToken token;
address owner = makeAddr("alice");
address trader = makeAddr("bob");
function setUp() public {
token = new MyToken(owner);
exchange = new Exchange(address(token));
vm.startPrank(owner);
token.mint(owner, 10000 ether);
token.mint(trader, 10000 ether);
token.approve(address(exchange), type(uint256).max);
vm.stopPrank();
vm.prank(trader);
token.approve(address(exchange), type(uint256).max);
vm.deal(owner, 100 ether);
vm.deal(trader, 100 ether);
}
function seedPool() internal {
vm.prank(owner);
exchange.addLiquidity{value: 10 ether}(5000 ether);
}
function testAddLiquidity() public {
seedPool();
assertEq(exchange.balanceOf(owner), 10 ether);
assertEq(token.balanceOf(address(exchange)), 5000 ether);
assertEq(address(exchange).balance, 10 ether);
}
function testRemoveLiquidity() public {
seedPool();
vm.prank(owner);
(uint ethAmount, uint tokenAmount) = exchange.removeLiquidity(10 ether);
assertEq(ethAmount, 10 ether);
assertEq(tokenAmount, 5000 ether);
assertEq(exchange.totalSupply(), 0);
}
function testUnbalancedDepositReverts() public {
seedPool();
vm.startPrank(trader);
vm.expectRevert(bytes("Token amount below reserve ratio"));
exchange.addLiquidity{value: 10 ether}(1);
vm.stopPrank();
assertEq(exchange.balanceOf(trader), 0);
assertEq(token.balanceOf(address(exchange)), 5000 ether);
}
function testSecondProviderPaysOnlyRequiredTokens() public {
seedPool();
uint beforeTokens = token.balanceOf(trader);
vm.prank(trader);
uint lp = exchange.addLiquidity{value: 1 ether}(1000 ether);
assertEq(lp, 1 ether);
assertEq(beforeTokens - token.balanceOf(trader), 500 ether + 1);
vm.prank(trader);
(uint ethOut, uint tokensOut) = exchange.removeLiquidity(lp);
assertEq(ethOut, 1 ether);
assertLe(tokensOut, 500 ether + 1);
}
function testSwapEthForTokens() public {
seedPool();
uint quote = exchange.getTokenAmount(1 ether);
vm.prank(trader);
uint received = exchange.swapEthForTokens{value: 1 ether}(quote, trader);
assertEq(received, quote);
assertEq(received, 453305446940074565790);
assertEq(token.balanceOf(trader), 10000 ether + received);
}
function testTokenForEthSwap() public {
seedPool();
uint quote = exchange.getEthAmount(2500 ether);
vm.prank(trader);
uint received = exchange.tokenForEthSwap(2500 ether, quote);
assertEq(received, 3326659993326659993);
assertEq(received, quote);
assertGe(address(exchange).balance * token.balanceOf(address(exchange)),
10 ether * 5000 ether);
}
function testSwapMinimumOutputReverts() public {
seedPool();
vm.startPrank(trader);
vm.expectRevert(bytes("Token amount less than expected"));
exchange.swapEthForTokens{value: 1 ether}(5000 ether, trader);
vm.expectRevert(bytes("ETH amount less than expected"));
exchange.tokenForEthSwap(1 ether, 10 ether);
vm.stopPrank();
}
function testTradesLargerThanInputReserves() public {
seedPool();
uint tokenQuote = exchange.getTokenAmount(11 ether);
vm.prank(trader);
assertEq(exchange.swapEthForTokens{value: 11 ether}(0, trader), tokenQuote);
uint ethQuote = exchange.getEthAmount(6000 ether);
vm.prank(trader);
assertEq(exchange.tokenForEthSwap(6000 ether, 0), ethQuote);
}
function testPartialWithdrawalAfterSmallSwap() public {
vm.startPrank(owner);
exchange.addLiquidity{value: 10}(5000);
vm.stopPrank();
vm.prank(trader);
exchange.swapEthForTokens{value: 1}(0, trader);
vm.prank(owner);
(uint ethOut, uint tokensOut) = exchange.removeLiquidity(1);
assertEq(ethOut, 1);
assertEq(tokensOut, 454);
}
function testFuzzSwapsPreserveProduct(uint96 rawEth, uint96 rawTokens) public {
seedPool();
uint ethIn = bound(rawEth, 1, 20 ether);
uint tokensIn = bound(rawTokens, 1, 10000 ether);
uint beforeK = address(exchange).balance * token.balanceOf(address(exchange));
vm.startPrank(trader);
exchange.swapEthForTokens{value: ethIn}(0, trader);
uint afterEthSwap = address(exchange).balance * token.balanceOf(address(exchange));
assertGe(afterEthSwap, beforeK);
exchange.tokenForEthSwap(tokensIn, 0);
vm.stopPrank();
assertGe(address(exchange).balance * token.balanceOf(address(exchange)), afterEthSwap);
}
}
Remember to save the file! Let's now recap the code.
The code above the other smart contract, Factory to create an exchange and a demo ERC20 token called Example ERC20. The test contract sets up the initial conditions by creating these contracts and funding two pseudo-users, Alice and Bob, with 10 Ether each. Various functions are provided to test the behavior of the exchange, such as testSetUp() for verifying the initial state of the exchange and token, testGetAmount() for confirming amount calculations, testAddLiquidity() for testing the liquidity provision feature, and testTokenForEthSwap() and testEthForTokenSwap() for simulating token to Ether and Ether to token swaps. We use assertions in the contract to confirm that all the operations result in the expected state changes.
Running Tests & Analyzing Results
With our tests created, let's now test them out. Run the following forge terminal command:
forge test
The Factory tests check both registry directions and token IDs. The Exchange tests check exact swap outputs, matching quotes, minimum-output reverts, proportional liquidity contributions, and the reserve product after swaps. The fuzz test repeats both swap directions with different input amounts.
All tests should pass before you deploy.
Notice that after the process has been completed, you will see two new folders named out and cache. The out directory contains the artifacts of your smart contract, including the ABI, while Forge utilizes the cache folder to only recompile the necessary components.
Although we have finished testing our DEX contracts, we still need to deploy them onto a blockchain. In the coming sections, we'll build out a frontend and show you how to deploy your smart contracts onto a testnet blockchain for the frontend lessons. This course uses Sepolia throughout.
Deploying to Sepolia Testnet
With our automated tests verified, we will now go through the process of deploying the set of contracts to a testnet such as Sepolia testnet. Before diving into the deployment process, we must fund our wallet and configure our deployment settings in Foundry. Deploying smart contracts with Foundry takes a single command (i.e., forge). Still, you will need to include an RPC URL, a funded wallet (i.e., private key), and constructor arguments (if applicable).
Create a Quicknode Sepolia Endpoint
In order to communicate with the Ethereum Sepolia network, we'll need access to an Ethereum node. You're welcome to use public nodes or deploy and manage your own infrastructure; however, a Quicknode endpoint gives you a managed, reliable connection without the maintenance.
Go to your Quicknode endpoints page, click New Endpoint, and select the Ethereum Sepolia testnet.

Quicknode provides both a HTTP and WSS URL we can use to communicate with the Sepolia testnet. Keep the HTTP Provider URL handy as we'll need it in the following section.
Fund Your Testnet Wallet
To deploy and interact with smart contracts on a testnet, you'll need some testnet tokens to pay for gas fees. Luckily, you can use the Quicknode Multi-Chain Faucet to get free testnet tokens.
Connect or paste your wallet address and select the Ethereum Sepolia testnet. You can also tweet for a bonus!

Note: you will need at least 0.001 ETH on Ethereum Mainnet to use the EVM faucets.
Deploying the DEX Contracts
To deploy your Factory contract onto the Sepolia testnet, run the following forge create command in your terminal within the defi_dex directory.
Import a disposable testnet wallet into Foundry's encrypted keystore, then enter your Sepolia RPC URL in the terminal. The import command prompts for the private key and a password. The read -s command hides the URL while you paste it, so it stays off your screen and out of your shell history.
cast wallet import defi-course --interactive
printf "Enter your Ethereum Sepolia RPC URL: "
read -rs SEPOLIA_RPC_URL
The variable lasts only for this terminal session. Run the printf and read commands again if you open a new terminal window.
Use the account name when deploying. --broadcast submits the transaction; without it, forge create only performs a dry run.
forge create src/Factory.sol:Factory \
--rpc-url "$SEPOLIA_RPC_URL" \
--account defi-course \
--broadcast
The output includes the deployer address, deployed Factory address and transaction hash. Wait for the receipt and check that the deployed address has bytecode.
Congrats! You just deployed your Factory contract to a public testnet! Check the block explorer to confirm your Factory contract exists. Once you confirmed it does, move onto the next section for verifying the smart contract!
Verifying Source Code
In this section, we'll walk you through how you can verify your Factory smart contract using Foundry. Later on, you can use these same practices to verify the other contracts (e.g. Exchange & ERC20)
Foundry makes it easy to verify your smart contracts. All you have to run is forge verify-contract along with the contract address, contract path (in our directory), and your Etherscan API key. If you still need to get one, create one now.
Then, in your main directory within defi_dex, run the following command to verify the Factory contract:
forge verify-contract \
--etherscan-api-key <your_etherscan_api_key> \
<the_contract_address> \
--chain 11155111 \
src/Factory.sol:Factory
If deploying on another network than Sepolia, you can update the chain ID in the command above.
You should see an output similiar to:
Start verifying contract `0xA8dFE14Fd3e1BcA4CFB654c8Aede16Fa7A28e27d` deployed on sepolia
...
...
Thats it! Your Factory contract should now be verified. Navigate back to the block explorer and check the Code tab (it should have a checkmark if its verified) to see if your contract code is now public.
Deploy ERC-20 Token
In order to test our DEX smart contract, we'll need a test token. For this, we'll deploy the MyToken contract we created earlier. Complete the command below by filling in the proper values then run the command in your terminal to deploy the ERC-20 token contract:
forge create src/ERC20.sol:MyToken \
--rpc-url "$SEPOLIA_RPC_URL" \
--account defi-course \
--broadcast \
--constructor-args YOUR_WALLET_ADDRESS
You'll see an output like:
Deployer: 0xe0f2b924422909626D539b0FBd96239B31767400
Deployed to: 0x821F5C6Fe6b1764Cc2c116BFD481A8df2171bCC0
Transaction hash: 0x531100f7f83fd76eb2f904604ec8ab25a14cbda991038026ffd758c0fdf15f78
Wrap Up & What's Next
You have tested the Factory and Exchange contracts and deployed the Factory and test token on Sepolia. The next lesson connects them to a React frontend.
Next lesson, get ready to make your DEX user-friendly as we switch gears to frontend development. We'll be setting up a React application that will interact with your smart contracts, creating a complete DEX experience. You'll learn how to connect a wallet, interact with the blockchain, and test the whole setup to ensure seamless user interactions. Stay tuned!