iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
0
Blockchain

區塊鏈應用開發實戰系列 第 25

25. 去中心化交易所用戶存提 ERC20 代幣功能實作

小明今天繼續完成的是用戶存提 ERC20 代幣的功能:

User 用戶功能

  • 存入 ERC20 代幣
    將用戶錢包中的 ERC20 代幣存入交易所
function depositToken(string symbolName, uint amount) public {
    uint8 symbolNameIndex = getSymbolIndexOrThrow(symbolName);
    require(tokens[symbolNameIndex].tokenContract != address(0));

    ERC20Interface token = ERC20Interface(tokens[symbolNameIndex].tokenContract);

    require(token.transferFrom(msg.sender, address(this), amount) == true);
    require(tokenBalanceForAddress[msg.sender][symbolNameIndex] + amount >= tokenBalanceForAddress[msg.sender][symbolNameIndex]);
    tokenBalanceForAddress[msg.sender][symbolNameIndex] += amount;
    emit DepositForTokenReceived(msg.sender, symbolNameIndex, amount, now);
}
  • 提領 ERC20 代幣
    將用戶在交易所的 ERC20 代幣領出到用戶錢包
function withdrawToken(string symbolName, uint amount) public {
    uint8 symbolNameIndex = getSymbolIndexOrThrow(symbolName);
    require(tokens[symbolNameIndex].tokenContract != address(0));

    ERC20Interface token = ERC20Interface(tokens[symbolNameIndex].tokenContract);

    require(tokenBalanceForAddress[msg.sender][symbolNameIndex] - amount >= 0);
    require(tokenBalanceForAddress[msg.sender][symbolNameIndex] - amount <= tokenBalanceForAddress[msg.sender][symbolNameIndex]);

    tokenBalanceForAddress[msg.sender][symbolNameIndex] -= amount;
    require(token.transfer(msg.sender, amount) == true);
    emit WithdrawalToken(msg.sender, symbolNameIndex, amount, now);
}
  • 檢視 ERC20 代幣餘額
    取得用戶 ERC20 代幣的餘額
function getBalance(string symbolName) view public returns (uint) {
    uint8 symbolNameIndex = getSymbolIndexOrThrow(symbolName);
    return tokenBalanceForAddress[msg.sender][symbolNameIndex];
}

本文同時發佈於作者部落格:https://www.bdetw.com/blog


/images/emoticon/emoticon34.gif想找區塊鏈人才或想學習區塊鏈知識的夥伴。歡迎參加社群小聚,一起來輕鬆交流、互相學習成長、認識新朋友、發現新機會!
 
台北區塊鏈社群
https://bitlly.co/Q4dIK
 
BDE 區塊鏈學院 - 提供專業的區塊鏈培訓與顧問服務。
https://bitlly.co/mbDwX


上一篇
24. 去中心化交易所用戶存提以太幣功能實作
下一篇
26. 去中心化交易所用戶檢視買單交易帳簿功能實作
系列文
區塊鏈應用開發實戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言