徐義鈞
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
      • Create new note
      • Create a note from template
        • 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
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Write
          • Only me
          • Signed-in users
          • Everyone
          Only me 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 No publishing access yet

        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.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        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
      • Save as template
      • 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 Create Help
    Create Create new note Create a note from template
    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
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me 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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    ###### tags: `Smart Contract` # Smart Contract-2 應用篇範例 第一篇都是基本語法 此處是第二篇 有實際的應用程式 也有著名的合約erc20 erc721等 不會每章介紹 挑較為常見的分析 https://solidity-by-example.org/ ## 第二篇應用程式範例 --- ### Ether Wallet 單純的合約 權限在owner身上 兩個function balance and withdraw payable(msg.sender).transfer(_amount); --- ### ERC20 #### IERC20和openzeppelin實作 不免俗地先從erc20開始 遵守EIP-20標準 https://eips.ethereum.org/EIPS/eip-20 IERC 是erc20的interface 需要實踐的介面 代表著有哪些標準的function可以使用 ERC20會實作這些介面 包括一些檢查 require看有沒有錯誤 像是transfer餘額不足之類的 **此處使用openzeppelin實作介紹 通過實作每個合約實際運作的邏輯不同** https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/ERC20.sol ![](https://i.imgur.com/fwxhJq7.png) totalSupply() 該代幣的總供應量 不過也可以改成動態設定 balanceOf() 該帳號的代幣的餘額 transfer() 設定好的數量轉移到指定的地址 同時會檢查balance餘額夠不夠 _msgSender發送 誰執行就扣誰的代幣 allowance() 返回津貼 一個地址在另一個地址可花費的餘額 查詢用 approve() 同意 設定給花費者的津貼額度 實作中只有transferFrom用到(是設定 不是新增) transferFrom() 指定A帳號轉移到B帳號 第一個疑問一定是 耶 這樣不就能指定別人的帳號送錢給我嗎 在openzeppelin的實作中 執行前會先查看_allowances(A,(B:amount))中的數量夠不夠 不夠會跳transfer amount exceeds allowance ``` _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); ``` sub如果扣掉是負數會跳錯誤 所以執行前帳號A沒有approve()足夠的餘額給B transferFrom()是不會有效的 transfer()就沒有這檢查 會直接從自己的帳號發送代幣到指定帳號 #### 作者實作 ![](https://i.imgur.com/hUfTE1w.png) 作者就寫的簡單直接 沒寫require 但基本上因為uint 變成負數會跳錯 基本上實作的跟openzeppelin差不多 transfer直接轉移 transferfrom 會扣掉allowance mint 會新增totalSupply ![](https://i.imgur.com/zLrPjOd.png) #### 簡易的erc20交換 透過constructor檢錄兩個符合IERC20標準的代幣 擁有地址 以及數量 ![](https://i.imgur.com/O8jXUUx.png) ![](https://i.imgur.com/amUszG4.png) 呼叫swap() 是沒有參數的 驗證呼叫人是owner1 or owner2 並且檢查兩個token中的allowance互相允許的餘額是否足夠 足夠的話在分別呼叫各個token中的transferFrom 有點令我意外 大多實作的swap也是這樣的概念嗎 是透過兩邊的allowance有沒有允許 有的話在兩個合約 分別寄送兩邊所需的數量 跟我想像的流動池pool不太一樣 後續解析uniswap再來多了解 --- ### ERC721 原作者沒有寫介紹 可能是介紹相關的文章太多了 也照慣例直接從interface帶到OP實作 該介紹有些細微處是舊版的 或是可能是作者自行實踐 像是內部isApprovedOrOwner就不太一樣 以OP新版為主 #### 簡單介紹流程 1.ming()產生NFT 2.setApprovalForAll() owner給予某地址spender所有的操作權限 包括設定approve() 可以給很多地址該權限 approve() 特定tokenid的的操作員權限 一個nft只會有一個操作員(不能是本人) 轉移NFT時會檢查這兩個權限 有其中一個就行 除非是NFT持有者操作才不需要任意的權限 3.透過safeTransferFrom()進行NFT的轉移 #### 介紹function: ![](https://i.imgur.com/EbDfYXM.png) balanceOf() NFT的餘額 持有數量 ownerOf() NFT所屬者是誰 通常是輸入ID 返回address transferFrom() 三個參數from to id 實際的NFT轉移 會先執行簡單的檢查 id的持有人是不是from地址 to是不是空地址 再進到_isApprovedOrOwner(msg.sender, id) 內部會先用找出該id的owner地址 此處會執行三個條件or 只要過一個就行 代表有權限 1.from是不是msg.sender 呼叫的是不是本人 2.isApprovedForAll[owner][msg.sender]是不是true 代表owner有沒有給呼叫者msg.sender權限操作 3.getApproved(tokenId)==msg.sender 該token的操作員是不是msg.sender 從這也能看出 一個NFT是有兩種權限的 一個是ApprovedForAll 紀錄的是地址owner是否給spender權限 一個是getApproved 紀錄的是特定tokenId的操作員是誰 檢查都通過後進到最後的_transfer()轉移過程 最後確認from是不是該id的持有者(個人覺得能直接挪到transferFrom裡先做) 該token的approve設為address(0)空地址 balances數量增減 owner換成to 這樣就結束了 內部還有beforeTokenTransfer跟afterTokenTransfer 沒有實踐 是留著給使用者擴展用 safeTransferFrom() 基本上執行的function都一樣 但多了一個_checkOnERC721Received() 如果接收者是合約 他會確認合約有沒有實現onERC721Received的缺口 沒有的話變退回 這有點是我的盲區了 尚未使用過合約接受NFT approve() 兩個參數 to跟tokenid 設定特定的tokenid操作員(只限一個) 會先檢查to跟該NFT持有者是不是同一人 是的話跳錯 等於自己設定自己 再來會or檢查 持有者是不是msg.sender 或是持有者有沒有給msg.sender的isapproveall權限 其中一個通過 就能設定to變成該tokenid的操作員 getApproved() 返回指定id的approve是誰 setApprovalForAll() 兩個參數 operator(address) approved(bool) 設定owner是否允許某個地址成為操作員 可以多個 並沒有from 所以是直接用msg.sender當owner 執行_setApprovalForAll(msg.sender,operator,to) 會使得_operatorApprovals[owner][operator]=approved 代表這個owner是否讓地址operator進行操作 isApprovedForAll() 返回owner地址的操作員bool mint() 鑄造NFTid給to地址 通常只留給合約持有者使用 或是白名單模式 設置balance跟owner給to burn() 燒毀該NFT 通常也是只留給合約持有者使用 清除balance跟owner跟approve() 複習完的感想 approve()是針對特定NFT的權限 而且NFT轉移後是會消除的 基本上是無所謂 你NFT賣了就轉了 給錯了他也只能賣那個特定的NFT 但setApprovalForAll() 真的不能亂給 他的set的流程跟特定NFT不太有關係的 等於是你在這個合約裡給了代理人所有權限 雖然說你能取消 但如果給了一堆人 還要一個一個取消掉 如果是被駭 大概率都是setApprovalForAll()給了某個人吧 所以可以把一個系列的NFT全部掃光 --- ### Precompute Contract Address with Create2 用Create2可以事先確定合約地址 同時也讓產生地址的方式不固定(透過salt) ![](https://i.imgur.com/umOhG0a.png) create跟create2不同之處在於 creat2多使用了一個salt參數 同時你能事前得知合約地址的數值 不知道有什麼用處 可能在某些需要事情得知合約地址的場合會應用 下面連結說可以挑一個喜歡的合約地址 https://ethereum.stackexchange.com/questions/101336/what-is-the-benefit-of-using-create2-to-create-a-smart-contract ---

    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
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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