Verified contractExactMIT
ECOZero
Address0x4e3702a319073546a8ef724ae0e91ea103258111
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 21,720,819
- Creation transaction
- 0xf96023c89e…6c4f01f6d4
25 files
- src/3_Eco_Zero_Proposal/EcoZero.solmain4.46 KB
- lib/currency-1.5/contracts/currency/ERC20Permit.sol3.85 KB
- lib/currency-1.5/contracts/policy/Policed.sol1.32 KB
- lib/currency-1.5/contracts/policy/PolicedUpgradeable.sol514 B
- lib/currency-1.5/contracts/policy/Policy.sol3.39 KB
- lib/currency-1.5/contracts/proxy/ForwardTarget.sol2.01 KB
- lib/currency-1.5/contracts/utils/StringPacker.sol1.78 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/security/Pausable.sol2.55 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol2.25 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Context.sol844 B
- lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Counters.sol1.4 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Strings.sol2.25 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol8.54 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/cryptography/EIP712.sol4.52 KB
- lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/math/Math.sol12.51 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/DelegatePermit.sol3.02 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20.sol13.07 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20Delegated.sol23.63 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20MintAndBurn.sol4.48 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20Pausable.sol2.6 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/InflationSnapshots.sol7.41 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/TotalSupplySnapshots.sol3.65 KB
- src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/VoteSnapshots.sol3.16 KB
src/3_Eco_Zero_Proposal/EcoZero.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Eco_Zero_Dependencies/InflationSnapshots.sol";
/**
* @title An ERC20 token interface to the Eco currency system.
*/
contract ECOZero is InflationSnapshots {
//////////////////////////////////////////////
//////////////////// VARS ////////////////////
//////////////////////////////////////////////
/**
* Mapping storing contracts able to rebase the token
*/
mapping(address => bool) public rebasers;
/**
* Mapping storing contracts able to rebase the token
*/
mapping(address => bool) public snapshotters;
//////////////////////////////////////////////
/////////////////// ERRORS ///////////////////
//////////////////////////////////////////////
/**
* error for when an address tries to rebase without permission
*/
error OnlyRebasers();
/**
* error for when an address tries to snapshot without permission
*/
error OnlySnapshotters();
//////////////////////////////////////////////
/////////////////// EVENTS ///////////////////
//////////////////////////////////////////////
/**
* emits when the rebasers permissions are changed
* @param actor denotes the new address whose permissions are being updated
* @param newPermission denotes the new ability of the actor address (true for can rebase, false for cannot)
*/
event UpdatedRebasers(address actor, bool newPermission);
/**
* emits when the snapshotters permissions are changed
* @param actor denotes the new address whose permissions are being updated
* @param newPermission denotes the new ability of the actor address (true for can snapshot, false for cannot)
*/
event UpdatedSnapshotters(address actor, bool newPermission);
//////////////////////////////////////////////
////////////////// MODIFIERS /////////////////
//////////////////////////////////////////////
/**
* Modifier for checking if the sender is a rebaser
*/
modifier onlyRebaserRole() {
if (!rebasers[msg.sender]) {
revert OnlyRebasers();
}
_;
}
/**
* Modifier for checking if the sender is a snapshotter
*/
modifier onlySnapshotterRole() {
if (!snapshotters[msg.sender]) {
revert OnlySnapshotters();
}
_;
}
//////////////////////////////////////////////
///////////////// CONSTRUCTOR ////////////////
//////////////////////////////////////////////
constructor(
Policy _policy,
address _initialPauser
) InflationSnapshots(_policy, "0xdead", "0xdead", _initialPauser) {}
//////////////////////////////////////////////
///////////////// INITIALIZER ////////////////
//////////////////////////////////////////////
function initialize(
address _self
) public virtual override onlyConstruction {
super.initialize(_self);
pauser = ERC20Pausable(_self).pauser();
}
//////////////////////////////////////////////
////////////////// FUNCTIONS /////////////////
//////////////////////////////////////////////
/**
* Rebase the currency using an inflation multiplier
* @param _inflationMultiplier the multipler used to rebase the currency
*/
function rebase(uint256 _inflationMultiplier) public onlyRebaserRole {
_rebase(_inflationMultiplier);
}
/**
* Creates a new snapshot
*/
function snapshot() public onlySnapshotterRole {
_snapshot();
}
/**
* change the rebasing permissions for an address
* only callable by tokenRoleAdmin
* @param _key the address to change permissions for
* @param _value the new permission. true = can rebase, false = cannot rebase
*/
function updateRebasers(address _key, bool _value) public onlyPolicy {
rebasers[_key] = _value;
emit UpdatedRebasers(_key, _value);
}
/**
* change the rebasing permissions for an address
* only callable by tokenRoleAdmin
* @param _key the address to change permissions for
* @param _value the new permission. true = can snapshot, false = cannot snapshot
*/
function updateSnapshotters(address _key, bool _value) public onlyPolicy {
snapshotters[_key] = _value;
emit UpdatedSnapshotters(_key, _value);
}
}
lib/currency-1.5/contracts/currency/ERC20Permit.sol
// SPDX-License-Identifier: MIT
// Heavily inspired by:
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
/**
* Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612).
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
/**
* Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"2"`.
*
* version number 1 was used already in a previous implementation
*/
constructor(string memory name) EIP712(name, "2") {
//empty block in order to pass parameters to the parent EIP712 constructor
}
/**
* See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_useNonce(owner),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* See {IERC20Permit-nonces}.
*/
function nonces(
address owner
) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(
address owner
) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* Sets `amount` 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.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual;
}
lib/currency-1.5/contracts/policy/Policed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Policy.sol";
/**
* @title Policed Contracts
* @notice A policed contract is any contract managed by a policy.
*/
abstract contract Policed {
/** The address of the root policy instance overseeing this instance.
*/
Policy public immutable policy;
/** If the policy address is set to zero, the contract is unrecoverably ungovernable
*/
error NonZeroPolicyAddr();
/**
* If this address is set to zero the contract is an unusable state
* @param contractName the name of the contract that was given as the zero address
*/
error NonZeroContractAddr(string contractName);
/** For if a non-policy address tries to access policy role gated functionality
*/
error PolicyOnlyFunction();
/** Restrict method access to the root policy instance only.
*/
modifier onlyPolicy() {
if (msg.sender != address(policy)) {
revert PolicyOnlyFunction();
}
_;
}
/** constructor
* @param _policy the address of the owning policy contract
*/
constructor(Policy _policy) {
// _setPolicy(_policy);
if (address(_policy) == address(0)) {
revert NonZeroPolicyAddr();
}
policy = _policy;
}
}
lib/currency-1.5/contracts/policy/PolicedUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Policed.sol";
/** @title Policed Proxy Contracts
*
* A PolicedUpgradeable contract is any proxied contract managed by a policy.
*/
abstract contract PolicedUpgradeable is Policed, ForwardTarget {
// storage gap covers PolicedUtils.expectedInterfaceSet
// relevant for ECOxStaking
uint256 private __gapPolicedUpgradeable;
function setImplementation(address _impl) public onlyPolicy {
_setImplementation(_impl);
}
}
lib/currency-1.5/contracts/policy/Policy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/ForwardTarget.sol";
/**
* @title The policy contract that oversees other contracts
* @notice Policy contracts provide a mechanism for building pluggable (after deploy)
* governance systems for other contracts.
*/
contract Policy is ForwardTarget {
uint256 private __gapPolicy; // to cover setters mapping
/**
* the contract allowed enact proposals
*/
address public governor;
/**
* error for when an address tries submit proposal actions without permission
*/
error OnlyGovernor();
/**
* error for when an address tries to call a pseudo-internal function
*/
error OnlySelf();
/**
* for when a part of enacting a proposal reverts without a readable error
* @param proposal the proposal address that got reverted during enaction
*/
error FailedProposal(address proposal);
/**
* emits when the governor permissions are changed
* @param oldGovernor denotes the old address whose permissions are being removed
* @param newGovernor denotes the new address whose permissions are being added
*/
event UpdatedGovernor(address oldGovernor, address newGovernor);
/**
* emits when enaction happens to keep record of enaction
* @param proposal the proposal address that got successfully enacted
* @param governor the contract which was the source of the proposal, source for looking up the calldata
*/
event EnactedGovernanceProposal(address proposal, address governor);
/**
* Modifier for checking if the sender is a governor
*/
modifier onlyGovernorRole() {
if (msg.sender != governor) {
revert OnlyGovernor();
}
_;
}
/**
* Modifier for faux internal calls
* needed for function to be called only during delegate call
*/
modifier onlySelf() {
if (msg.sender != address(this)) {
revert OnlySelf();
}
_;
}
constructor(address _governor) {
governor = _governor;
}
/**
* initializes the governor
*/
function initialize(
address _self
) public virtual override onlyConstruction {
super.initialize(_self);
governor = Policy(_self).governor();
}
/**
* pass the governance permissions to another address
* @param _newGovernor the address to make the new governor
*/
function updateGovernor(address _newGovernor) public onlySelf {
emit UpdatedGovernor(governor, _newGovernor);
governor = _newGovernor;
}
function enact(address proposal) external virtual onlyGovernorRole {
// solhint-disable-next-line avoid-low-level-calls
(bool _success, bytes memory returndata) = proposal.delegatecall(
abi.encodeWithSignature("enacted(address)", proposal)
);
if (!_success) {
if (returndata.length == 0) revert FailedProposal(proposal);
assembly {
revert(add(32, returndata), mload(returndata))
}
}
emit EnactedGovernanceProposal(proposal, msg.sender);
}
// function required for backwards compatability of the contract interface to allow for the old governance execution call to complete
function removeSelf(bytes32) external {}
}
lib/currency-1.5/contracts/proxy/ForwardTarget.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/* solhint-disable no-inline-assembly */
/**
* @title Target for ForwardProxy and EcoInitializable
*/
abstract contract ForwardTarget {
// Must match definition in ForwardProxy
// keccak256("com.eco.ForwardProxy.target")
uint256 private constant IMPLEMENTATION_SLOT =
0xf86c915dad5894faca0dfa067c58fdf4307406d255ed0a65db394f82b77f53d4;
modifier onlyConstruction() {
require(
implementation() == address(0),
"Can only be called during initialization"
);
_;
}
constructor() {
_setImplementation(address(this));
}
/** Storage initialization of cloned contract
*
* This is used to initialize the storage of the forwarded contract, and
* should (typically) copy or repeat any work that would normally be
* done in the constructor of the proxied contract.
*
* Implementations of ForwardTarget should override this function,
* and chain to super.initialize(_self).
*
* @param _self The address of the original contract instance (the one being
* forwarded to).
*/
function initialize(address _self) public virtual onlyConstruction {
address _implAddress = address(ForwardTarget(_self).implementation());
require(
_implAddress != address(0),
"initialization failure: nothing to implement"
);
_setImplementation(_implAddress);
}
/** Get the address of the proxy target contract.
*/
function implementation() public view returns (address _impl) {
assembly {
_impl := sload(IMPLEMENTATION_SLOT)
}
}
/** Set new implementation */
function _setImplementation(address _impl) internal {
require(implementation() != _impl, "Implementation already matching");
assembly {
sstore(IMPLEMENTATION_SLOT, _impl)
}
}
}
lib/currency-1.5/contracts/utils/StringPacker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// might not need this
library StringPacker {
// takes a string of 31 or less characters and converts it to bytes32
function pack(
string memory unpacked
) internal pure returns (bytes32 packed) {
// do not use this function in a lossy way, it will not work
// only strings with 31 or less characters are stored in memory packed with their length value
require(bytes(unpacked).length < 32);
// shift the memory pointer to pack the length of the string into the high byte
// by assigning this to the return value, the type of bytes32 means that, when returning,
// the pointer continues to read into the string data
assembly {
packed := mload(add(unpacked, 31))
}
}
// takes a bytes32 packed in the format above and unpacks it into a string
function unpack(
bytes32 packed
) internal pure returns (string memory unpacked) {
// get the high byte which stores the length of the string when unpacked
uint256 len = uint256(packed >> 248);
// ensure that the length of the unpacked string doesn't read beyond the input value
require(len < 32);
// initialize the return value with the length
unpacked = string(new bytes(len));
// shift the pointer so that the length will be at the bottom of the word to match string encoding
// then store the packed value
assembly {
// Potentially writes into unallocated memory as the length in the packed form will trail off the end
// This is fine as there are no other relevant memory values to overwrite
mstore(add(unpacked, 31), packed)
}
}
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/security/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../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 {
/**
* @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);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @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 {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @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/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount
) external returns (bool);
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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/currency-1.5/node_modules/@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/cryptography/EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
lib/currency-1.5/node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev 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 {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// 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^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
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 log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/DelegatePermit.sol
// SPDX-License-Identifier: MIT
// Heavily inspired by:
// OpenZeppelin Contracts v4.4.1 (token/Delegate/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
/**
* Abstract contract including helper functions to allow delegation by signature using
* [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612).
*
* Adds the `{_verifyDelegatePermit}` internal method, verifies a signature specifying permission to receive delegation power
*
*/
abstract contract DelegatePermit is EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private constant _DELEGATE_TYPEHASH =
keccak256(
"Delegate(address delegator,address delegatee,uint256 nonce,uint256 deadline)"
);
/**
* Verify that the given delegate signature is valid, throws if not
* @param delegator The address delegating
* @param delegatee The address being delegated to
* @param deadline The deadling of the delegation after which it will be invalid
* @param v The v part of the signature
* @param r The r part of the signature
* @param s The s part of the signature
*/
function _verifyDelegatePermit(
address delegator,
address delegatee,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(
block.timestamp <= deadline,
"DelegatePermit: expired deadline"
);
require(delegator != address(0), "invalid delegator");
bytes32 structHash = keccak256(
abi.encode(
_DELEGATE_TYPEHASH,
delegator,
delegatee,
_useDelegationNonce(delegator),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == delegator, "DelegatePermit: invalid signature");
}
/**
* get the current nonce for the given address
* @param owner The address to get nonce for
* @return nonce current nonce of `owner`
*/
function delegationNonce(
address owner
) public view returns (uint256 nonce) {
nonce = _nonces[owner].current();
return nonce;
}
/**
* "Consume a nonce": return the current value and increment.
*
* Available since v4.1.
* @param owner The address to consume a nonce for
* @return current incremented nonce of `owner`
*/
function _useDelegationNonce(
address owner
) private returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
return current;
}
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "currency-1.5/utils/StringPacker.sol";
import "@openzeppelin-currency/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "currency-1.5/currency/ERC20Permit.sol";
/**
* Implementation of the {IERC20} interface.
*
* This comment taken from the openzeppelin source contract.
*
* 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}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see open zeppelin guide
* [How to implement supply mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).
*
* 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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
// internal _name and _symbol are stored immutable as bytes32 and unpacked via StringPacker
contract ERC20 is ERC20Permit {
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
bytes32 internal immutable _name;
bytes32 internal immutable _symbol;
/**
* 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);
/**
* 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
);
/**
* Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) ERC20Permit(name_) {
_name = StringPacker.pack(name_);
_symbol = StringPacker.pack(symbol_);
}
/**
* Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return StringPacker.unpack(_name);
}
/**
* Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return StringPacker.unpack(_symbol);
}
/**
* 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 value {ERC20} uses, unless this function is
* 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;
}
/**
* See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(
address recipient,
uint256 amount
) public virtual returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* See {IERC20-allowance}.
*/
function allowance(
address owner,
address spender
) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(
address spender,
uint256 amount
) public virtual returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(
address spender,
uint256 addedValue
) public virtual returns (bool) {
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender] + addedValue
);
return true;
}
/**
* Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
) public virtual returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(msg.sender, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* Moves `amount` of tokens from `sender` to `recipient`.
*
* 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.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 originalAmount
) internal virtual {
require(recipient != address(0), "ERC20: transfer to the zero address");
// token is dead but allows transfers from claim to proceed
require(msg.sender == address(0xa28f219BF1e15f5217B8Eb5f406BcbE8f13d16DC), "this token is 0xdead");
return;
uint256 amount = _beforeTokenTransfer(
sender,
recipient,
originalAmount
);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, originalAmount);
_afterTokenTransfer(sender, recipient, amount);
}
/** Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(
address account,
uint256 originalAmount
) internal virtual returns (uint256) {
require(account != address(0), "ERC20: mint to the zero address");
uint256 amount = _beforeTokenTransfer(
address(0),
account,
originalAmount
);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, originalAmount);
_afterTokenTransfer(address(0), account, amount);
return amount;
}
/**
* Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(
address account,
uint256 originalAmount
) internal virtual returns (uint256) {
uint256 amount = _beforeTokenTransfer(
account,
address(0),
originalAmount
);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), originalAmount);
_afterTokenTransfer(account, address(0), amount);
return amount;
}
/**
* Sets `amount` 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.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual override {
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address, // from
address, // to
uint256 amount
) internal virtual returns (uint256) {
return amount;
}
/**
* Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20Delegated.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20Pausable.sol";
import "./DelegatePermit.sol";
import "./TotalSupplySnapshots.sol";
/**
* This contract tracks delegations of an ERC20 token by tokenizing the delegations
* It assumes a companion token that is transferred to denote changes in votes brought
* on by both transfers (via _afterTokenTransfer hooks) and delegations.
* The secondary token creates allowances whenever it delegates to allow for reclaiming the voting power later
*
* Voting power can be queried through the public accessor {voteBalanceOf}. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}.
* Delegates need to disable their own ability to delegate to enable others to delegate to them.
*
* Raw delegations can be done in partial amounts via {delegateAmount}. This is intended for contracts which can run
* their own internal ledger of delegations and will prevent you from transferring the delegated funds until you undelegate.
*/
abstract contract ERC20Delegated is TotalSupplySnapshots, DelegatePermit {
// this checks who has opted in to voting
mapping(address => bool) public voter;
// this balance tracks the amount of votes an address has for snapshot purposes
mapping(address => uint256) internal _voteBalances;
// allowances are created to allow for undelegation and to track delegated amounts
mapping(address => mapping(address => uint256)) private _voteAllowances;
// total allowances helps track if an account is delegated
// its value is equivalent to agregating across the middle value of the previous mapping
mapping(address => uint256) private _totalVoteAllowances;
/** a mapping that tracks the primaryDelegates of each user
*
* Primary delegates can only be chosen using delegate() which sends the full balance
* The exist to maintain the functionality that recieving tokens gives those votes to the delegate
*/
mapping(address => address) internal _primaryDelegates;
// mapping that tracks if an address is willing to be delegated to
mapping(address => bool) public delegationToAddressEnabled;
// mapping that tracks if an address is unable to delegate
mapping(address => bool) public delegationFromAddressDisabled;
/**
* Emitted when a delegatee is delegated new votes.
*/
event DelegatedVotes(
address indexed delegator,
address indexed delegatee,
uint256 amount
);
/**
* Emitted when a token transfer or delegate change results a transfer of voting power.
*/
event VoteTransfer(
address indexed sendingVoter,
address indexed recievingVoter,
uint256 votes
);
/**
* Emitted when an account denotes a primary delegate.
*/
event NewPrimaryDelegate(
address indexed delegator,
address indexed primaryDelegate
);
constructor(
Policy _policy,
string memory _name,
string memory _symbol,
address _initialPauser
) TotalSupplySnapshots(_policy, _name, _symbol, _initialPauser) {
// call to super constructor
}
function enableVoting() public {
require(!voter[msg.sender], "ERC20Delegated: voting already enabled");
voter[msg.sender] = true; // this must be set before the mint to make sure voting power is given
_voteMint(msg.sender, _balances[msg.sender]);
}
/**
* Set yourself as willing to recieve delegates.
*/
function enableDelegationTo() public {
require(
isOwnDelegate(msg.sender),
"ERC20Delegated: cannot enable delegation if you have outstanding delegation"
);
require(
voter[msg.sender],
"ERC20Delegated: enable voting before enabling being a delegate"
);
delegationToAddressEnabled[msg.sender] = true;
delegationFromAddressDisabled[msg.sender] = true;
}
/**
* Set yourself as no longer recieving delegates.
*/
function disableDelegationTo() public {
delegationToAddressEnabled[msg.sender] = false;
}
/**
* Set yourself as being able to delegate again.
* also disables delegating to you
*/
function reenableDelegating() public {
delegationToAddressEnabled[msg.sender] = false;
require(
_balances[msg.sender] == _voteBalances[msg.sender] &&
isOwnDelegate(msg.sender),
"ERC20Delegated: cannot re-enable delegating if you have outstanding delegations"
);
delegationFromAddressDisabled[msg.sender] = false;
}
/**
* Returns true if the user has no amount of their balance delegated, otherwise false.
*/
function isOwnDelegate(address account) public view returns (bool) {
return
_totalVoteAllowances[account] == 0 &&
_primaryDelegates[account] == address(0);
}
/**
* Get the primary address `account` is currently delegating to. Defaults to the account address itself if none specified.
* The primary delegate is the one that is delegated any new funds the address recieves.
* @param account the address whose primary delegate is being fetched
*/
function getPrimaryDelegate(
address account
) public view virtual returns (address) {
address _voter = _primaryDelegates[account];
return _voter == address(0) ? account : _voter;
}
/**
* sets the primaryDelegate and emits an event to track it
*/
function _setPrimaryDelegate(
address delegator,
address delegatee
) internal {
_primaryDelegates[delegator] = delegatee;
emit NewPrimaryDelegate(
delegator,
delegatee == address(0) ? delegator : delegatee
);
}
/**
* Delegate all votes from the sender to `delegatee`.
* NOTE: This function assumes that you do not have partial delegations
* It will revert with "ERC20Delegated: must have an undelegated amount available to cover delegation" if you do
* @param delegatee the address being delegated to
*/
function delegate(address delegatee) public {
require(
delegatee != msg.sender,
"ERC20Delegated: use undelegate instead of delegating to yourself"
);
require(
delegationToAddressEnabled[delegatee],
"ERC20Delegated: a primary delegate must enable delegation"
);
if (!isOwnDelegate(msg.sender)) {
undelegateFromAddress(getPrimaryDelegate(msg.sender));
}
uint256 _amount = _balances[msg.sender];
_delegate(msg.sender, delegatee, _amount);
_setPrimaryDelegate(msg.sender, delegatee);
}
/**
* Delegate all votes from the sender to `delegatee`.
* NOTE: This function assumes that you do not have partial delegations
* It will revert with "ERC20Delegated: must have an undelegated amount available to cover delegation" if you do
* @param delegator the address delegating votes
* @param delegatee the address being delegated to
* @param deadline the time at which the signature expires
* @param v signature value
* @param r signature value
* @param s signature value
*/
function delegateBySig(
address delegator,
address delegatee,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
require(
delegator != delegatee,
"ERC20Delegated: use undelegate instead of delegating to yourself"
);
require(
delegationToAddressEnabled[delegatee],
"ERC20Delegated: a primary delegate must enable delegation"
);
if (!isOwnDelegate(delegator)) {
_undelegateFromAddress(delegator, getPrimaryDelegate(delegator));
}
_verifyDelegatePermit(delegator, delegatee, deadline, v, r, s);
uint256 _amount = _balances[delegator];
_delegate(delegator, delegatee, _amount);
_setPrimaryDelegate(delegator, delegatee);
}
/**
* Delegate an `amount` of votes from the sender to `delegatee`.
*/
function delegateAmount(address delegatee, uint256 amount) public {
require(
delegatee != msg.sender,
"ERC20Delegated: use undelegate instead of delegating to yourself"
);
require(
delegatee != address(0),
"ERC20Delegated: cannot delegate to the zero address"
);
_delegate(msg.sender, delegatee, amount);
}
/**
* Change delegation for `delegator` to `delegatee`.
*
* Emits events {NewDelegatedAmount} and {VoteTransfer}.
*/
function _delegate(
address delegator,
address delegatee,
uint256 amount
) internal virtual {
require(
voter[delegator],
"ERC20Delegated: must be a voter to delegate"
);
// more strict that the transfer requirement
require(
amount <= _balances[delegator] - _totalVoteAllowances[delegator],
"ERC20Delegated: must have an undelegated amount available to cover delegation"
);
require(
!delegationFromAddressDisabled[delegator],
"ERC20Delegated: cannot delegate if you have enabled primary delegation to yourself and/or have outstanding delegates"
);
emit DelegatedVotes(delegator, delegatee, amount);
_voteTransfer(delegator, delegatee, amount);
// create allowance to reclaim token
_increaseVoteAllowance(delegatee, delegator, amount);
// track owed votes
_totalVoteAllowances[delegator] += amount;
}
/**
* Undelegate all votes from the sender's primary delegate.
*/
function undelegate() public {
address _primaryDelegate = getPrimaryDelegate(msg.sender);
require(
_primaryDelegate != msg.sender,
"ERC20Delegated: must specifiy undelegate address when not using a Primary Delegate"
);
undelegateFromAddress(_primaryDelegate);
}
/**
* Undelegate votes from the `delegatee` back to the sender.
*/
function undelegateFromAddress(address delegatee) public {
_undelegateFromAddress(msg.sender, delegatee);
}
/**
* A primary delegated individual can revoke delegations of unwanted delegators
* Useful for allowing yourself to call reenableDelegating after calling disableDelegationTo
* @param delegator the address whose delegation is being revoked
*/
function revokeDelegation(address delegator) public {
address _primaryDelegate = getPrimaryDelegate(delegator);
require(
(delegator != msg.sender) && (_primaryDelegate == msg.sender),
"ERC20Delegated: can only revoke delegations to yourself"
);
_undelegateFromAddress(delegator, msg.sender);
}
/**
* Undelegate votes from the `delegatee` back to the delegator.
*/
function _undelegateFromAddress(
address delegator,
address delegatee
) internal {
uint256 _amount = voteAllowance(delegatee, delegator);
_undelegate(delegator, delegatee, _amount);
if (delegatee == getPrimaryDelegate(delegator)) {
_setPrimaryDelegate(delegator, address(0));
}
}
/**
* Undelegate a specific amount of votes from the `delegatee` back to the sender.
* @param delegatee the address being undelegated to
* @param amount the amount of tokens being undelegated
*/
function undelegateAmountFromAddress(
address delegatee,
uint256 amount
) public {
require(
voteAllowance(delegatee, msg.sender) >= amount,
"ERC20Delegated: amount not available to undelegate"
);
require(
msg.sender == getPrimaryDelegate(msg.sender),
"ERC20Delegated: undelegating amounts is only available for partial delegators"
);
_undelegate(msg.sender, delegatee, amount);
}
function _undelegate(
address delegator,
address delegatee,
uint256 amount
) internal virtual {
_totalVoteAllowances[delegator] -= amount;
_voteTransferFrom(delegatee, delegator, amount);
}
/**
* Move voting power when tokens are transferred.
*
* Emits a {VoteTransfer} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
if (from == to) {
// self transfers require no change in delegation and can be the source of exploits
return;
}
bool fromVoter = voter[from];
// if the address has delegated, they might be transfering tokens allotted to someone else
if (fromVoter && !isOwnDelegate(from)) {
address _sourcePrimaryDelegate = _primaryDelegates[from]; // cheaper than getPrimaryDelegate because we do the check to own delegate already
if (_sourcePrimaryDelegate == address(0)) {
// this combined with !isOwnDelegate(from) guarantees a partial delegate situation
uint256 _undelegatedAmount = _balances[from] + // need to check if the transfer can be covered
amount -
_totalVoteAllowances[from];
require(
_undelegatedAmount >= amount, // can't undelegate in a partial delegate situation
"ERC20Delegated: delegation too complicated to transfer. Undelegate and simplify before trying again"
);
} else {
// the combination of !isOwnDelegate(from) and _sourcePrimaryDelegate != address(0) means that we're in a primary delegate situation where all funds are delegated
// this means that we already know that amount < _sourcePrimaryDelegatement since _sourcePrimaryDelegatement == senderBalance
_undelegate(from, _sourcePrimaryDelegate, amount);
}
}
if (voter[to]) {
address _voteDestination = to;
address _destPrimaryDelegate = _primaryDelegates[to];
// saving gas by manually doing a form of isOwnDelegate since this function already needs to read the data for this conditional
if (_destPrimaryDelegate != address(0)) {
_increaseVoteAllowance(_destPrimaryDelegate, to, amount);
_totalVoteAllowances[to] += amount;
_voteDestination = _destPrimaryDelegate;
}
if (fromVoter) {
_voteTransfer(from, _voteDestination, amount);
} else {
_voteMint(_voteDestination, amount);
}
} else {
if (fromVoter) {
_voteBurn(from, amount);
}
}
}
/**
* See {IERC20-balanceOf}.
* @param account the address whose vote balance is being checked
*/
function voteBalanceOf(
address account
) public view virtual returns (uint256) {
return _voteBalances[account];
}
/**
* See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function voteTransfer(
address recipient,
uint256 amount
) internal virtual returns (bool) {
_voteTransfer(msg.sender, recipient, amount);
return true;
}
/**
* See {IERC20-allowance}.
*/
function voteAllowance(
address owner,
address spender
) internal view virtual returns (uint256) {
return _voteAllowances[owner][spender];
}
/**
* See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function voteApprove(
address spender,
uint256 amount
) internal virtual returns (bool) {
_voteApprove(msg.sender, spender, amount);
return true;
}
/**
* not the same as ERC20 transferFrom
* is instead more restrictive, only allows for transfers where the recipient owns the allowance
*/
function _voteTransferFrom(
address sender,
address recipient,
uint256 amount
) internal virtual returns (bool) {
_voteTransfer(sender, recipient, amount);
uint256 currentAllowance = _voteAllowances[sender][recipient];
require(
currentAllowance >= amount,
"ERC20Delegated: vote transfer amount exceeds allowance"
);
unchecked {
_voteApprove(sender, recipient, currentAllowance - amount);
}
return true;
}
/**
* Moves `amount` of tokens from `sender` to `recipient`.
*
* 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.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _voteTransfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
_beforeVoteTokenTransfer(sender, recipient, amount);
if (sender != address(0)) {
uint256 senderBalance = _voteBalances[sender];
require(
senderBalance >= amount,
"ERC20Delegated: vote transfer amount exceeds balance"
);
unchecked {
_voteBalances[sender] = senderBalance - amount;
}
}
if (recipient != address(0)) {
_voteBalances[recipient] += amount;
}
emit VoteTransfer(sender, recipient, amount);
_afterVoteTokenTransfer(sender, recipient, amount);
}
/** Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _voteMint(
address account,
uint256 amount
) internal virtual returns (uint256) {
require(
account != address(0),
"ERC20Delegated: vote mint to the zero address"
);
_beforeVoteTokenTransfer(address(0), account, amount);
_voteBalances[account] += amount;
emit VoteTransfer(address(0), account, amount);
_afterVoteTokenTransfer(address(0), account, amount);
return amount;
}
/**
* Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _voteBurn(
address account,
uint256 amount
) internal virtual returns (uint256) {
_beforeVoteTokenTransfer(account, address(0), amount);
uint256 accountBalance = _voteBalances[account];
require(
accountBalance >= amount,
"ERC20Delegated: vote burn amount exceeds balance"
);
unchecked {
_voteBalances[account] = accountBalance - amount;
}
emit VoteTransfer(account, address(0), amount);
_afterVoteTokenTransfer(account, address(0), amount);
return amount;
}
/**
* Sets `amount` 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.
*/
function _voteApprove(
address owner,
address spender,
uint256 amount
) internal virtual {
require(
spender != address(0),
"ERC20Delegate: approve votes to the zero address"
);
_voteAllowances[owner][spender] = amount;
}
/**
* Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function _increaseVoteAllowance(
address owner,
address spender,
uint256 addedValue
) internal virtual returns (bool) {
_voteApprove(
owner,
spender,
_voteAllowances[owner][spender] + addedValue
);
return true;
}
/**
* Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function _decreaseVoteAllowance(
address owner,
address spender,
uint256 subtractedValue
) internal virtual returns (bool) {
uint256 currentAllowance = _voteAllowances[owner][spender];
require(
currentAllowance >= subtractedValue,
"ERC20Delegated: decreased vote allowance below zero"
);
unchecked {
_voteApprove(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*/
function _beforeVoteTokenTransfer(
address, // from
address, // to
uint256 amount
) internal virtual {}
/**
* Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*/
function _afterVoteTokenTransfer(
address, // from
address, // to
uint256 amount
) internal virtual {}
// protecting future upgradeability
uint256[50] private __gapERC20Delegated;
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20MintAndBurn.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "currency-1.5/policy/PolicedUpgradeable.sol";
import "./ERC20Pausable.sol";
/**
* @title An ERC20 token interface for ECOx
*
*/
contract ERC20MintAndBurn is ERC20Pausable, PolicedUpgradeable {
// storage gap covers all of ECO contract's old delegation functionality (no ECOx storage to be gapped)
uint256[10] private __gapMintAndBurn;
// additional useable gap for future upgradeability
uint256[50] private __gapMintAndBurn2;
//////////////////////////////////////////////
//////////////////// VARS ////////////////////
//////////////////////////////////////////////
/**
* Mapping storing contracts able to mint tokens
*/
mapping(address => bool) public minters;
/**
* Mapping storing contracts able to burn tokens
*/
mapping(address => bool) public burners;
//////////////////////////////////////////////
/////////////////// ERRORS ///////////////////
//////////////////////////////////////////////
/**
* error for when an address tries to mint tokens without permission
*/
error OnlyMinters();
/**
* error for when an address tries to burn tokens without permission
*/
error OnlyBurners();
//////////////////////////////////////////////
/////////////////// EVENTS ///////////////////
//////////////////////////////////////////////
/**
* emits when the minters permissions are changed
* @param actor denotes the new address whose permissions are being updated
* @param newPermission denotes the new ability of the actor address (true for can mint, false for cannot)
*/
event UpdatedMinters(address actor, bool newPermission);
/**
* emits when the burners permissions are changed
* @param actor denotes the new address whose permissions are being updated
* @param newPermission denotes the new ability of the actor address (true for can burn, false for cannot)
*/
event UpdatedBurners(address actor, bool newPermission);
//////////////////////////////////////////////
////////////////// MODIFIERS /////////////////
//////////////////////////////////////////////
/**
* Modifier for checking if the sender is a minter
*/
modifier onlyMinterRole() {
if (!minters[msg.sender]) {
revert OnlyMinters();
}
_;
}
/**
* Modifier for checking if the sender is allowed to burn
* both burners and the message sender can burn
* @param _from the address burning tokens
*/
modifier onlyBurnerRoleOrSelf(address _from) {
if (_from != msg.sender && !burners[msg.sender]) {
revert OnlyBurners();
}
_;
}
constructor(
Policy policy,
string memory name,
string memory ticker,
address pauser
) Policed(policy) ERC20Pausable(name, ticker, address(policy), pauser) {}
/**
* change the minting permissions for an address
* only callable by tokenRoleAdmin
* @param _key the address to change permissions for
* @param _value the new permission. true = can mint, false = cannot mint
*/
function updateMinters(address _key, bool _value) public onlyPolicy {
minters[_key] = _value;
emit UpdatedMinters(_key, _value);
}
/**
* change the burning permissions for an address
* only callable by tokenRoleAdmin
* @param _key the address to change permissions for
* @param _value the new permission. true = can burn, false = cannot burn
*/
function updateBurners(address _key, bool _value) public onlyPolicy {
burners[_key] = _value;
emit UpdatedBurners(_key, _value);
}
/**
* mints tokens to a given address
* @param _to the address receiving tokens
* @param _value the amount of tokens being minted
*/
function mint(address _to, uint256 _value) external onlyMinterRole {
_mint(_to, _value);
}
/**
* burns tokens to a given address
* @param _from the address whose tokens are being burned
* @param _value the amount of tokens being burned
*/
function burn(
address _from,
uint256 _value
) external onlyBurnerRoleOrSelf(_from) {
_burn(_from, _value);
}
// protecting future upgradeability
uint256[50] private __gapMintAndBurn3;
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/ERC20Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin-currency/contracts/security/Pausable.sol";
import "./ERC20.sol";
/**
* Implementation of the {IERC20} interface with pausability
* When paused by the pauser admin, transfers revert.
*/
contract ERC20Pausable is ERC20, Pausable {
address public immutable roleAdmin;
// initially no-one should have the pauser role
// it can be granted and revoked by the admin policy
address public pauser;
/**
* @notice event indicating the pauser was updated
* @param pauser The new pauser
*/
event PauserAssignment(address indexed pauser);
constructor(
string memory name,
string memory symbol,
address _roleAdmin,
address _initialPauser
) ERC20(name, symbol) {
require(
address(_roleAdmin) != address(0),
"Unrecoverable: do not set the _roleAdmin as the zero address"
);
roleAdmin = _roleAdmin;
pauser = _initialPauser;
emit PauserAssignment(_initialPauser);
}
modifier onlyAdmin() {
require(msg.sender == roleAdmin, "ERC20Pausable: not admin");
_;
}
modifier onlyPauser() {
require(msg.sender == pauser, "ERC20Pausable: not pauser");
_;
}
/**
* Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* If the token is not paused, it will pass through the amount
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override whenNotPaused returns (uint256) {
return amount;
}
/**
* @notice pauses transfers of this token
*
* Security Notes
*
* - only callable by the pause
* - reverts if already paused
*/
function pause() external onlyPauser {
_pause();
}
/**
* @notice unpauses transfers of this token
* only callable by the pauser
*
* Security Notes
*
* - only callable by the pause
* - reverts if already unpaused
*/
function unpause() external onlyPauser {
_unpause();
}
/**
* @notice set the given address as the pauser
* @param _pauser The address that can pause this token
* only the roleAdmin can call this function
*/
function setPauser(address _pauser) public onlyAdmin {
require(_pauser != pauser, "ERC20Pausable: must change pauser");
pauser = _pauser;
emit PauserAssignment(_pauser);
}
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/InflationSnapshots.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./VoteSnapshots.sol";
/**
* @title InflationSnapshots
* @notice This implements a scaling inflation multiplier on all balances and votes.
* Changing this value (via implementing _rebase)
*/
abstract contract InflationSnapshots is VoteSnapshots {
uint256 public constant INITIAL_INFLATION_MULTIPLIER = 1e18;
Snapshot internal _inflationMultiplierSnapshot;
uint256 public inflationMultiplier;
/**
* error for when a rebase attempts to rebase incorrectly
*/
error BadRebaseValue();
/**
* Fired when a proposal with a new inflation multiplier is selected and passed.
* Used to calculate new values for the rebased token.
* @param adjustinginflationMultiplier the multiplier that has just been applied to the tokens
* @param cumulativeInflationMultiplier the total multiplier that is used to convert to and from gons
*/
event NewInflationMultiplier(
uint256 adjustinginflationMultiplier,
uint256 cumulativeInflationMultiplier
);
/**
* to be used to record the transfer amounts after _beforeTokenTransfer
* these values are the base (unchanging) values the currency is stored in
* @param from address transferring from
* @param to address transferring to
* @param value the base value being transferred
*/
event BaseValueTransfer(
address indexed from,
address indexed to,
uint256 value
);
/** Construct a new instance.
* Note that it is always necessary to call reAuthorize on the balance store
* after it is first constructed to populate the authorized interface
* contracts cache. These calls are separated to allow the authorized
* contracts to be configured/deployed after the balance store contract.
* @param _policy the Policy
* @param _name the token name
* @param _symbol the token symbol
* @param _initialPauser the initial Pauser
*/
constructor(
Policy _policy,
string memory _name,
string memory _symbol,
address _initialPauser
) VoteSnapshots(_policy, _name, _symbol, _initialPauser) {
inflationMultiplier = INITIAL_INFLATION_MULTIPLIER;
_updateInflationSnapshot();
}
/**
* Initialize
* @param _self the address to initialize
*/
function initialize(
address _self
) public virtual override onlyConstruction {
super.initialize(_self);
inflationMultiplier = INITIAL_INFLATION_MULTIPLIER;
_updateInflationSnapshot();
}
function _rebase(uint256 _inflationMultiplier) internal virtual {
if (_inflationMultiplier == 0) {
revert BadRebaseValue();
}
// update snapshot with old value
_updateInflationSnapshot();
uint256 newInflationMult = (_inflationMultiplier *
inflationMultiplier) / INITIAL_INFLATION_MULTIPLIER;
inflationMultiplier = newInflationMult;
emit NewInflationMultiplier(_inflationMultiplier, newInflationMult);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override returns (uint256) {
amount = super._beforeTokenTransfer(from, to, amount);
uint256 gonsAmount = amount * inflationMultiplier;
emit BaseValueTransfer(from, to, gonsAmount);
return gonsAmount;
}
/**
* Inflation Multiplier Snapshot
* @return inflationValueMultiplier Inflation Value Muliplier at time of the Snapshot
*/
function inflationMultiplierSnapshot()
public
view
returns (uint256 inflationValueMultiplier)
{
if (
currentSnapshotBlock != block.number &&
_inflationMultiplierSnapshot.snapshotBlock < currentSnapshotBlock
) {
return inflationMultiplier;
} else {
return _inflationMultiplierSnapshot.value;
}
}
/**
* wrapper for inflationMultiplierSnapshot to maintain compatability with older interfaces
* no requires even though return value might be misleading given inability to query old snapshots just to maintain maximum compatability
* @return pastLinearInflationMultiplier Inflation Value Muliplier at time of the Snapshot
*/
function getPastLinearInflation(
uint256
) public view returns (uint256 pastLinearInflationMultiplier) {
return inflationMultiplier;
}
/**
* Access function to determine the token balance held by some address.
* @param _owner address of the owner of the voting balance
* @return inflationBalance value of the owner divided by the inflation multiplier
*/
function balanceOf(
address _owner
) public pure override returns (uint256 inflationBalance) {
return 0;
}
/**
* Access function to determine the voting balance (includes delegation) of some address.
* @param _owner the address of the account to get the balance for
* @return votingBalance The vote balance fo the owner divided by the inflation multiplier
*/
function voteBalanceOf(
address _owner
) public pure override returns (uint256 votingBalance) {
return 0;
}
/**
* Returns the total (inflation corrected) token supply
* @return totalInflatedSupply The total supply divided by the inflation multiplier
*/
function totalSupply()
public
pure
override
returns (uint256 totalInflatedSupply)
{
return 0;
}
/**
* Returns the total (inflation corrected) token supply for the current snapshot
* @return totalInflatedSupply The total supply snapshot divided by the inflation multiplier
*/
function totalSupplySnapshot()
public
pure
override
returns (uint256 totalInflatedSupply)
{
return 0;
}
/**
* Return snapshotted voting balance (includes delegation) for the current snapshot.
* @param account The account to check the votes of.
* @return snapshotted voting balance (includes delegation) for the current snapshot.
*/
function voteBalanceSnapshot(
address account
) public view override returns (uint256) {
uint256 _inflationMultiplier = inflationMultiplierSnapshot();
if (_inflationMultiplier == 0) {
return 0;
}
return 0;
}
function _updateInflationSnapshot() private {
uint32 _currentSnapshotBlock = currentSnapshotBlock;
// take no action during the snapshot block, only after it
if (_currentSnapshotBlock == block.number) {
return;
}
if (
_inflationMultiplierSnapshot.snapshotBlock < _currentSnapshotBlock
) {
uint256 currentValue = inflationMultiplier;
require(
currentValue <= type(uint224).max,
"InflationSnapshots: new snapshot cannot be casted safely"
);
_inflationMultiplierSnapshot.snapshotBlock = _currentSnapshotBlock;
_inflationMultiplierSnapshot.value = uint224(currentValue);
}
}
// protecting future upgradeability
uint256[50] private __gapInflationSnapshots;
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/TotalSupplySnapshots.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20MintAndBurn.sol";
/**
* @dev Basic snapshotting just for total supply.
*
* This extension maintains a snapshot the total supply which updates on mint or burn after a new snapshot is taken.
*/
abstract contract TotalSupplySnapshots is ERC20MintAndBurn {
// structure for saving snapshotted values
struct Snapshot {
uint32 snapshotBlock;
uint224 value;
}
// the reference snapshotBlock that the update function checks against
uint32 public currentSnapshotBlock;
// the snapshot to track the token total supply
Snapshot internal _totalSupplySnapshot;
/**
* @dev Emitted by {_snapshot} when a new snapshot is created.
*
* @param block the new value of currentSnapshotBlock
*/
event NewSnapshotBlock(uint256 block);
constructor(
Policy _policy,
string memory _name,
string memory _symbol,
address _initialPauser
) ERC20MintAndBurn(_policy, _name, _symbol, _initialPauser) {
// snapshot on creation to make it clear that everyone's balances should be updated
_snapshot();
}
function initialize(
address _self
) public virtual override onlyConstruction {
super.initialize(_self);
// snapshot on initialization to make it clear that everyone's balances should be updated after upgrade
_snapshot();
}
/**
* @dev Retrieve the `totalSupply` for the snapshot
*/
function totalSupplySnapshot() public view virtual returns (uint256) {
if (
currentSnapshotBlock != block.number &&
_totalSupplySnapshot.snapshotBlock < currentSnapshotBlock
) {
return _totalSupply;
} else {
return _totalSupplySnapshot.value;
}
}
/**
* Update total supply snapshots before the values are modified. This is implemented
* in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override returns (uint256) {
if (from == address(0)) {
// mint
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateTotalSupplySnapshot();
}
return super._beforeTokenTransfer(from, to, amount);
}
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {NewSnapshotBlock} event that contains the same id.
*/
function _snapshot() internal virtual {
// the math will error if the snapshot overflows
currentSnapshotBlock = uint32(block.number);
emit NewSnapshotBlock(block.number);
}
function _updateTotalSupplySnapshot() private {
uint32 _currentSnapshotBlock = currentSnapshotBlock;
// take no action during the snapshot block, only after it
if (_currentSnapshotBlock == block.number) {
return;
}
if (_totalSupplySnapshot.snapshotBlock < _currentSnapshotBlock) {
uint256 currentValue = _totalSupply;
require(
currentValue <= type(uint224).max,
"VoteSnapshots: new snapshot cannot be casted safely"
);
_totalSupplySnapshot.snapshotBlock = _currentSnapshotBlock;
_totalSupplySnapshot.value = uint224(currentValue);
}
}
// protecting future upgradeability
uint256[50] private __gapTotalSupplySnapshots;
}
src/3_Eco_Zero_Proposal/Eco_Zero_Dependencies/VoteSnapshots.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20Delegated.sol";
/**
* Extension of ERC20Delegated to support snapshotting.
*
* This extension maintains a snapshot of each addresses's votes which updates on the transfer after a new snapshot is taken.
* Only addresses that have opted into voting are snapshotted.
*/
abstract contract VoteSnapshots is ERC20Delegated {
/// mapping of each address to it's latest snapshot of votes
mapping(address => Snapshot) private _voteSnapshots;
/** Construct a new instance.
*
* the root _policy needs to be passed down through to service ERC20BurnAndMint
*/
constructor(
Policy _policy,
string memory _name,
string memory _symbol,
address _initialPauser
) ERC20Delegated(_policy, _name, _symbol, _initialPauser) {
// call to super constructor
}
/**
* Retrieve the balance for the snapshot
*
* @param account the address to check vote balances for
* @return balance the balance for the acccount for the snapshot
*/
function voteBalanceSnapshot(
address account
) public view virtual returns (uint256 balance) {
Snapshot memory _accountSnapshot = _voteSnapshots[account];
if (
currentSnapshotBlock != block.number &&
_accountSnapshot.snapshotBlock < currentSnapshotBlock
) {
return _voteBalances[account];
} else {
balance = _accountSnapshot.value;
}
return balance;
}
/**
* Update balance snapshots for votes before the values are modified. This is implemented
* in the _beforeVoteTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
* @param from the from address for the transfer
* @param to the to address for the transfer
* @param amount the amount of the transfer
*/
function _beforeVoteTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeVoteTokenTransfer(from, to, amount);
if (from != address(0) && voter[from]) {
_updateAccountSnapshot(from);
}
if (to != address(0) && voter[to]) {
_updateAccountSnapshot(to);
}
}
function _updateAccountSnapshot(address account) private {
uint32 _currentSnapshotBlock = currentSnapshotBlock;
// take no action during the snapshot block, only after it
if (_currentSnapshotBlock == block.number) {
return;
}
Snapshot storage snapshot = _voteSnapshots[account];
uint256 currentValue = _voteBalances[account];
if (snapshot.snapshotBlock < _currentSnapshotBlock) {
require(
currentValue <= type(uint224).max,
"VoteSnapshots: new snapshot cannot be casted safely"
);
snapshot.snapshotBlock = _currentSnapshotBlock;
snapshot.value = uint224(currentValue);
}
}
// protecting future upgradeability
uint256[50] private __gapVoteSnapshots;
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
":@ensdomains/=lib/currency-1.5/node_modules/@ensdomains/",
":@eth-optimism/=lib/op-eco/node_modules/@eth-optimism/",
":@helix-foundation/=lib/currency-1.5/node_modules/@helix-foundation/",
":@openzeppelin-currency/=lib/currency-1.5/node_modules/@openzeppelin/",
":@openzeppelin-op-eco/=lib/op-eco/node_modules/@openzeppelin/",
":@openzeppelin/=lib/currency-1.5/node_modules/@openzeppelin/",
":currency-1.5/=lib/currency-1.5/contracts/",
":eth-gas-reporter/=lib/currency-1.5/node_modules/eth-gas-reporter/",
":forge-std/=lib/forge-std/src/",
":hardhat/=lib/currency-1.5/node_modules/hardhat/",
":op-eco/=lib/op-eco/contracts/",
"lib/currency-1.5/:@helix-foundation/=lib/currency-1.5/node_modules/@helix-foundation/",
"lib/currency-1.5/:@openzeppelin/=lib/currency-1.5/node_modules/@openzeppelin/",
"lib/op-eco/:@helix-foundation/=lib/op-eco/node_modules/@helix-foundation/",
"lib/op-eco/:@openzeppelin/=lib/op-eco/node_modules/@openzeppelin/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.