Monday, September 25, 2023
CryptoMasInfo
No Result
View All Result
  • Home
  • Crypto News
  • Bitcoin
  • Altcoin
  • Blockchain
  • DeFi
  • Ethereum
  • Dogecoin
  • Mining
  • ETF
  • More
    • Market & Analysis
    • NFT
    • WEB-3.0
    • XRP
CryptoMasInfo
No Result
View All Result
Home WEB-3.0

Unit testing and deploying smart contracts with Forge

Adm1n by Adm1n
October 22, 2022
in WEB-3.0
0
Unit testing and deploying smart contracts with Forge
189
SHARES
1.5k
VIEWS
Share on FacebookShare on Twitter

Related articles

BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

BNB's Reign, $XRP's Buzz, or Borroe.Finance's ($ROE) Potential? The 2023 Crypto Face-off! | – Bitcoinist

September 24, 2023
BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

Crypto Wallets Explained: What Are They and How Do They Work? – AMBCrypto Blog

September 23, 2023


In December 2021, the world’s largest crypto-native funding agency, Paradigm Lab’s CTO Georgios launched a weblog relating to the discharge of a brand new framework for (evm-based) sensible contract improvement, known as Foundry.

It took the Crypto neighborhood by storm, and shortly grew to become the business customary for improvement and testing of sensible contracts, owing a lot to its effectivity compared to different frameworks.

With the intention to perceive the importance of Foundry, we have to first look into the issues it tries to resolve.

The primary downside that lies with frameworks like Hardhat and Truffle is that they require the builders to know a scripting language like JavaScript/TypeScript to be able to work with the framework.

As these scripting languages are internet development-heavy, the solidity developer needn’t know such languages for the sensible contract improvement as it’s thought-about extra backend oriented.

One other situation is that hardhat itself is carried out utilizing TypeScript, so it’s slower than Foundry because the latter is carried out utilizing Rust.

(Notice: If you’re concerned about checking the benchmarks, please take a look at this simulation)

Graph comparing compilation times between Forge and Hardhat

Foundry has plenty of cool options other than this like:

  • Name stack traces
  • Interactive debugger
  • Inbuilt-fuzzing
  • Solidity scripting

Now, I hope you have got an summary of Foundry and the need of testing sensible contracts utilizing Solidity. Foundry ships with two wonderful CLI instruments out-of-the-box:

  • Forge: Used for testing and deployment of sensible contracts
  • Solid: Used to work together with deployed sensible contracts

On this article we’re going to cowl the next:

Let’s get began.

Putting in Foundry

Putting in Foundry is easy and easy.

Open up your terminal and run:

curl -L https://foundry.paradigm.xyz | bash && foundryup

As soon as Foundry is put in, you can begin utilizing Forge and Solid straightaway.

For some OS, you may wish to install rust earlier than putting in Foundry.

Establishing a Foundry mission

You’ll be able to immediately setup a Foundry mission by instantly by working

forge init <PROJECT_NAME>

To make your life simpler, I’ve created a template repository, with which you may get began extra simply. It comprises the required libraries, scripts and listing setup. So, all it’s essential to do is simply run the next command in your terminal:

The above command creates a brand new listing known as foundry-faucet and initializes a brand new Foundry mission utilizing my template. This may be the listing construction. The essential directories and information that we wish to concentrate on are:

Directory structure

  • lib: This comprises all of the dependencies/libraries that we’re going to use. For instance, if we wanna use Solmate, it should reside as a git submodule inside this folder
  • scripts: This folder has all of the scripts, like deploying and verifying contracts
  • src: This folder has all of the contracts and the assessments related to the contracts
  • foundry.toml: This file comprises the configuration choices for the present Foundry mission

We also needs to replace and set up the libraries used; for that run the next instructions:

git submodule replace --init --recursive
forge set up

Making a easy Faucet contract

Now, we’re going to implement a faucet contract for our ERC20 token which may drip tokens when requested. We are able to additionally prohibit the quantity of tokens per request by setting a restrict which might be 100 by default in our contract.

Open up the src/Faucet.sol file and add the next code:

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

import {Ownable} from "openzeppelin-contracts/entry/Ownable.sol";
import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";

contract Faucet is Ownable {
   /// Deal with of the token that this faucet drips
   IERC20 public token;

   /// For charge limiting
   mapping(handle => uint256) public nextRequestAt;
   /// Max token restrict per request
   uint256 public restrict = 100;

   /// @param _token The handle of the tap's token
   constructor(IERC20 _token) {
       token = _token;
   }

   /// Used to ship the tokens
   /// @param _recipient The handle of the tokens recipient
   /// @param _amount The quantity of tokens required from the tap
   perform drip(handle _recipient, uint256 _amount) exterior {
       require(_recipient != handle(0), "INVALID_RECIPIENT");

       require(_amount <= restrict, "EXCEEDS_LIMIT");

       require(nextRequestAt[_recipient] <= block.timestamp, "TRY_LATER");
       nextRequestAt[_recipient] = block.timestamp + (5 minutes);

       token.switch(_recipient, _amount);
   }

   /// Used to set the max restrict per request
   /// @dev This methodology is restricted and needs to be known as solely by the proprietor
   /// @param _limit The brand new restrict for the tokens per request
   perform setLimit(uint256 _limit) exterior onlyOwner {
       restrict = _limit;
   }
}

Our faucet contract has been added. Now we will go forward and compile the contracts by working:

forge construct

If every thing goes nicely, it’s best to see an analogous output:

[⠒] Compiling...
[⠒] Compiling 14 information with 0.8.13
Compiler run profitable

Candy! We now have efficiently arrange our Foundry mission and compiled our contract with none errors! Good job, anon 🎉

Now, we will go forward and begin testing our Faucet contract.

Unit testing utilizing Forge

As , not like Hardhat, Forge helps us write unit assessments utilizing Solidity.

For those who open the src/check/Faucet.t.sol file you’ll already see some imports of utils and a BaseSetup contract.

Base setup contract

It has some preliminary setup that initializes just a few variables that we will use in our assessments. As well as, the setUp() perform is just like beforeEach in hardhat and it runs earlier than each check.

The setUp() perform creates two addresses and labels them Alice and Bob. It’s useful whenever you attempt to debug by way of name traces because the label seems within the traces together with the handle.

(Notice: vm.label is known as a cheatcode and it’s particular to Forge; It helps us to do some particular operations by interacting with the digital machine within the check env. We’ll be seeing extra cheatcodes through the course of the article. For the complete listing of cheatcodes, you’ll be able to refer to this link)

Exchange the Faucet.t.sol with the next code to get began with the unit assessments;


Extra nice articles from LogRocket:


// SPDX-License-Identifier: MIT
pragma solidity >=0.8;

import {console} from "forge-std/console.sol";
import {stdStorage, StdStorage, Check} from "forge-std/Check.sol";
import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";

import {Utils} from "./utils/Utils.sol";
import {Faucet} from "../Faucet.sol";
import {MockERC20} from "../MockERC20.sol";

contract BaseSetup is Check {
   Utils inside utils;
   Faucet inside faucet;
   MockERC20 inside token;

   handle payable[] inside customers;
   handle inside proprietor;
   handle inside dev;
   uint256 inside faucetBal = 1000;

   perform setUp() public digital {
       utils = new Utils();
       customers = utils.createUsers(2);
       proprietor = customers[0];
       vm.label(proprietor, "Proprietor");
       dev = customers[1];
       vm.label(dev, "Developer");

       token = new MockERC20();
       faucet = new Faucet(IERC20(token));
       token.mint(handle(faucet), faucetBal);
   }
}

You’ll be able to see that we’ve now created new state variables like faucet, token and in addition we’ve renamed alice and bob to proprietor and dev for simple interpretation. On this context, dev is somebody who requests tokens from the tap whereas the proprietor is the proprietor of the tap itself.

Within the final three strains of the setUp() methodology, we deploy a mock token for the tap, go its handle within the constructor of the new Faucet() (faucet deployment), after which name and mint some tokens to the deployed faucet contract.

Now, we’ll inherit the BaseSetup contract to jot down unit assessments for our Faucet contract.

Under the BaseSetup contract, add the next code:

contract FaucetTest is BaseSetup {
   uint256 amountToDrip = 1;

   perform setUp() public override {
       tremendous.setUp();
   }

As talked about earlier, the setUp() methodology runs earlier than all of the testcases and right here we’re calling the setUp() methodology of the bottom contract which is the BaseSetup contract by way of tremendous.setUp().

Alright, now allow us to begin including unit assessments for our contract. Proper under the setUp() methodology of the FaucetTest contract, add the next piece of code:

   perform test_drip_transferToDev() public {
       console.log(
           "Ought to switch tokens to recipient when `drip()` is known as"
       );
       uint256 _inititalDevBal = token.balanceOf(dev);

       /// Guarantee that preliminary dev stability is Zero
       assertEq(_inititalDevBal, 0);

       /// Request some tokens to the dev pockets from the pockets
       faucet.drip(dev, amountToDrip);

       uint256 _devBalAfterDrip = token.balanceOf(dev);

      /// The distinction needs to be equal to the quantity requested from the tap
       assertEq(_devBalAfterDrip - _inititalDevBal, amountToDrip);
   }

The above code helps us to check the drip() methodology. The workflow is easy.

  1. First, retailer the preliminary stability of the dev in a variable (_inititalDevBal)
  2. Make certain it’s 0, as we didn’t mint any tokens to the dev. That is what the road assertEq(_inititalDevBal, 0); does
  3. Then name the drip() methodology from the faucet contract occasion
  4. Fetch the stability of dev after the drip() is known as
  5. The distinction between the stability of the dev account earlier than and after the drip() needs to be equal to amountToDrip, which is saved as a state variable within the FaucetTest contract

Now, allow us to save the file and run the check: forge check.

You must see the output in your terminal one thing just like this:

Compiling test results in terminal

Cool! Let’s add some extra assessments.

The above check verifies that the drip() methodology transfers the tokens to the dev. So, we also needs to test that the switch is a legitimate one, which suggests the token stability of the tap needs to be decreased.

Add the next check under — the test_drip_transferToDev() methodology.

 perform test_drip_reduceFaucetBalance() public {
       console.log("The tap stability needs to be decreased");
       faucet.drip(dev, amountToDrip);
       assertEq(token.balanceOf(handle(faucet)), faucetBal - amountToDrip);
   }

This makes positive that the tokens that the dev obtained are literally despatched from the tap — in that case, the stability of the tap needs to be decreased.

We are able to make sure that by working the check suite once more : forge check

If every thing goes nicely, then your output needs to be just like this:

Compiling test results in terminal

Candy! When you’ve got seen, we’ve console.log statements in our check circumstances, however they aren’t displaying up within the console. The reason being that Forge doesn’t show logs by default. To get the logs displayed, we have to run the command with verbosity 2 : forge check -vv will show the logs.

Compiling test results in terminal

Additionally if there are any occasions which might be emitted by your contract, you’ll be able to view them within the assessments with verbosity three (-vvv). You will get an in depth name hint in your assessments as excessive as verbosity degree 5, which helps in higher debugging.

Alright, let’s preserve including extra assessments. Now we’re going to check our charge restrict mechanism. There needs to be at the very least a five-minute interval earlier than calling drip() with the identical recipient handle.

   perform test_drip_revertIfThrottled() public {
       console.log("Ought to revert if tried to throttle");
       faucet.drip(dev, amountToDrip);

       vm.expectRevert(abi.encodePacked("TRY_LATER"));
       faucet.drip(dev, amountToDrip);
   }

vm.expectRevert(bytes32) is one other cheat code that checks if the subsequent name reverts with the given error message. On this case, the error message is TRY_LATER. It accepts the error message as bytes not as a string, therefore we’re utilizing abi.encodePacked.

For those who keep in mind, I discussed that Forge ships with a fuzzer out-the-box. Let’s give it a strive.

We mix the assessments test_drip_transferToDev and test_drip_reduceFaucetBalance, and as a substitute of passing the inputs manually, we might permit the fuzzer to enter the values in order that we will ensure that our contract handles totally different inputs.

   perform test_drip_withFuzzing(handle _recipient, uint256 _amount) public {
       console.log("Ought to deal with fuzzing");
       /// inform the constraints to the fuzzer, in order that the assessments do not revert on dangerous inputs.
       vm.assume(_amount <= 100);
       vm.assume(_recipient != handle(0));
       uint256 _inititalBal = token.balanceOf(_recipient);
       faucet.drip(_recipient, _amount);
       uint256 _balAfterDrip = token.balanceOf(_recipient);
       assertEq(_balAfterDrip - _inititalBal, _amount);
       assertEq(token.balanceOf(handle(faucet)), faucetBal - _amount);
   }

Fuzzing is property-based testing. Forge will apply fuzzing to any check that takes at the very least one parameter.

While you execute the check suite, you will discover the next line within the output:

[PASS] test_drip_withFuzzing(handle,uint256) (runs: 256)

From the above output we will infer that the Forge fuzzer known as the test_drip_withFuzzing() methodology 256 instances with random inputs. Nevertheless, we will override this quantity utilizing the FOUNDRY_FUZZ_RUNS atmosphere variable.

Now, allow us to add a pair extra assessments for the owner-only methodology setLimit()

perform test_setLimit() public {
       console.log("Ought to set the restrict when known as by the proprietor");
       faucet.setLimit(1000);

       /// the restrict needs to be up to date assertEq(faucet.restrict(), 1000); } perform test_setLimit_revertIfNotOwner() public { console.log("Ought to revert if not known as by Proprietor"); /// Units the msg.sender as dev for the subsequent tx vm.prank(dev); vm.expectRevert(abi.encodePacked("Ownable: caller just isn't the proprietor")); faucet.setLimit(1000); }

Within the test_setLimit_revertIfNotOwner() methodology, a brand new cheatcode vm.prank(handle) is used. It pranks the vm by overriding the msg.sender with the given handle; in our case it’s dev. So, the setLimit() ought to revert with the caller just isn't the proprietor message as our Faucet contract inherits the Ownable contract.

Okay allow us to ensure that no assessments fail by working forge check once more.

Forge test terminal output

Candy 🥳 Now it’s time for deployment.

Contract deployment to Kovan testnet

Create a brand new file from .env.instance file and identify it as .env. Please fill your INFURA_API_KEY and the PRIVATE_KEY (with Kovan testnet funds).

As soon as all of the fields are populated, you might be all set for deployment to Kovan. Earlier than deploying the tap, we have to deploy our ERC20 token.

You will discover the deployment scripts contained in the scripts listing, and deploy the MockERC20 token to Kovan testnet by executing the ./scripts/deploy_token_kovan.sh bash script.

The output would look one thing like this:

Deployer: (YOUR_DEPLOYMENT_ADDRESS)

Deployed to: 0x1a70d8a2a02c9cf0faa5551304ba770b5496ed80

Transaction hash: 0xa3780d2e3e1d1f9346035144f3c2d62f31918b613a370f416a4fb1a6c2eadc77

To ensure that the transaction truly went by means of, you’ll be able to search the transaction hash in https://kovan.etherscan.io

Copy the Deployed to: handle, as it’s the handle of the MockERC20 token that we should always use for deploying our Faucet contract. To deploy the tap, you’ll be able to execute the ./scripts/deploy_faucet_kovan.shscript.

It can immediate you to enter the token handle; then enter the copied MockERC20 token handle that was deployed earlier.

The output ought to look one thing like this:

Entering token contract address and compiling

Woohoo 🚀🚀 We now have efficiently compiled, examined, and deployed our contract to the Kovan testnet utilizing Forge

We nonetheless have to confirm the contract on Etherscan and in addition mint some MockERC20 tokens to the Faucet (you should use forged for this!) for it to work as supposed. I’ll depart this to you guys as an train to strive it yourselves!

As all the time, you will discover the GitHub repository for this text here.

Conclusion

On this article we solely coated just a few items of Forge. Foundry is a really highly effective framework for sensible contracts and it’s quickly creating as nicely.

There are extra cool options like code-coverage, contract verification, gasoline snapshots, name traces, and interactive debugging. Be at liberty to mess around with the repo by testing out extra options. Joyful coding 🎊

Be a part of organizations like Bitso and Coinsquare who use LogRocket to proactively monitor their Web3 apps

Consumer-side points that impression customers’ skill to activate and transact in your apps can drastically have an effect on your backside line. For those who’re concerned about monitoring UX points, routinely surfacing JavaScript errors, and monitoring gradual community requests and element load time, try LogRocket.LogRocket Dashboard Free Trial Bannerhttps://logrocket.com/signup/

LogRocket is sort of a DVR for internet and cellular apps, recording every thing that occurs in your internet app or website. As a substitute of guessing why issues occur, you’ll be able to combination and report on key frontend efficiency metrics, replay consumer classes together with software state, log community requests, and routinely floor all errors.

Modernize the way you debug internet and cellular apps — Start monitoring for free.





Source link

Tags: ContractsdeployingForgeSmarttestingUnit
Share76Tweet47

Related Posts

BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

BNB's Reign, $XRP's Buzz, or Borroe.Finance's ($ROE) Potential? The 2023 Crypto Face-off! | – Bitcoinist

by Adm1n
September 24, 2023
0

BNB's Reign, $XRP's Buzz, or Borroe.Finance's ($ROE) Potential? The 2023 Crypto Face-off! |  Bitcoinist Source link

BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

Crypto Wallets Explained: What Are They and How Do They Work? – AMBCrypto Blog

by Adm1n
September 23, 2023
0

Crypto Wallets Explained: What Are They and How Do They Work?  AMBCrypto Weblog Source link

BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

Artelli invites Mr Doodle for his first visit to Macao, strengthening the … – PR Newswire

by Adm1n
September 22, 2023
0

Artelli invites Mr Doodle for his first visit to Macao, strengthening the ...  PR Newswire Source link

BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

Generative AI Is Breathing New Life Into Classic Computer Games – Forbes

by Adm1n
September 22, 2023
0

Generative AI Is Breathing New Life Into Classic Computer Games  Forbes Source link

My foray into Ethereum and creating something of value for a global ecosystem

My foray into Ethereum and creating something of value for a global ecosystem

by Adm1n
September 22, 2023
0

This month marks an enormous milestone for me within the Ethereum neighborhood. In September 2016, I announced the open-source library, Web3j, that I...

Load More
  • Trending
  • Comments
  • Latest
Binance’s CZ Confirms Participating as Equity Investor in Musk’s Twitter Takeover

Binance’s CZ Confirms Participating as Equity Investor in Musk’s Twitter Takeover

October 28, 2022
USDC Lost 20% Of Its Market Capitalization In The Last 30 Days

USDC Lost 20% Of Its Market Capitalization In The Last 30 Days

October 26, 2022
Quant, XRP, and THESE Cryptos are still set to PUMP into 2022

Quant, XRP, and THESE Cryptos are still set to PUMP into 2022

October 29, 2022
Cathie Wood’s ARK Fintech Innovation ETF Buys More Coinbase

Cathie Wood’s ARK Fintech Innovation ETF Buys More Coinbase

October 25, 2022
Ripple Launches Test Phase For Ethereum Based Smart Contracts On The XRPL

Ripple Launches Test Phase For Ethereum Based Smart Contracts On The XRPL

0
3 Crypto Predictions for 2023

3 Crypto Predictions for 2023

0
Cool Cats Lands On Its Feet And Does It In Style

Cool Cats Lands On Its Feet And Does It In Style

0
Waves price analysis: WAVES loses value at $3.49 after a bearish run

Waves price analysis: WAVES loses value at $3.49 after a bearish run

0
North Korean Lazarus Group amasses over $40M in Bitcoin, data reveals

North Korean Lazarus Group amasses over $40M in Bitcoin, data reveals

September 25, 2023
Bitcoin inflows to exchanges rise – Are traders preparing to sell?

Bitcoin inflows to exchanges rise – Are traders preparing to sell?

September 25, 2023
Chainlink (LINK) and Three Low-Cap Altcoins Could Witness More Rallies Amid Strong Network Activity: Santiment

Chainlink (LINK) and Three Low-Cap Altcoins Could Witness More Rallies Amid Strong Network Activity: Santiment

September 25, 2023
BlockJoy Secures Nearly $11 Million From Gradient Ventures, Draper Dragon, Active Capital and More To Launc… – The Daily Hodl

Hong Kong to reveal crypto applicants’ names as JPEX scandal worsens – South China Morning Post

September 25, 2023

Recent News

North Korean Lazarus Group amasses over $40M in Bitcoin, data reveals

North Korean Lazarus Group amasses over $40M in Bitcoin, data reveals

September 25, 2023
Bitcoin inflows to exchanges rise – Are traders preparing to sell?

Bitcoin inflows to exchanges rise – Are traders preparing to sell?

September 25, 2023
Chainlink (LINK) and Three Low-Cap Altcoins Could Witness More Rallies Amid Strong Network Activity: Santiment

Chainlink (LINK) and Three Low-Cap Altcoins Could Witness More Rallies Amid Strong Network Activity: Santiment

September 25, 2023

Categories

  • Altcoin
  • Bitcoin
  • Blockchain
  • Crypto News
  • DeFi
  • Dogecoin
  • ETF
  • Ethereum
  • Market & Analysis
  • Mining
  • NFT
  • WEB-3.0
  • XRP

Crypto Calculator

Cryptocurrency Prices 

© 2022 CryptoMasInfo

No Result
View All Result
  • Home
  • Crypto News
  • Bitcoin
  • Altcoin
  • Blockchain
  • DeFi
  • Ethereum
  • Dogecoin
  • Mining
  • ETF
  • More
    • Market & Analysis
    • NFT
    • WEB-3.0
    • XRP

© 2022 CryptoMasInfo