Skip to content

Instantly share code, notes, and snippets.

@k06a
Created November 18, 2019 10:02
Show Gist options
  • Save k06a/201149189b259277cf3e42b7727eafa7 to your computer and use it in GitHub Desktop.
Save k06a/201149189b259277cf3e42b7727eafa7 to your computer and use it in GitHub Desktop.
UniversalERC20
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
//
// using UniversalERC20 for IERC20;
//
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function universalTransfer(IERC20 token, address to, uint256 amount) internal {
if (token == IERC20(0)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (token != IERC20(0)) {
token.safeApprove(to, amount);
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (token == IERC20(0)) {
require(from == msg.sender && msg.value >= amount, "msg.value is zero");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (token == IERC20(0)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment