Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- DeployEqualTestnet
- Optimization enabled
- false
- Compiler version
- v0.8.24+commit.e11b9ed9
- EVM Version
- Verified at
- 2026-09-19T09:36:49.110522Z
Constructor Arguments
000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000006aae491f0000000000000000000000000000000000000000000000000000000000000e1000000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad9000000000000000000000000fe4a6b0c5c0792ebac17119625e913740941b722000000000000000000000000b94b5616d1afb26723cb6a9c0ca1a71d2ea138e700000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad90000000000000000000000008d928fbfa56b5e523fa888dd9cfbcc54a24bf40500000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad900000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad900000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad9
script/DeployEqualTestnet.s.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { Equal } from "../src/Equal.sol";
import { EqualAllocationVault } from "../src/EqualAllocationVault.sol";
import { EqualEmissionController } from "../src/EqualEmissionController.sol";
import { EqualScoreAdapter } from "../src/EqualScoreAdapter.sol";
/// @title EQUAL Testnet Deployment
/// @notice Atomic deployment tool for the bounded EQUAL contract graph.
/// @dev Testnet architecture only. This contract is not production protocol
/// runtime and conveys no production-launch authority.
///
/// authorities indexes:
/// 0 governance
/// 1 emission
/// 2 pause guardian
/// 3 POL release
/// 4 Treasury/Security release
/// 5 ecosystem release
/// 6 market/exchange release
/// 7 contributor release
contract DeployEqualTestnet {
uint256 public constant AUTHORITY_COUNT = 8;
bytes32 public constant DEPLOYMENT_ACTION = keccak256("VITALITY_EQUAL_TESTNET_DEPLOYMENT_V1");
uint256 public immutable epochsPerYear;
uint256 public immutable programmeStartTimestamp;
uint256 public immutable epochDurationSeconds;
EqualAllocationVault public emissionVault;
EqualAllocationVault public polVault;
EqualAllocationVault public treasurySecurityVault;
EqualAllocationVault public ecosystemVault;
EqualAllocationVault public marketExchangeVault;
EqualAllocationVault public contributorVault;
Equal public equal;
EqualScoreAdapter public scoreAdapter;
EqualEmissionController public emissionController;
address[AUTHORITY_COUNT] private _authorities;
error EqualTestnetZeroEpochsPerYear();
error EqualTestnetZeroEpochDuration();
error EqualTestnetZeroAuthority(uint256 authorityIndex);
error EqualTestnetAuthorityIsDeploymentContract(uint256 authorityIndex);
error EqualTestnetCriticalAuthorityCollision();
error EqualTestnetGovernanceTreasuryCollision();
error EqualTestnetAuthorityIndexOutOfRange(uint256 authorityIndex);
constructor(
uint256 epochsPerYear_,
uint256 programmeStartTimestamp_,
uint256 epochDurationSeconds_,
address[AUTHORITY_COUNT] memory authorities_
) {
_validateConfiguration(epochsPerYear_, epochDurationSeconds_);
_validateAuthorities(authorities_);
epochsPerYear = epochsPerYear_;
programmeStartTimestamp = programmeStartTimestamp_;
epochDurationSeconds = epochDurationSeconds_;
_storeAuthorities(authorities_);
_deployVaults();
_deployEqual();
_deployScoreAdapter();
_deployEmissionController();
_initializeVaults();
_assertCanonicalDeployment();
}
function authority(
uint256 authorityIndex
) external view returns (address) {
if (authorityIndex >= AUTHORITY_COUNT) {
revert EqualTestnetAuthorityIndexOutOfRange(authorityIndex);
}
return _authorities[authorityIndex];
}
function deploymentDigest() external view returns (bytes32) {
bytes32 contractsHash = _contractsHash();
bytes32 parametersHash =
keccak256(abi.encode(epochsPerYear, programmeStartTimestamp, epochDurationSeconds));
bytes32 authoritiesHash = keccak256(abi.encode(_authorities));
return keccak256(
abi.encode(
DEPLOYMENT_ACTION,
block.chainid,
address(this),
contractsHash,
parametersHash,
authoritiesHash
)
);
}
function _validateConfiguration(
uint256 epochsPerYear_,
uint256 epochDurationSeconds_
) internal pure {
if (epochsPerYear_ == 0) {
revert EqualTestnetZeroEpochsPerYear();
}
if (epochDurationSeconds_ == 0) {
revert EqualTestnetZeroEpochDuration();
}
}
function _validateAuthorities(
address[AUTHORITY_COUNT] memory authorities_
) internal view {
for (uint256 i = 0; i < AUTHORITY_COUNT; ++i) {
if (authorities_[i] == address(0)) {
revert EqualTestnetZeroAuthority(i);
}
if (authorities_[i] == address(this)) {
revert EqualTestnetAuthorityIsDeploymentContract(i);
}
}
if (
authorities_[0] == authorities_[1] || authorities_[0] == authorities_[2]
|| authorities_[1] == authorities_[2]
) {
revert EqualTestnetCriticalAuthorityCollision();
}
if (authorities_[0] == authorities_[4]) {
revert EqualTestnetGovernanceTreasuryCollision();
}
}
function _storeAuthorities(
address[AUTHORITY_COUNT] memory authorities_
) internal {
for (uint256 i = 0; i < AUTHORITY_COUNT; ++i) {
_authorities[i] = authorities_[i];
}
}
function _deployVaults() internal {
emissionVault =
new EqualAllocationVault(Equal.GenesisAllocationType.EmissionVault, address(this));
polVault = new EqualAllocationVault(
Equal.GenesisAllocationType.ProtocolOwnedLiquidity, address(this)
);
treasurySecurityVault =
new EqualAllocationVault(Equal.GenesisAllocationType.TreasurySecurity, address(this));
ecosystemVault =
new EqualAllocationVault(Equal.GenesisAllocationType.Ecosystem, address(this));
marketExchangeVault =
new EqualAllocationVault(Equal.GenesisAllocationType.MarketExchange, address(this));
contributorVault =
new EqualAllocationVault(Equal.GenesisAllocationType.Contributor, address(this));
}
function _deployEqual() internal {
equal = new Equal(
address(emissionVault),
address(polVault),
address(treasurySecurityVault),
address(ecosystemVault),
address(marketExchangeVault),
address(contributorVault)
);
}
function _deployScoreAdapter() internal {
scoreAdapter = new EqualScoreAdapter();
}
function _deployEmissionController() internal {
emissionController = new EqualEmissionController(
emissionVault,
epochsPerYear,
programmeStartTimestamp,
epochDurationSeconds,
_authorities[0],
_authorities[1],
_authorities[2]
);
}
function _initializeVaults() internal {
emissionVault.initialize(equal, address(emissionController));
polVault.initialize(equal, _authorities[3]);
treasurySecurityVault.initialize(equal, _authorities[4]);
ecosystemVault.initialize(equal, _authorities[5]);
marketExchangeVault.initialize(equal, _authorities[6]);
contributorVault.initialize(equal, _authorities[7]);
}
function _assertCanonicalDeployment() internal view {
assert(equal.totalSupply() == equal.MAX_SUPPLY());
assert(equal.balanceOf(address(emissionVault)) == equal.EMISSION_VAULT_ALLOCATION());
assert(equal.balanceOf(address(polVault)) == equal.POL_ALLOCATION());
assert(
equal.balanceOf(address(treasurySecurityVault)) == equal.TREASURY_SECURITY_ALLOCATION()
);
assert(equal.balanceOf(address(ecosystemVault)) == equal.ECOSYSTEM_ALLOCATION());
assert(equal.balanceOf(address(marketExchangeVault)) == equal.MARKET_EXCHANGE_ALLOCATION());
assert(equal.balanceOf(address(contributorVault)) == equal.CONTRIBUTOR_ALLOCATION());
}
function _contractsHash() internal view returns (bytes32) {
bytes32 vaultHash = keccak256(
abi.encode(
address(emissionVault),
address(polVault),
address(treasurySecurityVault),
address(ecosystemVault),
address(marketExchangeVault),
address(contributorVault)
)
);
return keccak256(
abi.encode(
address(equal), address(scoreAdapter), address(emissionController), vaultHash
)
);
}
}
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];
}
}
}
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/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/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/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/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/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/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/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/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/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);
}
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/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/EqualScoreAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
/// @title EQUAL Equilibrium Score Adapter
/// @notice Deterministic fixed-point implementation of the canonical
/// V / C / R / X Equilibrium score.
/// @dev Governed caps are explicit inputs rather than hidden mutable defaults.
/// The adapter has no mint, Treasury, emission or generic admin authority.
contract EqualScoreAdapter {
uint256 public constant WAD = 1e18;
uint256 public constant MAX_RELIC_POINTS = 14;
uint256 public constant QUALIFIED_MULTIPLIER_WAD = 1_100_000_000_000_000_000;
bytes32 public constant SCORE_ACTION = keccak256("VITALITY_EQUAL_EQUILIBRIUM_SCORE_V1");
struct GovernedParameters {
uint256 vtyCap;
uint256 durationCap;
uint256 chiCap;
}
struct ScoreInputs {
uint256 vtyCharged;
uint256 chargingDuration;
uint256 chiUsed90d;
uint256 relicPoints;
uint256 activityH;
uint256 activityA;
bool qualifiedSubscriber;
}
struct ScoreBreakdown {
uint256 v;
uint256 c;
uint256 r;
uint256 x;
uint256 baseScore;
uint256 multiplier;
uint256 finalScore;
}
error EqualScoreZeroVTYCap();
error EqualScoreZeroDurationCap();
error EqualScoreZeroCHICap();
error EqualScoreRelicPointsOutOfRange(uint256 relicPoints);
error EqualScoreActivityHOutOfRange(uint256 activityH);
error EqualScoreActivityAOutOfRange(uint256 activityA);
error EqualScoreZeroWallet();
error EqualScoreInvariantViolation();
function parameterHash(
GovernedParameters calldata parameters
) external pure returns (bytes32) {
return _parameterHash(parameters);
}
function inputHash(
ScoreInputs calldata inputs
) external pure returns (bytes32) {
return _inputHash(inputs);
}
function commitmentComponent(
uint256 vtyCharged,
uint256 vtyCap,
uint256 chargingDuration,
uint256 durationCap
) public pure returns (uint256) {
if (vtyCap == 0) {
revert EqualScoreZeroVTYCap();
}
if (durationCap == 0) {
revert EqualScoreZeroDurationCap();
}
uint256 vtyRatio = _normalisedRatio(vtyCharged, vtyCap);
uint256 durationRatio = _normalisedRatio(chargingDuration, durationCap);
uint256 vtyRoot = _sqrtWad(vtyRatio);
uint256 durationRoot = _sqrtWad(durationRatio);
return _wadMul(vtyRoot, durationRoot);
}
function chiComponent(
uint256 chiUsed90d,
uint256 chiCap
) public pure returns (uint256) {
if (chiCap == 0) {
revert EqualScoreZeroCHICap();
}
return _sqrtWad(_normalisedRatio(chiUsed90d, chiCap));
}
function relicComponent(
uint256 relicPoints
) public pure returns (uint256) {
if (relicPoints > MAX_RELIC_POINTS) {
revert EqualScoreRelicPointsOutOfRange(relicPoints);
}
return Math.mulDiv(relicPoints, WAD, MAX_RELIC_POINTS);
}
function activityComponent(
uint256 activityH,
uint256 activityA
) public pure returns (uint256) {
if (activityH > WAD) {
revert EqualScoreActivityHOutOfRange(activityH);
}
if (activityA > WAD) {
revert EqualScoreActivityAOutOfRange(activityA);
}
return Math.mulDiv(activityH, 4, 10) + Math.mulDiv(activityA, 6, 10);
}
function calculate(
GovernedParameters calldata parameters,
ScoreInputs calldata inputs
) external pure returns (ScoreBreakdown memory) {
return _calculate(parameters, inputs);
}
function scoreCommitment(
uint256 epochId,
address wallet,
GovernedParameters calldata parameters,
ScoreInputs calldata inputs
) external view returns (bytes32 commitment, ScoreBreakdown memory breakdown) {
if (wallet == address(0)) {
revert EqualScoreZeroWallet();
}
breakdown = _calculate(parameters, inputs);
commitment = keccak256(
abi.encode(
SCORE_ACTION,
block.chainid,
address(this),
epochId,
wallet,
_parameterHash(parameters),
_inputHash(inputs),
breakdown.finalScore
)
);
}
function _calculate(
GovernedParameters memory parameters,
ScoreInputs memory inputs
) internal pure returns (ScoreBreakdown memory result) {
uint256 v = commitmentComponent(
inputs.vtyCharged, parameters.vtyCap, inputs.chargingDuration, parameters.durationCap
);
uint256 c = chiComponent(inputs.chiUsed90d, parameters.chiCap);
uint256 r = relicComponent(inputs.relicPoints);
uint256 x = activityComponent(inputs.activityH, inputs.activityA);
uint256 baseScore = _weightedBaseScore(v, c, r, x);
uint256 multiplier = inputs.qualifiedSubscriber ? QUALIFIED_MULTIPLIER_WAD : WAD;
uint256 finalScore = _wadMul(baseScore, multiplier);
if (
v > WAD || c > WAD || r > WAD || x > WAD || baseScore > WAD
|| finalScore > QUALIFIED_MULTIPLIER_WAD
) {
revert EqualScoreInvariantViolation();
}
result = ScoreBreakdown({
v: v,
c: c,
r: r,
x: x,
baseScore: baseScore,
multiplier: multiplier,
finalScore: finalScore
});
}
function _parameterHash(
GovernedParameters memory parameters
) internal pure returns (bytes32) {
return keccak256(abi.encode(parameters.vtyCap, parameters.durationCap, parameters.chiCap));
}
function _inputHash(
ScoreInputs memory inputs
) internal pure returns (bytes32) {
return keccak256(
abi.encode(
inputs.vtyCharged,
inputs.chargingDuration,
inputs.chiUsed90d,
inputs.relicPoints,
inputs.activityH,
inputs.activityA,
inputs.qualifiedSubscriber
)
);
}
/// @dev
/// BaseScore =
/// V^(7/20) * C^(6/20) * R^(4/20) * X^(3/20)
///
/// This is exactly:
/// V^0.35 * C^0.30 * R^0.20 * X^0.15
function _weightedBaseScore(
uint256 v,
uint256 c,
uint256 r,
uint256 x
) internal pure returns (uint256) {
if (v == 0 || c == 0 || r == 0 || x == 0) {
return 0;
}
uint256 product = _wadPow(v, 7);
product = _wadMul(product, _wadPow(c, 6));
product = _wadMul(product, _wadPow(r, 4));
product = _wadMul(product, _wadPow(x, 3));
return _wadNthRoot(product, 20);
}
function _normalisedRatio(
uint256 amount,
uint256 cap
) internal pure returns (uint256) {
if (amount >= cap) {
return WAD;
}
return Math.mulDiv(amount, WAD, cap);
}
function _sqrtWad(
uint256 value
) internal pure returns (uint256) {
if (value == 0) {
return 0;
}
return Math.sqrt(value * WAD);
}
function _wadMul(
uint256 a,
uint256 b
) internal pure returns (uint256) {
return Math.mulDiv(a, b, WAD);
}
function _wadPow(
uint256 base,
uint256 exponent
) internal pure returns (uint256 result) {
result = WAD;
while (exponent > 0) {
if ((exponent & 1) == 1) {
result = _wadMul(result, base);
}
exponent >>= 1;
if (exponent > 0) {
base = _wadMul(base, base);
}
}
}
function _wadNthRoot(
uint256 value,
uint256 degree
) internal pure returns (uint256) {
if (value == 0 || value == WAD) {
return value;
}
uint256 low;
uint256 high = WAD;
while (low < high) {
uint256 mid = low + ((high - low + 1) / 2);
if (_wadPow(mid, degree) <= value) {
low = mid;
} else {
high = mid - 1;
}
}
return low;
}
}
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/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/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/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;
}
}
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);
}
}
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;
}
}
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/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
}
}
}
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;
}
}
}
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":"uint256","name":"epochsPerYear_","internalType":"uint256"},{"type":"uint256","name":"programmeStartTimestamp_","internalType":"uint256"},{"type":"uint256","name":"epochDurationSeconds_","internalType":"uint256"},{"type":"address[8]","name":"authorities_","internalType":"address[8]"}]},{"type":"error","name":"EqualTestnetAuthorityIndexOutOfRange","inputs":[{"type":"uint256","name":"authorityIndex","internalType":"uint256"}]},{"type":"error","name":"EqualTestnetAuthorityIsDeploymentContract","inputs":[{"type":"uint256","name":"authorityIndex","internalType":"uint256"}]},{"type":"error","name":"EqualTestnetCriticalAuthorityCollision","inputs":[]},{"type":"error","name":"EqualTestnetGovernanceTreasuryCollision","inputs":[]},{"type":"error","name":"EqualTestnetZeroAuthority","inputs":[{"type":"uint256","name":"authorityIndex","internalType":"uint256"}]},{"type":"error","name":"EqualTestnetZeroEpochDuration","inputs":[]},{"type":"error","name":"EqualTestnetZeroEpochsPerYear","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"AUTHORITY_COUNT","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"DEPLOYMENT_ACTION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"authority","inputs":[{"type":"uint256","name":"authorityIndex","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"contributorVault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"deploymentDigest","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"ecosystemVault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualEmissionController"}],"name":"emissionController","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"emissionVault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"epochDurationSeconds","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"epochsPerYear","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract Equal"}],"name":"equal","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"marketExchangeVault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"polVault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"programmeStartTimestamp","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualScoreAdapter"}],"name":"scoreAdapter","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract EqualAllocationVault"}],"name":"treasurySecurityVault","inputs":[]}]
Contract Creation Code
0x60e06040523480156200001157600080fd5b506040516200660e3803806200660e8339810160408190526200003491620010a8565b620000408483620000ab565b6200004b81620000f3565b608084905260a083905260c0829052620000658162000244565b6200006f620002a9565b62000079620004f0565b62000083620005a7565b6200008d620005f5565b62000097620006ae565b620000a162000945565b50505050620011d9565b81600003620000cd576040516350ae75e760e11b815260040160405180910390fd5b80600003620000ef576040516313c1f78560e11b815260040160405180910390fd5b5050565b60005b60088110156200019c57600082826008811062000117576200011762001158565b60200201516001600160a01b0316036200014c5760405163af7829f760e01b8152600481018290526024015b60405180910390fd5b3082826008811062000162576200016262001158565b60200201516001600160a01b031603620001935760405163b4481d9760e01b81526004810182905260240162000143565b600101620000f6565b50602081015181516001600160a01b0390811691161480620001cf5750604081015181516001600160a01b039081169116145b80620001ef5750604081015160208201516001600160a01b039081169116145b156200020e57604051635e748cad60e01b815260040160405180910390fd5b608081015181516001600160a01b039182169116036200024157604051632c98cf1560e11b815260040160405180910390fd5b50565b60005b6008811015620000ef5781816008811062000266576200026662001158565b60200201516009826008811062000281576200028162001158565b0180546001600160a01b0319166001600160a01b039290921691909117905560010162000247565b600030604051620002ba906200103d565b620002c79291906200116e565b604051809103906000f080158015620002e4573d6000803e3d6000fd5b506000806101000a8154816001600160a01b0302191690836001600160a01b031602179055506001306040516200031b906200103d565b620003289291906200116e565b604051809103906000f08015801562000345573d6000803e3d6000fd5b50600160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506002306040516200037d906200103d565b6200038a9291906200116e565b604051809103906000f080158015620003a7573d6000803e3d6000fd5b50600260006101000a8154816001600160a01b0302191690836001600160a01b03160217905550600330604051620003df906200103d565b620003ec9291906200116e565b604051809103906000f08015801562000409573d6000803e3d6000fd5b50600360006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060043060405162000441906200103d565b6200044e9291906200116e565b604051809103906000f0801580156200046b573d6000803e3d6000fd5b50600460006101000a8154816001600160a01b0302191690836001600160a01b03160217905550600530604051620004a3906200103d565b620004b09291906200116e565b604051809103906000f080158015620004cd573d6000803e3d6000fd5b50600580546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001546002546003546004546005546040516001600160a01b0396871696958616959485169493841693928316929091169062000530906200104b565b6001600160a01b0396871681529486166020860152928516604085015290841660608401528316608083015290911660a082015260c001604051809103906000f08015801562000584573d6000803e3d6000fd5b50600680546001600160a01b0319166001600160a01b0392909216919091179055565b604051620005b59062001059565b604051809103906000f080158015620005d2573d6000803e3d6000fd5b50600780546001600160a01b0319166001600160a01b0392909216919091179055565b60005460805160a05160c051600954600a54600b546040516001600160a01b0397881697938416939283169290911690620006309062001067565b6001600160a01b03978816815260208101969096526040860194909452606085019290925284166080840152831660a083015290911660c082015260e001604051809103906000f0801580156200068b573d6000803e3d6000fd5b50600880546001600160a01b0319166001600160a01b0392909216919091179055565b60005460065460085460405163485cc95560e01b81526001600160a01b039283166004820152908216602482015291169063485cc95590604401600060405180830381600087803b1580156200070357600080fd5b505af115801562000718573d6000803e3d6000fd5b5050600154600654600c5460405163485cc95560e01b81526001600160a01b03928316600482015290821660248201529116925063485cc9559150604401600060405180830381600087803b1580156200077157600080fd5b505af115801562000786573d6000803e3d6000fd5b5050600254600654600d5460405163485cc95560e01b81526001600160a01b03928316600482015290821660248201529116925063485cc9559150604401600060405180830381600087803b158015620007df57600080fd5b505af1158015620007f4573d6000803e3d6000fd5b5050600354600654600e5460405163485cc95560e01b81526001600160a01b03928316600482015290821660248201529116925063485cc9559150604401600060405180830381600087803b1580156200084d57600080fd5b505af115801562000862573d6000803e3d6000fd5b505060048054600654600f5460405163485cc95560e01b81526001600160a01b03928316948101949094528116602484015216925063485cc9559150604401600060405180830381600087803b158015620008bc57600080fd5b505af1158015620008d1573d6000803e3d6000fd5b505060055460065460105460405163485cc95560e01b81526001600160a01b03928316600482015290821660248201529116925063485cc9559150604401600060405180830381600087803b1580156200092a57600080fd5b505af11580156200093f573d6000803e3d6000fd5b50505050565b600660009054906101000a90046001600160a01b03166001600160a01b03166332cb6b0c6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000999573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620009bf9190620011a9565b600660009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000a13573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000a399190620011a9565b1462000a495762000a49620011c3565b600660009054906101000a90046001600160a01b03166001600160a01b031663ce5349996040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000a9d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000ac39190620011a9565b6006546000546040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa15801562000b10573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000b369190620011a9565b1462000b465762000b46620011c3565b600660009054906101000a90046001600160a01b03166001600160a01b03166398c57e386040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000b9a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000bc09190620011a9565b6006546001546040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa15801562000c0d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000c339190620011a9565b1462000c435762000c43620011c3565b600660009054906101000a90046001600160a01b03166001600160a01b0316635af70b726040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000c97573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000cbd9190620011a9565b6006546002546040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa15801562000d0a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000d309190620011a9565b1462000d405762000d40620011c3565b600660009054906101000a90046001600160a01b03166001600160a01b03166390534f246040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000d94573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000dba9190620011a9565b6006546003546040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa15801562000e07573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000e2d9190620011a9565b1462000e3d5762000e3d620011c3565b600660009054906101000a90046001600160a01b03166001600160a01b0316630c5feabf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000e91573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000eb79190620011a9565b600654600480546040516370a0823160e01b81526001600160a01b0391821692810192909252909116906370a0823190602401602060405180830381865afa15801562000f08573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000f2e9190620011a9565b1462000f3e5762000f3e620011c3565b600660009054906101000a90046001600160a01b03166001600160a01b0316638bf241a96040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000f92573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000fb89190620011a9565b6006546005546040516370a0823160e01b81526001600160a01b0391821660048201529116906370a0823190602401602060405180830381865afa15801562001005573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200102b9190620011a9565b146200103b576200103b620011c3565b565b610de7806200175e83390190565b611004806200254583390190565b610ea8806200354983390190565b61221d80620043f183390190565b634e487b7160e01b600052604160045260246000fd5b80516001600160a01b0381168114620010a357600080fd5b919050565b600080600080610160808688031215620010c157600080fd5b8551945060208087015194506040870151935087607f880112620010e457600080fd5b60405161010081016001600160401b03811182821017156200110a576200110a62001075565b6040529187019180898411156200112057600080fd5b606089015b84811015620011475762001139816200108b565b825290830190830162001125565b505080935050505092959194509250565b634e487b7160e01b600052603260045260246000fd5b60408101600684106200119157634e487b7160e01b600052602160045260246000fd5b9281526001600160a01b039190911660209091015290565b600060208284031215620011bc57600080fd5b5051919050565b634e487b7160e01b600052600160045260246000fd5b60805160a05160c0516105406200121e600039600081816101d701526103f301526000818161010a01526103cb0152600081816101b001526103a501526105406000f3fe608060405234801561001057600080fd5b50600436106101005760003560e01c80635fc89f69116100975780636dee2012116100665780636dee201214610259578063c5af220b1461026c578063d36d42c91461027f578063e82ec8931461029257600080fd5b80635fc89f69146101f95780636575f9001461020c5780636717699a146102335780636dbb02d51461024657600080fd5b80632c1e6193116100d35780632c1e619314610185578063386f97d41461019857806348999128146101ab57806356d9bcf3146101d257600080fd5b806312e8e01c14610105578063168687c41461013f5780631e228514146101475780631f7c850214610172575b600080fd5b61012c7f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020015b60405180910390f35b61012c600881565b60065461015a906001600160a01b031681565b6040516001600160a01b039091168152602001610136565b60005461015a906001600160a01b031681565b60075461015a906001600160a01b031681565b60035461015a906001600160a01b031681565b61012c7f000000000000000000000000000000000000000000000000000000000000000081565b61012c7f000000000000000000000000000000000000000000000000000000000000000081565b60045461015a906001600160a01b031681565b61012c7fb49f1dad082945466755042294bc3d0c0993bb056210b8e6c416c5d546cbb64381565b60055461015a906001600160a01b031681565b60025461015a906001600160a01b031681565b60085461015a906001600160a01b031681565b61015a61027a3660046104c9565b61029a565b60015461015a906001600160a01b031681565b61012c6102e8565b6000600882106102c45760405163224763ef60e01b81526004810183905260240160405180910390fd5b600982600881106102d7576102d76104e2565b01546001600160a01b031692915050565b60008061039f600054600154600254600354600454600554604080516001600160a01b03978816602080830191909152968816818301529487166060860152928616608085015290851660a0840152841660c0808401919091528151808403909101815260e083018252805190840120600654600754600854918716610100860152861661012085015290941661014083015261016080830194909452805180830390940184526101809091019052815191012090565b604080517f000000000000000000000000000000000000000000000000000000000000000060208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201529091506000906080016040516020818303038152906040528051906020012090506000600960405160200161044c91906104f8565b60408051808303601f1901815282825280516020918201207fb49f1dad082945466755042294bc3d0c0993bb056210b8e6c416c5d546cbb643828501524684840152306060850152608084019690965260a083019490945260c0808301959095528051808303909501855260e09091019052508151910120919050565b6000602082840312156104db57600080fd5b5035919050565b634e487b7160e01b600052603260045260246000fd5b6101008101818360005b600881101561052a5781546001600160a01b0316835260209092019160019182019101610502565b5050509291505056fea164736f6c6343000818000a60e06040523480156200001157600080fd5b5060405162000de738038062000de78339810160408190526200003491620001d4565b6001600160a01b0381166200005c57604051637661d82960e11b815260040160405180910390fd5b81600581111562000071576200007162000221565b608081600581111562000088576200008862000221565b9052506200009682620000ac565b60a0526001600160a01b031660c052506200025d565b600080826005811115620000c457620000c462000221565b03620000e857620000e2670de0b6b3a7640000632faf080062000237565b92915050565b6001826005811115620000ff57620000ff62000221565b036200011d57620000e2670de0b6b3a7640000630393870062000237565b600282600581111562000134576200013462000221565b036200015257620000e2670de0b6b3a76400006302625a0062000237565b600382600581111562000169576200016962000221565b036200018757620000e2670de0b6b3a76400006302625a0062000237565b60048260058111156200019e576200019e62000221565b03620001bc57620000e2670de0b6b3a76400006301c9c38062000237565b620000e2670de0b6b3a76400006301c9c38062000237565b60008060408385031215620001e857600080fd5b825160068110620001f857600080fd5b60208401519092506001600160a01b03811681146200021657600080fd5b809150509250929050565b634e487b7160e01b600052602160045260246000fd5b8082028115828204841417620000e257634e487b7160e01b600052601160045260246000fd5b60805160a05160c051610b0d620002da60003960008181610246015281816104cb015261057f0152600081816101900152818161032c01528181610361015281816104150152818161047c015281816107c2015281816107f6015261089e015260008181610203015281816103bc01526108690152610b0d6000f3fe608060405234801561001057600080fd5b50600436106101165760003560e01c806355f8aec8116100a2578063a5aa94ac11610071578063a5aa94ac146101fe578063a5c9cd8214610232578063ce29a7f914610241578063e3de54ea14610130578063fc0c546a1461026857600080fd5b806355f8aec8146101b257806361816832146101c25780639437e77c146101ed57806396132521146101f557600080fd5b806343f541da116100e957806343f541da14610170578063485cc95514610178578063504e49561461018b578063519b6aa3146101b257806352a7397e146101ba57600080fd5b80630357371d1461011b57806304d2e66a14610130578063158ef93e1461014b5780633dc9dc9c14610168575b600080fd5b61012e6101293660046109eb565b61027b565b005b61013861045c565b6040519081526020015b60405180910390f35b6003546101589060ff1681565b6040519015158152602001610142565b610138610475565b6101386104aa565b61012e610186366004610a17565b6104c0565b6101387f000000000000000000000000000000000000000000000000000000000000000081565b6101386108f1565b610138610907565b6001546101d5906001600160a01b031681565b6040516001600160a01b039091168152602001610142565b61013861091d565b61013860025481565b6102257f000000000000000000000000000000000000000000000000000000000000000081565b6040516101429190610a66565b610138670de0b6b3a764000081565b6101d57f000000000000000000000000000000000000000000000000000000000000000081565b6000546101d5906001600160a01b031681565b60035460ff1661029e576040516312c49eeb60e31b815260040160405180910390fd5b6001546001600160a01b031633146102d05760405163029ce6a360e51b81523360048201526024015b60405180910390fd5b6001600160a01b0382166102f75760405163fbcf44f560e01b815260040160405180910390fd5b806000036103185760405163b52f3b1560e01b815260040160405180910390fd5b6000816002546103289190610aa4565b90507f00000000000000000000000000000000000000000000000000000000000000008111156103945760405163bcb70de160e01b81527f00000000000000000000000000000000000000000000000000000000000000006004820152602481018290526044016102c7565b60028190556000546103b0906001600160a01b03168484610933565b826001600160a01b03167f000000000000000000000000000000000000000000000000000000000000000060058111156103ec576103ec610a50565b7ffa7a1e7b3ffe7bce69aa23e2ea09dd054df2629423087bc840d9376012659ecd8484610439817f0000000000000000000000000000000000000000000000000000000000000000610abd565b6040805193845260208401929092529082015260600160405180910390a3505050565b610472670de0b6b3a76400006301c9c380610ad0565b81565b60006002547f00000000000000000000000000000000000000000000000000000000000000006104a59190610abd565b905090565b610472670de0b6b3a76400006303938700610ad0565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461050b57604051634535ac7960e01b81523360048201526024016102c7565b60035460ff161561052f57604051635a1886cf60e11b815260040160405180910390fd5b6001600160a01b03821661055657604051638b707fe160e01b815260040160405180910390fd5b6001600160a01b03811661057d576040516309b110a160e41b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316816001600160a01b0316036105cf5760405163428849e160e01b815260040160405180910390fd5b6105e5670de0b6b3a7640000633b9aca00610ad0565b826001600160a01b03166332cb6b0c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610623573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106479190610ae7565b1415806106ca5750610665670de0b6b3a7640000633b9aca00610ad0565b826001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106a3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106c79190610ae7565b14155b806107355750816001600160a01b031663a098cbe56040518163ffffffff1660e01b8152600401602060405180830381865afa15801561070e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107329190610ae7565b15155b156107535760405163103365d160e11b815260040160405180910390fd5b6040516370a0823160e01b81523060048201526000906001600160a01b038416906370a0823190602401602060405180830381865afa15801561079a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107be9190610ae7565b90507f000000000000000000000000000000000000000000000000000000000000000081146108295760405163660e894160e11b81527f00000000000000000000000000000000000000000000000000000000000000006004820152602481018290526044016102c7565b600080546001600160a01b038086166001600160a01b031992831681179093556001805491861691909216811782556003805460ff1916909217909155907f0000000000000000000000000000000000000000000000000000000000000000600581111561089957610899610a50565b6040517f000000000000000000000000000000000000000000000000000000000000000081527f9d3a364d28da4b9d25b53e4db0b337a882c69623c9790901a8ffd8c74ca711539060200160405180910390a4505050565b610472670de0b6b3a76400006302625a00610ad0565b610472670de0b6b3a7640000632faf0800610ad0565b610472670de0b6b3a7640000633b9aca00610ad0565b610940838383600161096d565b61096857604051635274afe760e01b81526001600160a01b03841660048201526024016102c7565b505050565b60405163a9059cbb60e01b60008181526001600160a01b038616600452602485905291602083604481808b5af1925060016000511483166109c75783831516156109ba573d6000823e3d81fd5b6000873b113d1516831692505b60405250949350505050565b6001600160a01b03811681146109e857600080fd5b50565b600080604083850312156109fe57600080fd5b8235610a09816109d3565b946020939093013593505050565b60008060408385031215610a2a57600080fd5b8235610a35816109d3565b91506020830135610a45816109d3565b809150509250929050565b634e487b7160e01b600052602160045260246000fd5b6020810160068310610a8857634e487b7160e01b600052602160045260246000fd5b91905290565b634e487b7160e01b600052601160045260246000fd5b80820180821115610ab757610ab7610a8e565b92915050565b81810381811115610ab757610ab7610a8e565b8082028115828204841417610ab757610ab7610a8e565b600060208284031215610af957600080fd5b505191905056fea164736f6c6343000818000a60806040523480156200001157600080fd5b506040516200100438038062001004833981016040819052620000349162000523565b6040518060400160405280600b81526020016a457175696c69627269756d60a81b81525060405180604001604052806005815260200164115455505360da1b81525081600390816200008791906200064b565b5060046200009682826200064b565b50506040805160c080820183526001600160a01b03808b16835289811660208401528881168385015287811660608401528681166080840152851660a08301528251908101909252915060009080620000fc670de0b6b3a7640000632faf08006200072d565b815260200162000119670de0b6b3a764000063039387006200072d565b815260200162000136670de0b6b3a76400006302625a006200072d565b815260200162000153670de0b6b3a76400006302625a006200072d565b815260200162000170670de0b6b3a76400006301c9c3806200072d565b81526020016200018d670de0b6b3a76400006301c9c3806200072d565b9052905060005b60068110156200035b576000838260068110620001b557620001b56200074d565b60200201516001600160a01b031603620001ec57604051636dce91f760e01b815260ff821660048201526024015b60405180910390fd5b60005b8181101562000274578381600681106200020d576200020d6200074d565b60200201516001600160a01b03168483600681106200023057620002306200074d565b60200201516001600160a01b0316036200026b57604051630cf63dcd60e21b815260ff808316600483015283166024820152604401620001e3565b600101620001ef565b50620002b38382600681106200028e576200028e6200074d565b6020020151838360068110620002a857620002a86200074d565b602002015162000395565b828160068110620002c857620002c86200074d565b60200201516001600160a01b0316816005811115620002eb57620002eb62000763565b6005811115620002ff57620002ff62000763565b7ffec867d39dd5668ed4c308e487a8dbd622b198c451738bb62f33da8bc76689318484600681106200033557620003356200074d565b60200201516040516200034a91815260200190565b60405180910390a360010162000194565b5062000374670de0b6b3a7640000633b9aca006200072d565b6002541462000387576200038762000779565b5050505050505050620007a5565b6001600160a01b038216620003c15760405163ec442f0560e01b815260006004820152602401620001e3565b620003cf60008383620003d3565b5050565b6001600160a01b03831662000402578060026000828254620003f691906200078f565b90915550620004769050565b6001600160a01b03831660009081526020819052604090205481811015620004575760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401620001e3565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b0382166200049457600280548290039055620004b3565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051620004f991815260200190565b60405180910390a3505050565b80516001600160a01b03811681146200051e57600080fd5b919050565b60008060008060008060c087890312156200053d57600080fd5b620005488762000506565b9550620005586020880162000506565b9450620005686040880162000506565b9350620005786060880162000506565b9250620005886080880162000506565b91506200059860a0880162000506565b90509295509295509295565b634e487b7160e01b600052604160045260246000fd5b600181811c90821680620005cf57607f821691505b602082108103620005f057634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111562000646576000816000526020600020601f850160051c81016020861015620006215750805b601f850160051c820191505b8181101562000642578281556001016200062d565b5050505b505050565b81516001600160401b03811115620006675762000667620005a4565b6200067f81620006788454620005ba565b84620005f6565b602080601f831160018114620006b757600084156200069e5750858301515b600019600386901b1c1916600185901b17855562000642565b600085815260208120601f198616915b82811015620006e857888601518255948401946001909101908401620006c7565b5085821015620007075787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b600052601160045260246000fd5b808202811582820484141762000747576200074762000717565b92915050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052600160045260246000fd5b8082018082111562000747576200074762000717565b61084f80620007b56000396000f3fe608060405234801561001057600080fd5b50600436106101165760003560e01c80638bf241a9116100a2578063a098cbe511610071578063a098cbe5146101e5578063a5c9cd82146101ed578063a9059cbb146101fc578063ce5349991461020f578063dd62ed3e1461021757600080fd5b80638bf241a91461015c57806390534f24146101a457806395d89b41146101d557806398c57e38146101dd57600080fd5b806323b872dd116100e957806323b872dd1461017a578063313ce5671461018d57806332cb6b0c1461019c5780635af70b72146101a457806370a08231146101ac57600080fd5b806306fdde031461011b578063095ea7b3146101395780630c5feabf1461015c57806318160ddd14610172575b600080fd5b610123610250565b60405161013091906106a2565b60405180910390f35b61014c61014736600461070d565b6102e2565b6040519015158152602001610130565b6101646102fc565b604051908152602001610130565b600254610164565b61014c610188366004610737565b610315565b60405160128152602001610130565b610164610339565b61016461034f565b6101646101ba366004610773565b6001600160a01b031660009081526020819052604090205490565b610123610365565b610164610374565b610164600081565b610164670de0b6b3a764000081565b61014c61020a36600461070d565b61038a565b610164610398565b610164610225366004610795565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60606003805461025f906107c8565b80601f016020809104026020016040519081016040528092919081815260200182805461028b906107c8565b80156102d85780601f106102ad576101008083540402835291602001916102d8565b820191906000526020600020905b8154815290600101906020018083116102bb57829003601f168201915b5050505050905090565b6000336102f08185856103ae565b60019150505b92915050565b610312670de0b6b3a76400006301c9c380610818565b81565b6000336103238582856103c0565b61032e858585610444565b506001949350505050565b610312670de0b6b3a7640000633b9aca00610818565b610312670de0b6b3a76400006302625a00610818565b60606004805461025f906107c8565b610312670de0b6b3a76400006303938700610818565b6000336102f0818585610444565b610312670de0b6b3a7640000632faf0800610818565b6103bb83838360016104a3565b505050565b6001600160a01b0383811660009081526001602090815260408083209386168352929052205460001981101561043e578181101561042f57604051637dc7a0d960e11b81526001600160a01b038416600482015260248101829052604481018390526064015b60405180910390fd5b61043e848484840360006104a3565b50505050565b6001600160a01b03831661046e57604051634b637e8f60e11b815260006004820152602401610426565b6001600160a01b0382166104985760405163ec442f0560e01b815260006004820152602401610426565b6103bb838383610578565b6001600160a01b0384166104cd5760405163e602df0560e01b815260006004820152602401610426565b6001600160a01b0383166104f757604051634a1406b160e11b815260006004820152602401610426565b6001600160a01b038085166000908152600160209081526040808320938716835292905220829055801561043e57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161056a91815260200190565b60405180910390a350505050565b6001600160a01b0383166105a3578060026000828254610598919061082f565b909155506106159050565b6001600160a01b038316600090815260208190526040902054818110156105f65760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401610426565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b03821661063157600280548290039055610650565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161069591815260200190565b60405180910390a3505050565b60006020808352835180602085015260005b818110156106d0578581018301518582016040015282016106b4565b506000604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b038116811461070857600080fd5b919050565b6000806040838503121561072057600080fd5b610729836106f1565b946020939093013593505050565b60008060006060848603121561074c57600080fd5b610755846106f1565b9250610763602085016106f1565b9150604084013590509250925092565b60006020828403121561078557600080fd5b61078e826106f1565b9392505050565b600080604083850312156107a857600080fd5b6107b1836106f1565b91506107bf602084016106f1565b90509250929050565b600181811c908216806107dc57607f821691505b6020821081036107fc57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176102f6576102f6610802565b808201808211156102f6576102f661080256fea164736f6c6343000818000a608060405234801561001057600080fd5b50610e88806100206000396000f3fe608060405234801561001057600080fd5b50600436106100b45760003560e01c80638a39d789116100715780638a39d7891461014e5780638f5570b91461016f578063ab56a70d1461017e578063be3778e914610191578063c8288fac146101a4578063ce7a93a8146101ac57600080fd5b80631491f9ca146100b95780631716cdd9146100df578063306ffefa146101065780633fb8899914610119578063622a01031461012c5780636a1460241461013f575b600080fd5b6100cc6100c7366004610b16565b6101cc565b6040519081526020015b60405180910390f35b6100cc7fbcace4a7617e51a431fb9661a1fe7bf77592fa0ab0a4cb1b4f9becf1e042a2c081565b6100cc610114366004610b48565b61025f565b6100cc610127366004610b82565b6102eb565b6100cc61013a366004610bb0565b610304565b6100cc670de0b6b3a764000081565b61016161015c366004610bcc565b61031d565b6040516100d6929190610c6e565b6100cc670f43fc2c04ee000081565b6100cc61018c366004610b48565b61042c565b6100cc61019f366004610c83565b610461565b6100cc600e81565b6101bf6101ba366004610c9c565b61049c565b6040516100d69190610cd2565b6000836000036101ef5760405163b897593b60e01b815260040160405180910390fd5b81600003610210576040516326ac729d60e11b815260040160405180910390fd5b600061021c86866104c5565b9050600061022a85856104c5565b90506000610237836104f0565b90506000610244836104f0565b9050610250828261051c565b9450505050505b949350505050565b6000670de0b6b3a76400008311156102925760405163608ef2e560e01b8152600481018490526024015b60405180910390fd5b670de0b6b3a76400008211156102be5760405163764a966960e01b815260048101839052602401610289565b6102cb826006600a61052d565b6102d8846004600a61052d565b6102e29190610cf6565b90505b92915050565b60006102e56102ff36849003840184610d40565b6105e3565b60006102e561031836849003840184610daf565b610656565b6000610327610ad9565b6001600160a01b03851661034e576040516318a087b760e21b815260040160405180910390fd5b61037461036036869003860186610daf565b61036f36869003860186610d40565b610683565b90507fbcace4a7617e51a431fb9661a1fe7bf77592fa0ab0a4cb1b4f9becf1e042a2c0463088886103ad610318368b90038b018b610daf565b6103bf6102ff368b90038b018b610d40565b60c08089015160408051602081019a909a528901979097526001600160a01b03958616606089015260808801949094529390911660a08601529084015260e08301526101008201526101200160405160208183030381529060405280519060200120915094509492505050565b60008160000361044f57604051630b594fb960e11b815260040160405180910390fd5b6102e261045c84846104c5565b6104f0565b6000600e82111561048857604051631f4195b960e31b815260048101839052602401610289565b6102e582670de0b6b3a7640000600e61052d565b6104a4610ad9565b6102e26104b636859003850185610daf565b61036f36859003850185610d40565b60008183106104dd5750670de0b6b3a76400006102e5565b6102e283670de0b6b3a76400008461052d565b60008160000361050257506000919050565b6102e5610517670de0b6b3a764000084610e19565b6107e8565b60006102e28383670de0b6b3a76400005b600080600061053c8686610941565b91509150816000036105615783818161055757610557610e30565b04925050506105dc565b81841161057857610578600385150260111861095f565b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150505b9392505050565b805160208083015160408085015160608087015160808089015160a0808b015160c0808d015189519b8c019c909c52978a01989098529388019490945286015284015282015290151560e0820152600090610100015b604051602081830303815290604052805190602001209050919050565b80516020808301516040808501518151938401949094528201526060810191909152600090608001610639565b61068b610ad9565b60006106a983600001518560000151856020015187602001516101cc565b905060006106bf8460400151866040015161042c565b905060006106d08560600151610461565b905060006106e686608001518760a0015161025f565b905060006106f685858585610971565b905060008760c0015161071157670de0b6b3a764000061071b565b670f43fc2c04ee00005b90506000610729838361051c565b9050670de0b6b3a76400008711806107485750670de0b6b3a764000086115b8061075a5750670de0b6b3a764000085115b8061076c5750670de0b6b3a764000084115b8061077e5750670de0b6b3a764000083115b806107905750670f43fc2c04ee000081115b156107ae57604051630d4fd56f60e01b815260040160405180910390fd5b6040805160e0810182529788526020880196909652948601939093526060850191909152608084015260a083015260c08201529392505050565b6000600182116107f6575090565b816001600160801b821061080f5760809190911c9060401b5b68010000000000000000821061082a5760409190911c9060201b5b64010000000082106108415760209190911c9060101b5b6201000082106108565760109190911c9060081b5b610100821061086a5760089190911c9060041b5b6010821061087d5760049190911c9060021b5b600482106108895760011b5b600302600190811c908185816108a1576108a1610e30565b048201901c905060018185816108b9576108b9610e30565b048201901c905060018185816108d1576108d1610e30565b048201901c905060018185816108e9576108e9610e30565b048201901c9050600181858161090157610901610e30565b048201901c9050600181858161091957610919610e30565b048201901c905061093881858161093257610932610e30565b04821190565b90039392505050565b60008060001983850993909202808410938190039390930393915050565b634e487b71600052806020526024601cfd5b600084158061097e575083155b80610987575082155b80610990575081155b1561099d57506000610257565b60006109aa8660076109f9565b90506109c0816109bb8760066109f9565b61051c565b90506109d1816109bb8660046109f9565b90506109e2816109bb8560036109f9565b90506109ef816014610a40565b9695505050505050565b670de0b6b3a76400005b81156102e55781600116600103610a2157610a1e818461051c565b90505b60019190911c908115610a3b57610a38838461051c565b92505b610a03565b6000821580610a565750670de0b6b3a764000083145b15610a625750816102e5565b6000670de0b6b3a76400005b80821015610ad15760006002610a848484610e46565b610a8f906001610cf6565b610a999190610e59565b610aa39084610cf6565b905085610ab082876109f9565b11610abd57809250610acb565b610ac8600182610e46565b91505b50610a6e565b509392505050565b6040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b60008060008060808587031215610b2c57600080fd5b5050823594602084013594506040840135936060013592509050565b60008060408385031215610b5b57600080fd5b50508035926020909101359150565b600060e08284031215610b7c57600080fd5b50919050565b600060e08284031215610b9457600080fd5b6102e28383610b6a565b600060608284031215610b7c57600080fd5b600060608284031215610bc257600080fd5b6102e28383610b9e565b6000806000806101808587031215610be357600080fd5b8435935060208501356001600160a01b0381168114610c0157600080fd5b9250610c108660408701610b9e565b9150610c1f8660a08701610b6a565b905092959194509250565b805182526020810151602083015260408101516040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c08301525050565b82815261010081016105dc6020830184610c2a565b600060208284031215610c9557600080fd5b5035919050565b6000806101408385031215610cb057600080fd5b610cba8484610b9e565b9150610cc98460608501610b6a565b90509250929050565b60e081016102e58284610c2a565b634e487b7160e01b600052601160045260246000fd5b808201808211156102e5576102e5610ce0565b60405160e0810167ffffffffffffffff81118282101715610d3a57634e487b7160e01b600052604160045260246000fd5b60405290565b600060e08284031215610d5257600080fd5b610d5a610d09565b823581526020830135602082015260408301356040820152606083013560608201526080830135608082015260a083013560a082015260c08301358015158114610da357600080fd5b60c08201529392505050565b600060608284031215610dc157600080fd5b6040516060810181811067ffffffffffffffff82111715610df257634e487b7160e01b600052604160045260246000fd5b80604052508235815260208301356020820152604083013560408201528091505092915050565b80820281158282048414176102e5576102e5610ce0565b634e487b7160e01b600052601260045260246000fd5b818103818111156102e5576102e5610ce0565b600082610e7657634e487b7160e01b600052601260045260246000fd5b50049056fea164736f6c6343000818000a610120604052600a805460ff191660011790553480156200001f57600080fd5b506040516200221d3803806200221d833981016040819052620000429162000360565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556001600160a01b0387166200008e57604051635108aaef60e11b815260040160405180910390fd5b6000876001600160a01b031663a5aa94ac6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620000cf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000f59190620003fe565b6005811115620001095762000109620003e8565b1415806200019257506200012a670de0b6b3a7640000632faf080062000428565b876001600160a01b031663504e49566040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000169573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200018f919062000454565b14155b15620001b1576040516352030d0760e01b815260040160405180910390fd5b85600003620001d357604051635b5d689960e11b815260040160405180910390fd5b83600003620001f557604051635be84ddb60e01b815260040160405180910390fd5b6200020283838362000284565b6001600160a01b03871660805260a086905260c085905260e08490526200022b86601062000428565b610100908152600080546001600160a01b03958616909202610100600160a81b0319909216919091179055600180549284166001600160a01b031993841617905560028054919093169116179055506200046e92505050565b6001600160a01b0383161580620002a257506001600160a01b038216155b80620002b557506001600160a01b038116155b15620002d457604051636b3e672b60e01b815260040160405180910390fd5b816001600160a01b0316836001600160a01b03161480620003065750806001600160a01b0316836001600160a01b0316145b80620003235750806001600160a01b0316826001600160a01b0316145b15620003425760405163fbec30d160e01b815260040160405180910390fd5b505050565b6001600160a01b03811681146200035d57600080fd5b50565b600080600080600080600060e0888a0312156200037c57600080fd5b8751620003898162000347565b809750506020880151955060408801519450606088015193506080880151620003b28162000347565b60a0890151909350620003c58162000347565b60c0890151909250620003d88162000347565b8091505092959891949750929550565b634e487b7160e01b600052602160045260246000fd5b6000602082840312156200041157600080fd5b8151600681106200042157600080fd5b9392505050565b80820281158282048414176200044e57634e487b7160e01b600052601160045260246000fd5b92915050565b6000602082840312156200046757600080fd5b5051919050565b60805160a05160c05160e05161010051611d24620004f96000396000818161040c015261142f0152600081816103af015261104901526000818161029f015261108301526000818161037701528181610772015281816107a0015281816107d501526116cb0152600081816102d90152818161133b0152818161156d01526116000152611d246000f3fe608060405234801561001057600080fd5b50600436106102535760003560e01c80636c5ec94d11610146578063aa80559a116100c3578063cafef3b511610087578063cafef3b51461064a578063d28147ee14610678578063df82b02714610681578063ef94012f14610689578063fb6c3aff1461069c578063fd7f14da146106c557600080fd5b8063aa80559a146105fc578063acefa4a51461060f578063ae0b51df14610617578063bc8108e51461062a578063c81dbbe81461063257600080fd5b8063965d08af1161010a578063965d08af146105ab57806396a5d5ba146105be578063a18c3806146105d1578063a3c788d9146105e4578063a5c9cd82146105ed57600080fd5b80636c5ec94d14610407578063714f5bfc1461042e57806377e688f0146105625780638456cb5914610575578063873f6f9e1461057d57600080fd5b80633f7467ad116101d4578063582f38cb11610198578063582f38cb146103d15780635a80b57b146103d95780635c975abb146103e15780635f91a82a146103ec57806362195367146103f457600080fd5b80633f7467ad1461035557806348999128146103725780634b9094201461039957806355b14515146103a157806356d9bcf3146103aa57600080fd5b806324a3d6221161021b57806324a3d62214610313578063264f4202146103265780632b7a83651461032f5780633a627313146103385780633f4ba83a1461034b57600080fd5b80630b78b47d146102585780631140336a1461029257806312e8e01c1461029a578063197ec524146102c15780631f7c8502146102d4575b600080fd5b61027f7fb59288e4546edbbcf2dff905a79d3e24cf690a39d0cb2bffc8e45d4be40a3b4281565b6040519081526020015b60405180910390f35b61027f6106cd565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b61027f6102cf366004611a6a565b6106e6565b6102fb7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610289565b6002546102fb906001600160a01b031681565b61027f60085481565b61027f60075481565b61027f610346366004611aa2565b610760565b610353610802565b005b600a546103629060ff1681565b6040519015158152602001610289565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b61027f610843565b61027f60095481565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b61027f610859565b61027f61086f565b60005460ff16610362565b61027f610885565b610353610402366004611abb565b61089a565b61027f7f000000000000000000000000000000000000000000000000000000000000000081565b6104f961043c366004611aa2565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810191909152506000908152600460208181526040928390208351610100810185528154815260018201549281019290925260028101549382019390935260038301546060820152908201546080820152600582015460a082015260069091015463ffffffff811660c0830152640100000000900460ff16151560e082015290565b6040516102899190600061010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015263ffffffff60c08401511660c083015260e0830151151560e083015292915050565b61027f610570366004611aa2565b610c65565b610353610d04565b61036261058b366004611b0d565b600560209081526000928352604080842090915290825290205460ff1681565b6103536105b9366004611b51565b610d39565b6103536105cc366004611b6c565b610f02565b61027f6105df366004611aa2565b61103c565b61027f61019081565b61027f670de0b6b3a764000081565b61027f61060a366004611aa2565b6110a7565b6103536110ba565b610353610625366004611b98565b611152565b61027f600481565b6000546102fb9061010090046001600160a01b031681565b610362610658366004611aa2565b600090815260046020526040902060060154640100000000900460ff1690565b61027f60065481565b61027f611417565b6001546102fb906001600160a01b031681565b6102fb6106aa366004611b51565b6003602052600090815260409020546001600160a01b031681565b61027f601081565b6106e3670de0b6b3a76400006304c4b400611c31565b81565b604080517fb59288e4546edbbcf2dff905a79d3e24cf690a39d0cb2bffc8e45d4be40a3b4260208201524691810191909152306060820152608081018490526001600160a01b03831660a082015260c0810182905260009060e0016040516020818303038152906040528051906020012090509392505050565b600061076b8261142d565b60006107977f000000000000000000000000000000000000000000000000000000000000000084611c5e565b905060006107c57f000000000000000000000000000000000000000000000000000000000000000085611c72565b90506107fa6107d383610c65565b7f000000000000000000000000000000000000000000000000000000000000000083611473565b949350505050565b60005461010090046001600160a01b0316331461083957604051630742e48b60e41b81523360048201526024015b60405180910390fd5b6108416114fa565b565b6106e3670de0b6b3a76400006301312d00611c31565b6106e3670de0b6b3a76400006302625a00611c31565b6106e3670de0b6b3a76400006303938700611c31565b6106e3670de0b6b3a7640000624c4b40611c31565b6108a2611547565b6001546001600160a01b031633146108cf5760405163044782a760e31b8152336004820152602401610830565b60065485146108ff5760065460405163240c02db60e01b8152600481019190915260248101869052604401610830565b6109088561142d565b60006109138661103c565b905080421015610940576040516352b8ad3760e01b81526004810187905260248101829052604401610830565b61094861156b565b600061095387610760565b90506000610960826116aa565b90508186111561098d57604051633e6f357f60e21b81526004810183905260248101879052604401610830565b856000036109de5786156109b457604051638f2c67a960e01b815260040160405180910390fd5b63ffffffff8516156109d957604051630743b38f60e01b815260040160405180910390fd5b610a82565b866109fc576040516333dbed4b60e01b815260040160405180910390fd5b83610a1a57604051630ba213eb60e21b815260040160405180910390fd5b8463ffffffff16600003610a415760405163082a9ab760e31b815260040160405180910390fd5b6000610a538263ffffffff8816611c31565b905080871115610a80576040516354218a2d60e01b81526004810182905260248101889052604401610830565b505b600082600754610a929190611c86565b9050610aaa670de0b6b3a7640000632faf0800611c31565b811115610aca57604051635835335f60e11b815260040160405180910390fd5b600087600854610ada9190611c86565b9050610af2670de0b6b3a7640000632faf0800611c31565b811115610b1257604051635835335f60e11b815260040160405180910390fd5b600a5460ff168015610b375750610b34670de0b6b3a7640000624c4b40611c31565b81115b15610b5557604051637e44a93760e11b815260040160405180910390fd5b604051806101000160405280858152602001848152602001898152602001600081526020018a81526020018781526020018863ffffffff16815260200160011515815250600460008c8152602001908152602001600020600082015181600001556020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015560c08201518160060160006101000a81548163ffffffff021916908363ffffffff16021790555060e08201518160060160046101000a81548160ff0219169083151502179055509050508160078190555080600881905550896001610c4d9190611c86565b600655610c598a6116b8565b50505050505050505050565b600060108210610c8b5760405163ab6ea83160e01b815260048101839052602401610830565b6004821015610cb057610caa670de0b6b3a76400006304c4b400611c31565b92915050565b6008821015610ccf57610caa670de0b6b3a76400006303938700611c31565b600c821015610cee57610caa670de0b6b3a76400006302625a00611c31565b610caa670de0b6b3a76400006301312d00611c31565b6002546001600160a01b03163314610d3157604051633b03367360e21b8152336004820152602401610830565b61084161177d565b600060036000836002811115610d5157610d51611c99565b6002811115610d6257610d62611c99565b81526020810191909152604001600020546001600160a01b0316905080610d9c57604051638fc8bbf160e01b815260040160405180910390fd5b336001600160a01b03821614610dc55760405163de6e3b1360e01b815260040160405180910390fd5b610dcf82826117ba565b6000610dda836118cb565b90506000836002811115610df057610df0611c99565b03610e1a5760008054610100600160a81b0319166101006001600160a01b03851602179055610e6f565b6001836002811115610e2e57610e2e611c99565b03610e5357600180546001600160a01b0319166001600160a01b038416179055610e6f565b600280546001600160a01b0319166001600160a01b0384161790555b60036000846002811115610e8557610e85611c99565b6002811115610e9657610e96611c99565b8152602081019190915260400160002080546001600160a01b03191690556001600160a01b03828116908216846002811115610ed457610ed4611c99565b6040517f309d3105e9fb802b7b2d4c96ffac1c13eee06d01e5f21d24b57f6f2deeae51c390600090a4505050565b60005461010090046001600160a01b03163314610f3457604051630742e48b60e41b8152336004820152602401610830565b6001600160a01b038116610f5b57604051636b3e672b60e01b815260040160405180910390fd5b6000610f66836118cb565b9050806001600160a01b0316826001600160a01b031603610f9a57604051632356df2760e01b815260040160405180910390fd5b610fa483836117ba565b8160036000856002811115610fbb57610fbb611c99565b6002811115610fcc57610fcc611c99565b8152602081019190915260400160002080546001600160a01b0319166001600160a01b0392831617905582811690821684600281111561100e5761100e611c99565b6040517f5973b922b1a9ccd7bd4eaf356fe0d5053212ab06f3b1e3c153c2def03c0bad9290600090a4505050565b60006110478261142d565b7f0000000000000000000000000000000000000000000000000000000000000000611073836001611c86565b61107d9190611c31565b610caa907f0000000000000000000000000000000000000000000000000000000000000000611c86565b6000610caa6110b583610760565b6116aa565b60005461010090046001600160a01b031633146110ec57604051630742e48b60e41b8152336004820152602401610830565b600a5460ff1661110f5760405163da8ad54560e01b815260040160405180910390fd5b600a805460ff191690556008546040519081527fd37c003b13ef2b2b0d2a697e60cedb262038309a8e512d9932d0febdb033441d906020015b60405180910390a1565b61115a611547565b611162611936565b61116a61156b565b60008481526004602052604090206006810154640100000000900460ff166111a8576040516363d7266160e11b815260048101869052602401610830565b600085815260056020908152604080832033845290915290205460ff16156111ec57604051633cbd7ef760e01b815260048101869052336024820152604401610830565b8360000361120d576040516379d9727360e01b815260040160405180910390fd5b8060010154841115611242576001810154604051634e5d1d7160e11b8152600481019190915260248101859052604401610830565b600061124f8633876106e6565b90506112618484846004015484611964565b61127e57604051637b0ddadb60e01b815260040160405180910390fd5b60008583600301546112909190611c86565b905082600201548111156112b757604051635c1718d360e01b815260040160405180910390fd5b6000866009546112c79190611c86565b90506008548111156112ec576040516326c1025360e01b815260040160405180910390fd5b600088815260056020908152604080832033808552925291829020805460ff191660011790556003860184905560098390559051630357371d60e01b81526004810191909152602481018890527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690630357371d90604401600060405180830381600087803b15801561138757600080fd5b505af115801561139b573d6000803e3d6000fd5b5050604080518a8152602081018690529081018490523392508a91507f3c883b8d82099521701353cd20a52a3b88dbf0209de8a8028a0f0cccd9484f0a9060600160405180910390a35050505061141160017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b50505050565b6106e3670de0b6b3a7640000632faf0800611c31565b7f000000000000000000000000000000000000000000000000000000000000000081106114705760405163685861c560e11b815260048101829052602401610830565b50565b6000826000036114965760405163024f8f8d60e61b815260040160405180910390fd5b8282106114b657604051636a6a59a160e11b815260040160405180910390fd5b60006114c28486611c5e565b905060006114d08587611c72565b90508084106114e05760006114e3565b60015b6114f09060ff1683611c86565b9695505050505050565b61150261197c565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b039091168152602001611148565b60005460ff16156108415760405163d93c066560e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663158ef93e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ed9190611caf565b158061168c5750306001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663618168326040518163ffffffff1660e01b8152600401602060405180830381865afa15801561165c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116809190611cd1565b6001600160a01b031614155b1561084157604051631b1465cf60e11b815260040160405180910390fd5b6000610caa61019083611c5e565b60008181526004602052604090206116f07f000000000000000000000000000000000000000000000000000000000000000083611c5e565b81546001830154600284015485927f241dfe871a81ff176d033aa29a4b30725a6e8d921ae920e7e8aff141f1e3bec392909161172c8184611cee565b6006880154600489015460058a015460408051978852602088019690965294860193909352606085019190915263ffffffff16608084015260a083015260c082015260e00160405180910390a35050565b611785611547565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861152f3390565b60008260028111156117ce576117ce611c99565b0361181e576001546001600160a01b03828116911614806117fc57506002546001600160a01b038281169116145b1561181a5760405163fbec30d160e01b815260040160405180910390fd5b5050565b600182600281111561183257611832611c99565b03611881576000546001600160a01b038281166101009092041614806117fc57506002546001600160a01b0382811691160361181a5760405163fbec30d160e01b815260040160405180910390fd5b6000546001600160a01b038281166101009092041614806117fc57506001546001600160a01b0382811691160361181a5760405163fbec30d160e01b815260040160405180910390fd5b6000808260028111156118e0576118e0611c99565b036118fb57505060005461010090046001600160a01b031690565b600182600281111561190f5761190f611c99565b036119255750506001546001600160a01b031690565b50506002546001600160a01b031690565b61193e61199f565b60027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b6000826119728686856119e1565b1495945050505050565b60005460ff1661084157604051638dfc202b60e01b815260040160405180910390fd5b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005460020361084157604051633ee5aeb560e01b815260040160405180910390fd5b600081815b84811015611a1a57611a1082878784818110611a0457611a04611d01565b90506020020135611a23565b91506001016119e6565b50949350505050565b6000818310611a3f576000828152602084905260409020611a4e565b60008381526020839052604090205b9392505050565b6001600160a01b038116811461147057600080fd5b600080600060608486031215611a7f57600080fd5b833592506020840135611a9181611a55565b929592945050506040919091013590565b600060208284031215611ab457600080fd5b5035919050565b600080600080600060a08688031215611ad357600080fd5b853594506020860135935060408601359250606086013563ffffffff81168114611afc57600080fd5b949793965091946080013592915050565b60008060408385031215611b2057600080fd5b823591506020830135611b3281611a55565b809150509250929050565b803560038110611b4c57600080fd5b919050565b600060208284031215611b6357600080fd5b611a4e82611b3d565b60008060408385031215611b7f57600080fd5b611b8883611b3d565b91506020830135611b3281611a55565b60008060008060608587031215611bae57600080fd5b8435935060208501359250604085013567ffffffffffffffff80821115611bd457600080fd5b818701915087601f830112611be857600080fd5b813581811115611bf757600080fd5b8860208260051b8501011115611c0c57600080fd5b95989497505060200194505050565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610caa57610caa611c1b565b634e487b7160e01b600052601260045260246000fd5b600082611c6d57611c6d611c48565b500490565b600082611c8157611c81611c48565b500690565b80820180821115610caa57610caa611c1b565b634e487b7160e01b600052602160045260246000fd5b600060208284031215611cc157600080fd5b81518015158114611a4e57600080fd5b600060208284031215611ce357600080fd5b8151611a4e81611a55565b81810381811115610caa57610caa611c1b565b634e487b7160e01b600052603260045260246000fdfea164736f6c6343000818000a000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000006aae491f0000000000000000000000000000000000000000000000000000000000000e1000000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad9000000000000000000000000fe4a6b0c5c0792ebac17119625e913740941b722000000000000000000000000b94b5616d1afb26723cb6a9c0ca1a71d2ea138e700000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad90000000000000000000000008d928fbfa56b5e523fa888dd9cfbcc54a24bf40500000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad900000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad900000000000000000000000093f976141158b199fbbcf902c5ef5ff689e1aad9
Deployed ByteCode
0x608060405234801561001057600080fd5b50600436106101005760003560e01c80635fc89f69116100975780636dee2012116100665780636dee201214610259578063c5af220b1461026c578063d36d42c91461027f578063e82ec8931461029257600080fd5b80635fc89f69146101f95780636575f9001461020c5780636717699a146102335780636dbb02d51461024657600080fd5b80632c1e6193116100d35780632c1e619314610185578063386f97d41461019857806348999128146101ab57806356d9bcf3146101d257600080fd5b806312e8e01c14610105578063168687c41461013f5780631e228514146101475780631f7c850214610172575b600080fd5b61012c7f000000000000000000000000000000000000000000000000000000006aae491f81565b6040519081526020015b60405180910390f35b61012c600881565b60065461015a906001600160a01b031681565b6040516001600160a01b039091168152602001610136565b60005461015a906001600160a01b031681565b60075461015a906001600160a01b031681565b60035461015a906001600160a01b031681565b61012c7f000000000000000000000000000000000000000000000000000000000000000c81565b61012c7f0000000000000000000000000000000000000000000000000000000000000e1081565b60045461015a906001600160a01b031681565b61012c7fb49f1dad082945466755042294bc3d0c0993bb056210b8e6c416c5d546cbb64381565b60055461015a906001600160a01b031681565b60025461015a906001600160a01b031681565b60085461015a906001600160a01b031681565b61015a61027a3660046104c9565b61029a565b60015461015a906001600160a01b031681565b61012c6102e8565b6000600882106102c45760405163224763ef60e01b81526004810183905260240160405180910390fd5b600982600881106102d7576102d76104e2565b01546001600160a01b031692915050565b60008061039f600054600154600254600354600454600554604080516001600160a01b03978816602080830191909152968816818301529487166060860152928616608085015290851660a0840152841660c0808401919091528151808403909101815260e083018252805190840120600654600754600854918716610100860152861661012085015290941661014083015261016080830194909452805180830390940184526101809091019052815191012090565b604080517f000000000000000000000000000000000000000000000000000000000000000c60208201527f000000000000000000000000000000000000000000000000000000006aae491f918101919091527f0000000000000000000000000000000000000000000000000000000000000e1060608201529091506000906080016040516020818303038152906040528051906020012090506000600960405160200161044c91906104f8565b60408051808303601f1901815282825280516020918201207fb49f1dad082945466755042294bc3d0c0993bb056210b8e6c416c5d546cbb643828501524684840152306060850152608084019690965260a083019490945260c0808301959095528051808303909501855260e09091019052508151910120919050565b6000602082840312156104db57600080fd5b5035919050565b634e487b7160e01b600052603260045260246000fd5b6101008101818360005b600881101561052a5781546001600160a01b0316835260209092019160019182019101610502565b5050509291505056fea164736f6c6343000818000a