Polygon
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ## 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. ![image](https://i.ibb.co/zbY5rz1/sfsf.png) > 🏵 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 ![image](https://i.ibb.co/zbY5rz1/sfsf.png) > 👩‍💻 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

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully