Address.sol 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. pragma solidity ^0.7.6;
  3. pragma abicoder v2;
  4. library Address {
  5. function isContract(address account) internal view returns (bool) {
  6. uint256 size;
  7. assembly { size := extcodesize(account) }
  8. return size > 0;
  9. }
  10. function sendValue(address payable recipient, uint256 amount) internal {
  11. require(address(this).balance >= amount, "Address: insufficient balance");
  12. (bool success, ) = recipient.call{ value: amount }("");
  13. require(success, "Address: unable to send value, recipient may have reverted");
  14. }
  15. function functionCall(address target, bytes memory data) internal returns (bytes memory) {
  16. return functionCall(target, data, "Address: low-level call failed");
  17. }
  18. function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
  19. return functionCallWithValue(target, data, 0, errorMessage);
  20. }
  21. function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
  22. return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
  23. }
  24. function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
  25. require(address(this).balance >= value, "Address: insufficient balance for call");
  26. require(isContract(target), "Address: call to non-contract");
  27. (bool success, bytes memory returndata) = target.call{ value: value }(data);
  28. return _verifyCallResult(success, returndata, errorMessage);
  29. }
  30. function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
  31. if (success) {
  32. return returndata;
  33. } else {
  34. if (returndata.length > 0) {
  35. assembly {
  36. let returndata_size := mload(returndata)
  37. revert(add(32, returndata), returndata_size)
  38. }
  39. } else {
  40. revert(errorMessage);
  41. }
  42. }
  43. }
  44. }