Cheaper Gas

This commit is contained in:
2024-08-06 18:49:09 +08:00
parent aefe632675
commit 28ac29b8ba
4 changed files with 228 additions and 25 deletions
+29 -12
View File
@@ -41,12 +41,12 @@ contract FundMe {
/***** 6.1 Type Declarations *****/
using PriceConverter for uint256;
uint256 public constant MINIMUM_USD = 50 * 1e18;
address[] public funders;
address[] public s_funders;
address public immutable i_owner; // immutable only can declare 1 time at contructor
AggregatorV3Interface public priceFeed;
AggregatorV3Interface public s_priceFeed;
/***** 6.2 State Variable *****/
mapping(address => uint256) public addressToAmountFunded;
mapping(address => uint256) public s_addressToAmountFunded;
/***** 6.3 Modifier *****/
modifier onlyOwner() {
@@ -69,9 +69,9 @@ contract FundMe {
* View / Pure
* *****/
constructor(address priceFeedAddress) {
constructor(address s_priceFeedAddress) {
i_owner = msg.sender;
priceFeed = AggregatorV3Interface(priceFeedAddress);
s_priceFeed = AggregatorV3Interface(s_priceFeedAddress);
}
// What happens if someone send this contract ETH without calling the fund function
@@ -92,11 +92,11 @@ contract FundMe {
function fund() public payable {
//require (msg.value >= 1e18, "Didn't send enough"); // 1e18 = 1 * 10 * 18 = 1000000000000000000
require(
msg.value.getConversionRate(priceFeed) >= MINIMUM_USD,
msg.value.getConversionRate(s_priceFeed) >= MINIMUM_USD,
"Didn't send enough"
);
funders.push(msg.sender);
addressToAmountFunded[msg.sender] = msg.value;
s_funders.push(msg.sender);
s_addressToAmountFunded[msg.sender] = msg.value;
}
// Owner of this contract only can withdraw
@@ -107,14 +107,14 @@ contract FundMe {
/* starting index, eding index, step amount */
for (
uint256 funderIndex = 0;
funderIndex < funders.length;
funderIndex < s_funders.length;
funderIndex++
) {
address funder = funders[funderIndex];
addressToAmountFunded[funder] = 0;
address funder = s_funders[funderIndex];
s_addressToAmountFunded[funder] = 0;
}
// reset the array
funders = new address[](0);
s_funders = new address[](0);
/*
// transfer - over 2300 gas will cause exception
@@ -130,4 +130,21 @@ contract FundMe {
}("");
require(callSuccess, "Call failed");
}
function cheaperWithdraw() public onlyOwner {
address[] memory funders = s_funders;
for (
uint256 funderIndex = 0;
funderIndex < funders.length;
funderIndex++
) {
address funder = funders[funderIndex];
s_addressToAmountFunded[funder] = 0;
}
// reset the array
s_funders = new address[](0);
(bool callSuccess, ) = i_owner.call{value: address(this).balance}("");
require(callSuccess, "Call failed");
}
}