Last active
June 20, 2019 09:31
-
-
Save samparsky/ab6110c36a4070d6282c4d3ddacc3c6d to your computer and use it in GitHub Desktop.
SafeERC20 token transfer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pragma solidity ^0.5.2; | |
| interface BadToken { | |
| function transfer(address to, uint value) external; | |
| function transferFrom(address from, address to, uint value) external; | |
| } | |
| contract SafeTransfer { | |
| function safeTransfer(address token, address to, uint value, bool from) internal returns (bool result) { | |
| if (from) { | |
| BadToken(token).transferFrom(msg.sender, address(this), value); | |
| } else { | |
| BadToken(token).transfer(to, value); | |
| } | |
| // solium-disable-next-line security/no-inline-assembly | |
| assembly { | |
| switch returndatasize | |
| case 0 { | |
| // This is our BadToken | |
| result := not(0) // result is true | |
| } | |
| case 32 { | |
| // This is our GoodToken | |
| returndatacopy(0, 0, 32) | |
| result := mload(0) // result == returndata of external call | |
| } | |
| default { | |
| // This is not an ERC20 token | |
| result := 0 | |
| } | |
| } | |
| return result; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import "./SafeTransfer.sol" | |
| contract TestVault is SafeTransfer { | |
| function depositToken(address _tokenAddress, uint _amount) external returns uint { | |
| address sender = msg.sender; | |
| require(safeTransfer(_tokenAddress, sender, _amount, true), "token deposit must succeed"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment