1/5
_Follow along the course with this video._ --- ### Finishing mintDsc Ok, where were we!? We went down several rabbit holes all in effort of determining if a user should be able to call `mintDsc`. Let's get back to that function now and finish it off. ```js function mintDsc(uint256 amountDscToMint) external moreThanZero(amountDscToMint) nonReentrant { s_DSCMinted[msg.sender] += amountDscToMint; _revertIfHealthFactorIsBroken(msg.sender); } ``` To this point, our function is adding the amount requested to mint to the user's balance. We're then checking if this new balance is breaking the user's `Health Factor`, and if so, we're reverting. If this function _doesn't_ revert - it's time to mint! ```js function mintDsc(uint256 amountDscToMint) external moreThanZero(amountDscToMint) nonReentrant { s_DSCMinted[msg.sender] += amountDscToMint; _revertIfHealthFactorIsBroken(msg.sender); bool minted = i_dsc.mint(msg.sender, amountDscToMint); } ``` Our `mint` function returns a bool and takes `_to` and `_amount` parameters. We can use this bool to revert if minting our DSC fails for some reason. ```js function mintDsc(uint256 amountDscToMint) external moreThanZero(amountDscToMint) nonReentrant { s_DSCMinted[msg.sender] += amountDscToMint; _revertIfHealthFactorIsBroken(msg.sender); bool minted = i_dsc.mint(msg.sender, amountDscToMint); if(!minted){ revert DSCEngine__MintFailed(); } } ``` Lastly, add our new custom error to the appropriate section at the top of the contract: ```js /////////////////// // Errors // /////////////////// error DSCEngine__TokenAddressesAndPriceFeedAddressesAmountsDontMatch(); error DSCEngine__NeedsMoreThanZero(); error DSCEngine__TokenNotAllowed(address token); error DSCEngine__TransferFailed(); error DSCEngine__BreaksHealthFactor(uint256 healthFactor); error DSCEngine__MintFailed(); ``` ### Wrap Up Great work! This was just a short one to wrap up our minting logic, but we're getting really close to testing time. In the next lesson we'll approach our deploy script to prepare ourselves to start testing. See you soon! <details> <summary>DSCEngine.sol</summary> ```js // Layout of Contract: // version // imports // errors // interfaces, libraries, contracts // Type declarations // State variables // Events // Modifiers // Functions // Layout of Functions: // constructor // receive function (if exists) // fallback function (if exists) // external // public // internal // private // internal & private view & pure functions // external & public view & pure functions // SPDX-License-Identifier: MIT pragma solidity 0.8.18; import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { DecentralizedStableCoin } from "./DecentralizedStableCoin.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol"; /* * @title DSCEngine * @author Patrick Collins * * The system is designed to be as minimal as possible, and have the tokens maintain a 1 token == $1 peg at all times. * This is a stablecoin with the properties: * - Exogenously Collateralized * - Dollar Pegged * - Algorithmically Stable * * It is similar to DAI if DAI had no governance, no fees, and was backed by only WETH and WBTC. * * Our DSC system should always be "overcollateralized". At no point, should the value of * all collateral < the $ backed value of all the DSC. * * @notice This contract is the core of the Decentralized Stablecoin system. It handles all the logic * for minting and redeeming DSC, as well as depositing and withdrawing collateral. * @notice This contract is based on the MakerDAO DSS system */ contract DSCEngine is ReentrancyGuard { /////////////////// // Errors // /////////////////// error DSCEngine__TokenAddressesAndPriceFeedAddressesAmountsDontMatch(); error DSCEngine__NeedsMoreThanZero(); error DSCEngine__TokenNotAllowed(address token); error DSCEngine__TransferFailed(); error DSCEngine__BreaksHealthFactor(uint256 healthFactor); error DSCEngine__MintFailed(); ///////////////////////// // State Variables // ///////////////////////// mapping(address token => address priceFeed) private s_priceFeeds; DecentralizedStableCoin private immutable i_dsc; mapping(address user => mapping(address token => uint256 amount)) private s_collateralDeposited; mapping(address user => uint256 amountDscMinted) private s_DSCMinted; address[] private s_collateralTokens; uint256 private constant ADDITIONAL_FEED_PRECISION = 1e10; uint256 private constant PRECISION = 1e18; uint256 private constant LIQUIDATION_THRESHOLD = 50; uint256 private constant LIQUIDATION_PRECISION = 100; uint256 private constant MIN_HEALTH_FACTOR = 1e18; //////////////// // Events // //////////////// event CollateralDeposited(address indexed user, address indexed token, uint256 indexed amount); /////////////////// // Modifiers // /////////////////// modifier moreThanZero(uint256 amount){ if(amount <=0){ revert DSCEngine__NeedsMoreThanZero(); } _; } modifier isAllowedToken(address token) { if (s_priceFeeds[token] == address(0)) { revert DSCEngine__TokenNotAllowed(token); } _; } /////////////////// // Functions // /////////////////// constructor(address[] memory tokenAddresses, address[] memory priceFeedAddresses, address dscAddress){ if(tokenAddresses.length != priceFeedAddresses.length){ revert DSCEngine__TokenAddressesAndPriceFeedAddressesMustBeSameLength(); } for(uint256 i=0; i < tokenAddresses.length; i++){ s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i]; s_collateralTokens.push(tokenAddresses[i]); } i_dsc = DecentralizedStableCoin(dscAddress); } /////////////////////////// // External Functions // /////////////////////////// /* * @param tokenCollateralAddress: The ERC20 token address of the collateral you're depositing * @param amountCollateral: The amount of collateral you're depositing */ function depositCollateral( address tokenCollateralAddress, uint256 amountCollateral ) external moreThanZero(amountCollateral) nonReentrant isAllowedToken(tokenCollateralAddress) { s_collateralDeposited[msg.sender][tokenCollateralAddress] += amountCollateral; emit CollateralDeposited(msg.sender, tokenCollateralAddress, amountCollateral); bool success = IERC20(tokenCollateralAddress).transferFrom(msg.sender, address(this), amountCollateral); if (!success) { revert DSCEngine__TransferFailed(); } } /* * @param amountDscToMint: The amount of DSC you want to mint * You can only mint DSC if you hav enough collateral */ function mintDsc(uint256 amountDscToMint) external moreThanZero(amountDscToMint) nonReentrant { s_DSCMinted[msg.sender] += amountDscToMint; _revertIfHealthFactorIsBroken(msg.sender); bool minted = i_dsc.mint(msg.sender, amountDscToMint); if(!minted){ revert DSCEngine__MintFailed(); } } /////////////////////////////////////////// // Private & Internal View Functions // /////////////////////////////////////////// /* * Returns how close to liquidation a user is * If a user goes below 1, then they can be liquidated. */ function _healthFactor(address user) private view returns(uint256){ (uint256 totalDscMinted, uint256 collateralValueInUsd) = _getAccountInformation(user); uint256 collateralAdjustedForThreshold = (collateralValueInUsd * LIQUIDATION_THRESHOLD) / LIQUIDATION_PRECISION; return (collateralAdjustedForThreshold * PRECISION) / totalDscMinted; } function _getAccountInformation(address user) private view returns(uint256 totalDscMinted,uint256 collateralValueInUsd){ totalDscMinted = s_DSCMinted[user]; collateralValueInUsd = getAccountCollateralValue(user); } function _revertIfHealthFactorIsBroken(address user) internal view { uint256 userHealthFactor = _healthFactor(user); if(userHealthFactor < MIN_HEALTH_FACTOR){ revert DSCEngine__BreaksHealthFactor(userHealthFactor); } } ////////////////////////////////////////// // Public & External View Functions // ////////////////////////////////////////// function getAccountCollateralValue(address user) public view returns (uint256 totalCollateralValueInUsd) { for(uint256 i = 0; i < s_collateralTokens.length; i++){ address token = s_collateralTokens[i]; uint256 amount = s_collateralDeposited[user][token]; totalCollateralValueInUsd += getUsdValue(token, amount); } return totalCollateralValueInUsd; } function getUsdValue(address token, uint256 amount) public view returns(uint256){ AggregatorV3Interface priceFeed = AggregatorV3Interface(s_priceFeeds[token]); (,int256 price,,,) = priceFeed.latestRoundData(); return ((uint256(price) * ADDITIONAL_FEED_PRECISION) * amount) / PRECISION; } function depositCollaterAndMintDsc() external {} function redeemCollateralForDsc() external {} function redeemCollateral() external {} function burnDsc() external {} function liquidate() external {} function getHealthFactor() external view {} } ``` </details>
Complete the development of the mint function in DeFi, focusing on optimizing functionality, ensuring security, and integrating with the overall system.
Previous lesson
Previous
Next lesson
Next
Give us feedback
Course Overview
About the course
Advanced smart contract development
How to develop a stablecoin
How to develop a DeFi protocol
How to develop a DAO
Advanced smart contracts testing
Fuzz testing
Manual verification
Web3 Developer Relations
$85,000 - $125,000 (avg. salary)
Web3 developer
$60,000 - $150,000 (avg. salary)
Smart Contract Engineer
$100,000 - $150,000 (avg. salary)
Smart Contract Auditor
$100,000 - $200,000 (avg. salary)
Security researcher
$49,999 - $120,000 (avg. salary)
Guest lecturers:
Juliette Chevalier
Lead Developer relations at Aragon
Nader Dabit
Director of developer relations at Avara
Ally Haire
Developer relations at Protocol Labs
Harrison
Founder at GasliteGG
Last updated on November 29, 2024
Solidity Developer
Advanced FoundryDuration: 36min
Duration: 3h 06min
Duration: 5h 02min
Duration: 2h 47min
Duration: 1h 23min
Duration: 4h 28min
Duration: 1h 19min
Duration: 58min
Course Overview
About the course
Advanced smart contract development
How to develop a stablecoin
How to develop a DeFi protocol
How to develop a DAO
Advanced smart contracts testing
Fuzz testing
Manual verification
Web3 Developer Relations
$85,000 - $125,000 (avg. salary)
Web3 developer
$60,000 - $150,000 (avg. salary)
Smart Contract Engineer
$100,000 - $150,000 (avg. salary)
Smart Contract Auditor
$100,000 - $200,000 (avg. salary)
Security researcher
$49,999 - $120,000 (avg. salary)
Guest lecturers:
Juliette Chevalier
Lead Developer relations at Aragon
Nader Dabit
Director of developer relations at Avara
Ally Haire
Developer relations at Protocol Labs
Harrison
Founder at GasliteGG
Last updated on November 29, 2024
Testimonials
Read what our students have to say about this course.
Chainlink
Chainlink
Gustavo Gonzalez
Solutions Engineer at OpenZeppelin
Francesco Andreoli
Lead Devrel at Metamask
Albert Hu
DeForm Founding Engineer
Radek
Senior Developer Advocate at Ceramic
Boidushya
WalletConnect
Idris
Developer Relations Engineer at Axelar