iT邦幫忙

2022 iThome 鐵人賽

DAY 18
0
影片教學

在 2022 年,我們該如何寫智能合約系列 第 18

ERC20 實作 轉帳篇

  • 分享至 

  • xImage
  •  

#鐵人賽 #ethereum #solidity

今天開始來實作 ERC20 吧!
本日實作的函式:

  1. totalSupply()
  2. balanceOf()
  3. transfer()

本日影片: https://youtu.be/lEzEatQwdzQ
本日合約:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

interface IERC20 {
    event Transfer(address indexed from, address indexed to, uint256 value);
    //event Approval(address indexed owner, address indexed spender, uint256 value);

    function totalSupply() external view returns (uint256);

    function balanceOf(address account) external view returns (uint256);
    //function allowance(address owner, address spender) external view returns (uint256);
    
    //function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    //function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

contract ERC20 is IERC20 {
    uint256 _totalSupply;
    mapping(address => uint256) _balance;

    constructor() {
        _balance[msg.sender] = 10000;
        _totalSupply = 10000;
    }

    function totalSupply() public view returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view returns (uint256) {
        return _balance[account];
    }

    function transfer(address to, uint256 amount) public returns (bool) {
        uint256 myBalance = _balance[msg.sender];
        require(myBalance >= amount, "No money to transfer");
        require(to != address(0), "Transfer to address 0");

        _balance[msg.sender] = myBalance - amount;
        _balance[to] = _balance[to] + amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }
}

本影片提到的連結:
「Remix IDE」: https://remix.ethereum.org/
「在 2022 年,我們該如何寫智能合約」: https://ithelp.ithome.com.tw/users/20083367/ironman/5019
「那些關於 Ethereum 的事」: https://ithelp.ithome.com.tw/users/20083367/ironman/5136
「一本關於 Ethereum 與 Solidity 智能合約的書」: https://solidity.tw
「文章或主題許願池」: https://github.com/hydai/solidity-book/issues
「本系列播放清單」: https://www.youtube.com/playlist?list=PLHmOMPRfmOxQYDnXAc1hKY6ra4WDU8ZlM


上一篇
ERC20 Interface ERC20 介面
下一篇
ERC20 實作 授權篇
系列文
在 2022 年,我們該如何寫智能合約30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言