The source of the project is from:
https://github.com/PatrickAlphaC/smartcontract-lottery
https://www.youtube.com/watch?v=M576WGiDBdQ&t=22298s
The purpose of this walkthrough is to explain each part of the Smart Contract code with more context so that we can gain better understanding.
Lottery.sol
Think about the different processes for a lottery.
- Participants have to enter the lottery. We need to track down who are the participants for this lottery.
- We need to know how much to charge the participants for entering the lottery.
- Owner will need to start the lottery.
- Owner will end the lottery and we need a random way to calculate the winner of the lottery. And we need a robust way of generating the random winner that minimise the probability of participants cheating.
- We need to track the state of the lottery: whether it is opened, closed or the winner is being calculated.
Tracking Participants
We need to create an address array to track down the participants. Before we add the new player to the participant list, they have to pay an entry fee. This entry fee is calculated based on current Ether price.
address payable[] public players;
function enter() public payable {
require(msg.value > getEntranceFee());
players.push(msg.sender);
}
We can use ChainLink price feed to get the latest Ether data. To do so, we need to specify the dependencies and remappings in brownie-config.yaml
file.
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
[...]
AggregatorV3Interface internal ethUsdPriceFeed;
function getEntranceFee() public view returns (uint256) {
(, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
uint256 adjustedPrice = uint256(price) * 10**10;
uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
return costToEnter;
}