Skip to content

Instantly share code, notes, and snippets.

@samparsky
Last active June 20, 2019 09:31
Show Gist options
  • Select an option

  • Save samparsky/ab6110c36a4070d6282c4d3ddacc3c6d to your computer and use it in GitHub Desktop.

Select an option

Save samparsky/ab6110c36a4070d6282c4d3ddacc3c6d to your computer and use it in GitHub Desktop.
SafeERC20 token transfer
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;
}
}
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