|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | + |
| 3 | +pragma solidity ^0.8.20; |
| 4 | + |
| 5 | +import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Utility functions helpful when making different kinds of contract calls in Solidity. |
| 9 | + */ |
| 10 | +library Call { |
| 11 | + function call(address to, uint256 value, bytes memory data) internal returns (bool success) { |
| 12 | + return call(to, value, data, gasleft()); |
| 13 | + } |
| 14 | + |
| 15 | + function call(address to, uint256 value, bytes memory data, uint256 txGas) internal returns (bool success) { |
| 16 | + assembly ("memory-safe") { |
| 17 | + success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + function staticcall(address to, bytes memory data) internal view returns (bool success) { |
| 22 | + return staticcall(to, data, gasleft()); |
| 23 | + } |
| 24 | + |
| 25 | + function staticcall(address to, bytes memory data, uint256 txGas) internal view returns (bool success) { |
| 26 | + assembly ("memory-safe") { |
| 27 | + success := staticcall(txGas, to, add(data, 0x20), mload(data), 0, 0) |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + function delegateCall(address to, bytes memory data) internal returns (bool success) { |
| 32 | + return delegateCall(to, data, gasleft()); |
| 33 | + } |
| 34 | + |
| 35 | + function delegateCall(address to, bytes memory data, uint256 txGas) internal returns (bool success) { |
| 36 | + assembly ("memory-safe") { |
| 37 | + success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + function getReturnDataSize() internal pure returns (uint256 returnDataSize) { |
| 42 | + assembly ("memory-safe") { |
| 43 | + returnDataSize := returndatasize() |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + function getReturnData(uint256 maxLen) internal pure returns (bytes memory ptr) { |
| 48 | + return getReturnDataFixed(Math.min(maxLen, getReturnDataSize())); |
| 49 | + } |
| 50 | + |
| 51 | + function getReturnDataFixed(uint256 len) internal pure returns (bytes memory ptr) { |
| 52 | + assembly ("memory-safe") { |
| 53 | + ptr := mload(0x40) |
| 54 | + mstore(0x40, add(ptr, add(len, 0x20))) |
| 55 | + mstore(ptr, len) |
| 56 | + returndatacopy(add(ptr, 0x20), 0, len) |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + function revertWithData(bytes memory returnData) internal pure { |
| 61 | + assembly ("memory-safe") { |
| 62 | + revert(add(returnData, 0x20), mload(returnData)) |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + function revertWithCode(bytes32 code) internal pure { |
| 67 | + assembly ("memory-safe") { |
| 68 | + mstore(0, code) |
| 69 | + revert(0, 0x20) |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments