Created
November 7, 2022 14:51
-
-
Save nola11/214b622cf22a5f9261874c938e761944 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=true&runs=200&gist=
This file contains 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
// SPDX-License-Identifier: GPL-3.0-or-later | |
pragma solidity >=0.6.0; | |
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false | |
library TransferHelper { | |
function safeApprove( | |
address token, | |
address to, | |
uint256 value | |
) internal { | |
// bytes4(keccak256(bytes('approve(address,uint256)'))); | |
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); | |
require( | |
success && (data.length == 0 || abi.decode(data, (bool))), | |
'TransferHelper::safeApprove: approve failed' | |
); | |
} | |
function safeTransfer( | |
address token, | |
address to, | |
uint256 value | |
) internal { | |
// bytes4(keccak256(bytes('transfer(address,uint256)'))); | |
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); | |
require( | |
success && (data.length == 0 || abi.decode(data, (bool))), | |
'TransferHelper::safeTransfer: transfer failed' | |
); | |
} | |
function safeTransferFrom( | |
address token, | |
address from, | |
address to, | |
uint256 value | |
) internal { | |
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); | |
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); | |
require( | |
success && (data.length == 0 || abi.decode(data, (bool))), | |
'TransferHelper::transferFrom: transferFrom failed' | |
); | |
} | |
function safeTransferETH(address to, uint256 value) internal { | |
(bool success, ) = to.call{value: value}(new bytes(0)); | |
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment