## 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 Truffle, Remix, and Web3js.
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. 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.
### 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: Creating an ERC-20 Token
> 🤖 Smart contracts are kind of like "always on" *vending machines* that **anyone** can access. Let's make a decentralized, digital currency using Polygon PoS. Then, let's build an unstoppable vending machine that will buy and sell the currency. We'll learn about the "approve" pattern for ERC20s and how contract to contract interactions work.

> 🏵 Create `YourToken.sol` smart contract that inherits the **ERC20** token standard from OpenZeppelin. Set your token to `_mint()` **1000** (\* 10 \*\* 18) tokens to the `msg.sender`. Then create a `Vendor.sol` contract that sells your token using a payable `buyTokens()` function.
> 🎛 Edit the frontend that invites the user to `<input\>` an amount of tokens they want to buy. We'll display a preview of the amount of ETH (or MATIC) it will cost with a confirm button.
> 🔍 It will be important to verify your token's source code in the block explorer after you deploy. Supporters will want to be sure that it has a fixed supply and you can't just mint more.
🧫 Everything starts by ✏️ Editing `YourToken.sol` in `packages/hardhat/contracts`
---
## 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.)
7. Install [OpenZeppelin](https://www.openzeppelin.com/)
8. Read Ethereum's [ERC20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) specification
## 2. Preview the Minting Dapp for your contract
```bash
git clone https://github.com/llSourcell/scaffold-eth-challenges challenge-2-token-vendor
cd challenge-2-token-vendor
git checkout challenge-2-token-vendor
yarn install
```
🔏 Edit your smart contract `YourToken.sol` in `packages/hardhat/contracts`
You'll have three terminals up for:
```bash
yarn chain (hardhat backend)
yarn start (react app frontend)
yarn deploy (to compile, deploy, and publish your contracts to the frontend)
```
> 👀 Visit your frontend at http://localhost:3000

> 👩💻 Rerun `yarn deploy --reset` whenever you want to deploy new contracts to the frontend.
> ignore any warnings, we'll get to that...
---
## 3. 🏵Your Token 💵
> 👩💻 Edit `YourToken.sol` to inherit the **ERC20** token standard from OpenZeppelin
> Mint **1000** (\* 10 \*\* 18) to your frontend address using the `constructor()`.
```javascript
const result = await yourToken.transfer(
"**YOUR FRONTEND ADDRESS**",
ethers.utils.parseEther("1000")
);
```
(Your frontend address is the address in the top right of http://localhost:3000)
> You can `yarn deploy --reset` to deploy your contract until you get it right.
(Use an incognito window to create a new address and try sending to that new address. Use the `transfer()` function in the `Debug Contracts` tab.)
---
## 4: ⚖️ Vendor 🤖
> 👩💻 Edit the `Vendor.sol` contract with a **payable** `buyTokens()` function
Use a price variable named `tokensPerEth` set to **100**:
```solidity
uint256 public constant tokensPerEth = 100;
```
> 📝 The `buyTokens()` function in `Vendor.sol` should use `msg.value` and `tokensPerEth` to calculate an amount of tokens to `yourToken.transfer()` to `msg.sender`.
> 📟 Emit **event** `BuyTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens)` when tokens are purchased.
Edit `deploy/01_deploy_vendor.js` to deploy the `Vendor` (uncomment Vendor deploy lines).
## 5: 🤔 Vendor Buyback 🤯
👩🏫 The hardest part of this challenge is to build your `Vendor` to buy the tokens back.
🧐 The reason why this is hard is the `approve()` pattern in ERC20s.
😕 First, the user has to call `approve()` on the `YourToken` contract, approving the `Vendor` contract address to take some amount of tokens.
🤨 Then, the user makes a *second transaction* to the `Vendor` contract to `sellTokens(uint256 amount)`.
🤓 The `Vendor` should call `yourToken.transferFrom(msg.sender, address(this), theAmount)` and if the user has approved the `Vendor` correctly, tokens should transfer to the `Vendor` and ETH should be sent to the user.
> 📝 Edit `Vendor.sol` and add a `sellTokens(uint256 amount)` function!
⚠️ You will need extra UI for calling `approve()` before calling `sellTokens(uint256 amount)`.
🔨 Use the `Debug Contracts` tab to call the approve and sellTokens() at first but then...
🔍 Look in the `App.jsx` for the extra approve/sell UI to uncomment!
----
## 6: 💾 Deploy it! 🛰
📡 Edit the `defaultNetwork` in `packages/hardhat/hardhat.config.js`, as well as `targetNetwork` in `packages/react-app/src/App.jsx`, to [the Polygon Mumbai Testnet](https://www.alchemy.com/overviews/mumbai-testnet)
👩🚀 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.
🛰 Use a faucet like [faucet.paradigm.xyz](https://faucet.paradigm.xyz/) to fund your **deployer address** (run `yarn account` again to view balances)
> 🚀 Run `yarn deploy` to deploy to your public network of choice (😅 wherever you can get ⛽️ gas)
🔬 Inspect the block explorer for the network you deployed to... make sure your contract is there.
---
## 7: 🚢 Ship it! 🚁
📦 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.
🚔 Traffic to your url might break the [Infura](https://infura.io/) rate limit, edit your key: `constants.js` in `packages/react-app/src`.
---
## 8: 📜 Contract Verification
Update the `api-key` in `packages/hardhat/package.json`. 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 🛰
👀 You may see an address for both YouToken and Vendor. You will want the Vendor address.
---
### Question 1: Why type of standard is ERC20?
- A W3C
- B Ethereum
- C Mozilla
- D Brave
### Question 2: What does a block explorer do?
- A Modify the Blockchain
- B Visualize Transactions
- C Duplicate the Blockchain
- D Connect Blockchains