Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- EqualEmissionController
- Optimization enabled
- false
- Compiler version
- v0.8.24+commit.e11b9ed9
- EVM Version
- Verified at
- 2026-09-19T09:37:29.684377Z
Constructor Arguments
000000000000000000000000b7f11392542aceedb11dbef3b84064079e979a71000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000006aae491f0000000000000000000000000000000000000000000000000000000000000e1000000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad9000000000000000000000000fe4a6b0c5c0792ebac17119625e913740941b722000000000000000000000000b94b5616d1afb26723cb6a9c0ca1a71d2ea138e7
Arg [0] (address) : 0xb7f11392542aceedb11dbef3b84064079e979a71
Arg [1] (uint256) : 12
Arg [2] (uint256) : 1789806879
Arg [3] (uint256) : 3600
Arg [4] (address) : 0x93f976141158b199fbbcf902c5ef5ff689e1aad9
Arg [5] (address) : 0xfe4a6b0c5c0792ebac17119625e913740941b722
Arg [6] (address) : 0xb94b5616d1afb26723cb6a9c0ca1a71d2ea138e7
src/EqualEmissionController.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { Equal } from "./Equal.sol";
import { EqualAllocationVault } from "./EqualAllocationVault.sol";
import { EqualEmissionMath } from "./EqualEmissionMath.sol";
/// @title EQUAL Emission Controller
/// @notice Bounded epoch finality and claim authority for the canonical
/// 800M EQUAL emission programme.
/// @dev Scores are NOT calculated here. Sprint 07 owns governed V/C/R/X
/// scoring. Distribution roots must be produced from separately auditable
/// deterministic calculation authority.
contract EqualEmissionController is Pausable, ReentrancyGuard {
uint256 public constant TOKEN_UNIT = 10 ** 18;
uint256 public constant PROGRAMME_YEARS = 16;
uint256 public constant EMISSION_PROGRAM_CAP = 800_000_000 * TOKEN_UNIT;
uint256 public constant YEARS_PER_BAND = 4;
uint256 public constant BAND_ONE_ANNUAL_BUDGET = 80_000_000 * TOKEN_UNIT;
uint256 public constant BAND_TWO_ANNUAL_BUDGET = 60_000_000 * TOKEN_UNIT;
uint256 public constant BAND_THREE_ANNUAL_BUDGET = 40_000_000 * TOKEN_UNIT;
uint256 public constant BAND_FOUR_ANNUAL_BUDGET = 20_000_000 * TOKEN_UNIT;
uint256 public constant BOOTSTRAP_EMISSION_CAP = 5_000_000 * TOKEN_UNIT;
uint256 public constant WALLET_CAP_DENOMINATOR = 400;
bytes32 public constant CLAIM_ACTION = keccak256("VITALITY_EQUAL_EMISSION_CLAIM_V1");
enum AuthorityRole {
Governance,
Emission,
PauseGuardian
}
struct EpochState {
uint256 budget;
uint256 walletCap;
uint256 committedDistribution;
uint256 claimed;
bytes32 distributionRoot;
bytes32 calculationCommitment;
uint32 participantCount;
bool finalized;
}
error EqualEmissionZeroVault();
error EqualEmissionInvalidVault();
error EqualEmissionZeroEpochsPerYear();
error EqualEmissionZeroEpochDuration();
error EqualEmissionZeroAuthority();
error EqualEmissionAuthorityCollision();
error EqualEmissionUnauthorizedGovernance(address caller);
error EqualEmissionUnauthorizedEmission(address caller);
error EqualEmissionUnauthorizedPauseGuardian(address caller);
error EqualEmissionAuthorityUnchanged();
error EqualEmissionNoPendingAuthority();
error EqualEmissionPendingAuthorityMismatch();
error EqualEmissionYearOutOfRange(uint256 emissionYear);
error EqualEmissionEpochOutOfRange(uint256 epochId);
error EqualEmissionUnexpectedEpoch(uint256 expected, uint256 supplied);
error EqualEmissionEpochNotEnded(uint256 epochId, uint256 endTimestamp);
error EqualEmissionVaultNotBound();
error EqualEmissionDistributionExceedsBudget(uint256 budget, uint256 committed);
error EqualEmissionZeroDistributionRoot();
error EqualEmissionUnexpectedDistributionRoot();
error EqualEmissionZeroCalculationCommitment();
error EqualEmissionZeroParticipantCount();
error EqualEmissionUnexpectedParticipantCount();
error EqualEmissionParticipantAbsorptionExceeded(uint256 maximumAbsorption, uint256 committed);
error EqualEmissionProgrammeCapExceeded();
error EqualEmissionBootstrapCapExceeded();
error EqualEmissionBootstrapAlreadyEnded();
error EqualEmissionEpochNotFinalized(uint256 epochId);
error EqualEmissionAlreadyClaimed(uint256 epochId, address claimant);
error EqualEmissionZeroClaim();
error EqualEmissionWalletCapExceeded(uint256 walletCap, uint256 amount);
error EqualEmissionInvalidProof();
error EqualEmissionEpochClaimBoundExceeded();
error EqualEmissionGlobalClaimBoundExceeded();
event EpochFinalized(
uint256 indexed epochId,
uint256 indexed emissionYear,
uint256 budget,
uint256 walletCap,
uint256 committedDistribution,
uint256 undistributed,
uint32 participantCount,
bytes32 distributionRoot,
bytes32 calculationCommitment
);
event EmissionClaimed(
uint256 indexed epochId,
address indexed claimant,
uint256 amount,
uint256 epochClaimed,
uint256 cumulativeClaimed
);
event AuthorityTransferProposed(
AuthorityRole indexed role,
address indexed currentAuthority,
address indexed pendingAuthority
);
event AuthorityTransferAccepted(
AuthorityRole indexed role, address indexed previousAuthority, address indexed newAuthority
);
event BootstrapEmissionPhaseEnded(uint256 cumulativeCommittedDistribution);
EqualAllocationVault public immutable emissionVault;
uint256 public immutable epochsPerYear;
uint256 public immutable programmeStartTimestamp;
uint256 public immutable epochDurationSeconds;
uint256 public immutable totalEpochs;
address public governanceAuthority;
address public emissionAuthority;
address public pauseGuardian;
mapping(AuthorityRole => address) public pendingAuthority;
mapping(uint256 => EpochState) private _epochs;
mapping(uint256 => mapping(address => bool)) public hasClaimed;
uint256 public nextEpochId;
uint256 public cumulativeFinalizedBudget;
uint256 public cumulativeCommittedDistribution;
uint256 public cumulativeClaimed;
bool public bootstrapEmissionPhase = true;
modifier onlyGovernance() {
if (msg.sender != governanceAuthority) {
revert EqualEmissionUnauthorizedGovernance(msg.sender);
}
_;
}
modifier onlyEmissionAuthority() {
if (msg.sender != emissionAuthority) {
revert EqualEmissionUnauthorizedEmission(msg.sender);
}
_;
}
modifier onlyPauseGuardian() {
if (msg.sender != pauseGuardian) {
revert EqualEmissionUnauthorizedPauseGuardian(msg.sender);
}
_;
}
constructor(
EqualAllocationVault emissionVault_,
uint256 epochsPerYear_,
uint256 programmeStartTimestamp_,
uint256 epochDurationSeconds_,
address governanceAuthority_,
address emissionAuthority_,
address pauseGuardian_
) {
if (address(emissionVault_) == address(0)) {
revert EqualEmissionZeroVault();
}
if (
emissionVault_.allocationType() != Equal.GenesisAllocationType.EmissionVault
|| emissionVault_.allocationCap() != EMISSION_PROGRAM_CAP
) {
revert EqualEmissionInvalidVault();
}
if (epochsPerYear_ == 0) {
revert EqualEmissionZeroEpochsPerYear();
}
if (epochDurationSeconds_ == 0) {
revert EqualEmissionZeroEpochDuration();
}
_validateThreeAuthorities(governanceAuthority_, emissionAuthority_, pauseGuardian_);
emissionVault = emissionVault_;
epochsPerYear = epochsPerYear_;
programmeStartTimestamp = programmeStartTimestamp_;
epochDurationSeconds = epochDurationSeconds_;
totalEpochs = PROGRAMME_YEARS * epochsPerYear_;
governanceAuthority = governanceAuthority_;
emissionAuthority = emissionAuthority_;
pauseGuardian = pauseGuardian_;
}
function annualBudget(
uint256 emissionYear
) public pure returns (uint256) {
if (emissionYear >= PROGRAMME_YEARS) {
revert EqualEmissionYearOutOfRange(emissionYear);
}
if (emissionYear < 4) {
return BAND_ONE_ANNUAL_BUDGET;
}
if (emissionYear < 8) {
return BAND_TWO_ANNUAL_BUDGET;
}
if (emissionYear < 12) {
return BAND_THREE_ANNUAL_BUDGET;
}
return BAND_FOUR_ANNUAL_BUDGET;
}
function epochBudget(
uint256 epochId
) public view returns (uint256) {
_requireEpochInRange(epochId);
uint256 emissionYear = epochId / epochsPerYear;
uint256 epochIndex = epochId % epochsPerYear;
return
EqualEmissionMath.decomposeBudget(annualBudget(emissionYear), epochsPerYear, epochIndex);
}
function walletCapForEpoch(
uint256 epochId
) public view returns (uint256) {
return EqualEmissionMath.walletCap(epochBudget(epochId));
}
function epochEndTimestamp(
uint256 epochId
) public view returns (uint256) {
_requireEpochInRange(epochId);
return programmeStartTimestamp + ((epochId + 1) * epochDurationSeconds);
}
function claimLeaf(
uint256 epochId,
address claimant,
uint256 amount
) public view returns (bytes32) {
return keccak256(
abi.encode(CLAIM_ACTION, block.chainid, address(this), epochId, claimant, amount)
);
}
function epochState(
uint256 epochId
) external view returns (EpochState memory) {
return _epochs[epochId];
}
function epochFinalized(
uint256 epochId
) external view returns (bool) {
return _epochs[epochId].finalized;
}
function finalizeEpoch(
uint256 epochId,
bytes32 distributionRoot,
uint256 committedDistribution,
uint32 participantCount,
bytes32 calculationCommitment
) external whenNotPaused onlyEmissionAuthority {
if (epochId != nextEpochId) {
revert EqualEmissionUnexpectedEpoch(nextEpochId, epochId);
}
_requireEpochInRange(epochId);
uint256 endTimestamp = epochEndTimestamp(epochId);
if (block.timestamp < endTimestamp) {
revert EqualEmissionEpochNotEnded(epochId, endTimestamp);
}
_requireVaultBinding();
uint256 budget = epochBudget(epochId);
uint256 cap = EqualEmissionMath.walletCap(budget);
if (committedDistribution > budget) {
revert EqualEmissionDistributionExceedsBudget(budget, committedDistribution);
}
if (committedDistribution == 0) {
if (distributionRoot != bytes32(0)) {
revert EqualEmissionUnexpectedDistributionRoot();
}
if (participantCount != 0) {
revert EqualEmissionUnexpectedParticipantCount();
}
} else {
if (distributionRoot == bytes32(0)) {
revert EqualEmissionZeroDistributionRoot();
}
if (calculationCommitment == bytes32(0)) {
revert EqualEmissionZeroCalculationCommitment();
}
if (participantCount == 0) {
revert EqualEmissionZeroParticipantCount();
}
uint256 maximumAbsorption = uint256(participantCount) * cap;
if (committedDistribution > maximumAbsorption) {
revert EqualEmissionParticipantAbsorptionExceeded(
maximumAbsorption, committedDistribution
);
}
}
uint256 newFinalizedBudget = cumulativeFinalizedBudget + budget;
if (newFinalizedBudget > EMISSION_PROGRAM_CAP) {
revert EqualEmissionProgrammeCapExceeded();
}
uint256 newCommitted = cumulativeCommittedDistribution + committedDistribution;
if (newCommitted > EMISSION_PROGRAM_CAP) {
revert EqualEmissionProgrammeCapExceeded();
}
if (bootstrapEmissionPhase && newCommitted > BOOTSTRAP_EMISSION_CAP) {
revert EqualEmissionBootstrapCapExceeded();
}
_epochs[epochId] = EpochState({
budget: budget,
walletCap: cap,
committedDistribution: committedDistribution,
claimed: 0,
distributionRoot: distributionRoot,
calculationCommitment: calculationCommitment,
participantCount: participantCount,
finalized: true
});
cumulativeFinalizedBudget = newFinalizedBudget;
cumulativeCommittedDistribution = newCommitted;
nextEpochId = epochId + 1;
_emitEpochFinalized(epochId);
}
function claim(
uint256 epochId,
uint256 amount,
bytes32[] calldata proof
) external whenNotPaused nonReentrant {
_requireVaultBinding();
EpochState storage state = _epochs[epochId];
if (!state.finalized) {
revert EqualEmissionEpochNotFinalized(epochId);
}
if (hasClaimed[epochId][msg.sender]) {
revert EqualEmissionAlreadyClaimed(epochId, msg.sender);
}
if (amount == 0) {
revert EqualEmissionZeroClaim();
}
if (amount > state.walletCap) {
revert EqualEmissionWalletCapExceeded(state.walletCap, amount);
}
bytes32 leaf = claimLeaf(epochId, msg.sender, amount);
if (!MerkleProof.verifyCalldata(proof, state.distributionRoot, leaf)) {
revert EqualEmissionInvalidProof();
}
uint256 newEpochClaimed = state.claimed + amount;
if (newEpochClaimed > state.committedDistribution) {
revert EqualEmissionEpochClaimBoundExceeded();
}
uint256 newCumulativeClaimed = cumulativeClaimed + amount;
if (newCumulativeClaimed > cumulativeCommittedDistribution) {
revert EqualEmissionGlobalClaimBoundExceeded();
}
hasClaimed[epochId][msg.sender] = true;
state.claimed = newEpochClaimed;
cumulativeClaimed = newCumulativeClaimed;
emissionVault.release(msg.sender, amount);
emit EmissionClaimed(epochId, msg.sender, amount, newEpochClaimed, newCumulativeClaimed);
}
function pause() external onlyPauseGuardian {
_pause();
}
function unpause() external onlyGovernance {
_unpause();
}
function endBootstrapEmissionPhase() external onlyGovernance {
if (!bootstrapEmissionPhase) {
revert EqualEmissionBootstrapAlreadyEnded();
}
bootstrapEmissionPhase = false;
emit BootstrapEmissionPhaseEnded(cumulativeCommittedDistribution);
}
function proposeAuthority(
AuthorityRole role,
address candidate
) external onlyGovernance {
if (candidate == address(0)) {
revert EqualEmissionZeroAuthority();
}
address current = _authorityFor(role);
if (candidate == current) {
revert EqualEmissionAuthorityUnchanged();
}
_requireCandidateDoesNotCollide(role, candidate);
pendingAuthority[role] = candidate;
emit AuthorityTransferProposed(role, current, candidate);
}
function acceptAuthority(
AuthorityRole role
) external {
address candidate = pendingAuthority[role];
if (candidate == address(0)) {
revert EqualEmissionNoPendingAuthority();
}
if (msg.sender != candidate) {
revert EqualEmissionPendingAuthorityMismatch();
}
_requireCandidateDoesNotCollide(role, candidate);
address previous = _authorityFor(role);
if (role == AuthorityRole.Governance) {
governanceAuthority = candidate;
} else if (role == AuthorityRole.Emission) {
emissionAuthority = candidate;
} else {
pauseGuardian = candidate;
}
delete pendingAuthority[role];
emit AuthorityTransferAccepted(role, previous, candidate);
}
function _emitEpochFinalized(
uint256 epochId
) internal {
EpochState storage state = _epochs[epochId];
emit EpochFinalized(
epochId,
epochId / epochsPerYear,
state.budget,
state.walletCap,
state.committedDistribution,
state.budget - state.committedDistribution,
state.participantCount,
state.distributionRoot,
state.calculationCommitment
);
}
function _authorityFor(
AuthorityRole role
) internal view returns (address) {
if (role == AuthorityRole.Governance) {
return governanceAuthority;
}
if (role == AuthorityRole.Emission) {
return emissionAuthority;
}
return pauseGuardian;
}
function _requireCandidateDoesNotCollide(
AuthorityRole role,
address candidate
) internal view {
if (role == AuthorityRole.Governance) {
if (candidate == emissionAuthority || candidate == pauseGuardian) {
revert EqualEmissionAuthorityCollision();
}
return;
}
if (role == AuthorityRole.Emission) {
if (candidate == governanceAuthority || candidate == pauseGuardian) {
revert EqualEmissionAuthorityCollision();
}
return;
}
if (candidate == governanceAuthority || candidate == emissionAuthority) {
revert EqualEmissionAuthorityCollision();
}
}
function _validateThreeAuthorities(
address governanceAuthority_,
address emissionAuthority_,
address pauseGuardian_
) internal pure {
if (
governanceAuthority_ == address(0) || emissionAuthority_ == address(0)
|| pauseGuardian_ == address(0)
) {
revert EqualEmissionZeroAuthority();
}
if (
governanceAuthority_ == emissionAuthority_ || governanceAuthority_ == pauseGuardian_
|| emissionAuthority_ == pauseGuardian_
) {
revert EqualEmissionAuthorityCollision();
}
}
function _requireEpochInRange(
uint256 epochId
) internal view {
if (epochId >= totalEpochs) {
revert EqualEmissionEpochOutOfRange(epochId);
}
}
function _requireVaultBinding() internal view {
if (!emissionVault.initialized() || emissionVault.releaseAuthority() != address(this)) {
revert EqualEmissionVaultNotBound();
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/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);
}
lib/openzeppelin-contracts/contracts/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";
lib/openzeppelin-contracts/contracts/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;
}
}
lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts/contracts/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";
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.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 Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @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 approve
* @param bubble Behavior switch if the approve 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)
}
}
}
lib/openzeppelin-contracts/contracts/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);
}
lib/openzeppelin-contracts/contracts/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);
}
lib/openzeppelin-contracts/contracts/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)
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
lib/openzeppelin-contracts/contracts/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);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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) {
unchecked {
// (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 buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 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 first 16 bytes (most significant half).
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));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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 a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a 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 A 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))
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
* @dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}
src/EqualEmissionMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
/// @title EQUAL Emission Math
/// @notice Deterministic reference math for epoch decomposition and capped
/// water-filling.
/// @dev The production controller does not iterate over participant arrays.
/// This library supplies deterministic Solidity reference behaviour for
/// off-chain/root construction and contract-level acceptance tests.
library EqualEmissionMath {
uint256 internal constant WALLET_CAP_DENOMINATOR = 400;
error EqualEmissionMathZeroEpochCount();
error EqualEmissionMathEpochIndexOutOfRange();
error EqualEmissionMathLengthMismatch();
error EqualEmissionMathZeroWallet(uint256 index);
error EqualEmissionMathWalletOrderInvalid(uint256 index);
error EqualEmissionMathInvariantViolation();
function walletCap(
uint256 epochBudget
) internal pure returns (uint256) {
return epochBudget / WALLET_CAP_DENOMINATOR;
}
function decomposeBudget(
uint256 annualBudget,
uint256 epochCount,
uint256 epochIndex
) internal pure returns (uint256) {
if (epochCount == 0) {
revert EqualEmissionMathZeroEpochCount();
}
if (epochIndex >= epochCount) {
revert EqualEmissionMathEpochIndexOutOfRange();
}
uint256 baseBudget = annualBudget / epochCount;
uint256 remainder = annualBudget % epochCount;
return baseBudget + (epochIndex < remainder ? 1 : 0);
}
function waterfill(
address[] memory wallets,
uint256[] memory scores,
uint256 epochBudget
)
internal
pure
returns (uint256[] memory allocations, uint256 distributed, uint256 undistributed)
{
if (wallets.length != scores.length) {
revert EqualEmissionMathLengthMismatch();
}
uint256 count = wallets.length;
allocations = new uint256[](count);
if (count == 0) {
return (allocations, 0, epochBudget);
}
bool[] memory active = new bool[](count);
uint256 remainingScore;
for (uint256 i = 0; i < count; ++i) {
if (wallets[i] == address(0)) {
revert EqualEmissionMathZeroWallet(i);
}
if (i > 0 && uint160(wallets[i]) <= uint160(wallets[i - 1])) {
revert EqualEmissionMathWalletOrderInvalid(i);
}
if (scores[i] > 0) {
active[i] = true;
remainingScore += scores[i];
}
}
uint256 cap = walletCap(epochBudget);
if (epochBudget == 0 || remainingScore == 0 || cap == 0) {
return (allocations, 0, epochBudget);
}
uint256 remainingBudget = epochBudget;
(remainingBudget, remainingScore, distributed) =
_fixAboveCap(active, allocations, scores, cap, remainingBudget, remainingScore);
if (remainingScore > 0 && remainingBudget > 0) {
(uint256 floorDistributed, uint256[] memory remainders) =
_floorShares(active, allocations, scores, cap, remainingBudget, remainingScore);
distributed += floorDistributed;
uint256 residual = remainingBudget - floorDistributed;
distributed += _assignResidual(wallets, active, allocations, remainders, cap, residual);
}
if (distributed > epochBudget) {
revert EqualEmissionMathInvariantViolation();
}
undistributed = epochBudget - distributed;
}
function _fixAboveCap(
bool[] memory active,
uint256[] memory allocations,
uint256[] memory scores,
uint256 cap,
uint256 remainingBudget,
uint256 remainingScore
) private pure returns (uint256 updatedBudget, uint256 updatedScore, uint256 distributed) {
updatedBudget = remainingBudget;
updatedScore = remainingScore;
while (updatedScore > 0 && updatedBudget > 0) {
bool fixedAny;
for (uint256 i = 0; i < active.length; ++i) {
if (!active[i]) {
continue;
}
uint256 floorShare = Math.mulDiv(updatedBudget, scores[i], updatedScore);
uint256 fractionalRemainder = mulmod(updatedBudget, scores[i], updatedScore);
bool exceedsCap = floorShare > cap || (floorShare == cap && fractionalRemainder > 0);
if (!exceedsCap) {
continue;
}
allocations[i] = cap;
active[i] = false;
updatedBudget -= cap;
updatedScore -= scores[i];
distributed += cap;
fixedAny = true;
}
if (!fixedAny) {
break;
}
}
}
function _floorShares(
bool[] memory active,
uint256[] memory allocations,
uint256[] memory scores,
uint256 cap,
uint256 remainingBudget,
uint256 remainingScore
) private pure returns (uint256 floorDistributed, uint256[] memory remainders) {
remainders = new uint256[](active.length);
for (uint256 i = 0; i < active.length; ++i) {
if (!active[i]) {
continue;
}
uint256 floorShare = Math.mulDiv(remainingBudget, scores[i], remainingScore);
if (floorShare > cap) {
revert EqualEmissionMathInvariantViolation();
}
allocations[i] = floorShare;
floorDistributed += floorShare;
remainders[i] = mulmod(remainingBudget, scores[i], remainingScore);
}
}
function _assignResidual(
address[] memory wallets,
bool[] memory active,
uint256[] memory allocations,
uint256[] memory remainders,
uint256 cap,
uint256 residual
) private pure returns (uint256 assigned) {
while (residual > 0) {
uint256 bestIndex = type(uint256).max;
uint256 bestRemainder;
for (uint256 i = 0; i < active.length; ++i) {
if (!active[i] || allocations[i] >= cap) {
continue;
}
uint256 candidate = remainders[i];
if (candidate > bestRemainder) {
bestIndex = i;
bestRemainder = candidate;
} else if (
candidate == bestRemainder && candidate > 0 && bestIndex != type(uint256).max
&& uint160(wallets[i]) < uint160(wallets[bestIndex])
) {
bestIndex = i;
}
}
if (bestIndex == type(uint256).max || bestRemainder == 0) {
break;
}
allocations[bestIndex] += 1;
remainders[bestIndex] = 0;
residual -= 1;
assigned += 1;
}
}
}
lib/openzeppelin-contracts/contracts/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);
}
}
}
}
lib/openzeppelin-contracts/contracts/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);
}
src/EqualAllocationVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Equal } from "./Equal.sol";
/// @title EQUAL Allocation Vault
/// @notice Canonically bounded custody for one EQUAL genesis allocation domain.
/// @dev Deployed once per canonical allocation type. The bootstrap authority may
/// bind the canonical EQUAL token and final release authority exactly once.
/// After initialization the bootstrap authority has no release capability.
contract EqualAllocationVault {
using SafeERC20 for IERC20;
uint256 public constant TOKEN_UNIT = 10 ** 18;
uint256 public constant CANONICAL_MAX_SUPPLY = 1_000_000_000 * TOKEN_UNIT;
uint256 public constant EMISSION_VAULT_CAP = 800_000_000 * TOKEN_UNIT;
uint256 public constant POL_CAP = 60_000_000 * TOKEN_UNIT;
uint256 public constant TREASURY_SECURITY_CAP = 40_000_000 * TOKEN_UNIT;
uint256 public constant ECOSYSTEM_CAP = 40_000_000 * TOKEN_UNIT;
uint256 public constant MARKET_EXCHANGE_CAP = 30_000_000 * TOKEN_UNIT;
uint256 public constant CONTRIBUTOR_CAP = 30_000_000 * TOKEN_UNIT;
error EqualAllocationVaultZeroBootstrapAuthority();
error EqualAllocationVaultUnauthorizedBootstrap(address caller);
error EqualAllocationVaultAlreadyInitialized();
error EqualAllocationVaultZeroToken();
error EqualAllocationVaultZeroReleaseAuthority();
error EqualAllocationVaultBootstrapCannotRemainReleaseAuthority();
error EqualAllocationVaultInvalidTokenAuthority();
error EqualAllocationVaultFundingMismatch(uint256 expected, uint256 actual);
error EqualAllocationVaultNotInitialized();
error EqualAllocationVaultUnauthorizedRelease(address caller);
error EqualAllocationVaultZeroRecipient();
error EqualAllocationVaultZeroAmount();
error EqualAllocationVaultCapExceeded(uint256 cap, uint256 attemptedReleased);
Equal.GenesisAllocationType public immutable allocationType;
uint256 public immutable allocationCap;
address public immutable bootstrapAuthority;
Equal public token;
address public releaseAuthority;
uint256 public released;
bool public initialized;
event AllocationVaultInitialized(
Equal.GenesisAllocationType indexed allocationType,
address indexed token,
address indexed releaseAuthority,
uint256 allocationCap
);
event AllocationReleased(
Equal.GenesisAllocationType indexed allocationType,
address indexed recipient,
uint256 amount,
uint256 cumulativeReleased,
uint256 remainingAllocation
);
constructor(
Equal.GenesisAllocationType allocationType_,
address bootstrapAuthority_
) {
if (bootstrapAuthority_ == address(0)) {
revert EqualAllocationVaultZeroBootstrapAuthority();
}
allocationType = allocationType_;
allocationCap = _canonicalAllocationCap(allocationType_);
bootstrapAuthority = bootstrapAuthority_;
}
/// @notice One-time binding of the canonical EQUAL token and final authority.
/// @dev The vault must already contain exactly its canonical genesis allocation.
function initialize(
Equal token_,
address releaseAuthority_
) external {
if (msg.sender != bootstrapAuthority) {
revert EqualAllocationVaultUnauthorizedBootstrap(msg.sender);
}
if (initialized) {
revert EqualAllocationVaultAlreadyInitialized();
}
if (address(token_) == address(0)) {
revert EqualAllocationVaultZeroToken();
}
if (releaseAuthority_ == address(0)) {
revert EqualAllocationVaultZeroReleaseAuthority();
}
if (releaseAuthority_ == bootstrapAuthority) {
revert EqualAllocationVaultBootstrapCannotRemainReleaseAuthority();
}
if (
token_.MAX_SUPPLY() != CANONICAL_MAX_SUPPLY
|| token_.totalSupply() != CANONICAL_MAX_SUPPLY || token_.TRANSFER_TAX_BPS() != 0
) {
revert EqualAllocationVaultInvalidTokenAuthority();
}
uint256 fundedBalance = token_.balanceOf(address(this));
if (fundedBalance != allocationCap) {
revert EqualAllocationVaultFundingMismatch(allocationCap, fundedBalance);
}
token = token_;
releaseAuthority = releaseAuthority_;
initialized = true;
emit AllocationVaultInitialized(
allocationType, address(token_), releaseAuthority_, allocationCap
);
}
/// @notice Releases EQUAL within the immutable canonical allocation cap.
/// @dev State is advanced before the fixed EQUAL token transfer.
function release(
address recipient,
uint256 amount
) external {
if (!initialized) {
revert EqualAllocationVaultNotInitialized();
}
if (msg.sender != releaseAuthority) {
revert EqualAllocationVaultUnauthorizedRelease(msg.sender);
}
if (recipient == address(0)) {
revert EqualAllocationVaultZeroRecipient();
}
if (amount == 0) {
revert EqualAllocationVaultZeroAmount();
}
uint256 cumulativeReleased = released + amount;
if (cumulativeReleased > allocationCap) {
revert EqualAllocationVaultCapExceeded(allocationCap, cumulativeReleased);
}
released = cumulativeReleased;
IERC20(address(token)).safeTransfer(recipient, amount);
emit AllocationReleased(
allocationType,
recipient,
amount,
cumulativeReleased,
allocationCap - cumulativeReleased
);
}
function remainingAllocation() external view returns (uint256) {
return allocationCap - released;
}
function _canonicalAllocationCap(
Equal.GenesisAllocationType allocationType_
) internal pure returns (uint256) {
if (allocationType_ == Equal.GenesisAllocationType.EmissionVault) {
return EMISSION_VAULT_CAP;
}
if (allocationType_ == Equal.GenesisAllocationType.ProtocolOwnedLiquidity) {
return POL_CAP;
}
if (allocationType_ == Equal.GenesisAllocationType.TreasurySecurity) {
return TREASURY_SECURITY_CAP;
}
if (allocationType_ == Equal.GenesisAllocationType.Ecosystem) {
return ECOSYSTEM_CAP;
}
if (allocationType_ == Equal.GenesisAllocationType.MarketExchange) {
return MARKET_EXCHANGE_CAP;
}
return CONTRIBUTOR_CAP;
}
}
src/Equal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @title Equilibrium (EQUAL)
/// @notice Immutable fixed-supply token core for the Vitality Trinity.
/// @dev No owner, administrator, post-constructor mint, proxy, pause, or transfer tax.
contract Equal is ERC20 {
uint256 public constant TOKEN_UNIT = 10 ** 18;
uint256 public constant MAX_SUPPLY = 1_000_000_000 * TOKEN_UNIT;
uint256 public constant EMISSION_VAULT_ALLOCATION = 800_000_000 * TOKEN_UNIT;
uint256 public constant POL_ALLOCATION = 60_000_000 * TOKEN_UNIT;
uint256 public constant TREASURY_SECURITY_ALLOCATION = 40_000_000 * TOKEN_UNIT;
uint256 public constant ECOSYSTEM_ALLOCATION = 40_000_000 * TOKEN_UNIT;
uint256 public constant MARKET_EXCHANGE_ALLOCATION = 30_000_000 * TOKEN_UNIT;
uint256 public constant CONTRIBUTOR_ALLOCATION = 30_000_000 * TOKEN_UNIT;
uint256 public constant TRANSFER_TAX_BPS = 0;
enum GenesisAllocationType {
EmissionVault,
ProtocolOwnedLiquidity,
TreasurySecurity,
Ecosystem,
MarketExchange,
Contributor
}
error EqualZeroAllocationRecipient(uint8 allocationType);
error EqualDuplicateAllocationRecipient(uint8 firstAllocationType, uint8 secondAllocationType);
event GenesisAllocation(
GenesisAllocationType indexed allocationType, address indexed recipient, uint256 amount
);
constructor(
address emissionVault,
address protocolOwnedLiquidity,
address treasurySecurity,
address ecosystem,
address marketExchange,
address contributor
) ERC20("Equilibrium", "EQUAL") {
address[6] memory recipients = [
emissionVault,
protocolOwnedLiquidity,
treasurySecurity,
ecosystem,
marketExchange,
contributor
];
uint256[6] memory amounts = [
EMISSION_VAULT_ALLOCATION,
POL_ALLOCATION,
TREASURY_SECURITY_ALLOCATION,
ECOSYSTEM_ALLOCATION,
MARKET_EXCHANGE_ALLOCATION,
CONTRIBUTOR_ALLOCATION
];
for (uint256 i = 0; i < recipients.length; ++i) {
if (recipients[i] == address(0)) {
revert EqualZeroAllocationRecipient(uint8(i));
}
for (uint256 j = 0; j < i; ++j) {
if (recipients[i] == recipients[j]) {
revert EqualDuplicateAllocationRecipient(uint8(j), uint8(i));
}
}
_mint(recipients[i], amounts[i]);
emit GenesisAllocation(GenesisAllocationType(i), recipients[i], amounts[i]);
}
assert(totalSupply() == MAX_SUPPLY);
}
}
Compiler Settings
{"viaIR":false,"remappings":["@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/","erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/","forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/","halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/","openzeppelin-contracts/=lib/openzeppelin-contracts/"],"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}},"optimizer":{"runs":200,"enabled":true},"metadata":{"useLiteralContent":false,"bytecodeHash":"none","appendCBOR":true},"libraries":{},"evmVersion":"paris"}
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address","name":"emissionVault_","internalType":"contract EqualAllocationVault"},{"type":"uint256","name":"epochsPerYear_","internalType":"uint256"},{"type":"uint256","name":"programmeStartTimestamp_","internalType":"uint256"},{"type":"uint256","name":"epochDurationSeconds_","internalType":"uint256"},{"type":"address","name":"governanceAuthority_","internalType":"address"},{"type":"address","name":"emissionAuthority_","internalType":"address"},{"type":"address","name":"pauseGuardian_","internalType":"address"}]},{"type":"error","name":"EnforcedPause","inputs":[]},{"type":"error","name":"EqualEmissionAlreadyClaimed","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"},{"type":"address","name":"claimant","internalType":"address"}]},{"type":"error","name":"EqualEmissionAuthorityCollision","inputs":[]},{"type":"error","name":"EqualEmissionAuthorityUnchanged","inputs":[]},{"type":"error","name":"EqualEmissionBootstrapAlreadyEnded","inputs":[]},{"type":"error","name":"EqualEmissionBootstrapCapExceeded","inputs":[]},{"type":"error","name":"EqualEmissionDistributionExceedsBudget","inputs":[{"type":"uint256","name":"budget","internalType":"uint256"},{"type":"uint256","name":"committed","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionEpochClaimBoundExceeded","inputs":[]},{"type":"error","name":"EqualEmissionEpochNotEnded","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"},{"type":"uint256","name":"endTimestamp","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionEpochNotFinalized","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionEpochOutOfRange","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionGlobalClaimBoundExceeded","inputs":[]},{"type":"error","name":"EqualEmissionInvalidProof","inputs":[]},{"type":"error","name":"EqualEmissionInvalidVault","inputs":[]},{"type":"error","name":"EqualEmissionMathEpochIndexOutOfRange","inputs":[]},{"type":"error","name":"EqualEmissionMathZeroEpochCount","inputs":[]},{"type":"error","name":"EqualEmissionNoPendingAuthority","inputs":[]},{"type":"error","name":"EqualEmissionParticipantAbsorptionExceeded","inputs":[{"type":"uint256","name":"maximumAbsorption","internalType":"uint256"},{"type":"uint256","name":"committed","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionPendingAuthorityMismatch","inputs":[]},{"type":"error","name":"EqualEmissionProgrammeCapExceeded","inputs":[]},{"type":"error","name":"EqualEmissionUnauthorizedEmission","inputs":[{"type":"address","name":"caller","internalType":"address"}]},{"type":"error","name":"EqualEmissionUnauthorizedGovernance","inputs":[{"type":"address","name":"caller","internalType":"address"}]},{"type":"error","name":"EqualEmissionUnauthorizedPauseGuardian","inputs":[{"type":"address","name":"caller","internalType":"address"}]},{"type":"error","name":"EqualEmissionUnexpectedDistributionRoot","inputs":[]},{"type":"error","name":"EqualEmissionUnexpectedEpoch","inputs":[{"type":"uint256","name":"expected","internalType":"uint256"},{"type":"uint256","name":"supplied","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionUnexpectedParticipantCount","inputs":[]},{"type":"error","name":"EqualEmissionVaultNotBound","inputs":[]},{"type":"error","name":"EqualEmissionWalletCapExceeded","inputs":[{"type":"uint256","name":"walletCap","internalType":"uint256"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionYearOutOfRange","inputs":[{"type":"uint256","name":"emissionYear","internalType":"uint256"}]},{"type":"error","name":"EqualEmissionZeroAuthority","inputs":[]},{"type":"error","name":"EqualEmissionZeroCalculationCommitment","inputs":[]},{"type":"error","name":"EqualEmissionZeroClaim","inputs":[]},{"type":"error","name":"EqualEmissionZeroDistributionRoot","inputs":[]},{"type":"error","name":"EqualEmissionZeroEpochDuration","inputs":[]},{"type":"error","name":"EqualEmissionZeroEpochsPerYear","inputs":[]},{"type":"error","name":"EqualEmissionZeroParticipantCount","inputs":[]},{"type":"error","name":"EqualEmissionZeroVault","inputs":[]},{"type":"error","name":"ExpectedPause","inputs":[]},{"type":"error","name":"ReentrancyGuardReentrantCall","inputs":[]},{"type":"event","name":"AuthorityTransferAccepted","inputs":[{"type":"uint8","name":"role","internalType":"enum EqualEmissionController.AuthorityRole","indexed":true},{"type":"address","name":"previousAuthority","internalType":"address","indexed":true},{"type":"address","name":"newAuthority","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"AuthorityTransferProposed","inputs":[{"type":"uint8","name":"role","internalType":"enum EqualEmissionController.AuthorityRole","indexed":true},{"type":"address","name":"currentAuthority","internalType":"address","indexed":true},{"type":"address","name":"pendingAuthority","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"BootstrapEmissionPhaseEnded","inputs":[{"type":"uint256","name":"cumulativeCommittedDistribution","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"EmissionClaimed","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256","indexed":true},{"type":"address","name":"claimant","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false},{"type":"uint256","name":"epochClaimed","internalType":"uint256","indexed":false},{"type":"uint256","name":"cumulativeClaimed","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"EpochFinalized","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256","indexed":true},{"type":"uint256","name":"emissionYear","internalType":"uint256","indexed":true},{"type":"uint256","name":"budget","internalType":"uint256","indexed":false},{"type":"uint256","name":"walletCap","internalType":"uint256","indexed":false},{"type":"uint256","name":"committedDistribution","internalType":"uint256","indexed":false},{"type":"uint256","name":"undistributed","internalType":"uint256","indexed":false},{"type":"uint32","name":"participantCount","internalType":"uint32","indexed":false},{"type":"bytes32","name":"distributionRoot","internalType":"bytes32","indexed":false},{"type":"bytes32","name":"calculationCommitment","internalType":"bytes32","indexed":false}],"anonymous":false},{"type":"event","name":"Paused","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"Unpaused","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"BAND_FOUR_ANNUAL_BUDGET","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"BAND_ONE_ANNUAL_BUDGET","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"BAND_THREE_ANNUAL_BUDGET","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"BAND_TWO_ANNUAL_BUDGET","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"BOOTSTRAP_EMISSION_CAP","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"CLAIM_ACTION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"EMISSION_PROGRAM_CAP","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"PROGRAMME_YEARS","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"TOKEN_UNIT","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"WALLET_CAP_DENOMINATOR","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"YEARS_PER_BAND","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"acceptAuthority","inputs":[{"type":"uint8","name":"role","internalType":"enum EqualEmissionController.AuthorityRole"}]},{"type":"function","stateMutability":"pure","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"annualBudget","inputs":[{"type":"uint256","name":"emissionYear","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"bootstrapEmissionPhase","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"claim","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"},{"type":"uint256","name":"amount","internalType":"uint256"},{"type":"bytes32[]","name":"proof","internalType":"bytes32[]"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"claimLeaf","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"},{"type":"address","name":"claimant","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"cumulativeClaimed","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"cumulativeCommittedDistribution","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"cumulativeFinalizedBudget","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"emissionAuthority","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"emissionVault","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"endBootstrapEmissionPhase","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"epochBudget","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"epochDurationSeconds","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"epochEndTimestamp","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"epochFinalized","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"tuple","name":"","internalType":"struct EqualEmissionController.EpochState","components":[{"type":"uint256","name":"budget","internalType":"uint256"},{"type":"uint256","name":"walletCap","internalType":"uint256"},{"type":"uint256","name":"committedDistribution","internalType":"uint256"},{"type":"uint256","name":"claimed","internalType":"uint256"},{"type":"bytes32","name":"distributionRoot","internalType":"bytes32"},{"type":"bytes32","name":"calculationCommitment","internalType":"bytes32"},{"type":"uint32","name":"participantCount","internalType":"uint32"},{"type":"bool","name":"finalized","internalType":"bool"}]}],"name":"epochState","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"epochsPerYear","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"finalizeEpoch","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"},{"type":"bytes32","name":"distributionRoot","internalType":"bytes32"},{"type":"uint256","name":"committedDistribution","internalType":"uint256"},{"type":"uint32","name":"participantCount","internalType":"uint32"},{"type":"bytes32","name":"calculationCommitment","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"governanceAuthority","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"hasClaimed","inputs":[{"type":"uint256","name":"","internalType":"uint256"},{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"nextEpochId","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"pause","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"pauseGuardian","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"paused","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"pendingAuthority","inputs":[{"type":"uint8","name":"","internalType":"enum EqualEmissionController.AuthorityRole"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"programmeStartTimestamp","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"proposeAuthority","inputs":[{"type":"uint8","name":"role","internalType":"enum EqualEmissionController.AuthorityRole"},{"type":"address","name":"candidate","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalEpochs","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"unpause","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"walletCapForEpoch","inputs":[{"type":"uint256","name":"epochId","internalType":"uint256"}]}]
Contract Creation Code
0x610120604052600a805460ff191660011790553480156200001f57600080fd5b506040516200221d3803806200221d833981016040819052620000429162000360565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556001600160a01b0387166200008e57604051635108aaef60e11b815260040160405180910390fd5b6000876001600160a01b031663a5aa94ac6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620000cf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000f59190620003fe565b6005811115620001095762000109620003e8565b1415806200019257506200012a670de0b6b3a7640000632faf080062000428565b876001600160a01b031663504e49566040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000169573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200018f919062000454565b14155b15620001b1576040516352030d0760e01b815260040160405180910390fd5b85600003620001d357604051635b5d689960e11b815260040160405180910390fd5b83600003620001f557604051635be84ddb60e01b815260040160405180910390fd5b6200020283838362000284565b6001600160a01b03871660805260a086905260c085905260e08490526200022b86601062000428565b610100908152600080546001600160a01b03958616909202610100600160a81b0319909216919091179055600180549284166001600160a01b031993841617905560028054919093169116179055506200046e92505050565b6001600160a01b0383161580620002a257506001600160a01b038216155b80620002b557506001600160a01b038116155b15620002d457604051636b3e672b60e01b815260040160405180910390fd5b816001600160a01b0316836001600160a01b03161480620003065750806001600160a01b0316836001600160a01b0316145b80620003235750806001600160a01b0316826001600160a01b0316145b15620003425760405163fbec30d160e01b815260040160405180910390fd5b505050565b6001600160a01b03811681146200035d57600080fd5b50565b600080600080600080600060e0888a0312156200037c57600080fd5b8751620003898162000347565b809750506020880151955060408801519450606088015193506080880151620003b28162000347565b60a0890151909350620003c58162000347565b60c0890151909250620003d88162000347565b8091505092959891949750929550565b634e487b7160e01b600052602160045260246000fd5b6000602082840312156200041157600080fd5b8151600681106200042157600080fd5b9392505050565b80820281158282048414176200044e57634e487b7160e01b600052601160045260246000fd5b92915050565b6000602082840312156200046757600080fd5b5051919050565b60805160a05160c05160e05161010051611d24620004f96000396000818161040c015261142f0152600081816103af015261104901526000818161029f015261108301526000818161037701528181610772015281816107a0015281816107d501526116cb0152600081816102d90152818161133b0152818161156d01526116000152611d246000f3fe608060405234801561001057600080fd5b50600436106102535760003560e01c80636c5ec94d11610146578063aa80559a116100c3578063cafef3b511610087578063cafef3b51461064a578063d28147ee14610678578063df82b02714610681578063ef94012f14610689578063fb6c3aff1461069c578063fd7f14da146106c557600080fd5b8063aa80559a146105fc578063acefa4a51461060f578063ae0b51df14610617578063bc8108e51461062a578063c81dbbe81461063257600080fd5b8063965d08af1161010a578063965d08af146105ab57806396a5d5ba146105be578063a18c3806146105d1578063a3c788d9146105e4578063a5c9cd82146105ed57600080fd5b80636c5ec94d14610407578063714f5bfc1461042e57806377e688f0146105625780638456cb5914610575578063873f6f9e1461057d57600080fd5b80633f7467ad116101d4578063582f38cb11610198578063582f38cb146103d15780635a80b57b146103d95780635c975abb146103e15780635f91a82a146103ec57806362195367146103f457600080fd5b80633f7467ad1461035557806348999128146103725780634b9094201461039957806355b14515146103a157806356d9bcf3146103aa57600080fd5b806324a3d6221161021b57806324a3d62214610313578063264f4202146103265780632b7a83651461032f5780633a627313146103385780633f4ba83a1461034b57600080fd5b80630b78b47d146102585780631140336a1461029257806312e8e01c1461029a578063197ec524146102c15780631f7c8502146102d4575b600080fd5b61027f7fb59288e4546edbbcf2dff905a79d3e24cf690a39d0cb2bffc8e45d4be40a3b4281565b6040519081526020015b60405180910390f35b61027f6106cd565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b61027f6102cf366004611a6a565b6106e6565b6102fb7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610289565b6002546102fb906001600160a01b031681565b61027f60085481565b61027f60075481565b61027f610346366004611aa2565b610760565b610353610802565b005b600a546103629060ff1681565b6040519015158152602001610289565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b61027f610843565b61027f60095481565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b61027f610859565b61027f61086f565b60005460ff16610362565b61027f610885565b610353610402366004611abb565b61089a565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b6104f961043c366004611aa2565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810191909152506000908152600460208181526040928390208351610100810185528154815260018201549281019290925260028101549382019390935260038301546060820152908201546080820152600582015460a082015260069091015463ffffffff811660c0830152640100000000900460ff16151560e082015290565b6040516102899190600061010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015263ffffffff60c08401511660c083015260e0830151151560e083015292915050565b61027f610570366004611aa2565b610c65565b610353610d04565b61036261058b366004611b0d565b600560209081526000928352604080842090915290825290205460ff1681565b6103536105b9366004611b51565b610d39565b6103536105cc366004611b6c565b610f02565b61027f6105df366004611aa2565b61103c565b61027f61019081565b61027f670de0b6b3a764000081565b61027f61060a366004611aa2565b6110a7565b6103536110ba565b610353610625366004611b98565b611152565b61027f600481565b6000546102fb9061010090046001600160a01b031681565b610362610658366004611aa2565b600090815260046020526040902060060154640100000000900460ff1690565b61027f60065481565b61027f611417565b6001546102fb906001600160a01b031681565b6102fb6106aa366004611b51565b6003602052600090815260409020546001600160a01b031681565b61027f601081565b6106e3670de0b6b3a76400006304c4b400611c31565b81565b604080517fb59288e4546edbbcf2dff905a79d3e24cf690a39d0cb2bffc8e45d4be40a3b4260208201524691810191909152306060820152608081018490526001600160a01b03831660a082015260c0810182905260009060e0016040516020818303038152906040528051906020012090509392505050565b600061076b8261142d565b60006107977f000000000000000000000000000000000000000000000000000000000000000084611c5e565b905060006107c57f000000000000000000000000000000000000000000000000000000000000000085611c72565b90506107fa6107d383610c65565b7f000000000000000000000000000000000000000000000000000000000000000083611473565b949350505050565b60005461010090046001600160a01b0316331461083957604051630742e48b60e41b81523360048201526024015b60405180910390fd5b6108416114fa565b565b6106e3670de0b6b3a76400006301312d00611c31565b6106e3670de0b6b3a76400006302625a00611c31565b6106e3670de0b6b3a76400006303938700611c31565b6106e3670de0b6b3a7640000624c4b40611c31565b6108a2611547565b6001546001600160a01b031633146108cf5760405163044782a760e31b8152336004820152602401610830565b60065485146108ff5760065460405163240c02db60e01b8152600481019190915260248101869052604401610830565b6109088561142d565b60006109138661103c565b905080421015610940576040516352b8ad3760e01b81526004810187905260248101829052604401610830565b61094861156b565b600061095387610760565b90506000610960826116aa565b90508186111561098d57604051633e6f357f60e21b81526004810183905260248101879052604401610830565b856000036109de5786156109b457604051638f2c67a960e01b815260040160405180910390fd5b63ffffffff8516156109d957604051630743b38f60e01b815260040160405180910390fd5b610a82565b866109fc576040516333dbed4b60e01b815260040160405180910390fd5b83610a1a57604051630ba213eb60e21b815260040160405180910390fd5b8463ffffffff16600003610a415760405163082a9ab760e31b815260040160405180910390fd5b6000610a538263ffffffff8816611c31565b905080871115610a80576040516354218a2d60e01b81526004810182905260248101889052604401610830565b505b600082600754610a929190611c86565b9050610aaa670de0b6b3a7640000632faf0800611c31565b811115610aca57604051635835335f60e11b815260040160405180910390fd5b600087600854610ada9190611c86565b9050610af2670de0b6b3a7640000632faf0800611c31565b811115610b1257604051635835335f60e11b815260040160405180910390fd5b600a5460ff168015610b375750610b34670de0b6b3a7640000624c4b40611c31565b81115b15610b5557604051637e44a93760e11b815260040160405180910390fd5b604051806101000160405280858152602001848152602001898152602001600081526020018a81526020018781526020018863ffffffff16815260200160011515815250600460008c8152602001908152602001600020600082015181600001556020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015560c08201518160060160006101000a81548163ffffffff021916908363ffffffff16021790555060e08201518160060160046101000a81548160ff0219169083151502179055509050508160078190555080600881905550896001610c4d9190611c86565b600655610c598a6116b8565b50505050505050505050565b600060108210610c8b5760405163ab6ea83160e01b815260048101839052602401610830565b6004821015610cb057610caa670de0b6b3a76400006304c4b400611c31565b92915050565b6008821015610ccf57610caa670de0b6b3a76400006303938700611c31565b600c821015610cee57610caa670de0b6b3a76400006302625a00611c31565b610caa670de0b6b3a76400006301312d00611c31565b6002546001600160a01b03163314610d3157604051633b03367360e21b8152336004820152602401610830565b61084161177d565b600060036000836002811115610d5157610d51611c99565b6002811115610d6257610d62611c99565b81526020810191909152604001600020546001600160a01b0316905080610d9c57604051638fc8bbf160e01b815260040160405180910390fd5b336001600160a01b03821614610dc55760405163de6e3b1360e01b815260040160405180910390fd5b610dcf82826117ba565b6000610dda836118cb565b90506000836002811115610df057610df0611c99565b03610e1a5760008054610100600160a81b0319166101006001600160a01b03851602179055610e6f565b6001836002811115610e2e57610e2e611c99565b03610e5357600180546001600160a01b0319166001600160a01b038416179055610e6f565b600280546001600160a01b0319166001600160a01b0384161790555b60036000846002811115610e8557610e85611c99565b6002811115610e9657610e96611c99565b8152602081019190915260400160002080546001600160a01b03191690556001600160a01b03828116908216846002811115610ed457610ed4611c99565b6040517f309d3105e9fb802b7b2d4c96ffac1c13eee06d01e5f21d24b57f6f2deeae51c390600090a4505050565b60005461010090046001600160a01b03163314610f3457604051630742e48b60e41b8152336004820152602401610830565b6001600160a01b038116610f5b57604051636b3e672b60e01b815260040160405180910390fd5b6000610f66836118cb565b9050806001600160a01b0316826001600160a01b031603610f9a57604051632356df2760e01b815260040160405180910390fd5b610fa483836117ba565b8160036000856002811115610fbb57610fbb611c99565b6002811115610fcc57610fcc611c99565b8152602081019190915260400160002080546001600160a01b0319166001600160a01b0392831617905582811690821684600281111561100e5761100e611c99565b6040517f5973b922b1a9ccd7bd4eaf356fe0d5053212ab06f3b1e3c153c2def03c0bad9290600090a4505050565b60006110478261142d565b7f0000000000000000000000000000000000000000000000000000000000000000611073836001611c86565b61107d9190611c31565b610caa907f0000000000000000000000000000000000000000000000000000000000000000611c86565b6000610caa6110b583610760565b6116aa565b60005461010090046001600160a01b031633146110ec57604051630742e48b60e41b8152336004820152602401610830565b600a5460ff1661110f5760405163da8ad54560e01b815260040160405180910390fd5b600a805460ff191690556008546040519081527fd37c003b13ef2b2b0d2a697e60cedb262038309a8e512d9932d0febdb033441d906020015b60405180910390a1565b61115a611547565b611162611936565b61116a61156b565b60008481526004602052604090206006810154640100000000900460ff166111a8576040516363d7266160e11b815260048101869052602401610830565b600085815260056020908152604080832033845290915290205460ff16156111ec57604051633cbd7ef760e01b815260048101869052336024820152604401610830565b8360000361120d576040516379d9727360e01b815260040160405180910390fd5b8060010154841115611242576001810154604051634e5d1d7160e11b8152600481019190915260248101859052604401610830565b600061124f8633876106e6565b90506112618484846004015484611964565b61127e57604051637b0ddadb60e01b815260040160405180910390fd5b60008583600301546112909190611c86565b905082600201548111156112b757604051635c1718d360e01b815260040160405180910390fd5b6000866009546112c79190611c86565b90506008548111156112ec576040516326c1025360e01b815260040160405180910390fd5b600088815260056020908152604080832033808552925291829020805460ff191660011790556003860184905560098390559051630357371d60e01b81526004810191909152602481018890527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690630357371d90604401600060405180830381600087803b15801561138757600080fd5b505af115801561139b573d6000803e3d6000fd5b5050604080518a8152602081018690529081018490523392508a91507f3c883b8d82099521701353cd20a52a3b88dbf0209de8a8028a0f0cccd9484f0a9060600160405180910390a35050505061141160017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b50505050565b6106e3670de0b6b3a7640000632faf0800611c31565b7f000000000000000000000000000000000000000000000000000000000000000081106114705760405163685861c560e11b815260048101829052602401610830565b50565b6000826000036114965760405163024f8f8d60e61b815260040160405180910390fd5b8282106114b657604051636a6a59a160e11b815260040160405180910390fd5b60006114c28486611c5e565b905060006114d08587611c72565b90508084106114e05760006114e3565b60015b6114f09060ff1683611c86565b9695505050505050565b61150261197c565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b039091168152602001611148565b60005460ff16156108415760405163d93c066560e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663158ef93e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ed9190611caf565b158061168c5750306001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663618168326040518163ffffffff1660e01b8152600401602060405180830381865afa15801561165c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116809190611cd1565b6001600160a01b031614155b1561084157604051631b1465cf60e11b815260040160405180910390fd5b6000610caa61019083611c5e565b60008181526004602052604090206116f07f000000000000000000000000000000000000000000000000000000000000000083611c5e565b81546001830154600284015485927f241dfe871a81ff176d033aa29a4b30725a6e8d921ae920e7e8aff141f1e3bec392909161172c8184611cee565b6006880154600489015460058a015460408051978852602088019690965294860193909352606085019190915263ffffffff16608084015260a083015260c082015260e00160405180910390a35050565b611785611547565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861152f3390565b60008260028111156117ce576117ce611c99565b0361181e576001546001600160a01b03828116911614806117fc57506002546001600160a01b038281169116145b1561181a5760405163fbec30d160e01b815260040160405180910390fd5b5050565b600182600281111561183257611832611c99565b03611881576000546001600160a01b038281166101009092041614806117fc57506002546001600160a01b0382811691160361181a5760405163fbec30d160e01b815260040160405180910390fd5b6000546001600160a01b038281166101009092041614806117fc57506001546001600160a01b0382811691160361181a5760405163fbec30d160e01b815260040160405180910390fd5b6000808260028111156118e0576118e0611c99565b036118fb57505060005461010090046001600160a01b031690565b600182600281111561190f5761190f611c99565b036119255750506001546001600160a01b031690565b50506002546001600160a01b031690565b61193e61199f565b60027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b6000826119728686856119e1565b1495945050505050565b60005460ff1661084157604051638dfc202b60e01b815260040160405180910390fd5b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005460020361084157604051633ee5aeb560e01b815260040160405180910390fd5b600081815b84811015611a1a57611a1082878784818110611a0457611a04611d01565b90506020020135611a23565b91506001016119e6565b50949350505050565b6000818310611a3f576000828152602084905260409020611a4e565b60008381526020839052604090205b9392505050565b6001600160a01b038116811461147057600080fd5b600080600060608486031215611a7f57600080fd5b833592506020840135611a9181611a55565b929592945050506040919091013590565b600060208284031215611ab457600080fd5b5035919050565b600080600080600060a08688031215611ad357600080fd5b853594506020860135935060408601359250606086013563ffffffff81168114611afc57600080fd5b949793965091946080013592915050565b60008060408385031215611b2057600080fd5b823591506020830135611b3281611a55565b809150509250929050565b803560038110611b4c57600080fd5b919050565b600060208284031215611b6357600080fd5b611a4e82611b3d565b60008060408385031215611b7f57600080fd5b611b8883611b3d565b91506020830135611b3281611a55565b60008060008060608587031215611bae57600080fd5b8435935060208501359250604085013567ffffffffffffffff80821115611bd457600080fd5b818701915087601f830112611be857600080fd5b813581811115611bf757600080fd5b8860208260051b8501011115611c0c57600080fd5b95989497505060200194505050565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610caa57610caa611c1b565b634e487b7160e01b600052601260045260246000fd5b600082611c6d57611c6d611c48565b500490565b600082611c8157611c81611c48565b500690565b80820180821115610caa57610caa611c1b565b634e487b7160e01b600052602160045260246000fd5b600060208284031215611cc157600080fd5b81518015158114611a4e57600080fd5b600060208284031215611ce357600080fd5b8151611a4e81611a55565b81810381811115610caa57610caa611c1b565b634e487b7160e01b600052603260045260246000fdfea164736f6c6343000818000a000000000000000000000000b7f11392542aceedb11dbef3b84064079e979a71000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000006aae491f0000000000000000000000000000000000000000000000000000000000000e1000000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad9000000000000000000000000fe4a6b0c5c0792ebac17119625e913740941b722000000000000000000000000b94b5616d1afb26723cb6a9c0ca1a71d2ea138e7
Deployed ByteCode
0x608060405234801561001057600080fd5b50600436106102535760003560e01c80636c5ec94d11610146578063aa80559a116100c3578063cafef3b511610087578063cafef3b51461064a578063d28147ee14610678578063df82b02714610681578063ef94012f14610689578063fb6c3aff1461069c578063fd7f14da146106c557600080fd5b8063aa80559a146105fc578063acefa4a51461060f578063ae0b51df14610617578063bc8108e51461062a578063c81dbbe81461063257600080fd5b8063965d08af1161010a578063965d08af146105ab57806396a5d5ba146105be578063a18c3806146105d1578063a3c788d9146105e4578063a5c9cd82146105ed57600080fd5b80636c5ec94d14610407578063714f5bfc1461042e57806377e688f0146105625780638456cb5914610575578063873f6f9e1461057d57600080fd5b80633f7467ad116101d4578063582f38cb11610198578063582f38cb146103d15780635a80b57b146103d95780635c975abb146103e15780635f91a82a146103ec57806362195367146103f457600080fd5b80633f7467ad1461035557806348999128146103725780634b9094201461039957806355b14515146103a157806356d9bcf3146103aa57600080fd5b806324a3d6221161021b57806324a3d62214610313578063264f4202146103265780632b7a83651461032f5780633a627313146103385780633f4ba83a1461034b57600080fd5b80630b78b47d146102585780631140336a1461029257806312e8e01c1461029a578063197ec524146102c15780631f7c8502146102d4575b600080fd5b61027f7fb59288e4546edbbcf2dff905a79d3e24cf690a39d0cb2bffc8e45d4be40a3b4281565b6040519081526020015b60405180910390f35b61027f6106cd565b61027f7f000000000000000000000000000000000000000000000000000000006aae491f81565b61027f6102cf366004611a6a565b6106e6565b6102fb7f000000000000000000000000b7f11392542aceedb11dbef3b84064079e979a7181565b6040516001600160a01b039091168152602001610289565b6002546102fb906001600160a01b031681565b61027f60085481565b61027f60075481565b61027f610346366004611aa2565b610760565b610353610802565b005b600a546103629060ff1681565b6040519015158152602001610289565b61027f7f000000000000000000000000000000000000000000000000000000000000000c81565b61027f610843565b61027f60095481565b61027f7f0000000000000000000000000000000000000000000000000000000000000e1081565b61027f610859565b61027f61086f565b60005460ff16610362565b61027f610885565b610353610402366004611abb565b61089a565b61027f7f00000000000000000000000000000000000000000000000000000000000000c081565b6104f961043c366004611aa2565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810191909152506000908152600460208181526040928390208351610100810185528154815260018201549281019290925260028101549382019390935260038301546060820152908201546080820152600582015460a082015260069091015463ffffffff811660c0830152640100000000900460ff16151560e082015290565b6040516102899190600061010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015263ffffffff60c08401511660c083015260e0830151151560e083015292915050565b61027f610570366004611aa2565b610c65565b610353610d04565b61036261058b366004611b0d565b600560209081526000928352604080842090915290825290205460ff1681565b6103536105b9366004611b51565b610d39565b6103536105cc366004611b6c565b610f02565b61027f6105df366004611aa2565b61103c565b61027f61019081565b61027f670de0b6b3a764000081565b61027f61060a366004611aa2565b6110a7565b6103536110ba565b610353610625366004611b98565b611152565b61027f600481565b6000546102fb9061010090046001600160a01b031681565b610362610658366004611aa2565b600090815260046020526040902060060154640100000000900460ff1690565b61027f60065481565b61027f611417565b6001546102fb906001600160a01b031681565b6102fb6106aa366004611b51565b6003602052600090815260409020546001600160a01b031681565b61027f601081565b6106e3670de0b6b3a76400006304c4b400611c31565b81565b604080517fb59288e4546edbbcf2dff905a79d3e24cf690a39d0cb2bffc8e45d4be40a3b4260208201524691810191909152306060820152608081018490526001600160a01b03831660a082015260c0810182905260009060e0016040516020818303038152906040528051906020012090509392505050565b600061076b8261142d565b60006107977f000000000000000000000000000000000000000000000000000000000000000c84611c5e565b905060006107c57f000000000000000000000000000000000000000000000000000000000000000c85611c72565b90506107fa6107d383610c65565b7f000000000000000000000000000000000000000000000000000000000000000c83611473565b949350505050565b60005461010090046001600160a01b0316331461083957604051630742e48b60e41b81523360048201526024015b60405180910390fd5b6108416114fa565b565b6106e3670de0b6b3a76400006301312d00611c31565b6106e3670de0b6b3a76400006302625a00611c31565b6106e3670de0b6b3a76400006303938700611c31565b6106e3670de0b6b3a7640000624c4b40611c31565b6108a2611547565b6001546001600160a01b031633146108cf5760405163044782a760e31b8152336004820152602401610830565b60065485146108ff5760065460405163240c02db60e01b8152600481019190915260248101869052604401610830565b6109088561142d565b60006109138661103c565b905080421015610940576040516352b8ad3760e01b81526004810187905260248101829052604401610830565b61094861156b565b600061095387610760565b90506000610960826116aa565b90508186111561098d57604051633e6f357f60e21b81526004810183905260248101879052604401610830565b856000036109de5786156109b457604051638f2c67a960e01b815260040160405180910390fd5b63ffffffff8516156109d957604051630743b38f60e01b815260040160405180910390fd5b610a82565b866109fc576040516333dbed4b60e01b815260040160405180910390fd5b83610a1a57604051630ba213eb60e21b815260040160405180910390fd5b8463ffffffff16600003610a415760405163082a9ab760e31b815260040160405180910390fd5b6000610a538263ffffffff8816611c31565b905080871115610a80576040516354218a2d60e01b81526004810182905260248101889052604401610830565b505b600082600754610a929190611c86565b9050610aaa670de0b6b3a7640000632faf0800611c31565b811115610aca57604051635835335f60e11b815260040160405180910390fd5b600087600854610ada9190611c86565b9050610af2670de0b6b3a7640000632faf0800611c31565b811115610b1257604051635835335f60e11b815260040160405180910390fd5b600a5460ff168015610b375750610b34670de0b6b3a7640000624c4b40611c31565b81115b15610b5557604051637e44a93760e11b815260040160405180910390fd5b604051806101000160405280858152602001848152602001898152602001600081526020018a81526020018781526020018863ffffffff16815260200160011515815250600460008c8152602001908152602001600020600082015181600001556020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015560c08201518160060160006101000a81548163ffffffff021916908363ffffffff16021790555060e08201518160060160046101000a81548160ff0219169083151502179055509050508160078190555080600881905550896001610c4d9190611c86565b600655610c598a6116b8565b50505050505050505050565b600060108210610c8b5760405163ab6ea83160e01b815260048101839052602401610830565b6004821015610cb057610caa670de0b6b3a76400006304c4b400611c31565b92915050565b6008821015610ccf57610caa670de0b6b3a76400006303938700611c31565b600c821015610cee57610caa670de0b6b3a76400006302625a00611c31565b610caa670de0b6b3a76400006301312d00611c31565b6002546001600160a01b03163314610d3157604051633b03367360e21b8152336004820152602401610830565b61084161177d565b600060036000836002811115610d5157610d51611c99565b6002811115610d6257610d62611c99565b81526020810191909152604001600020546001600160a01b0316905080610d9c57604051638fc8bbf160e01b815260040160405180910390fd5b336001600160a01b03821614610dc55760405163de6e3b1360e01b815260040160405180910390fd5b610dcf82826117ba565b6000610dda836118cb565b90506000836002811115610df057610df0611c99565b03610e1a5760008054610100600160a81b0319166101006001600160a01b03851602179055610e6f565b6001836002811115610e2e57610e2e611c99565b03610e5357600180546001600160a01b0319166001600160a01b038416179055610e6f565b600280546001600160a01b0319166001600160a01b0384161790555b60036000846002811115610e8557610e85611c99565b6002811115610e9657610e96611c99565b8152602081019190915260400160002080546001600160a01b03191690556001600160a01b03828116908216846002811115610ed457610ed4611c99565b6040517f309d3105e9fb802b7b2d4c96ffac1c13eee06d01e5f21d24b57f6f2deeae51c390600090a4505050565b60005461010090046001600160a01b03163314610f3457604051630742e48b60e41b8152336004820152602401610830565b6001600160a01b038116610f5b57604051636b3e672b60e01b815260040160405180910390fd5b6000610f66836118cb565b9050806001600160a01b0316826001600160a01b031603610f9a57604051632356df2760e01b815260040160405180910390fd5b610fa483836117ba565b8160036000856002811115610fbb57610fbb611c99565b6002811115610fcc57610fcc611c99565b8152602081019190915260400160002080546001600160a01b0319166001600160a01b0392831617905582811690821684600281111561100e5761100e611c99565b6040517f5973b922b1a9ccd7bd4eaf356fe0d5053212ab06f3b1e3c153c2def03c0bad9290600090a4505050565b60006110478261142d565b7f0000000000000000000000000000000000000000000000000000000000000e10611073836001611c86565b61107d9190611c31565b610caa907f000000000000000000000000000000000000000000000000000000006aae491f611c86565b6000610caa6110b583610760565b6116aa565b60005461010090046001600160a01b031633146110ec57604051630742e48b60e41b8152336004820152602401610830565b600a5460ff1661110f5760405163da8ad54560e01b815260040160405180910390fd5b600a805460ff191690556008546040519081527fd37c003b13ef2b2b0d2a697e60cedb262038309a8e512d9932d0febdb033441d906020015b60405180910390a1565b61115a611547565b611162611936565b61116a61156b565b60008481526004602052604090206006810154640100000000900460ff166111a8576040516363d7266160e11b815260048101869052602401610830565b600085815260056020908152604080832033845290915290205460ff16156111ec57604051633cbd7ef760e01b815260048101869052336024820152604401610830565b8360000361120d576040516379d9727360e01b815260040160405180910390fd5b8060010154841115611242576001810154604051634e5d1d7160e11b8152600481019190915260248101859052604401610830565b600061124f8633876106e6565b90506112618484846004015484611964565b61127e57604051637b0ddadb60e01b815260040160405180910390fd5b60008583600301546112909190611c86565b905082600201548111156112b757604051635c1718d360e01b815260040160405180910390fd5b6000866009546112c79190611c86565b90506008548111156112ec576040516326c1025360e01b815260040160405180910390fd5b600088815260056020908152604080832033808552925291829020805460ff191660011790556003860184905560098390559051630357371d60e01b81526004810191909152602481018890527f000000000000000000000000b7f11392542aceedb11dbef3b84064079e979a716001600160a01b031690630357371d90604401600060405180830381600087803b15801561138757600080fd5b505af115801561139b573d6000803e3d6000fd5b5050604080518a8152602081018690529081018490523392508a91507f3c883b8d82099521701353cd20a52a3b88dbf0209de8a8028a0f0cccd9484f0a9060600160405180910390a35050505061141160017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b50505050565b6106e3670de0b6b3a7640000632faf0800611c31565b7f00000000000000000000000000000000000000000000000000000000000000c081106114705760405163685861c560e11b815260048101829052602401610830565b50565b6000826000036114965760405163024f8f8d60e61b815260040160405180910390fd5b8282106114b657604051636a6a59a160e11b815260040160405180910390fd5b60006114c28486611c5e565b905060006114d08587611c72565b90508084106114e05760006114e3565b60015b6114f09060ff1683611c86565b9695505050505050565b61150261197c565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b039091168152602001611148565b60005460ff16156108415760405163d93c066560e01b815260040160405180910390fd5b7f000000000000000000000000b7f11392542aceedb11dbef3b84064079e979a716001600160a01b031663158ef93e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ed9190611caf565b158061168c5750306001600160a01b03167f000000000000000000000000b7f11392542aceedb11dbef3b84064079e979a716001600160a01b031663618168326040518163ffffffff1660e01b8152600401602060405180830381865afa15801561165c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116809190611cd1565b6001600160a01b031614155b1561084157604051631b1465cf60e11b815260040160405180910390fd5b6000610caa61019083611c5e565b60008181526004602052604090206116f07f000000000000000000000000000000000000000000000000000000000000000c83611c5e565b81546001830154600284015485927f241dfe871a81ff176d033aa29a4b30725a6e8d921ae920e7e8aff141f1e3bec392909161172c8184611cee565b6006880154600489015460058a015460408051978852602088019690965294860193909352606085019190915263ffffffff16608084015260a083015260c082015260e00160405180910390a35050565b611785611547565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861152f3390565b60008260028111156117ce576117ce611c99565b0361181e576001546001600160a01b03828116911614806117fc57506002546001600160a01b038281169116145b1561181a5760405163fbec30d160e01b815260040160405180910390fd5b5050565b600182600281111561183257611832611c99565b03611881576000546001600160a01b038281166101009092041614806117fc57506002546001600160a01b0382811691160361181a5760405163fbec30d160e01b815260040160405180910390fd5b6000546001600160a01b038281166101009092041614806117fc57506001546001600160a01b0382811691160361181a5760405163fbec30d160e01b815260040160405180910390fd5b6000808260028111156118e0576118e0611c99565b036118fb57505060005461010090046001600160a01b031690565b600182600281111561190f5761190f611c99565b036119255750506001546001600160a01b031690565b50506002546001600160a01b031690565b61193e61199f565b60027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b6000826119728686856119e1565b1495945050505050565b60005460ff1661084157604051638dfc202b60e01b815260040160405180910390fd5b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005460020361084157604051633ee5aeb560e01b815260040160405180910390fd5b600081815b84811015611a1a57611a1082878784818110611a0457611a04611d01565b90506020020135611a23565b91506001016119e6565b50949350505050565b6000818310611a3f576000828152602084905260409020611a4e565b60008381526020839052604090205b9392505050565b6001600160a01b038116811461147057600080fd5b600080600060608486031215611a7f57600080fd5b833592506020840135611a9181611a55565b929592945050506040919091013590565b600060208284031215611ab457600080fd5b5035919050565b600080600080600060a08688031215611ad357600080fd5b853594506020860135935060408601359250606086013563ffffffff81168114611afc57600080fd5b949793965091946080013592915050565b60008060408385031215611b2057600080fd5b823591506020830135611b3281611a55565b809150509250929050565b803560038110611b4c57600080fd5b919050565b600060208284031215611b6357600080fd5b611a4e82611b3d565b60008060408385031215611b7f57600080fd5b611b8883611b3d565b91506020830135611b3281611a55565b60008060008060608587031215611bae57600080fd5b8435935060208501359250604085013567ffffffffffffffff80821115611bd457600080fd5b818701915087601f830112611be857600080fd5b813581811115611bf757600080fd5b8860208260051b8501011115611c0c57600080fd5b95989497505060200194505050565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610caa57610caa611c1b565b634e487b7160e01b600052601260045260246000fd5b600082611c6d57611c6d611c48565b500490565b600082611c8157611c81611c48565b500690565b80820180821115610caa57610caa611c1b565b634e487b7160e01b600052602160045260246000fd5b600060208284031215611cc157600080fd5b81518015158114611a4e57600080fd5b600060208284031215611ce357600080fd5b8151611a4e81611a55565b81810381811115610caa57610caa611c1b565b634e487b7160e01b600052603260045260246000fdfea164736f6c6343000818000a