Files
dodo-contractV2/contracts/lib/UniversalERC20.sol

70 lines
2.0 KiB
Solidity
Raw Normal View History

2020-11-09 14:26:38 +08:00
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
import {SafeMath} from "./SafeMath.sol";
import {IERC20} from "../intf/IERC20.sol";
import {SafeERC20} from "./SafeERC20.sol";
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
2020-11-27 15:35:36 +08:00
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
2020-11-09 14:26:38 +08:00
2020-11-18 21:47:06 +08:00
function isETH(IERC20 token) internal pure returns (bool) {
return (token == ZERO_ADDRESS || token == ETH_ADDRESS);
2020-11-09 14:26:38 +08:00
}
2020-11-18 21:47:06 +08:00
function universalTransfer(IERC20 token, address payable to, uint256 amount) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
2020-11-09 14:26:38 +08:00
} else {
2020-11-18 21:47:06 +08:00
token.safeTransfer(to, amount);
2020-11-09 14:26:38 +08:00
}
}
}
2020-11-18 21:47:06 +08:00
function universalApprove(IERC20 token, address to, uint256 amount) internal {
require(!isETH(token), "ETH Don't need approve");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
2020-11-16 10:54:05 +08:00
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
2020-11-09 14:26:38 +08:00
}
}
2020-11-27 15:35:36 +08:00
function universalApproveMax(IERC20 token, address to, uint256 amount) internal {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, uint(-1));
}
}
2020-11-09 14:26:38 +08:00
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
2020-11-18 21:47:06 +08:00
if (isETH(token)) {
2020-11-09 14:26:38 +08:00
return who.balance;
} else {
return token.balanceOf(who);
}
}
}