當 ERC20 Token 越發越多了,有沒有辦法做一個跨 Token 的交易呢?答案是可以的!今天就讓我們來看看 Token Exchange 要怎麼做吧!
本次的 Example 一樣感謝我的朋友 polarjack 給予程式碼建議。
本日合約:
pragma solidity ^0.4.25;
import "browser/IERC20.sol";
contract TokenExchange {
// From => UserA, TokenA
address fromAddress;
address fromToken;
uint256 fromAmount;
// To => UserB, TokenB
address toToken;
uint256 toAmount;
// 假設 UserA 已經 Approve
function CreateExchange(
address _fromToken, uint256 _fromAmount,
address _toToken, uint256 _toAmount) public {
require(IERC20(_fromToken).transferFrom(msg.sender, this, _fromAmount));
fromAddress = msg.sender;
fromToken = _fromToken;
fromAmount = _fromAmount;
toToken = _toToken;
toAmount = _toAmount;
}
function DoChange() public {
require(IERC20(toToken).transferFrom(msg.sender, this, toAmount));
IERC20(fromToken).transfer(msg.sender, fromAmount);
IERC20(toToken).transfer(fromAddress, toAmount);
}
}
本日影片:
https://youtu.be/1CvTpXEProc
Smart Contract 實戰教學播放清單:
https://www.youtube.com/playlist?list=PLHmOMPRfmOxSJcrlwyandWYiuP9ZAMYoF
想請問為何是require(IERC20(_fromToken).transferFrom(msg.sender, this, _fromAmount))呢?
不太懂為何這裡require(IERC20(_fromToken)是這樣寫,想知道老師的邏輯思考方式,謝謝
想知道兩個問題:
1.為何需要寫require
2.(IERC20(_fromToken)這樣寫是什麼意思,為何這麼寫
這個是用來檢查 transferFrom
的回傳值,確定他一定有成功,否則就直接終止。
好的 我知道了,謝謝你了