1-Libraries
Libraries(库)与智能合约类似,但是不能声明任何静态变量,也不能发送ETH。
Library | Solidity by Example | 0.8.26
如何创建一个库?
建立文件PriceConverter.sol,回到FundMe.sol文件中,复制最后三个函数直接放入PriceConverter.sol中。
那么现在PriceConverter.sol,现在只关注getConversionRate函数就可以:
//SPDX-License-Identifier: MIT pragma solidity ^0.8.30; import "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol"; //直接导入 library PriceConverter { // 所有库中的函数都必须是internal,让库中的不同函数都可以被uint256调用 function getPrice() internal view returns(uint256) { // conver msg.value to USD // need two thing: ABI Address(0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43) // AggregatorV3Interface(0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43).version(); AggregatorV3Interface priceFeed = AggregatorV3Interface(0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43); (,int256 price,,,) = priceFeed.latestRoundData(); //price:BTC in terms of USD // 9033.148958846, remenber: priceFeed 返回的值中有八个是在小数点之后的(from function decimal:AggregatorV3Interface.sol) return uint256(price * 1e10); // 1e10 == 1**10 == 10000000000 } function getVersion() internal view returns (uint256) { AggregatorV3Interface priceFeed = AggregatorV3Interface(0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43); return priceFeed.version(); } function getConversionRate(uint256 ethAmount) internal view returns (uint256) { uint256 ethPrice = getPrice(); uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1e18; return ethAmountInUsd; } }FundMe.sol改为如下样式:
// Get funds from users // Withdraw funds // Set a minimum funding value in USD // SPDX-License-Identifier: MIT pragma solidity ^0.8.30; import "./PriceConverter.sol"; //直接导入 contract FundMe { using PriceConverter for uint256; // uint256 public number; uint256 public minimumUsd = 50 * 1e18; //最小USD金额为美金计算 address[] public funders; //记录每个捐款人 mapping (address => uint256) public addressToAmountFunded; //记录每个地址发送资金的数量 function fund() public payable { // want to be able to set a minimum fund amount in USD // 1. How do we send ETH to this contract? // 如果要求至少发送 1 ether ,关键词 require 会检查 msg.value 是否大于 1 // require(msg.value > 1e18 , "Didn't send enough!"); //1e18 == 1*10**18 == 1000000000000000000 wei == 1 ether,value单位为ETH require(msg.value.getConversionRate() >= minimumUsd , "Didn't send enough!"); //如何将ether转换为usd?这就是oracles的作用 //msg.value:18 decimals funders.push(msg.sender); addressToAmountFunded[msg.sender] = msg.value; // What is reverting? // undo any action before, and send remaining gas back // number = 5; // 如果fund函数运行成功,那么number = 5,运行失败则整个函数回滚,number = 0, 消耗的gas也会原