## Getting Started with Smart Contracts on Polygon PoS
### 1. Polygon Proof-of-Stake (PoS) Explained
Polygon creates blockchain protocols & technologies that enable developers to build scalable user-friendly dApps on Ethereum, with low transaction fees but without ever sacrificing security. Like Ethereum, Polygon's live blockchain in production uses the [Proof-of-Stake consensus mechanism](https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/) (PoS for short). In this guide, we'll learn how to build and deploy our first Solidity smart contracts to Polygon PoS.
##### Key Features of Polygon
- **Speed** The Polygon Network uses a high-throughput blockchain with consensus provided by a group of Block Producers selected by stakeholders at each checkpoint. A Proof of Stake layer is used to validate blocks and periodically post proofs of Block Producers to the Ethereum mainnet. This enables rapid block confirmation rates of about 2 seconds while preserving a high amount of decentralization, resulting in excellent throughput for the network.
- **Scalability** Polygon Network achieves a hypothetical transaction speed of fewer than 2 seconds on a single sidechain. Using multiple sidechains helps the network to handle millions of transactions per second. This mechanism (already demonstrated in the first Matic sidechain) allows the Polygon network to scale easily.
- **Security** Polygon's smart contracts rely on Ethereum’s security. To safeguard the network, it employs three critical security models. It uses Ethereum's staking management contracts and a group of incentivized validators running Heimdall and Bor nodes. Developers can also implement both models (Hybrid) into their dApp.
- **EVM-Compatability** Polygon is designed to provide the ultimate Layer-2 scaling solution for Ethereum. You don't have to worry about the underlying architecture while moving or deploying your dApps to the Polygon Network as long as it is EVM-compatible. Deploying your dApp to the Polygon Mainnet allows you to leverage Polygon as a faster transaction layer for your dApp.
#### Building on Polygon
If you are an Ethereum developer, you are already a Polygon developer. Simply switch to the Polygon RPC and get started. All the tools you are familiar with on the Ethereum blockchain are supported on Polygon by default, such as HardHat / Truffle, Remix, and Web3js / ethers.js
You can deploy decentralized applications to either Polygon Mumbai Testnet or the Mainnet. The Polygon Mumbai Testnet connects with the Ethereum Goërli Testnet, which acts as its ParentChain. In order to deploy on the Mumbai testnet, you need Mumbai test tokens. To get test tokens, you can use free Mumbai faucets like [mumbaifaucet.com](https://mumbaifaucet.com).You can find all the network-related details in the network documentation.
#### Interacting with the Polygon Network: two approaches
##### Wallets
Polygon PoS runs on Ethereum Virtual Machine (EVM). To interact with the Polygon Network, you need to have an [Ethereum-based wallet](https://ethereum.org/en/wallets/) like Metamask or Arkane Wallet. Ethereum wallets are applications that let you interact with your Ethereum account. Think of it like an internet banking app – without the bank. Your wallet lets you read your balance, send transactions and connect to applications.
##### Smart Contracts
Polygon supports many services you can use to test, compile, debug, and deploy [smart contracts](https://ethereum.org/en/developers/docs/smart-contracts/), the programs that decentralized Ethereum applications run on, onto the Polygon Network. Where wallets allow users to interact with the Ethereum blockhain manually, smart contracts let us automate the interactons between the blockchain and aDapp. Examples of interactions include deployment using Alchemy, Chainstack, QuickNode, Remix, Truffle, Hardhat, and Replit.
To learn how to code and deploy your own Polygon smart contract, you can follow this [beginner step-by-step tutorial](https://docs.alchemy.com/docs/how-to-code-and-deploy-a-polygon-smart-contract).
### Question 1. What consensus mechanism does Polygon's public chain use?
- A Proof of Work
- B Proof of Stake
- C Proof of Storage
- D Proof of History
### Question 2. Which of the following is NOT TRUE about smart contracts?
- A The allow Dapps to launch transactions on the Ethereum blockchain
- B They speed up transactions on Ethereum
- C They collections of code and state that run on Ethereum
- D They can only be used to request the creation of new blocks on the Ethereum blockchain
# Smart Contract Example: Staking Polygon
A superpower of Polygon is allowing you, the builder, to create a simple set of rules that an adversarial group of players can use to work together. In this challenge, you create a decentralized application where users can coordinate a group funding effort. If the users cooperate, the money is collected in a second smart contract. If they defect, the worst that can happen is everyone gets their money back. The users only have to trust the code.

> 🏦 Build a `Staker.sol` contract that collects **ETH** from numerous addresses using a payable `stake()` function and keeps track of `balances`. After some `deadline` if it has at least some `threshold` of ETH, it sends it to an `ExampleExternalContract` and triggers the `complete()` action sending the full balance. If not enough **ETH** is collected, allow users to `withdraw()`.
> 🎛 Building the frontend to display the information and UI is just as important as writing the contract. The goal is to deploy the contract and the app to allow anyone to stake using your app. Use a `Stake(address,uint256)` event to <List/> all stakes.
> 🌟 The final deliverable is deploying a Dapp that lets users send ether to a contract and stake if the conditions are met, then `yarn build` and `yarn surge` your app to a public webserver.
---
## 1. Before we start: 📦 Set up your dev environment
This worked example assumes you have the following dependencies installed in your system before you start:
1. Install [VS Code IDE](https://code.visualstudio.com/)
2. Install the [👷♀️ HardHat](https://hardhat.org/getting-started/) extension for VS code will let you compile and deploy smart contracts.
3. Install and set up [Git](https://git-scm.com/downloads)
4. Install [Node JS](https://nodejs.org/dist/latest-v16.x/) (🧨 Currently use Node v16 as v17 & v18 are unstable 🧨)
5. Install [Yarn](https://classic.yarnpkg.com/en/docs/install/#mac-stable) (⚠️ Don't install the linux package `yarn` make sure you install yarn with `npm i -g yarn` or even `sudo npm i -g yarn`!)
6. Set up your [Metamask](https://metamask.io/) wallet (You will need a wallet installed for all the following activities in this guide. If you don't currently have one installed, follow ETH Global's [getting started with Metamask guide](https://ethglobal.com/guides/getting-started-with-metamask-cjf72) to set one up first.)
## 2. Preview the Staking Dapp for your contract
```bash
git clone https://github.com/llsourcell/scaffold-eth-challenges.git challenge-1-decentralized-staking
cd challenge-1-decentralized-staking
git checkout challenge-1-decentralized-staking
yarn install
```
🔏 Edit your smart contract `Staker.sol` in `packages/hardhat/contracts`
You'll have three terminals up for:
```bash
yarn start (react app frontend)
yarn chain (hardhat backend)
yarn deploy (to compile, deploy, and publish your contracts to the frontend)
```
> 💻 View your frontend at http://localhost:3000/

> 👩💻 Rerun `yarn deploy --reset` whenever you want to deploy new contracts to the frontend.
---
## 3: 🥩 Staking 💵
You'll need to track individual `balances` using a mapping:
```solidity
mapping ( address => uint256 ) public balances;
```
And also track a constant `threshold` at ```1 ether```
```solidity
uint256 public constant threshold = 1 ether;
```
> 👩💻 Write your `stake()` function and test it with the `Debug Contracts` tab in the frontend
💸 Need more funds from the faucet? Enter your frontend address into the wallet to get as much as you need!
.
You can also get free Mumbai test tokens from [mumbaifaucet.com](https://mumbaifaucet.com).
✏ Need to troubleshoot your code? If you import `hardhat/console.sol` to your contract, you can call `console.log()` right in your Solidity code. The output will appear in your `yarn chain` terminal.
---
## 4: 🔬 State Machine / Timing ⏱
> ⚙️ Think of your smart contract like a *state machine*. First, there is a **stake** period. Then, if you have gathered the `threshold` worth of ETH, there is a **success** state. Or, we go into a **withdraw** state to let users withdraw their funds.
Set a `deadline` of ```block.timestamp + 30 seconds```
```solidity
uint256 public deadline = block.timestamp + 30 seconds;
```
👨🏫 Smart contracts can't execute automatically, you always need to have a transaction execute to change state. Because of this, you will need to have an `execute()` function that *anyone* can call, just once, after the `deadline` has expired.
> 👩💻 Write your `execute()` function and test it with the `Debug Contracts` tab
> Check the ExampleExternalContract.sol for the bool you can use to test if it has been completed or not. But do not edit the ExampleExternalContract.sol as it can slow the auto grading.
If the `address(this).balance` of the contract is over the `threshold` by the `deadline`, you will want to call: ```exampleExternalContract.complete{value: address(this).balance}()```
If the balance is less than the `threshold`, you want to set a `openForWithdraw` bool to `true` and allow users to `withdraw()` their funds.
(You'll have 30 seconds after deploying until the deadline is reached, you can adjust this in the contract.)
> 👩💻 Create a `timeLeft()` function including ```public view returns (uint256)``` that returns how much time is left.
⚠️ Be careful! if `block.timestamp >= deadline` you want to ```return 0;```
⏳ The time will only update if a transaction occurs. You can see the time update by getting funds from the faucet just to trigger a new block.
> 👩💻 You can call `yarn deploy --reset` any time you want a fresh contract
## 5: 💵 Receive Function / UX 🙎
🎀 To improve the user experience, set your contract up so it accepts ETH sent to it and calls `stake()`. You will use what is called the `receive()` function.
> Use the [receive()](https://docs.soliditylang.org/en/v0.8.9/contracts.html?highlight=receive#receive-ether-function) function in solidity to "catch" ETH sent to the contract and call `stake()` to update `balances`.
---
## 6: 🚢 Ship it 🚁
📡 Edit the `defaultNetwork` to [the Polygon Mumbai Testnet](https://www.alchemy.com/overviews/mumbai-testnet) in `packages/hardhat/hardhat.config.js`
👩🚀 You will want to run `yarn account` to see if you have a **deployer address**
🔐 If you don't have one, run `yarn generate` to create a mnemonic and save it locally for deploying.
⛽️ You will need to send ETH to your **deployer address** with your wallet.
> 📝 If you plan on submitting this challenge, be sure to set your ```deadline``` to at least ```block.timestamp + 72 hours```
> 🚀 Run `yarn deploy` to deploy your smart contract to a public network (selected in hardhat.config.js). The first network is the Mumbai testnet. Then, once it's been successfully deployed there, you can deploy to Polygon Mainnet. Both testnet and mainnet deployments can be done through an RPC provider like [Alchemy](https://docs.alchemy.com/reference/polygon-api-quickstart) or [Quicknode](https://quicknode.com).
---
## 7: 🎚 Frontend 🧘♀️
> 📝 Edit the `targetNetwork` in `App.jsx` (in `packages/react-app/src`) to be the public network where you deployed your smart contract.
> 💻 View your frontend at http://localhost:3000/

📡 When you are ready to ship the frontend app...
📦 Run `yarn build` to package up your frontend.
💽 Upload your app to surge with `yarn surge` (you could also `yarn s3` or maybe even `yarn ipfs`?)
> 😬 Windows users beware! You may have to change the surge code in `packages/react-app/package.json` to just `"surge": "surge ./build",`
⚙ If you get a permissions error `yarn surge` again until you get a unique URL, or customize it in the command line.
---
## 8. 📜 Contract Verification
Update the api-key in packages/hardhat/package.json file. You can get your key [here](https://etherscan.io/myapikey).

> Now you are ready to run the `yarn verify --network your_network` command to verify your contracts on etherscan 🛰
### Question 1: Why use a faucet?
- A Instant access to test tokens
- B It is free to use
- C It's a great tool for web3 developers
- D All of the above
### Question 2: What is Yarn?
- A A Command line tool
- B A Rust library
- C An API
- D None of the above