-
Notifications
You must be signed in to change notification settings - Fork 4
/
TransferHelper.sol
64 lines (56 loc) · 2.97 KB
/
TransferHelper.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title TransferHelper
* @dev Wrappers around ERC20 operations that returns the value received by recipent and the actual allowance of approval.
* To use this library you can add a `using TransferHelper for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library TransferHelper{
// using SafeMath for uint;
function safeTransfer(IERC20 _token, address _to, uint _amount) internal returns (uint amountReceived){
if (_amount > 0){
uint balanceBefore = _token.balanceOf(_to);
address(_token).call(abi.encodeWithSelector(_token.transfer.selector, _to, _amount));
uint balanceAfter = _token.balanceOf(_to);
require(balanceAfter > balanceBefore, "TF");
amountReceived = balanceAfter - balanceBefore;
}
}
function safeTransferFrom(IERC20 _token, address _from, address _to, uint _amount) internal returns (uint amountReceived){
if (_amount > 0){
uint balanceBefore = _token.balanceOf(_to);
address(_token).call(abi.encodeWithSelector(_token.transferFrom.selector, _from, _to, _amount));
// _token.transferFrom(_from, _to, _amount);
uint balanceAfter = _token.balanceOf(_to);
require(balanceAfter > balanceBefore, "TFF");
amountReceived = balanceAfter - balanceBefore;
}
}
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (uint) {
bool success;
if (_token.allowance(address(this), _spender) != 0){
(success, ) = address(_token).call(abi.encodeWithSelector(_token.approve.selector, _spender, 0));
require(success, "AF");
}
(success, ) = address(_token).call(abi.encodeWithSelector(_token.approve.selector, _spender, _amount));
require(success, "AF");
return _token.allowance(address(this), _spender);
}
// function safeIncreaseAllowance(IERC20 _token, address _spender, uint256 _amount) internal returns (uint) {
// uint256 allowanceBefore = _token.allowance(address(this), _spender);
// uint256 allowanceNew = allowanceBefore.add(_amount);
// uint256 allowanceAfter = safeApprove(_token, _spender, allowanceNew);
// require(allowanceAfter == allowanceNew, "AF");
// return allowanceNew;
// }
// function safeDecreaseAllowance(IERC20 _token, address _spender, uint256 _amount) internal returns (uint) {
// uint256 allowanceBefore = _token.allowance(address(this), _spender);
// uint256 allowanceNew = allowanceBefore.sub(_amount);
// uint256 allowanceAfter = safeApprove(_token, _spender, allowanceNew);
// require(allowanceAfter == allowanceNew, "AF");
// return allowanceNew;
// }
}