Verified contractExactMIT
GatewayOnrampV6
Address0x1835cf43dcbc0c56731366975567159e9d5a0129
- Balance
0 ETH
- Transactions
18
- Compiler
solc 0.8.27
- Same code
Only this contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- No
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,792,223
- Creation transaction
- 0xdf36dc0cdf…c549957661
32 files
- src/GatewayOnrampV6.solmain13.05 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/BTCUtils.sol39.09 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/BytesLib.sol18.96 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/SafeMath.sol2.69 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/ValidateSPV.sol5.72 KB
- dependencies/@bob-collective-bob-v1/contracts/src/gateway/IStrategy.sol969 B
- dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelay.sol1.33 KB
- dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelayWithVerify.sol397 B
- dependencies/@bob-collective-bob-v1/contracts/src/relay/ILightRelay.sol1.18 KB
- dependencies/@bob-collective-bob-v1/contracts/src/utils/BitcoinTx.sol22.7 KB
- dependencies/@openzeppelin-contracts-5.5.0/access/Ownable.sol3.1 KB
- dependencies/@openzeppelin-contracts-5.5.0/access/Ownable2Step.sol2.48 KB
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC1363.sol4.45 KB
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC165.sol193 B
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC20.sol182 B
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/draft-IERC6093.sol6.54 KB
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/ERC20.sol10.8 KB
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/extensions/IERC20Metadata.sol684 B
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/utils/SafeERC20.sol13.25 KB
- dependencies/@openzeppelin-contracts-5.5.0/utils/Address.sol6.8 KB
- dependencies/@openzeppelin-contracts-5.5.0/utils/Context.sol963 B
- dependencies/@openzeppelin-contracts-5.5.0/utils/Errors.sol896 B
- dependencies/@openzeppelin-contracts-5.5.0/utils/LowLevelCall.sol5.5 KB
- dependencies/@openzeppelin-contracts-5.5.0/utils/Panic.sol1.97 KB
- dependencies/@openzeppelin-contracts-5.5.0/utils/introspection/IERC165.sol871 B
- dependencies/@openzeppelin-contracts-5.5.0/utils/math/Math.sol32.39 KB
- dependencies/@openzeppelin-contracts-5.5.0/utils/math/SafeCast.sol34.94 KB
- src/CommonStructs.sol4.56 KB
- src/IERC20Ext.sol321 B
- src/IGatewayOnrampV6.sol4.32 KB
- src/swapper/ISwapper.sol689 B
src/GatewayOnrampV6.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IGatewayOnrampV6} from "./IGatewayOnrampV6.sol";
import {ISwapper} from "./swapper/ISwapper.sol";
import {IStrategy} from "@bob-collective/bob/gateway/IStrategy.sol";
import {IERC20Ext} from "./IERC20Ext.sol";
import {OnrampOrderArgs, FeeDetails} from "./CommonStructs.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
contract GatewayOnrampV6 is IGatewayOnrampV6, Ownable2Step {
using SafeERC20 for IERC20;
using Address for address;
/// @inheritdoc IGatewayOnrampV6
uint16 public constant override VERSION = 6;
/// @inheritdoc IGatewayOnrampV6
uint256 public constant override MAX_PROTOCOL_FEE = 10000;
/// @inheritdoc IGatewayOnrampV6
IERC20Ext public immutable override token;
/// @inheritdoc IGatewayOnrampV6
ISwapper public override swapper;
/// @inheritdoc IGatewayOnrampV6
uint256 public override gasSpentFixedOverhead;
/// @inheritdoc IGatewayOnrampV6
FeeDetails public override protocolFeeDetails;
/// @inheritdoc IGatewayOnrampV6
mapping(bytes32 => bool) public override spentTxHashes;
/// @dev Constructor
/// @param _owner The owner of the contract
/// @param _token The ERC20 token contract address that is used to fill the onramp orders
/// @param _swapper The swapper contract used to convert a part of the order to ETH
/// @param _gasSpentFixedOverhead A fixed gas overhead for the releaseFundsAndCallStrategy function that is not factored into the metering
/// @param _protocolFeeDetails The protocol fee details
constructor(
address _owner,
IERC20Ext _token,
ISwapper _swapper,
uint256 _gasSpentFixedOverhead,
FeeDetails memory _protocolFeeDetails
) Ownable(_owner) {
if (_owner == address(0)) revert ZeroAddress();
token = _token;
swapper = _swapper;
gasSpentFixedOverhead = _gasSpentFixedOverhead;
if (_protocolFeeDetails.amount > MAX_PROTOCOL_FEE) revert ProtocolFeeExceedsMax();
protocolFeeDetails = _protocolFeeDetails;
}
/// @inheritdoc IGatewayOnrampV6
function releaseFundsAndCallStrategy(bytes32 _txHash, OnrampOrderArgs calldata _onrampOrderArgs)
external
override
onlyOwner
{
uint256 gasStart = gasleft();
if (spentTxHashes[_txHash]) revert TransactionAlreadySpent();
spentTxHashes[_txHash] = true;
IERC20(token).safeTransferFrom(_msgSender(), address(this), _onrampOrderArgs.tokenFillAmount);
(uint256 tokenAmountToSendToUserMinusProtocolFees, uint256 protocolFeesAmount) =
_handleProtocolFees(_onrampOrderArgs.tokenFillAmount);
(uint256 tokenAmountToSendToUser, uint256 affiliateFeesAmount) =
_handleAffiliateFees(_onrampOrderArgs.affiliateFees, tokenAmountToSendToUserMinusProtocolFees);
bool skipStrategy;
uint256 receivedEthFromSwap;
if (_onrampOrderArgs.tokenToSwapToEthAmount > 0) {
// Cap the amount to swap by the amount of tokens available
uint256 tokenToSwapToEthAmountCapped =
Math.min(_onrampOrderArgs.tokenToSwapToEthAmount, tokenAmountToSendToUser);
// Swap tokenToSwapToEthAmountCapped to eth using swapExactTokensForNative
// The min amount out for the swap is set to 0, as the small amount of converted Btc will make sandwich attacks
// not economically worthwhile to carry out.
// Denial of service attacks are still possible where an attacker would make sandwich attacks to decrease the amount of
// Eth the user receives to a near 0 amount. It would be costly though for the attacker.
IERC20(token).safeIncreaseAllowance(address(swapper), tokenToSwapToEthAmountCapped);
try swapper.swapExactTokensForNative(token, tokenToSwapToEthAmountCapped, 0) returns (uint256 amountOut) {
// we now subtract the amount of tokens that were swapped from the amount to send to the recipient
tokenAmountToSendToUser -= tokenToSwapToEthAmountCapped;
receivedEthFromSwap = amountOut;
} catch (bytes memory revertData) {
emit EthSwapFailed(revertData);
IERC20(token).safeDecreaseAllowance(address(swapper), tokenToSwapToEthAmountCapped);
// skip the strategy if the swaps fail
skipStrategy = true;
}
}
// skip the strategy if the gas price exceeds the limit
skipStrategy = tx.gasprice > _onrampOrderArgs.userGasPriceLimit ? true : skipStrategy;
if (tokenAmountToSendToUser > 0) {
// if there is no strategy set or the swap attempt failed or the gas price exceeds the limit, transfer the tokens directly to the recipient
if (address(_onrampOrderArgs.strategy) == address(0) || skipStrategy) {
IERC20(token).safeTransfer(_onrampOrderArgs.recipient, tokenAmountToSendToUser);
} else {
// myAddress.call(abi.encodeWithSelector(...)) will always return true if myAddress is NOT
// a contract address. If there is any misconfiguration, then _onrampOrderArgs.strategy could
// be a non-contract address. The following contract codesize check handles this rare misconfiguration error.
if (address(_onrampOrderArgs.strategy).code.length > 0) {
IERC20(token).safeIncreaseAllowance(address(_onrampOrderArgs.strategy), tokenAmountToSendToUser);
// Ensuring execution of the following low level call does not fail silently if the relayer does not supply enough gas
_checkGasLeftForLowLevelCall(_onrampOrderArgs.strategyGasLimit);
// If the gas limit is exceeded, the strategy will revert and tokens will be transferred to the recipient
uint256 gasBeforeStrategy = gasleft();
(bool success, bytes memory data) = address(_onrampOrderArgs.strategy)
.call{gas: _onrampOrderArgs.strategyGasLimit}(
abi.encodeWithSelector(
IStrategy.handleGatewayMessage.selector,
IERC20(token),
tokenAmountToSendToUser,
_onrampOrderArgs.recipient,
_onrampOrderArgs.strategyExtraData
)
);
uint256 gasSpentByStrategy = gasBeforeStrategy - gasleft();
if (!success) {
// Out of gas errors will have no revert data, so instead we check if the gas spent hit the limit.
// If so its likely that the strategy ran out of gas.
bool strategyGasLimitExceeded =
gasSpentByStrategy > _onrampOrderArgs.strategyGasLimit && data.length == 0;
emit StrategyFailed(address(_onrampOrderArgs.strategy), data, strategyGasLimitExceeded);
IERC20(token).safeDecreaseAllowance(address(_onrampOrderArgs.strategy), tokenAmountToSendToUser);
IERC20(token).safeTransfer(_onrampOrderArgs.recipient, tokenAmountToSendToUser);
}
} else {
IERC20(token).safeTransfer(_onrampOrderArgs.recipient, tokenAmountToSendToUser);
}
}
}
// calculate the gas spent overall
uint256 gasSpent = gasStart - gasleft() + gasSpentFixedOverhead;
// The gas price is capped to the gas price limit set in the order
uint256 cappedGasCost = gasSpent * Math.min(tx.gasprice, _onrampOrderArgs.userGasPriceLimit);
// Send the gas fee to the relayer, including the transaction cost overhead sent with the order
// If the fee exceeds the amount of eth received from the swap, then send the full amount of eth received from the swap
uint256 ethToSendToRelayer =
Math.min(cappedGasCost + _onrampOrderArgs.transactionCostOverhead, receivedEthFromSwap);
// Ensuring execution of the following low level call does not fail silently if the solver does not supply enough gas
_checkGasLeftForLowLevelCall(_onrampOrderArgs.ethTransferGasLimit);
_msgSender().call{value: ethToSendToRelayer, gas: _onrampOrderArgs.ethTransferGasLimit}("");
// if there is any excess eth left from the swap after fees are paid, send it to the recipient
uint256 excessEth = receivedEthFromSwap - ethToSendToRelayer;
if (excessEth > 0) {
// Ensuring execution of the following low level call does not fail silently if the relayer does not supply enough gas
_checkGasLeftForLowLevelCall(_onrampOrderArgs.ethTransferGasLimit);
_onrampOrderArgs.recipient.call{value: excessEth, gas: _onrampOrderArgs.ethTransferGasLimit}("");
}
emit OnrampExecuted(
_onrampOrderArgs.recipient,
tokenAmountToSendToUser,
protocolFeesAmount,
affiliateFeesAmount,
ethToSendToRelayer,
excessEth,
skipStrategy
);
}
/// @inheritdoc IGatewayOnrampV6
function setSwapper(ISwapper _swapper) external override onlyOwner {
if (_swapper == ISwapper(address(0))) revert ZeroAddress();
swapper = _swapper;
}
/// @inheritdoc IGatewayOnrampV6
function setGasSpentFixedOverhead(uint256 _gasSpentFixedOverhead) external override onlyOwner {
gasSpentFixedOverhead = _gasSpentFixedOverhead;
}
/// @inheritdoc IGatewayOnrampV6
function setProtocolFeeDetails(FeeDetails memory _protocolFeeDetails) external override onlyOwner {
if (_protocolFeeDetails.amount > MAX_PROTOCOL_FEE) revert ProtocolFeeExceedsMax();
protocolFeeDetails = _protocolFeeDetails;
}
/// @inheritdoc IGatewayOnrampV6
receive() external payable override {}
/// @dev Checks that the available gas is enough for a low level call with the given gas limit
function _checkGasLeftForLowLevelCall(uint256 _gasLimit) internal view {
// Factor 64/63 is to account for EIP-150 which limits the gas that can be consumed by a call to 63/64 of the available gas of the caller
// adding 500 as a buffer to account for the gas used between the gasleft() query and when the actual call is executed
if (gasleft() < (((_gasLimit * 64) / 63) + 500)) revert InsufficientGas();
}
/// @dev Handles the affiliate fees for the onramp order
function _handleAffiliateFees(FeeDetails[] memory _affiliateFees, uint256 _amount)
internal
returns (uint256, uint256)
{
uint256 totalAffiliateFeesAmount = 0;
for (uint256 i = 0; i < _affiliateFees.length; i++) {
// check fee is not zero and recipient is not zero address, if either is not true, skip the fee
if (_affiliateFees[i].amount != 0 && _affiliateFees[i].recipient != address(0)) {
totalAffiliateFeesAmount += _affiliateFees[i].amount;
// check that the total affiliate fees are not greater than the available amount
if (totalAffiliateFeesAmount > _amount) revert AffiliateFeesExceedAvailableAmount();
// send the affiliate fee to the recipient
IERC20(token).safeTransfer(_affiliateFees[i].recipient, _affiliateFees[i].amount);
}
}
return (_amount - totalAffiliateFeesAmount, totalAffiliateFeesAmount);
}
/// @dev Calculates the protocol fees for the onramp order and subtracts them from the amount
function _handleProtocolFees(uint256 _amount) internal returns (uint256, uint256 protocolFeeAmount) {
// check that the protocol fee is not zero and recipient is not zero address, if either is not true, skip the fee
if (protocolFeeDetails.amount > 0 && protocolFeeDetails.recipient != address(0)) {
// calculate the protocol fee amount from the bps value
protocolFeeAmount = _amount * protocolFeeDetails.amount / 10000;
// check that the protocol fee is not greater than the available amount
if (protocolFeeAmount > _amount) revert ProtocolFeesExceedAvailableAmount();
// send the protocol fee to the recipient
IERC20(token).safeTransfer(protocolFeeDetails.recipient, protocolFeeAmount);
}
return (_amount - protocolFeeAmount, protocolFeeAmount);
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/BTCUtils.sol
pragma solidity ^0.8.4;
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
/// @title BTCUtils
/// @author Summa (https://github.com/summa-tx) and Bob (https://github.com/bob-collective)
/// @notice Utility library for Bitcoin Actions
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
// The target at minimum Difficulty. Also the target of the genesis block
uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;
uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds
uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks
uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {
return determineVarIntDataLengthAt(_flag, 0);
}
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _b The byte array containing a VarInt
/// @param _at The position of the VarInt in the array
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {
if (uint8(_b[_at]) == 0xff) {
return 8; // one-byte flag, 8 bytes data
}
if (uint8(_b[_at]) == 0xfe) {
return 4; // one-byte flag, 4 bytes data
}
if (uint8(_b[_at]) == 0xfd) {
return 2; // one-byte flag, 2 bytes data
}
return 0; // flag is data
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string starting with a VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {
return parseVarIntAt(_b, 0);
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string containing a VarInt
/// @param _at The position of the VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {
uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);
if (_dataLen == 0) {
return (0, uint8(_b[_at]));
}
if (_b.length < 1 + _dataLen + _at) {
return (ERR_BAD_ARG, 0);
}
uint256 _number;
if (_dataLen == 2) {
_number = reverseUint16(uint16(_b.slice2(1 + _at)));
} else if (_dataLen == 4) {
_number = reverseUint32(uint32(_b.slice4(1 + _at)));
} else if (_dataLen == 8) {
_number = reverseUint64(uint64(_b.slice8(1 + _at)));
}
return (_dataLen, _number);
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {
bytes memory _newValue = new bytes(_b.length);
for (uint256 i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
/// @notice Changes the endianness of a uint256
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF)
| ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF)
| ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF)
| ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF)
| ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/// @notice Changes the endianness of a uint64
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint64(uint64 _b) internal pure returns (uint64 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = (v >> 32) | (v << 32);
}
/// @notice Changes the endianness of a uint32
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint32(uint32 _b) internal pure returns (uint32 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = (v >> 16) | (v << 16);
}
/// @notice Changes the endianness of a uint24
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint24(uint24 _b) internal pure returns (uint24 v) {
v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);
}
/// @notice Changes the endianness of a uint16
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint16(uint16 _b) internal pure returns (uint16 v) {
v = (_b << 8) | (_b >> 8);
}
/// @notice Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
uint256 _number;
for (uint256 i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {
uint256 _start = _b.length.sub(_num);
return _b.slice(_start, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) internal pure returns (bytes memory) {
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
/// @notice Implements bitcoin's hash160 (sha2 + ripemd160)
/// @dev sha2 precompile at address(2), ripemd160 at address(3)
/// @param _b The pre-image
/// @return res The digest
function hash160View(bytes memory _b) internal view returns (bytes20 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))
pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))
// read from position 12 = 0c
res := mload(0x0c)
}
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) internal pure returns (bytes32) {
return sha256(abi.encodePacked(sha256(_b)));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The pre-image
/// @return res The digest
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/// @notice Implements bitcoin's hash256 on a pair of bytes32
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _a The first bytes32 of the pre-image
/// @param _b The second bytes32 of the pre-image
/// @return res The digest
function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
mstore(0x00, _a)
mstore(0x20, _b)
pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The array containing the pre-image
/// @param at The start of the pre-image
/// @param len The length of the pre-image
/// @return res The digest
function hash256Slice(bytes memory _b, uint256 at, uint256 len) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nIns, "Vin read overrun");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i++) {
_len = determineInputLengthAt(_vin, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
_len = determineInputLengthAt(_vin, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _vin.slice(_offset, _len);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) internal pure returns (bool) {
return _input[36] != hex"00";
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input.
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {
return extractScriptSigLenAt(_input, 0);
}
/// @notice Determines the length of a scriptSig in an input
/// starting at the specified position
/// @dev Will return 0 if passed a witness input.
/// @param _input The byte array containing the LEGACY input
/// @param _at The position of the input in the array
/// @return The length of the script sig
function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {
if (_input.length < 37 + _at) {
return (ERR_BAD_ARG, 0);
}
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);
return (_varIntDataLen, _scriptSigLen);
}
/// @notice Determines the length of an input from its scriptSig
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input) internal pure returns (uint256) {
return determineInputLengthAt(_input, 0);
}
/// @notice Determines the length of an input from its scriptSig,
/// starting at the specified position
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The byte array containing the input
/// @param _at The position of the input in the array
/// @return The length of the input in bytes
function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {
uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));
uint32 _beSequence = reverseUint32(_leSeqence);
return _beSequence;
}
/// @notice Extracts the VarInt-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended scriptSig
function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(37);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {
uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));
uint32 _inputeSequence = reverseUint32(_leSeqence);
return _inputeSequence;
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32-byte tx id with 4-byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(0, 36);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32-byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {
return _input.slice32(0);
}
/// @notice Extracts the outpoint tx id from an input
/// starting at the specified position
/// @dev 32-byte tx id
/// @param _input The byte array containing the input
/// @param _at The position of the input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {
return _input.slice32(_at);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4-byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(32);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// starting at the specified position
/// @dev 4-byte tx index
/// @param _input The byte array containing the input
/// @param _at The position of the input
/// @return The tx index (little-endian bytes)
function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {
return _input.slice4(32 + _at);
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev Works with any properly formatted output
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output) internal pure returns (uint256) {
return determineOutputLengthAt(_output, 0);
}
/// @notice Determines the length of an output
/// starting at the specified position
/// @dev Works with any properly formatted output
/// @param _output The byte array containing the output
/// @param _at The position of the output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {
if (_output.length < 9 + _at) {
return ERR_BAD_ARG;
}
uint256 _varIntDataLen;
uint256 _scriptPubkeyLength;
(_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
// 8-byte value, 1-byte for tag itself
return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;
}
/// @notice Extracts the output at a given index in the TxOuts vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nOuts, "Vout read overrun");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i++) {
_len = determineOutputLengthAt(_vout, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
_offset += _len;
}
_len = determineOutputLengthAt(_vout, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
return _vout.slice(_offset, _len);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output) internal pure returns (bytes8) {
return _output.slice8(0);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) internal pure returns (uint64) {
uint64 _leValue = uint64(extractValueLE(_output));
uint64 _beValue = reverseUint64(_leValue);
return _beValue;
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The byte array containing the output
/// @param _at The starting index of the output in the array
/// @return The output value
function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {
uint64 _leValue = uint64(_output.slice8(_at));
uint64 _beValue = reverseUint64(_leValue);
return _beValue;
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {
if (_output[9] != hex"6a") {
return hex"";
}
bytes1 _dataLen = _output[10];
return _output.slice(11, uint256(uint8(_dataLen)));
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The output
/// @return The hash committed to by the pk_script, or null for errors
function extractHash(bytes memory _output) internal pure returns (bytes memory) {
return extractHashAt(_output, 8, _output.length - 8);
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The byte array containing the output
/// @param _at The starting index of the output script in the array
/// (output start + 8)
/// @param _len The length of the output script
/// (output length - 8)
/// @return The hash committed to by the pk_script, or null for errors
function extractHashAt(bytes memory _output, uint256 _at, uint256 _len) internal pure returns (bytes memory) {
uint8 _scriptLen = uint8(_output[_at]);
// don't have to worry about overflow here.
// if _scriptLen + 1 overflows, then output length would have to be < 1
// for this check to pass. if it's < 1, then we errored when assigning
// _scriptLen
if (_scriptLen + 1 != _len) {
return hex"";
}
// version opcode is 0x00 for p2wpkh and p2wsh, 0x51 for p2tr
uint256 _version = uint8(_output[_at + 1]);
if (_version == 0x00 || _version == 0x51) {
// p2wpkh, p2wsh, p2tr
if (_scriptLen < 2) {
return hex"";
}
uint256 _payloadLen = uint8(_output[_at + 2]);
// Check for maliciously formatted witness outputs.
// No need to worry about underflow as long b/c of the `< 2` check
// p2wsh and p2tr have a payload length of 32 bytes, p2wpkh has a payload length of 20 bytes
if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {
return hex"";
}
return _output.slice(_at + 3, _payloadLen);
} else {
bytes3 _tag = _output.slice3(_at);
// p2pkh
if (_tag == hex"1976a9") {
// Check for maliciously formatted p2pkh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_at + 3]) != 0x14 || _output.slice2(_at + _len - 2) != hex"88ac") {
return hex"";
}
return _output.slice(_at + 4, 20);
//p2sh
} else if (_tag == hex"17a914") {
// Check for maliciously formatted p2sh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_at + _len - 1]) != 0x87) {
return hex"";
}
return _output.slice(_at + 3, 20);
}
}
return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
// Not valid if it says there are too many or no inputs
if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nIns; i++) {
// If we're at the end, but still expect more
if (_offset >= _vin.length) {
return false;
}
// Grab the next input and determine its length.
uint256 _nextLen = determineInputLengthAt(_vin, _offset);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
// Increase the offset by that much
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vin.length;
}
/// @notice Checks that the vout passed up is properly formatted
/// @dev Consider a vout with a valid scriptpubkey
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted vout
function validateVout(bytes memory _vout) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
// Not valid if it says there are too many or no outputs
if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nOuts; i++) {
// If we're at the end, but still expect more
if (_offset >= _vout.length) {
return false;
}
// Grab the next output and determine its length.
// Increase the offset by that much
uint256 _nextLen = determineOutputLengthAt(_vout, _offset);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vout.length;
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {
return _header.slice32(36);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header) internal pure returns (uint256) {
return extractTargetAt(_header, 0);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The array containing the header
/// @param at The start of the header
/// @return The target threshold
function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {
uint24 _m = uint24(_header.slice3(72 + at));
uint8 _e = uint8(_header[75 + at]);
uint256 _mantissa = uint256(reverseUint24(_m));
uint256 _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target) internal pure returns (uint256) {
// Difficulty 1 calculated from 0x1d00ffff
return DIFF1_TARGET.div(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {
return _header.slice32(4);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The array containing the header
/// @param at The start of the header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLEAt(bytes memory _header, uint256 at) internal pure returns (bytes32) {
return _header.slice32(4 + at);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {
return _header.slice4(68);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header) internal pure returns (uint32) {
return reverseUint32(uint32(extractTimestampLE(_header)));
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header) internal pure returns (uint256) {
return calculateDifficulty(extractTarget(_header));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {
return hash256View(abi.encodePacked(_a, _b));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {
return hash256Pair(_a, _b);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed. Inefficient version.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint256 _index) internal view returns (bool) {
// Not an even number of hashes
if (_proof.length % 32 != 0) {
return false;
}
// Special case for coinbase-only blocks
if (_proof.length == 32) {
return true;
}
// Should never occur
if (_proof.length == 64) {
return false;
}
bytes32 _root = _proof.slice32(_proof.length - 32);
bytes32 _current = _proof.slice32(0);
bytes memory _tree = _proof.slice(32, _proof.length - 64);
return verifyHash256Merkle(_current, _tree, _root, _index);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed. Efficient version.
/// @param _leaf The leaf of the proof. LE sha256 hash.
/// @param _tree The intermediate nodes in the proof.
/// Tightly packed LE sha256 hashes.
/// @param _root The root of the proof. LE sha256 hash.
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes32 _leaf, bytes memory _tree, bytes32 _root, uint256 _index)
internal
view
returns (bool)
{
// Not an even number of hashes
if (_tree.length % 32 != 0) {
return false;
}
// Should never occur
if (_tree.length == 0) {
return false;
}
uint256 _idx = _index;
bytes32 _current = _leaf;
// i moves in increments of 32
for (uint256 i = 0; i < _tree.length; i += 32) {
if (_idx % 2 == 1) {
_current = _hash256MerkleStep(_tree.slice32(i), _current);
} else {
_current = _hash256MerkleStep(_current, _tree.slice32(i));
}
_idx = _idx >> 1;
}
return _current == _root;
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp)
internal
pure
returns (uint256)
{
uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);
// Normalize ratio to factor of 4 if very long or very short
if (_elapsedTime < RETARGET_PERIOD.div(4)) {
_elapsedTime = RETARGET_PERIOD.div(4);
}
if (_elapsedTime > RETARGET_PERIOD.mul(4)) {
_elapsedTime = RETARGET_PERIOD.mul(4);
}
/*
NB: high targets e.g. ffff0020 can cause overflows here
so we divide it by 256**2, then multiply by 256**2 later
we know the target is evenly divisible by 256**2, so this isn't an issue
*/
uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);
return _adjusted.div(RETARGET_PERIOD).mul(65536);
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/BytesLib.sol
pragma solidity ^0.8.4;
/*
https://github.com/GNSPS/solidity-bytes-utils/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*/
/**
* @title BytesLib *
*/
/**
* @author https://github.com/GNSPS *
*/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory res) {
if (_length == 0) {
return hex"";
}
uint256 _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40)
mstore(0x40, add(add(res, 64), _length))
mstore(res, _length)
// Compute distance between source and destination pointers
let diff := sub(res, add(_bytes, _start))
for {
let src := add(add(_bytes, 32), _start)
let end := add(src, _length)
} lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) }
}
}
/// @notice Take a slice of the byte array, overwriting the destination.
/// The length of the slice will equal the length of the destination array.
/// @dev Make sure the destination array has afterspace if required.
/// @param _bytes The source array
/// @param _dest The destination array.
/// @param _start The location to start in the source array.
function sliceInPlace(bytes memory _bytes, bytes memory _dest, uint256 _start) internal pure {
uint256 _length = _dest.length;
uint256 _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
for {
let src := add(add(_bytes, 32), _start)
let res := add(_dest, 32)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
res := add(res, 32)
} { mstore(res, mload(src)) }
}
}
// Static slice functions, no bounds checking
/// @notice take a 32-byte slice from the specified position
function slice32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(_bytes, 32), _start))
}
}
/// @notice take a 20-byte slice from the specified position
function slice20(bytes memory _bytes, uint256 _start) internal pure returns (bytes20) {
return bytes20(slice32(_bytes, _start));
}
/// @notice take a 8-byte slice from the specified position
function slice8(bytes memory _bytes, uint256 _start) internal pure returns (bytes8) {
return bytes8(slice32(_bytes, _start));
}
/// @notice take a 4-byte slice from the specified position
function slice4(bytes memory _bytes, uint256 _start) internal pure returns (bytes4) {
return bytes4(slice32(_bytes, _start));
}
/// @notice take a 3-byte slice from the specified position
function slice3(bytes memory _bytes, uint256 _start) internal pure returns (bytes3) {
return bytes3(slice32(_bytes, _start));
}
/// @notice take a 2-byte slice from the specified position
function slice2(bytes memory _bytes, uint256 _start) internal pure returns (bytes2) {
return bytes2(slice32(_bytes, _start));
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
uint256 _totalLen = _start + 20;
require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
uint256 _totalLen = _start + 32;
require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for { let cc := add(_postBytes, 0x20) }
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function toBytes32(bytes memory _source) internal pure returns (bytes32 result) {
if (_source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
function keccak256Slice(bytes memory _bytes, uint256 _start, uint256 _length)
internal
pure
returns (bytes32 result)
{
uint256 _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
result := keccak256(add(add(_bytes, 32), _start), _length)
}
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/SafeMath.sol
pragma solidity ^0.8.4;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/ValidateSPV.sol
pragma solidity ^0.8.4;
/**
* @title ValidateSPV
*/
/**
* @author Summa (https://summa.one)
*/
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
import {BTCUtils} from "./BTCUtils.sol";
library ValidateSPV {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using SafeMath for uint256;
enum InputTypes {
NONE,
LEGACY,
COMPATIBILITY,
WITNESS
}
enum OutputTypes {
NONE,
WPKH,
WSH,
OP_RETURN,
PKH,
SH,
NONSTANDARD
}
uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
function getErrBadLength() internal pure returns (uint256) {
return ERR_BAD_LENGTH;
}
function getErrInvalidChain() internal pure returns (uint256) {
return ERR_INVALID_CHAIN;
}
function getErrLowWork() internal pure returns (uint256) {
return ERR_LOW_WORK;
}
/// @notice Validates a tx inclusion in the block
/// @dev `index` is not a reliable indicator of location within a block
/// @param _txid The txid (LE)
/// @param _merkleRoot The merkle root (as in the block header)
/// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)
/// @param _index The leaf's index in the tree (0-indexed)
/// @return true if fully valid, false otherwise
function prove(bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint256 _index)
internal
view
returns (bool)
{
// Shortcut the empty-block case
if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {
return true;
}
// If the Merkle proof failed, bubble up error
return BTCUtils.verifyHash256Merkle(_txid, _intermediateNodes, _merkleRoot, _index);
}
/// @notice Hashes transaction to get txid
/// @dev Supports Legacy and Witness
/// @param _version 4-bytes version
/// @param _vin Raw bytes length-prefixed input vector
/// @param _vout Raw bytes length-prefixed output vector
/// @param _locktime 4-byte tx locktime
/// @return 32-byte transaction id, little endian
function calculateTxId(bytes4 _version, bytes memory _vin, bytes memory _vout, bytes4 _locktime)
internal
view
returns (bytes32)
{
// Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)
return abi.encodePacked(_version, _vin, _vout, _locktime).hash256View();
}
/// @notice Checks validity of header chain
/// @notice Compares the hash of each header to the prevHash in the next header
/// @param headers Raw byte array of header chain
/// @return totalDifficulty The total accumulated difficulty of the header chain, or an error code
function validateHeaderChain(bytes memory headers) internal view returns (uint256 totalDifficulty) {
// Check header chain length
if (headers.length % 80 != 0) return ERR_BAD_LENGTH;
// Initialize header start index
bytes32 digest;
totalDifficulty = 0;
for (uint256 start = 0; start < headers.length; start += 80) {
// After the first header, check that headers are in a chain
if (start != 0) {
if (!validateHeaderPrevHash(headers, start, digest)) return ERR_INVALID_CHAIN;
}
// ith header target
uint256 target = headers.extractTargetAt(start);
// Require that the header has sufficient work
digest = headers.hash256Slice(start, 80);
if (uint256(digest).reverseUint256() > target) {
return ERR_LOW_WORK;
}
// Add ith header difficulty to difficulty sum
totalDifficulty = totalDifficulty + target.calculateDifficulty();
}
}
/// @notice Checks validity of header work
/// @param digest Header digest
/// @param target The target threshold
/// @return true if header work is valid, false otherwise
function validateHeaderWork(bytes32 digest, uint256 target) internal pure returns (bool) {
if (digest == bytes32(0)) return false;
return (uint256(digest).reverseUint256() < target);
}
/// @notice Checks validity of header chain
/// @dev Compares current header prevHash to previous header's digest
/// @param headers The raw bytes array containing the header
/// @param at The position of the header
/// @param prevHeaderDigest The previous header's digest
/// @return true if the connect is valid, false otherwise
function validateHeaderPrevHash(bytes memory headers, uint256 at, bytes32 prevHeaderDigest)
internal
pure
returns (bool)
{
// Extract prevHash of current header
bytes32 prevHash = headers.extractPrevBlockLEAt(at);
// Compare prevHash of current header to previous header's digest
if (prevHash != prevHeaderDigest) return false;
return true;
}
}
dependencies/@bob-collective-bob-v1/contracts/src/gateway/IStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStrategy {
event TokenOutput(address tokenReceived, uint256 amountOut);
function handleGatewayMessage(IERC20 tokenSent, uint256 amountIn, address recipient, bytes memory message) external;
}
abstract contract IStrategyWithSlippageArgs is IStrategy {
function handleGatewayMessageWithSlippageArgs(
IERC20 tokenSent,
uint256 amountIn,
address recipient,
StrategySlippageArgs memory args
) public virtual;
function handleGatewayMessage(IERC20 tokenSent, uint256 amountIn, address recipient, bytes memory message)
external
{
StrategySlippageArgs memory args = abi.decode(message, (StrategySlippageArgs));
handleGatewayMessageWithSlippageArgs(tokenSent, amountIn, recipient, args);
}
}
struct StrategySlippageArgs {
uint256 amountOutMin;
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelay.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.17;
interface IFullRelay {
event Extension(bytes32 indexed _first, bytes32 indexed _last);
event NewTip(bytes32 indexed _from, bytes32 indexed _to, bytes32 indexed _gcd);
function getCurrentEpochDifficulty() external view returns (uint256);
function getPrevEpochDifficulty() external view returns (uint256);
function getRelayGenesis() external view returns (bytes32);
function getBestKnownDigest() external view returns (bytes32);
function getLastReorgCommonAncestor() external view returns (bytes32);
function findHeight(bytes32 _digest) external view returns (uint256);
function findAncestor(bytes32 _digest, uint256 _offset) external view returns (bytes32);
function isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) external view returns (bool);
function addHeaders(bytes calldata _anchor, bytes calldata _headers) external returns (bool);
function addHeadersWithRetarget(
bytes calldata _oldPeriodStartHeader,
bytes calldata _oldPeriodEndHeader,
bytes calldata _headers
) external returns (bool);
function markNewHeaviest(bytes32 _ancestor, bytes calldata _currentBest, bytes calldata _newBest, uint256 _limit)
external
returns (bool);
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelayWithVerify.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.17;
import {IFullRelay} from "./IFullRelay.sol";
interface IFullRelayWithVerify is IFullRelay {
function verifyProof(bytes calldata _header, bytes calldata _proof, bytes32 _txId, uint256 _index, uint8 _numConfs)
external
view;
function verifyHeaderHash(bytes32 _headerHash, uint8 _numConfs) external view;
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/ILightRelay.sol
// SPDX-License-Identifier: GPL-3.0-only
// Forked from https://github.com/keep-network/tbtc-v2s
pragma solidity ^0.8.17;
/// @title Interface for the Bitcoin Light relay
interface ILightRelay {
event Genesis(uint256 blockHeight);
event Retarget(uint256 oldDifficulty, uint256 newDifficulty);
event ProofLengthChanged(uint256 newLength);
event AuthorizationRequirementChanged(bool newStatus);
event SubmitterAuthorized(address submitter);
event SubmitterDeauthorized(address submitter);
function retarget(bytes memory headers) external;
function validateChain(bytes memory headers)
external
view
returns (uint256 startingHeaderTimestamp, uint256 headerCount);
function getBlockDifficulty(uint256 blockNumber) external view returns (uint256);
/// @notice Returns the difficulty of the current epoch.
function getCurrentEpochDifficulty() external view returns (uint256);
/// @notice Returns the difficulty of the previous epoch.
function getPrevEpochDifficulty() external view returns (uint256);
function getRelayRange() external view returns (uint256 relayGenesis, uint256 currentEpochEnd);
}
dependencies/@bob-collective-bob-v1/contracts/src/utils/BitcoinTx.sol
// SPDX-License-Identifier: GPL-3.0-only
// Forked from https://github.com/keep-network/tbtc-v2
pragma solidity ^0.8.17;
import {BTCUtils} from "@bob-collective/bitcoin-spv/BTCUtils.sol";
import {BytesLib} from "@bob-collective/bitcoin-spv/BytesLib.sol";
import {ValidateSPV} from "@bob-collective/bitcoin-spv/ValidateSPV.sol";
import {ILightRelay} from "../relay/ILightRelay.sol";
import {IFullRelayWithVerify} from "../relay/IFullRelayWithVerify.sol";
/// @title Bitcoin transaction
/// @notice Allows to reference Bitcoin raw transaction in Solidity.
/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format
// Raw Bitcoin transaction data:
// | Bytes | Name | BTC type | Description |
// |--------|--------------|------------------------|---------------------------|
// | 4 | version | int32_t (LE) | TX version number |
// | varies | tx_in_count | compactSize uint (LE) | Number of TX inputs |
// | varies | tx_in | txIn[] | TX inputs |
// | varies | tx_out_count | compactSize uint (LE) | Number of TX outputs |
// | varies | tx_out | txOut[] | TX outputs |
// | 4 | lock_time | uint32_t (LE) | Unix time or block number |
//
// Non-coinbase transaction input (txIn):
//
// | Bytes | Name | BTC type | Description |
// |--------|------------------|------------------------|---------------------------------------------|
// | 36 | previous_output | outpoint | The previous outpoint being spent |
// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the signature script |
// | varies | signature_script | char[] | The signature script, empty for P2WSH |
// | 4 | sequence | uint32_t (LE) | Sequence number |
//
//
// The reference to transaction being spent (outpoint):
//
// | Bytes | Name | BTC type | Description |
// |-------|-------|---------------|------------------------------------------|
// | 32 | hash | char[32] | Hash of the transaction to spend |
// | 4 | index | uint32_t (LE) | Index of the specific output from the TX |
//
//
// Transaction output (txOut):
//
// | Bytes | Name | BTC type | Description |
// |--------|-----------------|-----------------------|--------------------------------------|
// | 8 | value | int64_t (LE) | Number of satoshis to spend |
// | 1+ | pk_script_bytes | compactSize uint (LE) | Number of bytes in the pubkey script |
// | varies | pk_script | char[] | Pubkey script |
//
// compactSize uint format:
//
// | Value | Bytes | Format |
// |-----------------------------------------|-------|----------------------------------------------|
// | >= 0 && <= 252 | 1 | uint8_t |
// | >= 253 && <= 0xffff | 3 | 0xfd followed by the number as uint16_t (LE) |
// | >= 0x10000 && <= 0xffffffff | 5 | 0xfe followed by the number as uint32_t (LE) |
// | >= 0x100000000 && <= 0xffffffffffffffff | 9 | 0xff followed by the number as uint64_t (LE) |
//
// (*) compactSize uint is often references as VarInt)
//
// Coinbase transaction input (txIn):
//
// | Bytes | Name | BTC type | Description |
// |--------|------------------|------------------------|---------------------------------------------|
// | 32 | hash | char[32] | A 32-byte 0x0 null (no previous_outpoint) |
// | 4 | index | uint32_t (LE) | 0xffffffff (no previous_outpoint) |
// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the coinbase script |
// | varies | height | char[] | The block height of this block (BIP34) (*) |
// | varies | coinbase_script | none | Arbitrary data, max 100 bytes |
// | 4 | sequence | uint32_t (LE) | Sequence number
//
// (*) Uses script language: starts with a data-pushing opcode that indicates how many bytes to push to
// the stack followed by the block height as a little-endian unsigned integer. This script must be as
// short as possible, otherwise it may be rejected. The data-pushing opcode will be 0x03 and the total
// size four bytes until block 16,777,216 about 300 years from now.
library BitcoinTx {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using ValidateSPV for bytes;
using ValidateSPV for bytes32;
/// @notice Represents Bitcoin transaction data.
struct Info {
/// @notice Bitcoin transaction version.
/// @dev `version` from raw Bitcoin transaction data.
/// Encoded as 4-bytes signed integer, little endian.
bytes4 version;
/// @notice All Bitcoin transaction inputs, prepended by the number of
/// transaction inputs.
/// @dev `tx_in_count | tx_in` from raw Bitcoin transaction data.
///
/// The number of transaction inputs encoded as compactSize
/// unsigned integer, little-endian.
///
/// Note that some popular block explorers reverse the order of
/// bytes from `outpoint`'s `hash` and display it as big-endian.
/// Solidity code expects hashes in little-endian, just like
/// they are represented in a raw Bitcoin transaction.
bytes inputVector;
/// @notice All Bitcoin transaction outputs prepended by the number of
/// transaction outputs.
/// @dev `tx_out_count | tx_out` from raw Bitcoin transaction data.
///
/// The number of transaction outputs encoded as a compactSize
/// unsigned integer, little-endian.
bytes outputVector;
/// @notice Bitcoin transaction locktime.
///
/// @dev `lock_time` from raw Bitcoin transaction data.
/// Encoded as 4-bytes unsigned integer, little endian.
bytes4 locktime;
}
/// @notice Represents data needed to perform a Bitcoin SPV proof.
struct Proof {
/// @notice The merkle proof of transaction inclusion in a block.
bytes merkleProof;
/// @notice Transaction index in the block (0-indexed).
uint256 txIndexInBlock;
/// @notice Single byte-string of 80-byte bitcoin headers,
/// lowest height first.
bytes bitcoinHeaders;
/// @notice The sha256 preimage of the coinbase tx hash
/// i.e. the sha256 hash of the coinbase transaction.
bytes32 coinbasePreimage;
/// @notice The merkle proof of the coinbase transaction.
bytes coinbaseProof;
}
/// @notice Represents info about an unspent transaction output.
struct UTXO {
/// @notice Hash of the transaction the output belongs to.
/// @dev Byte order corresponds to the Bitcoin internal byte order.
bytes32 txHash;
/// @notice Index of the transaction output (0-indexed).
uint32 txOutputIndex;
/// @notice Value of the transaction output.
uint64 txOutputValue;
}
/// @notice Validates the SPV proof of the Bitcoin transaction using a light relay contract.
/// Reverts in case the validation or proof verification fail.
/// @param relay Bitcoin light relay providing the current Bitcoin network difficulty.
/// @param txProofDifficultyFactor The number of confirmations required on the Bitcoin chain.
/// @param txInfo Bitcoin transaction data.
/// @param proof Bitcoin proof data.
/// @return txHash Proven 32-byte transaction hash.
function validateProof(ILightRelay relay, uint256 txProofDifficultyFactor, Info memory txInfo, Proof memory proof)
internal
view
returns (bytes32 txHash)
{
txHash = computeTxHash(txInfo);
verifySPVProof(txHash, proof);
evaluateProofDifficulty(relay, txProofDifficultyFactor, proof.bitcoinHeaders);
return txHash;
}
/// @notice Validates the SPV proof of the Bitcoin transaction using a full relay contract.
/// Reverts in case the validation or proof verification fail.
/// @param relay Bitcoin full relay contract.
/// @param minConfirmations The minimumnumber of confirmations required on the Bitcoin chain stored in the full relay.
/// @param txInfo Bitcoin transaction data.
/// @param proof Bitcoin proof data.
/// @return txHash Proven 32-byte transaction hash.
function validateProof(IFullRelayWithVerify relay, uint256 minConfirmations, Info memory txInfo, Proof memory proof)
internal
view
returns (bytes32 txHash)
{
txHash = computeTxHash(txInfo);
verifySPVProof(txHash, proof);
verifyHeader(relay, minConfirmations, proof.bitcoinHeaders);
return txHash;
}
/// @notice Verifies an SPV proof of a Bitcoin transaction.
/// @param txHash The hash of the transaction to verify.
/// @param proof The proof.
function verifySPVProof(bytes32 txHash, Proof memory proof) internal view {
require(isMerkleArrayValidLength(proof.merkleProof), "Bad merkle array proof");
// Due to a vulnerability in the Bitcoin SPV proof verification detailed here:
// https://bitslog.com/2018/06/09/leaf-node-weakness-in-bitcoin-merkle-tree-design/
// we verify a proof of the coinbase tx in the block as well as the tx we want to verify
// and then ensure that both proofs are the same length.
require(
proof.merkleProof.length == proof.coinbaseProof.length, "Tx not on same level of merkle tree as coinbase"
);
bytes32 root = proof.bitcoinHeaders.extractMerkleRootLE();
require(
txHash.prove(root, proof.merkleProof, proof.txIndexInBlock),
"Tx merkle proof is not valid for provided header and tx hash"
);
bytes32 coinbaseHash = sha256(abi.encodePacked(proof.coinbasePreimage));
// Coinbase tx always has an index of 0
require(
coinbaseHash.prove(root, proof.coinbaseProof, 0),
"Coinbase merkle proof is not valid for provided header and hash"
);
}
/// @notice Validates Bitcoin transaction input and output vectors then computes the hash.
/// @param txInfo Bitcoin transaction data.
/// @return txHash 32-byte transaction hash.
function computeTxHash(Info memory txInfo) internal view returns (bytes32 txHash) {
require(txInfo.inputVector.validateVin(), "Invalid input vector provided");
require(txInfo.outputVector.validateVout(), "Invalid output vector provided");
return abi.encodePacked(txInfo.version, txInfo.inputVector, txInfo.outputVector, txInfo.locktime).hash256View();
}
/// @notice Evaluates the given Bitcoin proof difficulty against the actual
/// Bitcoin chain difficulty provided by the light relay oracle.
/// Reverts in case the evaluation fails.
/// @param relay Bitcoin light relay providing the current Bitcoin network difficulty.
/// @param txProofDifficultyFactor The number of confirmations required on the Bitcoin chain.
/// @param bitcoinHeaders Bitcoin headers chain being part of the SPV
/// proof. Used to extract the observed proof difficulty.
function evaluateProofDifficulty(ILightRelay relay, uint256 txProofDifficultyFactor, bytes memory bitcoinHeaders)
internal
view
{
uint256 currentEpochDifficulty = relay.getCurrentEpochDifficulty();
uint256 previousEpochDifficulty = relay.getPrevEpochDifficulty();
uint256 requestedDiff = 0;
uint256 firstHeaderDiff = bitcoinHeaders.extractTarget().calculateDifficulty();
if (firstHeaderDiff == currentEpochDifficulty) {
requestedDiff = currentEpochDifficulty;
} else if (firstHeaderDiff == previousEpochDifficulty) {
requestedDiff = previousEpochDifficulty;
} else {
revert("Not at current or previous difficulty");
}
uint256 observedDiff = bitcoinHeaders.validateHeaderChain();
require(observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain");
require(observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain");
require(observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header");
require(
observedDiff >= requestedDiff * txProofDifficultyFactor,
"Insufficient accumulated difficulty in header chain"
);
}
/// @notice Validates the header using the full relay contract by checking it against the chain stored in the full relay.
/// @param relay Bitcoin full relay contract.
/// @param minConfirmations The minimum number of confirmations required on the Bitcoin chain stored in the full relay.
/// @param bitcoinHeader Bitcoin header to verify.
function verifyHeader(IFullRelayWithVerify relay, uint256 minConfirmations, bytes memory bitcoinHeader)
internal
view
{
require(isHeaderValidLength(bitcoinHeader), "Bad header block");
bytes32 headerHash = bitcoinHeader.hash256();
relay.verifyHeaderHash(headerHash, uint8(minConfirmations));
}
/// @notice Represents temporary information needed during the processing of
/// the Bitcoin transaction outputs. This structure is an internal one
/// and should not be exported outside of the transaction processing code.
/// @dev Allows to mitigate "stack too deep" errors on EVM.
struct TxOutputsProcessingInfo {
// The first output starting index in the transaction.
uint256 outputStartingIndex;
// The number of outputs in the transaction.
uint256 outputsCount;
}
/// @notice Represents an outcome of the Bitcoin transaction
/// outputs processing.
struct TxOutputsInfo {
// Sum of all outputs values spending to the output.
uint64 value;
// Optional EVM address specified in OP_RETURN.
address evmAddress;
// Optional hash specified in OP_RETURN.
bytes32 hash;
}
/// @notice Processes all outputs from the transaction.
/// @param txOutputVector Bitcoin transaction output vector. This function
/// assumes vector's structure is valid so it must be validated using
/// e.g. `BTCUtils.validateVout` function before it is passed here.
/// @param scriptPubKeyHash Expected Bitcoin scriptPubKey keccak256 hash.
function processTxOutputs(bytes memory txOutputVector, bytes32 scriptPubKeyHash)
internal
pure
returns (TxOutputsInfo memory resultInfo)
{
// needed to avoid stack too deep errors
TxOutputsProcessingInfo memory processInfo;
// Determining the total number of transaction outputs in the same way as
// for number of inputs. See `BitcoinTx.outputVector` docs for more details.
(processInfo.outputStartingIndex, processInfo.outputsCount) = txOutputVector.parseVarInt();
// To determine the first output starting index, we must jump over
// the compactSize uint which prepends the output vector. One byte
// must be added because `BtcUtils.parseVarInt` does not include
// compactSize uint tag in the returned length.
//
// For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
// returns `0`, so we jump over one byte of compactSize uint.
//
// For >= 253 && <= 0xffff there is `0xfd` tag,
// `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
// tag byte included) so we need to jump over 1+2 bytes of
// compactSize uint.
//
// Please refer `BTCUtils` library and compactSize uint
// docs in `BitcoinTx` library for more details.
processInfo.outputStartingIndex++;
// Helper flag indicating whether there was at least one
// output present
bool outputPresent = false;
// Outputs processing loop.
for (uint256 i = 0; i < processInfo.outputsCount; i++) {
uint256 outputLength = txOutputVector.determineOutputLengthAt(processInfo.outputStartingIndex);
// Extract the value from given output.
uint64 outputValue = txOutputVector.extractValueAt(processInfo.outputStartingIndex);
// The output consists of an 8-byte value and a variable length
// script. To hash that script we slice the output starting from
// 9th byte until the end.
uint256 scriptLength = outputLength - 8;
uint256 outputScriptStart = processInfo.outputStartingIndex + 8;
bytes32 outputScriptHash;
/* solhint-disable-next-line no-inline-assembly */
assembly {
// The first argument to assembly keccak256 is the pointer.
// We point to `txOutputVector` but at the position indicated
// by `outputScriptStart`. To load that position, we
// need to call `add(outputScriptStart, 32)` because
// `outputScriptStart` has 32 bytes.
outputScriptHash := keccak256(add(txOutputVector, add(outputScriptStart, 32)), scriptLength)
}
if (scriptPubKeyHash == outputScriptHash) {
outputPresent = true;
// Accumulate the total in case there are multiple
// payments to the same output
resultInfo.value += outputValue;
} else {
address outputEvmAddress = extractEvmAddressFromOutput(txOutputVector, processInfo.outputStartingIndex);
if (outputEvmAddress != address(0)) {
// NOTE: this will overwrite if there are multiple OP_RETURN outputs
resultInfo.evmAddress = outputEvmAddress;
}
bytes32 outputHash = extractHashFromOutput(txOutputVector, processInfo.outputStartingIndex);
if (outputHash != 0) {
// NOTE: this will overwrite if there are multiple OP_RETURN outputs
resultInfo.hash = outputHash;
}
}
// Make the `outputStartingIndex` pointing to the next output by
// increasing it by current output's length.
processInfo.outputStartingIndex += outputLength;
}
require(outputPresent, "No output found for scriptPubKey");
}
function extractEvmAddressFromOutput(bytes memory _output, uint256 _at) internal pure returns (address evmAddress) {
// OP_RETURN
if (_output[_at + 9] != hex"6a") {
return address(0);
}
bytes1 _dataLen = _output[_at + 10];
if (uint256(uint8(_dataLen)) == 20) {
uint256 opReturnStart = _at + 11;
assembly {
evmAddress := mload(add(_output, add(opReturnStart, 20)))
}
}
}
function extractHashFromOutput(bytes memory _output, uint256 _at) internal pure returns (bytes32 outputHash) {
// OP_RETURN
if (_output[_at + 9] != hex"6a") {
return 0;
}
bytes1 _dataLen = _output[_at + 10];
if (uint256(uint8(_dataLen)) == 32) {
uint256 opReturnStart = _at + 11;
assembly {
outputHash := mload(add(_output, add(opReturnStart, 32)))
}
}
}
function reverseEndianness(bytes32 b) internal pure returns (bytes32 txHash) {
bytes memory newValue = new bytes(b.length);
for (uint256 i = 0; i < b.length; i++) {
newValue[b.length - i - 1] = b[i];
}
assembly {
txHash := mload(add(newValue, 32))
}
}
function ensureTxInputSpendsUtxo(bytes memory _vin, BitcoinTx.UTXO memory utxo) internal pure {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = BTCUtils.parseVarInt(_vin);
require(_varIntDataLen != BTCUtils.ERR_BAD_ARG, "Read overrun during VarInt parsing");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
bytes32 expectedTxHash = reverseEndianness(utxo.txHash);
for (uint256 _i = 0; _i < _nIns; _i++) {
bytes32 outpointTxHash = _vin.extractInputTxIdLeAt(_offset);
uint32 outpointIndex = BTCUtils.reverseUint32(uint32(_vin.extractTxIndexLeAt(_offset)));
// check if it matches tx
if (expectedTxHash == outpointTxHash && utxo.txOutputIndex == outpointIndex) {
return;
}
_len = BTCUtils.determineInputLengthAt(_vin, _offset);
require(_len != BTCUtils.ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
revert("Transaction does not spend the required utxo");
}
/// @notice Checks whether the header is 80 bytes long
/// @param _header The header for which the length is checked
/// @return True if the header's length is 80 bytes, and false otherwise
function isHeaderValidLength(bytes memory _header) internal pure returns (bool) {
return _header.length == 80;
}
/// @notice Checks whether the merkle proof array's length is a multiple of 32 bytes
/// @param _merkleProofArray The merkle proof array for which the length is checked
/// @return True if the merkle proof array's length is a multiple of 32 bytes, and false otherwise
function isMerkleArrayValidLength(bytes memory _merkleProofArray) internal pure returns (bool) {
return _merkleProofArray.length % 32 == 0;
}
}
dependencies/@openzeppelin-contracts-5.5.0/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
dependencies/@openzeppelin-contracts-5.5.0/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
dependencies/@openzeppelin-contracts-5.5.0/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(IERC1363 token, address from, address to, uint256 value, bytes memory data)
internal
{
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(IERC20 token, address from, address to, uint256 value, bool bubble)
private
returns (bool success)
{
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bool success = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
bool success = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
bool success = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(address target, bool success, bytes memory returndata)
internal
view
returns (bytes memory)
{
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
dependencies/@openzeppelin-contracts-5.5.0/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(address target, bytes memory data)
internal
returns (bool success, bytes32 result1, bytes32 result2)
{
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
function callReturn64Bytes(address target, uint256 value, bytes memory data)
internal
returns (bool success, bytes32 result1, bytes32 result2)
{
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(address target, bytes memory data)
internal
view
returns (bool success, bytes32 result1, bytes32 result2)
{
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(address target, bytes memory data)
internal
returns (bool success, bytes32 result1, bytes32 result2)
{
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
dependencies/@openzeppelin-contracts-5.5.0/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) =
(
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) =
(
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(bytes memory b, bytes memory e, bytes memory m)
internal
view
returns (bool success, bytes memory result)
{
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/CommonStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IStrategy} from "@bob-collective/bob/gateway/IStrategy.sol";
import {IERC20Ext} from "./IERC20Ext.sol";
import {ISwapper} from "./swapper/ISwapper.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {BitcoinTx} from "@bob-collective/bob/utils/BitcoinTx.sol";
struct OnrampOrderArgs {
uint256 tokenFillAmount; // The amount of tokens that will be sent by the LP to fill the order.
IStrategy strategy; // The address of the strategy that will be called when the order is filled, zero address if there is no strategy
uint256 tokenToSwapToEthAmount; // The amount of tokens from the user's order fill amount that will be swapped to eth to cover the gas and l1 data fees, if there is any leftover it will be sent to the recipient
address recipient; // The address that will receive the tokens from the LP when the order is filled
uint256 ethTransferGasLimit; // gas limit for all eth transfers
uint256 strategyGasLimit; // gas limit for the strategy call, if this is exceeded the strategy will revert and tokens will be transferred to the recipient directly
uint256 userGasPriceLimit; // user gas price limit for the overall releaseFundsAndCallStrategy call, if the gas price exceeds this limit the gas price for the user will be capped to the limit and the strategy will be skipped
uint256 transactionCostOverhead; // A fixed transaction cost overhead in wei for costs not covered by the on-chain gas metering. This may include chain specific fees such as L1 data fees and operator fees.
FeeDetails[] affiliateFees; // Affiliate fee details
bytes strategyExtraData; // Calldata for the strategy call
}
// Details of an offramp solver.
struct OfframpSolverDetails {
uint256 minSatToBridge; // Minimum fee amount to bridge in sats required by quote calculations (used in API)
address recipient; // Address to receive funds when orders are processed
bool isRegistered; // Whether the offramp has been registered by the contract owner
}
// Arguments required to submit an offramp order.
struct OfframpOrderArgs {
uint256 tokenAmountToLock; // Total token amount locked by the user
uint256 satOutputMinimum; // Minimum amount of sats of BTC that the user is willing to receive from the order, taking into account all fees and the token/BTC exchange rate
FeeDetails[] affiliateFees; // Affiliate fee details
uint256 creationDeadline; // Timestamp that the order must be created by
bytes outputScript; // User's Bitcoin output script (scriptPubKey)
address token; // Address of the token that will be used to pay the solver for filling the order
address owner; // Address of the order owner, can bump the order fee or request a refund
}
struct OfframpOrderDetails {
uint256 tokenAmountToLock; // Total token amount locked by the user
uint256 satOutputMinimum; // Minimum amount of sats of BTC that the user is willing to receive from the order, taking into account all fees and the token/BTC exchange rate
FeeDetails[] affiliateFees; // Affiliate fee details
address owner; // Address of the order owner, can bump the order fee or request a refund
bytes outputScript; // User's Bitcoin output script (scriptPubKey)
OfframpOrderStatus status; // Current status of the order
uint256 timestamp; // Timestamp when the order was created or its fee was last bumped
address token; // Address of the token that will be used to pay the solver for filling the order
address solverOwner; // Address of the offramp solver that will fill the order, only set when the order is accepted
address solverRecipient; // Address where the solver will receive their tokens after filling the order
}
enum OfframpOrderStatus {
Active, // Order is active and awaiting processing
Accepted, // Order has been accepted by the solver
Processed, // Order has been successfully processed by the solver
Refunded // User has claimed a refund for the order
}
struct FinalizeOfframpOrderArgs {
BitcoinTx.Info txInfo; // Bitcoin transaction information
BitcoinTx.Proof txProof; // SPV proof data for the transaction
uint256 orderId; // ID of the associated off-ramp order
}
struct AssetConfig {
address token;
address pricer;
}
struct FeeDetails {
uint256 amount; // The fee amount, this is a bps value for the protocol fee and a fixed token amount for the affiliate fee
address recipient; // The address of the affiliate fee recipient
}
src/IERC20Ext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Extension of the IERC20 interface to include functions that
// almost all ERC20 contract supports.
interface IERC20Ext is IERC20 {
function decimals() external view returns (uint8);
}
src/IGatewayOnrampV6.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IERC20Ext} from "./IERC20Ext.sol";
import {ISwapper} from "./swapper/ISwapper.sol";
import {OnrampOrderArgs, FeeDetails} from "./CommonStructs.sol";
/// @title Gateway Onramp V5 Interface
interface IGatewayOnrampV6 {
/// @notice Thrown if the zero address is provided as an argument to a function that does not allow it
error ZeroAddress();
/// @notice Thrown if not enough gas is supplied by the caller
error InsufficientGas();
/// @notice Thrown if the transaction hash has already been spent, to prevent double spending
error TransactionAlreadySpent();
/// @notice Thrown if the affiliate fees exceed the available amount
error AffiliateFeesExceedAvailableAmount();
/// @notice Thrown if the protocol fees exceed the available amount
error ProtocolFeesExceedAvailableAmount();
/// @notice Thrown if the protocol fee exceeds the maximum allowed value
error ProtocolFeeExceedsMax();
/// @notice Emitted if the ETH swap fails
/// @param revertData The revert data of the swap if there is any
event EthSwapFailed(bytes revertData);
/// @notice Emitted if the strategy call fails
/// @param strategy The address of the strategy that failed
/// @param revertData The revert data of the strategy call if there is any
/// @param strategyGasLimitExceeded Whether the strategy reverted because it ran out of gas
event StrategyFailed(address strategy, bytes revertData, bool strategyGasLimitExceeded);
/// @notice Emitted when the onramp is executed
/// @param recipient The address of the recipient
/// @param tokenAmountOut The amount of tokens that were sent to the recipient or strategy if there is one
/// @param protocolFeesAmount The amount of tokens taken as a protocol fee
/// @param affiliateFeesAmount The total amount of tokens taken as affiliate fees
/// @param relayerEthFee The amount of ETH that was sent to the relayer for the transaction costs
/// @param excessEth The amount of ETH that was sent to the recipient
/// @param strategySkipped Whether the strategy was skipped, either because the swap failed or the gas price exceeded the limit
event OnrampExecuted(
address indexed recipient,
uint256 tokenAmountOut,
uint256 protocolFeesAmount,
uint256 affiliateFeesAmount,
uint256 relayerEthFee,
uint256 excessEth,
bool strategySkipped
);
/// @notice The maximum allowed protocol fee in bps (100%)
function MAX_PROTOCOL_FEE() external view returns (uint256);
/// @notice The implementation version of the gateway onramp
function VERSION() external view returns (uint16);
/// @notice A fixed gas overhead for the releaseFundsAndCallStrategy function that is not factored into the metering
function gasSpentFixedOverhead() external view returns (uint256);
/// @notice The swapper contract used to convert a part of the order to ETH
function swapper() external view returns (ISwapper);
/// @notice The tokenized bitcoin ERC20 contract address that is used to fill the onramp orders
function token() external view returns (IERC20Ext);
/// @notice The protocol fee details (amount in bps, recipient address)
function protocolFeeDetails() external view returns (uint256 amount, address recipient);
/// @notice A mapping of spent transaction hashes to boolean values indicating if the transaction has been spent
function spentTxHashes(bytes32 txHash) external view returns (bool);
/// @notice Executes the onramp order and attempts to call the strategy if there is one
function releaseFundsAndCallStrategy(bytes32 _txHash, OnrampOrderArgs memory _onrampOrderArgs) external;
/// @notice Sets the swapper contract
function setSwapper(ISwapper _swapper) external;
/// @notice Sets the fixed gas overhead for the releaseFundsAndCallStrategy function
function setGasSpentFixedOverhead(uint256 _gasSpentFixedOverhead) external;
/// @notice Sets the protocol fee details
function setProtocolFeeDetails(FeeDetails memory _protocolFeeDetails) external;
/// @notice Allows the contract to receive ETH, which is required for the swapper to work
receive() external payable;
}
src/swapper/ISwapper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
/**
* @title ISwapper interface
* @dev This interface allows the easy integration of AMMs from different vendors for the purpose of swapping.
* For each vendor a new contract has to be written implementing the ISwapper interface.
*/
interface ISwapper {
function swapExactTokensForNative(IERC20 _token, uint256 _amountIn, uint256 _amountOutMin)
external
returns (uint256 outAmount);
function swapTokensForExactNative(IERC20 token, uint256 amountOut, uint256 amountInMax)
external
returns (uint256 amountIn);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": false
},
"evmVersion": "prague",
"remappings": [
"@ERC4337/=dependencies/@rhinestone-core-modules-v1/node_modules/@ERC4337/",
"@bob-collective/bitcoin-spv/=dependencies/@bob-collective-bitcoin-spv-v1/src/",
"@bob-collective/bob/=dependencies/@bob-collective-bob-v1/contracts/src/",
"@layerzerolabs/lz-evm-messagelib-v2/=dependencies/@layerzerolabs-layerzero-v2-v1/packages/layerzero-v2/evm/messagelib/",
"@layerzerolabs/lz-evm-protocol-v2/=dependencies/@layerzerolabs-layerzero-v2-v1/packages/layerzero-v2/evm/protocol/",
"@layerzerolabs/oapp/=dependencies/@layerzerolabs-layerzero-v2-v1/packages/layerzero-v2/evm/oapp/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.5.0/",
"@prb/math/=dependencies/@rhinestone-core-modules-v1/node_modules/@prb/math/src/",
"@rhinestone/core-modules/=dependencies/@rhinestone-core-modules-v1/",
"@rhinestone/modulekit-v1/=dependencies/@rhinestone-modulekit-v1/",
"@rhinestone/modulekit/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/modulekit/src/",
"@uniswap/swap-router-contracts/=dependencies/@uniswap-swap-router-contracts-v1/",
"@uniswap/v3-core/=dependencies/@uniswap-v3-core-v1/",
"@uniswap/v3-periphery/=dependencies/@uniswap-v3-periphery-v1/",
"ExcessivelySafeCall/=dependencies/@rhinestone-core-modules-v1/node_modules/excessively-safe-call/src/",
"account-abstraction-v0.6/=dependencies/@rhinestone-core-modules-v1/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
"account-abstraction/=dependencies/@rhinestone-core-modules-v1/node_modules/@ERC4337/account-abstraction/contracts/",
"erc4337-validation/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/erc4337-validation/src/",
"erc7579-implementation/=dependencies/@erc7579-implementation-v1/",
"forge-std/=dependencies/forge-std-1.14.0/src/",
"modulekit/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/modulekit/src/",
"sentinellist/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/sentinellist/src/",
"solady/=dependencies/@rhinestone-core-modules-v1/node_modules/solady/src/",
"solarray/=dependencies/@rhinestone-core-modules-v1/node_modules/solarray/src/",
"solidity-bytes-utils/=dependencies/@solidity-bytes-utils-v1/",
"@bob-collective-bitcoin-spv-v1/=dependencies/@bob-collective-bitcoin-spv-v1/",
"@bob-collective-bob-v1/=dependencies/@bob-collective-bob-v1/",
"@erc7579-implementation-v1/=dependencies/@erc7579-implementation-v1/src/",
"@erc7579/=dependencies/@rhinestone-core-modules-v1/node_modules/@erc7579/enumerablemap4337/src/",
"@gnosis.pm/=dependencies/@rhinestone-core-modules-v1/node_modules/@gnosis.pm/",
"@layerzerolabs-layerzero-v2-v1/=dependencies/@layerzerolabs-layerzero-v2-v1/",
"@openzeppelin-contracts-5.5.0/=dependencies/@openzeppelin-contracts-5.5.0/",
"@rhinestone-core-modules-v1/=dependencies/@rhinestone-core-modules-v1/",
"@rhinestone-modulekit-v1/=dependencies/@rhinestone-modulekit-v1/src/",
"@safe-global/=dependencies/@rhinestone-core-modules-v1/node_modules/@safe-global/",
"@solidity-bytes-utils-v1/=dependencies/@solidity-bytes-utils-v1/contracts/",
"@uniswap-swap-router-contracts-v1/=dependencies/@uniswap-swap-router-contracts-v1/contracts/",
"@uniswap-v3-core-v1/=dependencies/@uniswap-v3-core-v1/",
"@uniswap-v3-periphery-v1/=dependencies/@uniswap-v3-periphery-v1/contracts/",
"@webauthn/=dependencies/@rhinestone-core-modules-v1/node_modules/webauthn-sol/src/",
"FreshCryptoLib/=dependencies/@rhinestone-core-modules-v1/node_modules/FreshCryptoLib/solidity/src/",
"checknsignatures/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/checknsignatures/src/",
"ds-test/=dependencies/@rhinestone-core-modules-v1/node_modules/ds-test/src/",
"excessively-safe-call/=dependencies/@rhinestone-core-modules-v1/node_modules/excessively-safe-call/",
"flatbytes/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/flatbytes/src/",
"forge-std-1.14.0/=dependencies/forge-std-1.14.0/src/",
"hardhat-deploy/=dependencies/@rhinestone-core-modules-v1/node_modules/hardhat-deploy/",
"hardhat/=dependencies/@rhinestone-core-modules-v1/node_modules/hardhat/",
"solmate/=dependencies/@rhinestone-core-modules-v1/node_modules/solmate/src/",
"webauthn-sol/=dependencies/@rhinestone-core-modules-v1/node_modules/webauthn-sol/",
"node_modules/webauthn-sol/src/:openzeppelin-contracts/=dependencies/@rhinestone-core-modules-v1/node_modules/@openzeppelin/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.