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 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. ![image](https://i.ibb.co/cczWJC2/Screen-Shot-2022-11-09-at-11-11-38-AM.jpg) > 🏦 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/ ![image](https://i.ibb.co/cczWJC2/Screen-Shot-2022-11-09-at-11-11-38-AM.jpg) > 👩‍💻 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! ![Wallet_Medium](https://user-images.githubusercontent.com/12072395/159990402-d5535875-f1eb-4c75-86a7-6fbd5e6cbe5f.png). 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/ ![image](https://i.ibb.co/cczWJC2/Screen-Shot-2022-11-09-at-11-11-38-AM.jpg) 📡 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). ![Screen Shot 2021-11-30 at 10 21 01 AM](https://user-images.githubusercontent.com/9419140/144075208-c50b70aa-345f-4e36-81d6-becaa5f74857.png) > 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

    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