ETH Price: $1,980.02 (-3.31%)
Gas: 0.18 Gwei

Transaction Decoder

Block:
14876092 at May-31-2022 02:01:21 AM +UTC
Transaction Fee:
0.001039977421269588 ETH $2.06
Gas Used:
39,726 Gas / 26.178760038 Gwei

Account State Difference:

  Address   Before After State Difference Code
(2Miners: PPLNS)
7,539.239523580568043769 Eth7,539.239573560649043217 Eth0.000049980080999448
0x6B0b3a98...1cE324181
0x84A2dDeD...C870CA60b
0.00157072560228 Eth
Nonce: 0
0.000530748181010412 Eth
Nonce: 1
0.001039977421269588

Execution Trace

AliERC20v2.transfer( _to=0x120051a72966950B8ce12eB5496B5D1eEEC1541B, _value=1619579296810168495826 ) => ( success=True )
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/ERC1363Spec.sol";
import "../interfaces/EIP2612.sol";
import "../interfaces/EIP3009.sol";
import "../utils/AccessControl.sol";
import "../lib/AddressUtils.sol";
import "../lib/ECDSA.sol";
/**
 * @title Artificial Liquid Intelligence ERC20 Token (Alethea, ALI)
 *
 * @notice ALI is the native utility token of the Alethea AI Protocol.
 *      It serves as protocol currency, participates in iNFTs lifecycle,
 *      (locked when iNFT is created, released when iNFT is destroyed,
 *      consumed when iNFT is upgraded).
 *      ALI token powers up the governance protocol (Alethea DAO)
 *
 * @notice Token Summary:
 *      - Symbol: ALI
 *      - Name: Artificial Liquid Intelligence Token
 *      - Decimals: 18
 *      - Initial/maximum total supply: 10,000,000,000 ALI
 *      - Initial supply holder (initial holder) address: // TODO: [DEFINE]
 *      - Not mintable: new tokens cannot be created
 *      - Burnable: existing tokens may get destroyed, total supply may decrease
 *      - DAO Support: supports voting delegation
 *
 * @notice Features Summary:
 *      - Supports atomic allowance modification, resolves well-known ERC20 issue with approve (arXiv:1907.00903)
 *      - Voting delegation and delegation on behalf via EIP-712 (like in Compound CMP token) - gives ALI token
 *        powerful governance capabilities by allowing holders to form voting groups by electing delegates
 *      - Unlimited approval feature (like in 0x ZRX token) - saves gas for transfers on behalf
 *        by eliminating the need to update “unlimited” allowance value
 *      - ERC-1363 Payable Token - ERC721-like callback execution mechanism for transfers,
 *        transfers on behalf and approvals; allows creation of smart contracts capable of executing callbacks
 *        in response to transfer or approval in a single transaction
 *      - EIP-2612: permit - 712-signed approvals - improves user experience by allowing to use a token
 *        without having an ETH to pay gas fees
 *      - EIP-3009: Transfer With Authorization - improves user experience by allowing to use a token
 *        without having an ETH to pay gas fees
 *
 * @dev Even though smart contract has mint() function which is used to mint initial token supply,
 *      the function is disabled forever after smart contract deployment by revoking `TOKEN_CREATOR`
 *      permission from the deployer account
 *
 * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum
 *      possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens)
 *
 * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe.
 *      Additionally, Solidity 0.8.7 enforces overflow/underflow safety.
 *
 * @dev Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) - resolved
 *      Related events and functions are marked with "arXiv:1907.00903" tag:
 *        - event Transfer(address indexed _by, address indexed _from, address indexed _to, uint256 _value)
 *        - event Approve(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value)
 *        - function increaseAllowance(address _spender, uint256 _value) public returns (bool)
 *        - function decreaseAllowance(address _spender, uint256 _value) public returns (bool)
 *      See: https://arxiv.org/abs/1907.00903v1
 *           https://ieeexplore.ieee.org/document/8802438
 *      See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
 *
 * @dev Reviewed
 *      ERC-20   - according to https://eips.ethereum.org/EIPS/eip-20
 *      ERC-1363 - according to https://eips.ethereum.org/EIPS/eip-1363
 *      EIP-2612 - according to https://eips.ethereum.org/EIPS/eip-2612
 *      EIP-3009 - according to https://eips.ethereum.org/EIPS/eip-3009
 *
 * @dev ERC20: contract has passed
 *      - OpenZeppelin ERC20 tests
 *        https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js
 *        https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js
 *      - Ref ERC1363 tests
 *        https://github.com/vittominacori/erc1363-payable-token/blob/master/test/token/ERC1363/ERC1363.behaviour.js
 *      - OpenZeppelin EIP2612 tests
 *        https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/draft-ERC20Permit.test.js
 *      - Coinbase EIP3009 tests
 *        https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts
 *      - Compound voting delegation tests
 *        https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js
 *        https://github.com/compound-finance/compound-protocol/blob/master/tests/Utils/EIP712.js
 *      - OpenZeppelin voting delegation tests
 *        https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/ERC20Votes.test.js
 *      See adopted copies of all the tests in the project test folder
 *
 * @dev Compound-like voting delegation functions', public getters', and events' names
 *      were changed for better code readability (Alethea Name <- Comp/Zeppelin name):
 *      - votingDelegates           <- delegates
 *      - votingPowerHistory        <- checkpoints
 *      - votingPowerHistoryLength  <- numCheckpoints
 *      - totalSupplyHistory        <- _totalSupplyCheckpoints (private)
 *      - usedNonces                <- nonces (note: nonces are random instead of sequential)
 *      - DelegateChanged (unchanged)
 *      - VotingPowerChanged        <- DelegateVotesChanged
 *      - votingPowerOf             <- getCurrentVotes
 *      - votingPowerAt             <- getPriorVotes
 *      - totalSupplyAt             <- getPriorTotalSupply
 *      - delegate (unchanged)
 *      - delegateWithAuthorization <- delegateBySig
 * @dev Compound-like voting delegation improved to allow the use of random nonces like in EIP-3009,
 *      instead of sequential; same `usedNonces` EIP-3009 mapping is used to track nonces
 *
 * @dev Reference implementations "used":
 *      - Atomic allowance:    https://github.com/OpenZeppelin/openzeppelin-contracts
 *      - Unlimited allowance: https://github.com/0xProject/protocol
 *      - Voting delegation:   https://github.com/compound-finance/compound-protocol
 *                             https://github.com/OpenZeppelin/openzeppelin-contracts
 *      - ERC-1363:            https://github.com/vittominacori/erc1363-payable-token
 *      - EIP-2612:            https://github.com/Uniswap/uniswap-v2-core
 *      - EIP-3009:            https://github.com/centrehq/centre-tokens
 *                             https://github.com/CoinbaseStablecoin/eip-3009
 *      - Meta transactions:   https://github.com/0xProject/protocol
 *
 * @dev Includes resolutions for ALI ERC20 Audit by Miguel Palhas, https://hackmd.io/@naps62/alierc20-audit
 */
contract AliERC20v2 is ERC1363, EIP2612, EIP3009, AccessControl {
\t/**
\t * @dev Smart contract unique identifier, a random number
\t *
\t * @dev Should be regenerated each time smart contact source code is changed
\t *      and changes smart contract itself is to be redeployed
\t *
\t * @dev Generated using https://www.random.org/bytes/
\t */
\tuint256 public constant TOKEN_UID = 0x8d4fb97da97378ef7d0ad259aec651f42bd22c200159282baa58486bb390286b;
\t/**
\t * @notice Name of the token: Artificial Liquid Intelligence Token
\t *
\t * @notice ERC20 name of the token (long name)
\t *
\t * @dev ERC20 `function name() public view returns (string)`
\t *
\t * @dev Field is declared public: getter name() is created when compiled,
\t *      it returns the name of the token.
\t */
\tstring public constant name = "Artificial Liquid Intelligence Token";
\t/**
\t * @notice Symbol of the token: ALI
\t *
\t * @notice ERC20 symbol of that token (short name)
\t *
\t * @dev ERC20 `function symbol() public view returns (string)`
\t *
\t * @dev Field is declared public: getter symbol() is created when compiled,
\t *      it returns the symbol of the token
\t */
\tstring public constant symbol = "ALI";
\t/**
\t * @notice Decimals of the token: 18
\t *
\t * @dev ERC20 `function decimals() public view returns (uint8)`
\t *
\t * @dev Field is declared public: getter decimals() is created when compiled,
\t *      it returns the number of decimals used to get its user representation.
\t *      For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should
\t *      be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`).
\t *
\t * @dev NOTE: This information is only used for _display_ purposes: it in
\t *      no way affects any of the arithmetic of the contract, including balanceOf() and transfer().
\t */
\tuint8 public constant decimals = 18;
\t/**
\t * @notice Total supply of the token: initially 10,000,000,000,
\t *      with the potential to decline over time as some tokens may get burnt but not minted
\t *
\t * @dev ERC20 `function totalSupply() public view returns (uint256)`
\t *
\t * @dev Field is declared public: getter totalSupply() is created when compiled,
\t *      it returns the amount of tokens in existence.
\t */
\tuint256 public override totalSupply; // is set to 10 billion * 10^18 in the constructor
\t/**
\t * @dev A record of all the token balances
\t * @dev This mapping keeps record of all token owners:
\t *      owner => balance
\t */
\tmapping(address => uint256) private tokenBalances;
\t/**
\t * @notice A record of each account's voting delegate
\t *
\t * @dev Auxiliary data structure used to sum up an account's voting power
\t *
\t * @dev This mapping keeps record of all voting power delegations:
\t *      voting delegator (token owner) => voting delegate
\t */
\tmapping(address => address) public votingDelegates;
\t/**
\t * @notice Auxiliary structure to store key-value pair, used to store:
\t *      - voting power record (key: block.timestamp, value: voting power)
\t *      - total supply record (key: block.timestamp, value: total supply)
\t * @notice A voting power record binds voting power of a delegate to a particular
\t *      block when the voting power delegation change happened
\t *         k: block.number when delegation has changed; starting from
\t *            that block voting power value is in effect
\t *         v: cumulative voting power a delegate has obtained starting
\t *            from the block stored in blockNumber
\t * @notice Total supply record binds total token supply to a particular
\t *      block when total supply change happened (due to mint/burn operations)
\t */
\tstruct KV {
\t\t/*
\t\t * @dev key, a block number
\t\t */
\t\tuint64 k;
\t\t/*
\t\t * @dev value, token balance or voting power
\t\t */
\t\tuint192 v;
\t}
\t/**
\t * @notice A record of each account's voting power historical data
\t *
\t * @dev Primarily data structure to store voting power for each account.
\t *      Voting power sums up from the account's token balance and delegated
\t *      balances.
\t *
\t * @dev Stores current value and entire history of its changes.
\t *      The changes are stored as an array of checkpoints (key-value pairs).
\t *      Checkpoint is an auxiliary data structure containing voting
\t *      power (number of votes) and block number when the checkpoint is saved
\t *
\t * @dev Maps voting delegate => voting power record
\t */
\tmapping(address => KV[]) public votingPowerHistory;
\t/**
\t * @notice A record of total token supply historical data
\t *
\t * @dev Primarily data structure to store total token supply.
\t *
\t * @dev Stores current value and entire history of its changes.
\t *      The changes are stored as an array of checkpoints (key-value pairs).
\t *      Checkpoint is an auxiliary data structure containing total
\t *      token supply and block number when the checkpoint is saved
\t */
\tKV[] public totalSupplyHistory;
\t/**
\t * @dev A record of nonces for signing/validating signatures in EIP-2612 `permit`
\t *
\t * @dev Note: EIP2612 doesn't imply a possibility for nonce randomization like in EIP-3009
\t *
\t * @dev Maps delegate address => delegate nonce
\t */
\tmapping(address => uint256) public override nonces;
\t/**
\t * @dev A record of used nonces for EIP-3009 transactions
\t *
\t * @dev A record of used nonces for signing/validating signatures
\t *      in `delegateWithAuthorization` for every delegate
\t *
\t * @dev Maps authorizer address => nonce => true/false (used unused)
\t */
\tmapping(address => mapping(bytes32 => bool)) private usedNonces;
\t/**
\t * @notice A record of all the allowances to spend tokens on behalf
\t * @dev Maps token owner address to an address approved to spend
\t *      some tokens on behalf, maps approved address to that amount
\t * @dev owner => spender => value
\t */
\tmapping(address => mapping(address => uint256)) private transferAllowances;
\t/**
\t * @notice Enables ERC20 transfers of the tokens
\t *      (transfer by the token owner himself)
\t * @dev Feature FEATURE_TRANSFERS must be enabled in order for
\t *      `transfer()` function to succeed
\t */
\tuint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
\t/**
\t * @notice Enables ERC20 transfers on behalf
\t *      (transfer by someone else on behalf of token owner)
\t * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for
\t *      `transferFrom()` function to succeed
\t * @dev Token owner must call `approve()` first to authorize
\t *      the transfer on behalf
\t */
\tuint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002;
\t/**
\t * @dev Defines if the default behavior of `transfer` and `transferFrom`
\t *      checks if the receiver smart contract supports ERC20 tokens
\t * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not
\t *      check if the receiver smart contract supports ERC20 tokens,
\t *      i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom`
\t * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers
\t *      check if the receiver smart contract supports ERC20 tokens,
\t *      i.e. `transfer` and `transferFrom` behave like `transferFromAndCall`
\t */
\tuint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
\t/**
\t * @notice Enables token owners to burn their own tokens
\t *
\t * @dev Feature FEATURE_OWN_BURNS must be enabled in order for
\t *      `burn()` function to succeed when called by token owner
\t */
\tuint32 public constant FEATURE_OWN_BURNS = 0x0000_0008;
\t/**
\t * @notice Enables approved operators to burn tokens on behalf of their owners
\t *
\t * @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for
\t *      `burn()` function to succeed when called by approved operator
\t */
\tuint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
\t/**
\t * @notice Enables delegators to elect delegates
\t * @dev Feature FEATURE_DELEGATIONS must be enabled in order for
\t *      `delegate()` function to succeed
\t */
\tuint32 public constant FEATURE_DELEGATIONS = 0x0000_0020;
\t/**
\t * @notice Enables delegators to elect delegates on behalf
\t *      (via an EIP712 signature)
\t * @dev Feature FEATURE_DELEGATIONS_ON_BEHALF must be enabled in order for
\t *      `delegateWithAuthorization()` function to succeed
\t */
\tuint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040;
\t/**
\t * @notice Enables ERC-1363 transfers with callback
\t * @dev Feature FEATURE_ERC1363_TRANSFERS must be enabled in order for
\t *      ERC-1363 `transferFromAndCall` functions to succeed
\t */
\tuint32 public constant FEATURE_ERC1363_TRANSFERS = 0x0000_0080;
\t/**
\t * @notice Enables ERC-1363 approvals with callback
\t * @dev Feature FEATURE_ERC1363_APPROVALS must be enabled in order for
\t *      ERC-1363 `approveAndCall` functions to succeed
\t */
\tuint32 public constant FEATURE_ERC1363_APPROVALS = 0x0000_0100;
\t/**
\t * @notice Enables approvals on behalf (EIP2612 permits
\t *      via an EIP712 signature)
\t * @dev Feature FEATURE_EIP2612_PERMITS must be enabled in order for
\t *      `permit()` function to succeed
\t */
\tuint32 public constant FEATURE_EIP2612_PERMITS = 0x0000_0200;
\t/**
\t * @notice Enables meta transfers on behalf (EIP3009 transfers
\t *      via an EIP712 signature)
\t * @dev Feature FEATURE_EIP3009_TRANSFERS must be enabled in order for
\t *      `transferWithAuthorization()` function to succeed
\t */
\tuint32 public constant FEATURE_EIP3009_TRANSFERS = 0x0000_0400;
\t/**
\t * @notice Enables meta transfers on behalf (EIP3009 transfers
\t *      via an EIP712 signature)
\t * @dev Feature FEATURE_EIP3009_RECEPTIONS must be enabled in order for
\t *      `receiveWithAuthorization()` function to succeed
\t */
\tuint32 public constant FEATURE_EIP3009_RECEPTIONS = 0x0000_0800;
\t/**
\t * @notice Token creator is responsible for creating (minting)
\t *      tokens to an arbitrary address
\t * @dev Role ROLE_TOKEN_CREATOR allows minting tokens
\t *      (calling `mint` function)
\t */
\tuint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
\t/**
\t * @notice Token destroyer is responsible for destroying (burning)
\t *      tokens owned by an arbitrary address
\t * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
\t *      (calling `burn` function)
\t */
\tuint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000;
\t/**
\t * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks,
\t *      which may be useful to simplify tokens transfers into "legacy" smart contracts
\t * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having
\t *      `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens
\t *      via `transfer` and `transferFrom` functions in the same way they
\t *      would via `unsafeTransferFrom` function
\t * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission
\t *      doesn't affect the transfer behaviour since
\t *      `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
\t * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER
\t */
\tuint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000;
\t/**
\t * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks,
\t *      which may be useful to simplify tokens transfers into "legacy" smart contracts
\t * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having
\t *      `ROLE_ERC20_SENDER` permission are allowed to send tokens
\t *      via `transfer` and `transferFrom` functions in the same way they
\t *      would via `unsafeTransferFrom` function
\t * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission
\t *      doesn't affect the transfer behaviour since
\t *      `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
\t * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER
\t */
\tuint32 public constant ROLE_ERC20_SENDER = 0x0008_0000;
\t/**
\t * @notice EIP-712 contract's domain typeHash,
\t *      see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
\t *
\t * @dev Note: we do not include version into the domain typehash/separator,
\t *      it is implied version is concatenated to the name field, like "AliERC20v2"
\t */
\t// keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)")
\tbytes32 public constant DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866;
\t/**
\t * @notice EIP-712 contract's domain separator,
\t *      see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
\t */
\tbytes32 public immutable override DOMAIN_SEPARATOR;
\t/**
\t * @notice EIP-712 delegation struct typeHash,
\t *      see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
\t */
\t// keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)")
\tbytes32 public constant DELEGATION_TYPEHASH = 0xff41620983935eb4d4a3c7384a066ca8c1d10cef9a5eca9eb97ca735cd14a755;
\t/**
\t * @notice EIP-712 permit (EIP-2612) struct typeHash,
\t *      see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
\t */
\t// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
\tbytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
\t/**
\t * @notice EIP-712 TransferWithAuthorization (EIP-3009) struct typeHash,
\t *      see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
\t */
\t// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
\tbytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
\t/**
\t * @notice EIP-712 ReceiveWithAuthorization (EIP-3009) struct typeHash,
\t *      see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
\t */
\t// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
\tbytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
\t/**
\t * @notice EIP-712 CancelAuthorization (EIP-3009) struct typeHash,
\t *      see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
\t */
\t// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
\tbytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
\t/**
\t * @dev Fired in mint() function
\t *
\t * @param by an address which minted some tokens (transaction sender)
\t * @param to an address the tokens were minted to
\t * @param value an amount of tokens minted
\t */
\tevent Minted(address indexed by, address indexed to, uint256 value);
\t/**
\t * @dev Fired in burn() function
\t *
\t * @param by an address which burned some tokens (transaction sender)
\t * @param from an address the tokens were burnt from
\t * @param value an amount of tokens burnt
\t */
\tevent Burnt(address indexed by, address indexed from, uint256 value);
\t/**
\t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
\t *
\t * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer
\t *
\t * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
\t *
\t * @param by an address which performed the transfer
\t * @param from an address tokens were consumed from
\t * @param to an address tokens were sent to
\t * @param value number of tokens transferred
\t */
\tevent Transfer(address indexed by, address indexed from, address indexed to, uint256 value);
\t/**
\t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
\t *
\t * @dev Similar to ERC20 Approve event, but also logs old approval value
\t *
\t * @dev Fired in approve(), increaseAllowance(), decreaseAllowance() functions,
\t *      may get fired in transfer functions
\t *
\t * @param owner an address which granted a permission to transfer
\t *      tokens on its behalf
\t * @param spender an address which received a permission to transfer
\t *      tokens on behalf of the owner `_owner`
\t * @param oldValue previously granted amount of tokens to transfer on behalf
\t * @param value new granted amount of tokens to transfer on behalf
\t */
\tevent Approval(address indexed owner, address indexed spender, uint256 oldValue, uint256 value);
\t/**
\t * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed,
\t *      i.e. a delegator address has changed its delegate address
\t *
\t * @param source delegator address, a token owner, effectively transaction sender (`by`)
\t * @param from old delegate, an address which delegate right is revoked
\t * @param to new delegate, an address which received the voting power
\t */
\tevent DelegateChanged(address indexed source, address indexed from, address indexed to);
\t/**
\t * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed,
\t *      i.e. a delegate's voting power has changed.
\t *
\t * @param by an address which executed delegate, mint, burn, or transfer operation
\t *      which had led to delegate voting power change
\t * @param target delegate whose voting power has changed
\t * @param fromVal previous number of votes delegate had
\t * @param toVal new number of votes delegate has
\t */
\tevent VotingPowerChanged(address indexed by, address indexed target, uint256 fromVal, uint256 toVal);
\t/**
\t * @dev Deploys the token smart contract,
\t *      assigns initial token supply to the address specified
\t *
\t * @param _initialHolder owner of the initial token supply
\t */
\tconstructor(address _initialHolder) {
\t\t// verify initial holder address non-zero (is set)
\t\trequire(_initialHolder != address(0), "_initialHolder not set (zero address)");
\t\t// build the EIP-712 contract domain separator, see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
\t\t// note: we specify contract version in its name
\t\tDOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("AliERC20v2")), block.chainid, address(this)));
\t\t// mint initial supply
\t\tmint(_initialHolder, 10_000_000_000e18);
\t}
\t/**
\t * @inheritdoc ERC165
\t */
\tfunction supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
\t\t// reconstruct from current interface(s) and super interface(s) (if any)
\t\treturn interfaceId == type(ERC165).interfaceId
\t\t    || interfaceId == type(ERC20).interfaceId
\t\t    || interfaceId == type(ERC1363).interfaceId
\t\t    || interfaceId == type(EIP2612).interfaceId
\t\t    || interfaceId == type(EIP3009).interfaceId;
\t}
\t// ===== Start: ERC-1363 functions =====
\t/**
\t * @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver
\t *
\t * @inheritdoc ERC1363
\t *
\t * @dev Called by token owner (an address which has a
\t *      positive token balance tracked by this smart contract)
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * EOA or smart contract which doesn't support ERC1363Receiver interface
\t * @dev Returns true on success, throws otherwise
\t *
\t * @param _to an address to transfer tokens to,
\t *      must be a smart contract, implementing ERC1363Receiver
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @return true unless throwing
\t */
\tfunction transferAndCall(address _to, uint256 _value) public override returns (bool) {
\t\t// delegate to `transferFromAndCall` passing `msg.sender` as `_from`
\t\treturn transferFromAndCall(msg.sender, _to, _value);
\t}
\t/**
\t * @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver
\t *
\t * @inheritdoc ERC1363
\t *
\t * @dev Called by token owner (an address which has a
\t *      positive token balance tracked by this smart contract)
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * EOA or smart contract which doesn't support ERC1363Receiver interface
\t * @dev Returns true on success, throws otherwise
\t *
\t * @param _to an address to transfer tokens to,
\t *      must be a smart contract, implementing ERC1363Receiver
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @param _data [optional] additional data with no specified format,
\t *      sent in onTransferReceived call to `_to`
\t * @return true unless throwing
\t */
\tfunction transferAndCall(address _to, uint256 _value, bytes memory _data) public override returns (bool) {
\t\t// delegate to `transferFromAndCall` passing `msg.sender` as `_from`
\t\treturn transferFromAndCall(msg.sender, _to, _value, _data);
\t}
\t/**
\t * @notice Transfers some tokens on behalf of address `_from' (token owner)
\t *      to some other address `_to` and then executes `onTransferReceived` callback on the receiver
\t *
\t * @inheritdoc ERC1363
\t *
\t * @dev Called by token owner on his own or approved address,
\t *      an address approved earlier by token owner to
\t *      transfer some amount of tokens on its behalf
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * EOA or smart contract which doesn't support ERC1363Receiver interface
\t * @dev Returns true on success, throws otherwise
\t *
\t * @param _from token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to an address to transfer tokens to,
\t *      must be a smart contract, implementing ERC1363Receiver
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @return true unless throwing
\t */
\tfunction transferFromAndCall(address _from, address _to, uint256 _value) public override returns (bool) {
\t\t// delegate to `transferFromAndCall` passing empty data param
\t\treturn transferFromAndCall(_from, _to, _value, "");
\t}
\t/**
\t * @notice Transfers some tokens on behalf of address `_from' (token owner)
\t *      to some other address `_to` and then executes a `onTransferReceived` callback on the receiver
\t *
\t * @inheritdoc ERC1363
\t *
\t * @dev Called by token owner on his own or approved address,
\t *      an address approved earlier by token owner to
\t *      transfer some amount of tokens on its behalf
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * EOA or smart contract which doesn't support ERC1363Receiver interface
\t * @dev Returns true on success, throws otherwise
\t *
\t * @param _from token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to an address to transfer tokens to,
\t *      must be a smart contract, implementing ERC1363Receiver
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @param _data [optional] additional data with no specified format,
\t *      sent in onTransferReceived call to `_to`
\t * @return true unless throwing
\t */
\tfunction transferFromAndCall(address _from, address _to, uint256 _value, bytes memory _data) public override returns (bool) {
\t\t// ensure ERC-1363 transfers are enabled
\t\trequire(isFeatureEnabled(FEATURE_ERC1363_TRANSFERS), "ERC1363 transfers are disabled");
\t\t// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer
\t\tunsafeTransferFrom(_from, _to, _value);
\t\t// after the successful transfer - check if receiver supports
\t\t// ERC1363Receiver and execute a callback handler `onTransferReceived`,
\t\t// reverting whole transaction on any error
\t\t_notifyTransferred(_from, _to, _value, _data, false);
\t\t// function throws on any error, so if we're here - it means operation successful, just return true
\t\treturn true;
\t}
\t/**
\t * @notice Approves address called `_spender` to transfer some amount
\t *      of tokens on behalf of the owner, then executes a `onApprovalReceived` callback on `_spender`
\t *
\t * @inheritdoc ERC1363
\t *
\t * @dev Caller must not necessarily own any tokens to grant the permission
\t *
\t * @dev Throws if `_spender` is an EOA or a smart contract which doesn't support ERC1363Spender interface
\t *
\t * @param _spender an address approved by the caller (token owner)
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens spender `_spender` is allowed to
\t *      transfer on behalf of the token owner
\t * @return success true on success, throws otherwise
\t */
\tfunction approveAndCall(address _spender, uint256 _value) public override returns (bool) {
\t\t// delegate to `approveAndCall` passing empty data
\t\treturn approveAndCall(_spender, _value, "");
\t}
\t/**
\t * @notice Approves address called `_spender` to transfer some amount
\t *      of tokens on behalf of the owner, then executes a callback on `_spender`
\t *
\t * @inheritdoc ERC1363
\t *
\t * @dev Caller must not necessarily own any tokens to grant the permission
\t *
\t * @param _spender an address approved by the caller (token owner)
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens spender `_spender` is allowed to
\t *      transfer on behalf of the token owner
\t * @param _data [optional] additional data with no specified format,
\t *      sent in onApprovalReceived call to `_spender`
\t * @return success true on success, throws otherwise
\t */
\tfunction approveAndCall(address _spender, uint256 _value, bytes memory _data) public override returns (bool) {
\t\t// ensure ERC-1363 approvals are enabled
\t\trequire(isFeatureEnabled(FEATURE_ERC1363_APPROVALS), "ERC1363 approvals are disabled");
\t\t// execute regular ERC20 approve - delegate to `approve`
\t\tapprove(_spender, _value);
\t\t// after the successful approve - check if receiver supports
\t\t// ERC1363Spender and execute a callback handler `onApprovalReceived`,
\t\t// reverting whole transaction on any error
\t\t_notifyApproved(_spender, _value, _data);
\t\t// function throws on any error, so if we're here - it means operation successful, just return true
\t\treturn true;
\t}
\t/**
\t * @dev Auxiliary function to invoke `onTransferReceived` on a target address
\t *      The call is not executed if the target address is not a contract; in such
\t *      a case function throws if `allowEoa` is set to false, succeeds if it's true
\t *
\t * @dev Throws on any error; returns silently on success
\t *
\t * @param _from representing the previous owner of the given token value
\t * @param _to target address that will receive the tokens
\t * @param _value the amount mount of tokens to be transferred
\t * @param _data [optional] data to send along with the call
\t * @param allowEoa indicates if function should fail if `_to` is an EOA
\t */
\tfunction _notifyTransferred(address _from, address _to, uint256 _value, bytes memory _data, bool allowEoa) private {
\t\t// if recipient `_to` is EOA
\t\tif (!AddressUtils.isContract(_to)) {
\t\t\t// ensure EOA recipient is allowed
\t\t\trequire(allowEoa, "EOA recipient");
\t\t\t// exit if successful
\t\t\treturn;
\t\t}
\t\t// otherwise - if `_to` is a contract - execute onTransferReceived
\t\tbytes4 response = ERC1363Receiver(_to).onTransferReceived(msg.sender, _from, _value, _data);
\t\t// expected response is ERC1363Receiver(_to).onTransferReceived.selector
\t\t// bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
\t\trequire(response == ERC1363Receiver(_to).onTransferReceived.selector, "invalid onTransferReceived response");
\t}
\t/**
\t * @dev Auxiliary function to invoke `onApprovalReceived` on a target address
\t *      The call is not executed if the target address is not a contract; in such
\t *      a case function throws if `allowEoa` is set to false, succeeds if it's true
\t *
\t * @dev Throws on any error; returns silently on success
\t *
\t * @param _spender the address which will spend the funds
\t * @param _value the amount of tokens to be spent
\t * @param _data [optional] data to send along with the call
\t */
\tfunction _notifyApproved(address _spender, uint256 _value, bytes memory _data) private {
\t\t// ensure recipient is not EOA
\t\trequire(AddressUtils.isContract(_spender), "EOA spender");
\t\t// otherwise - if `_to` is a contract - execute onApprovalReceived
\t\tbytes4 response = ERC1363Spender(_spender).onApprovalReceived(msg.sender, _value, _data);
\t\t// expected response is ERC1363Spender(_to).onApprovalReceived.selector
\t\t// bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
\t\trequire(response == ERC1363Spender(_spender).onApprovalReceived.selector, "invalid onApprovalReceived response");
\t}
\t// ===== End: ERC-1363 functions =====
\t// ===== Start: ERC20 functions =====
\t/**
\t * @notice Gets the balance of a particular address
\t *
\t * @inheritdoc ERC20
\t *
\t * @param _owner the address to query the the balance for
\t * @return balance an amount of tokens owned by the address specified
\t */
\tfunction balanceOf(address _owner) public view override returns (uint256 balance) {
\t\t// read the balance and return
\t\treturn tokenBalances[_owner];
\t}
\t/**
\t * @notice Transfers some tokens to an external address or a smart contract
\t *
\t * @inheritdoc ERC20
\t *
\t * @dev Called by token owner (an address which has a
\t *      positive token balance tracked by this smart contract)
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * self address or
\t *          * smart contract which doesn't support ERC20
\t *
\t * @param _to an address to transfer tokens to,
\t *      must be either an external address or a smart contract,
\t *      compliant with the ERC20 standard
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @return success true on success, throws otherwise
\t */
\tfunction transfer(address _to, uint256 _value) public override returns (bool success) {
\t\t// just delegate call to `transferFrom`,
\t\t// `FEATURE_TRANSFERS` is verified inside it
\t\treturn transferFrom(msg.sender, _to, _value);
\t}
\t/**
\t * @notice Transfers some tokens on behalf of address `_from' (token owner)
\t *      to some other address `_to`
\t *
\t * @inheritdoc ERC20
\t *
\t * @dev Called by token owner on his own or approved address,
\t *      an address approved earlier by token owner to
\t *      transfer some amount of tokens on its behalf
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * smart contract which doesn't support ERC20
\t *
\t * @param _from token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to an address to transfer tokens to,
\t *      must be either an external address or a smart contract,
\t *      compliant with the ERC20 standard
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @return success true on success, throws otherwise
\t */
\tfunction transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) {
\t\t// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
\t\t// or unsafe transfer
\t\t// if `FEATURE_UNSAFE_TRANSFERS` is enabled
\t\t// or receiver has `ROLE_ERC20_RECEIVER` permission
\t\t// or sender has `ROLE_ERC20_SENDER` permission
\t\tif(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)
\t\t\t|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER)
\t\t\t|| isSenderInRole(ROLE_ERC20_SENDER)) {
\t\t\t// we execute unsafe transfer - delegate call to `unsafeTransferFrom`,
\t\t\t// `FEATURE_TRANSFERS` is verified inside it
\t\t\tunsafeTransferFrom(_from, _to, _value);
\t\t}
\t\t// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled
\t\t// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission
\t\telse {
\t\t\t// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,
\t\t\t// `FEATURE_TRANSFERS` is verified inside it
\t\t\tsafeTransferFrom(_from, _to, _value, "");
\t\t}
\t\t// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so
\t\t// if we're here - it means operation successful,
\t\t// just return true
\t\treturn true;
\t}
\t/**
\t * @notice Transfers some tokens on behalf of address `_from' (token owner)
\t *      to some other address `_to` and then executes `onTransferReceived` callback
\t *      on the receiver if it is a smart contract (not an EOA)
\t *
\t * @dev Called by token owner on his own or approved address,
\t *      an address approved earlier by token owner to
\t *      transfer some amount of tokens on its behalf
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * smart contract which doesn't support ERC1363Receiver interface
\t * @dev Returns true on success, throws otherwise
\t *
\t * @param _from token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to an address to transfer tokens to,
\t *      must be either an external address or a smart contract,
\t *      implementing ERC1363Receiver
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @param _data [optional] additional data with no specified format,
\t *      sent in onTransferReceived call to `_to` in case if its a smart contract
\t * @return true unless throwing
\t */
\tfunction safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public returns (bool) {
\t\t// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer
\t\tunsafeTransferFrom(_from, _to, _value);
\t\t// after the successful transfer - check if receiver supports
\t\t// ERC1363Receiver and execute a callback handler `onTransferReceived`,
\t\t// reverting whole transaction on any error
\t\t_notifyTransferred(_from, _to, _value, _data, true);
\t\t// function throws on any error, so if we're here - it means operation successful, just return true
\t\treturn true;
\t}
\t/**
\t * @notice Transfers some tokens on behalf of address `_from' (token owner)
\t *      to some other address `_to`
\t *
\t * @dev In contrast to `transferFromAndCall` doesn't check recipient
\t *      smart contract to support ERC20 tokens (ERC1363Receiver)
\t * @dev Designed to be used by developers when the receiver is known
\t *      to support ERC20 tokens but doesn't implement ERC1363Receiver interface
\t * @dev Called by token owner on his own or approved address,
\t *      an address approved earlier by token owner to
\t *      transfer some amount of tokens on its behalf
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t * @dev Returns silently on success, throws otherwise
\t *
\t * @param _from token sender, token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to token receiver, an address to transfer tokens to
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t */
\tfunction unsafeTransferFrom(address _from, address _to, uint256 _value) public {
\t\t// make an internal transferFrom - delegate to `__transferFrom`
\t\t__transferFrom(msg.sender, _from, _to, _value);
\t}
\t/**
\t * @dev Powers the meta transactions for `unsafeTransferFrom` - EIP-3009 `transferWithAuthorization`
\t *      and `receiveWithAuthorization`
\t *
\t * @dev See `unsafeTransferFrom` and `transferFrom` soldoc for details
\t *
\t * @param _by an address executing the transfer, it can be token owner itself,
\t *      or an operator previously approved with `approve()`
\t * @param _from token sender, token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to token receiver, an address to transfer tokens to
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t */
\tfunction __transferFrom(address _by, address _from, address _to, uint256 _value) private {
\t\t// if `_from` is equal to sender, require transfers feature to be enabled
\t\t// otherwise require transfers on behalf feature to be enabled
\t\trequire(_from == _by && isFeatureEnabled(FEATURE_TRANSFERS)
\t\t     || _from != _by && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
\t\t        _from == _by? "transfers are disabled": "transfers on behalf are disabled");
\t\t// non-zero source address check - Zeppelin
\t\t// obviously, zero source address is a client mistake
\t\t// it's not part of ERC20 standard but it's reasonable to fail fast
\t\t// since for zero value transfer transaction succeeds otherwise
\t\trequire(_from != address(0), "transfer from the zero address");
\t\t// non-zero recipient address check
\t\trequire(_to != address(0), "transfer to the zero address");
\t\t// sender and recipient cannot be the same
\t\trequire(_from != _to, "sender and recipient are the same (_from = _to)");
\t\t// sending tokens to the token smart contract itself is a client mistake
\t\trequire(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
\t\t// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
\t\t// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
\t\tif(_value == 0) {
\t\t\t// emit an ERC20 transfer event
\t\t\temit Transfer(_from, _to, _value);
\t\t\t// don't forget to return - we're done
\t\t\treturn;
\t\t}
\t\t// no need to make arithmetic overflow check on the _value - by design of mint()
\t\t// in case of transfer on behalf
\t\tif(_from != _by) {
\t\t\t// read allowance value - the amount of tokens allowed to transfer - into the stack
\t\t\tuint256 _allowance = transferAllowances[_from][_by];
\t\t\t// verify sender has an allowance to transfer amount of tokens requested
\t\t\trequire(_allowance >= _value, "transfer amount exceeds allowance");
\t\t\t// we treat max uint256 allowance value as an "unlimited" and
\t\t\t// do not decrease allowance when it is set to "unlimited" value
\t\t\tif(_allowance < type(uint256).max) {
\t\t\t\t// update allowance value on the stack
\t\t\t\t_allowance -= _value;
\t\t\t\t// update the allowance value in storage
\t\t\t\ttransferAllowances[_from][_by] = _allowance;
\t\t\t\t// emit an improved atomic approve event
\t\t\t\temit Approval(_from, _by, _allowance + _value, _allowance);
\t\t\t\t// emit an ERC20 approval event to reflect the decrease
\t\t\t\temit Approval(_from, _by, _allowance);
\t\t\t}
\t\t}
\t\t// verify sender has enough tokens to transfer on behalf
\t\trequire(tokenBalances[_from] >= _value, "transfer amount exceeds balance");
\t\t// perform the transfer:
\t\t// decrease token owner (sender) balance
\t\ttokenBalances[_from] -= _value;
\t\t// increase `_to` address (receiver) balance
\t\ttokenBalances[_to] += _value;
\t\t// move voting power associated with the tokens transferred
\t\t__moveVotingPower(_by, votingDelegates[_from], votingDelegates[_to], _value);
\t\t// emit an improved transfer event (arXiv:1907.00903)
\t\temit Transfer(_by, _from, _to, _value);
\t\t// emit an ERC20 transfer event
\t\temit Transfer(_from, _to, _value);
\t}
\t/**
\t * @notice Approves address called `_spender` to transfer some amount
\t *      of tokens on behalf of the owner (transaction sender)
\t *
\t * @inheritdoc ERC20
\t *
\t * @dev Transaction sender must not necessarily own any tokens to grant the permission
\t *
\t * @param _spender an address approved by the caller (token owner)
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens spender `_spender` is allowed to
\t *      transfer on behalf of the token owner
\t * @return success true on success, throws otherwise
\t */
\tfunction approve(address _spender, uint256 _value) public override returns (bool success) {
\t\t// make an internal approve - delegate to `__approve`
\t\t__approve(msg.sender, _spender, _value);
\t\t// operation successful, return true
\t\treturn true;
\t}
\t/**
\t * @dev Powers the meta transaction for `approve` - EIP-2612 `permit`
\t *
\t * @dev Approves address called `_spender` to transfer some amount
\t *      of tokens on behalf of the `_owner`
\t *
\t * @dev `_owner` must not necessarily own any tokens to grant the permission
\t * @dev Throws if `_spender` is a zero address
\t *
\t * @param _owner owner of the tokens to set approval on behalf of
\t * @param _spender an address approved by the token owner
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens spender `_spender` is allowed to
\t *      transfer on behalf of the token owner
\t */
\tfunction __approve(address _owner, address _spender, uint256 _value) private {
\t\t// non-zero spender address check - Zeppelin
\t\t// obviously, zero spender address is a client mistake
\t\t// it's not part of ERC20 standard but it's reasonable to fail fast
\t\trequire(_spender != address(0), "approve to the zero address");
\t\t// read old approval value to emmit an improved event (arXiv:1907.00903)
\t\tuint256 _oldValue = transferAllowances[_owner][_spender];
\t\t// perform an operation: write value requested into the storage
\t\ttransferAllowances[_owner][_spender] = _value;
\t\t// emit an improved atomic approve event (arXiv:1907.00903)
\t\temit Approval(_owner, _spender, _oldValue, _value);
\t\t// emit an ERC20 approval event
\t\temit Approval(_owner, _spender, _value);
\t}
\t/**
\t * @notice Returns the amount which _spender is still allowed to withdraw from _owner.
\t *
\t * @inheritdoc ERC20
\t *
\t * @dev A function to check an amount of tokens owner approved
\t *      to transfer on its behalf by some other address called "spender"
\t *
\t * @param _owner an address which approves transferring some tokens on its behalf
\t * @param _spender an address approved to transfer some tokens on behalf
\t * @return remaining an amount of tokens approved address `_spender` can transfer on behalf
\t *      of token owner `_owner`
\t */
\tfunction allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
\t\t// read the value from storage and return
\t\treturn transferAllowances[_owner][_spender];
\t}
\t// ===== End: ERC20 functions =====
\t// ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) =====
\t/**
\t * @notice Increases the allowance granted to `spender` by the transaction sender
\t *
\t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
\t *
\t * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow
\t *
\t * @param _spender an address approved by the caller (token owner)
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens to increase by
\t * @return success true on success, throws otherwise
\t */
\tfunction increaseAllowance(address _spender, uint256 _value) public returns (bool) {
\t\t// read current allowance value
\t\tuint256 currentVal = transferAllowances[msg.sender][_spender];
\t\t// non-zero _value and arithmetic overflow check on the allowance
\t\tunchecked {
\t\t\t// put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+
\t\t\trequire(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
\t\t}
\t\t// delegate call to `approve` with the new value
\t\treturn approve(_spender, currentVal + _value);
\t}
\t/**
\t * @notice Decreases the allowance granted to `spender` by the caller.
\t *
\t * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
\t *
\t * @dev Throws if value to decrease by is zero or is greater than currently allowed value
\t *
\t * @param _spender an address approved by the caller (token owner)
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens to decrease by
\t * @return success true on success, throws otherwise
\t */
\tfunction decreaseAllowance(address _spender, uint256 _value) public returns (bool) {
\t\t// read current allowance value
\t\tuint256 currentVal = transferAllowances[msg.sender][_spender];
\t\t// non-zero _value check on the allowance
\t\trequire(_value > 0, "zero value approval decrease");
\t\t// verify allowance decrease doesn't underflow
\t\trequire(currentVal >= _value, "ERC20: decreased allowance below zero");
\t\t// delegate call to `approve` with the new value
\t\treturn approve(_spender, currentVal - _value);
\t}
\t// ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) =====
\t// ===== Start: Minting/burning extension =====
\t/**
\t * @dev Mints (creates) some tokens to address specified
\t * @dev The value specified is treated as is without taking
\t *      into account what `decimals` value is
\t *
\t * @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission
\t *
\t * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256
\t *
\t * @param _to an address to mint tokens to
\t * @param _value an amount of tokens to mint (create)
\t */
\tfunction mint(address _to, uint256 _value) public {
\t\t// check if caller has sufficient permissions to mint tokens
\t\trequire(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied");
\t\t// non-zero recipient address check
\t\trequire(_to != address(0), "zero address");
\t\t// non-zero _value and arithmetic overflow check on the total supply
\t\t// this check automatically secures arithmetic overflow on the individual balance
\t\tunchecked {
\t\t\t// put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+
\t\t\trequire(totalSupply + _value > totalSupply, "zero value or arithmetic overflow");
\t\t}
\t\t// uint192 overflow check (required by voting delegation)
\t\trequire(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)");
\t\t// perform mint:
\t\t// increase total amount of tokens value
\t\ttotalSupply += _value;
\t\t// increase `_to` address balance
\t\ttokenBalances[_to] += _value;
\t\t// update total token supply history
\t\t__updateHistory(totalSupplyHistory, add, _value);
\t\t// create voting power associated with the tokens minted
\t\t__moveVotingPower(msg.sender, address(0), votingDelegates[_to], _value);
\t\t// fire a minted event
\t\temit Minted(msg.sender, _to, _value);
\t\t// emit an improved transfer event (arXiv:1907.00903)
\t\temit Transfer(msg.sender, address(0), _to, _value);
\t\t// fire ERC20 compliant transfer event
\t\temit Transfer(address(0), _to, _value);
\t}
\t/**
\t * @dev Burns (destroys) some tokens from the address specified
\t *
\t * @dev The value specified is treated as is without taking
\t *      into account what `decimals` value is
\t *
\t * @dev Requires executor to have `ROLE_TOKEN_DESTROYER` permission
\t *      or FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features to be enabled
\t *
\t * @dev Can be disabled by the contract creator forever by disabling
\t *      FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features and then revoking
\t *      its own roles to burn tokens and to enable burning features
\t *
\t * @param _from an address to burn some tokens from
\t * @param _value an amount of tokens to burn (destroy)
\t */
\tfunction burn(address _from, uint256 _value) public {
\t\t// check if caller has sufficient permissions to burn tokens
\t\t// and if not - check for possibility to burn own tokens or to burn on behalf
\t\tif(!isSenderInRole(ROLE_TOKEN_DESTROYER)) {
\t\t\t// if `_from` is equal to sender, require own burns feature to be enabled
\t\t\t// otherwise require burns on behalf feature to be enabled
\t\t\trequire(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS)
\t\t\t     || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF),
\t\t\t        _from == msg.sender? "burns are disabled": "burns on behalf are disabled");
\t\t\t// in case of burn on behalf
\t\t\tif(_from != msg.sender) {
\t\t\t\t// read allowance value - the amount of tokens allowed to be burnt - into the stack
\t\t\t\tuint256 _allowance = transferAllowances[_from][msg.sender];
\t\t\t\t// verify sender has an allowance to burn amount of tokens requested
\t\t\t\trequire(_allowance >= _value, "burn amount exceeds allowance");
\t\t\t\t// we treat max uint256 allowance value as an "unlimited" and
\t\t\t\t// do not decrease allowance when it is set to "unlimited" value
\t\t\t\tif(_allowance < type(uint256).max) {
\t\t\t\t\t// update allowance value on the stack
\t\t\t\t\t_allowance -= _value;
\t\t\t\t\t// update the allowance value in storage
\t\t\t\t\ttransferAllowances[_from][msg.sender] = _allowance;
\t\t\t\t\t// emit an improved atomic approve event (arXiv:1907.00903)
\t\t\t\t\temit Approval(msg.sender, _from, _allowance + _value, _allowance);
\t\t\t\t\t// emit an ERC20 approval event to reflect the decrease
\t\t\t\t\temit Approval(_from, msg.sender, _allowance);
\t\t\t\t}
\t\t\t}
\t\t}
\t\t// at this point we know that either sender is ROLE_TOKEN_DESTROYER or
\t\t// we burn own tokens or on behalf (in latest case we already checked and updated allowances)
\t\t// we have left to execute balance checks and burning logic itself
\t\t// non-zero burn value check
\t\trequire(_value != 0, "zero value burn");
\t\t// non-zero source address check - Zeppelin
\t\trequire(_from != address(0), "burn from the zero address");
\t\t// verify `_from` address has enough tokens to destroy
\t\t// (basically this is a arithmetic overflow check)
\t\trequire(tokenBalances[_from] >= _value, "burn amount exceeds balance");
\t\t// perform burn:
\t\t// decrease `_from` address balance
\t\ttokenBalances[_from] -= _value;
\t\t// decrease total amount of tokens value
\t\ttotalSupply -= _value;
\t\t// update total token supply history
\t\t__updateHistory(totalSupplyHistory, sub, _value);
\t\t// destroy voting power associated with the tokens burnt
\t\t__moveVotingPower(msg.sender, votingDelegates[_from], address(0), _value);
\t\t// fire a burnt event
\t\temit Burnt(msg.sender, _from, _value);
\t\t// emit an improved transfer event (arXiv:1907.00903)
\t\temit Transfer(msg.sender, _from, address(0), _value);
\t\t// fire ERC20 compliant transfer event
\t\temit Transfer(_from, address(0), _value);
\t}
\t// ===== End: Minting/burning extension =====
\t// ===== Start: EIP-2612 functions =====
\t/**
\t * @inheritdoc EIP2612
\t *
\t * @dev Executes approve(_spender, _value) on behalf of the owner who EIP-712
\t *      signed the transaction, i.e. as if transaction sender is the EIP712 signer
\t *
\t * @dev Sets the `_value` as the allowance of `_spender` over `_owner` tokens,
\t *      given `_owner` EIP-712 signed approval
\t *
\t * @dev Inherits the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
\t *      vulnerability in the same way as ERC20 `approve`, use standard ERC20 workaround
\t *      if this might become an issue:
\t *      https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit
\t *
\t * @dev Emits `Approval` event(s) in the same way as `approve` does
\t *
\t * @dev Requires:
\t *     - `_spender` to be non-zero address
\t *     - `_exp` to be a timestamp in the future
\t *     - `v`, `r` and `s` to be a valid `secp256k1` signature from `_owner`
\t *        over the EIP712-formatted function arguments.
\t *     - the signature to use `_owner` current nonce (see `nonces`).
\t *
\t * @dev For more information on the signature format, see the
\t *      https://eips.ethereum.org/EIPS/eip-2612#specification
\t *
\t * @param _owner owner of the tokens to set approval on behalf of,
\t *      an address which signed the EIP-712 message
\t * @param _spender an address approved by the token owner
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens spender `_spender` is allowed to
\t *      transfer on behalf of the token owner
\t * @param _exp signature expiration time (unix timestamp)
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction permit(address _owner, address _spender, uint256 _value, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public override {
\t\t// verify permits are enabled
\t\trequire(isFeatureEnabled(FEATURE_EIP2612_PERMITS), "EIP2612 permits are disabled");
\t\t// derive signer of the EIP712 Permit message, and
\t\t// update the nonce for that particular signer to avoid replay attack!!! --------->>> ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
\t\taddress signer = __deriveSigner(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _exp), v, r, s);
\t\t// perform message integrity and security validations
\t\trequire(signer == _owner, "invalid signature");
\t\trequire(block.timestamp < _exp, "signature expired");
\t\t// delegate call to `__approve` - execute the logic required
\t\t__approve(_owner, _spender, _value);
\t}
\t// ===== End: EIP-2612 functions =====
\t// ===== Start: EIP-3009 functions =====
\t/**
\t * @inheritdoc EIP3009
\t *
\t * @notice Checks if specified nonce was already used
\t *
\t * @dev Nonces are expected to be client-side randomly generated 32-byte values
\t *      unique to the authorizer's address
\t *
\t * @dev Alias for usedNonces(authorizer, nonce)
\t *
\t * @param _authorizer an address to check nonce for
\t * @param _nonce a nonce to check
\t * @return true if the nonce was used, false otherwise
\t */
\tfunction authorizationState(address _authorizer, bytes32 _nonce) public override view returns (bool) {
\t\t// simply return the value from the mapping
\t\treturn usedNonces[_authorizer][_nonce];
\t}
\t/**
\t * @inheritdoc EIP3009
\t *
\t * @notice Execute a transfer with a signed authorization
\t *
\t * @param _from token sender and transaction authorizer
\t * @param _to token receiver
\t * @param _value amount to be transferred
\t * @param _validAfter signature valid after time (unix timestamp)
\t * @param _validBefore signature valid before time (unix timestamp)
\t * @param _nonce unique random nonce
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction transferWithAuthorization(
\t\taddress _from,
\t\taddress _to,
\t\tuint256 _value,
\t\tuint256 _validAfter,
\t\tuint256 _validBefore,
\t\tbytes32 _nonce,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) public override {
\t\t// ensure EIP-3009 transfers are enabled
\t\trequire(isFeatureEnabled(FEATURE_EIP3009_TRANSFERS), "EIP3009 transfers are disabled");
\t\t// derive signer of the EIP712 TransferWithAuthorization message
\t\taddress signer = __deriveSigner(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s);
\t\t// perform message integrity and security validations
\t\trequire(signer == _from, "invalid signature");
\t\trequire(block.timestamp > _validAfter, "signature not yet valid");
\t\trequire(block.timestamp < _validBefore, "signature expired");
\t\t// use the nonce supplied (verify, mark as used, emit event)
\t\t__useNonce(_from, _nonce, false);
\t\t// delegate call to `__transferFrom` - execute the logic required
\t\t__transferFrom(signer, _from, _to, _value);
\t}
\t/**
\t * @inheritdoc EIP3009
\t *
\t * @notice Receive a transfer with a signed authorization from the payer
\t *
\t * @dev This has an additional check to ensure that the payee's address
\t *      matches the caller of this function to prevent front-running attacks.
\t *
\t * @param _from token sender and transaction authorizer
\t * @param _to token receiver
\t * @param _value amount to be transferred
\t * @param _validAfter signature valid after time (unix timestamp)
\t * @param _validBefore signature valid before time (unix timestamp)
\t * @param _nonce unique random nonce
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction receiveWithAuthorization(
\t\taddress _from,
\t\taddress _to,
\t\tuint256 _value,
\t\tuint256 _validAfter,
\t\tuint256 _validBefore,
\t\tbytes32 _nonce,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) public override {
\t\t// verify EIP3009 receptions are enabled
\t\trequire(isFeatureEnabled(FEATURE_EIP3009_RECEPTIONS), "EIP3009 receptions are disabled");
\t\t// derive signer of the EIP712 ReceiveWithAuthorization message
\t\taddress signer = __deriveSigner(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s);
\t\t// perform message integrity and security validations
\t\trequire(signer == _from, "invalid signature");
\t\trequire(block.timestamp > _validAfter, "signature not yet valid");
\t\trequire(block.timestamp < _validBefore, "signature expired");
\t\trequire(_to == msg.sender, "access denied");
\t\t// use the nonce supplied (verify, mark as used, emit event)
\t\t__useNonce(_from, _nonce, false);
\t\t// delegate call to `__transferFrom` - execute the logic required
\t\t__transferFrom(signer, _from, _to, _value);
\t}
\t/**
\t * @inheritdoc EIP3009
\t *
\t * @notice Attempt to cancel an authorization
\t *
\t * @param _authorizer transaction authorizer
\t * @param _nonce unique random nonce to cancel (mark as used)
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction cancelAuthorization(
\t\taddress _authorizer,
\t\tbytes32 _nonce,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) public override {
\t\t// derive signer of the EIP712 ReceiveWithAuthorization message
\t\taddress signer = __deriveSigner(abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, _authorizer, _nonce), v, r, s);
\t\t// perform message integrity and security validations
\t\trequire(signer == _authorizer, "invalid signature");
\t\t// cancel the nonce supplied (verify, mark as used, emit event)
\t\t__useNonce(_authorizer, _nonce, true);
\t}
\t/**
\t * @dev Auxiliary function to verify structured EIP712 message signature and derive its signer
\t *
\t * @param abiEncodedTypehash abi.encode of the message typehash together with all its parameters
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction __deriveSigner(bytes memory abiEncodedTypehash, uint8 v, bytes32 r, bytes32 s) private view returns(address) {
\t\t// build the EIP-712 hashStruct of the message
\t\tbytes32 hashStruct = keccak256(abiEncodedTypehash);
\t\t// calculate the EIP-712 digest "\\x19\\x01" ‖ domainSeparator ‖ hashStruct(message)
\t\tbytes32 digest = keccak256(abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR, hashStruct));
\t\t// recover the address which signed the message with v, r, s
\t\taddress signer = ECDSA.recover(digest, v, r, s);
\t\t// return the signer address derived from the signature
\t\treturn signer;
\t}
\t/**
\t * @dev Auxiliary function to use/cancel the nonce supplied for a given authorizer:
\t *      1. Verifies the nonce was not used before
\t *      2. Marks the nonce as used
\t *      3. Emits an event that the nonce was used/cancelled
\t *
\t * @dev Set `_cancellation` to false (default) to use nonce,
\t *      set `_cancellation` to true to cancel nonce
\t *
\t * @dev It is expected that the nonce supplied is a randomly
\t *      generated uint256 generated by the client
\t *
\t * @param _authorizer an address to use/cancel nonce for
\t * @param _nonce random nonce to use
\t * @param _cancellation true to emit `AuthorizationCancelled`, false to emit `AuthorizationUsed` event
\t */
\tfunction __useNonce(address _authorizer, bytes32 _nonce, bool _cancellation) private {
\t\t// verify nonce was not used before
\t\trequire(!usedNonces[_authorizer][_nonce], "invalid nonce");
\t\t// update the nonce state to "used" for that particular signer to avoid replay attack
\t\tusedNonces[_authorizer][_nonce] = true;
\t\t// depending on the usage type (use/cancel)
\t\tif(_cancellation) {
\t\t\t// emit an event regarding the nonce cancelled
\t\t\temit AuthorizationCanceled(_authorizer, _nonce);
\t\t}
\t\telse {
\t\t\t// emit an event regarding the nonce used
\t\t\temit AuthorizationUsed(_authorizer, _nonce);
\t\t}
\t}
\t// ===== End: EIP-3009 functions =====
\t// ===== Start: DAO Support (Compound-like voting delegation) =====
\t/**
\t * @notice Gets current voting power of the account `_of`
\t *
\t * @param _of the address of account to get voting power of
\t * @return current cumulative voting power of the account,
\t *      sum of token balances of all its voting delegators
\t */
\tfunction votingPowerOf(address _of) public view returns (uint256) {
\t\t// get a link to an array of voting power history records for an address specified
\t\tKV[] storage history = votingPowerHistory[_of];
\t\t// lookup the history and return latest element
\t\treturn history.length == 0? 0: history[history.length - 1].v;
\t}
\t/**
\t * @notice Gets past voting power of the account `_of` at some block `_blockNum`
\t *
\t * @dev Throws if `_blockNum` is not in the past (not the finalized block)
\t *
\t * @param _of the address of account to get voting power of
\t * @param _blockNum block number to get the voting power at
\t * @return past cumulative voting power of the account,
\t *      sum of token balances of all its voting delegators at block number `_blockNum`
\t */
\tfunction votingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) {
\t\t// make sure block number is not in the past (not the finalized block)
\t\trequire(_blockNum < block.number, "block not yet mined"); // Compound msg not yet determined
\t\t// `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending;
\t\t// apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that
\t\t// `votingPowerHistory[_of][i].k <= _blockNum`, but in the same time
\t\t// `votingPowerHistory[_of][i + 1].k > _blockNum`
\t\t// return the result - voting power found at index `i`
\t\treturn __binaryLookup(votingPowerHistory[_of], _blockNum);
\t}
\t/**
\t * @dev Reads an entire voting power history array for the delegate specified
\t *
\t * @param _of delegate to query voting power history for
\t * @return voting power history array for the delegate of interest
\t */
\tfunction votingPowerHistoryOf(address _of) public view returns(KV[] memory) {
\t\t// return an entire array as memory
\t\treturn votingPowerHistory[_of];
\t}
\t/**
\t * @dev Returns length of the voting power history array for the delegate specified;
\t *      useful since reading an entire array just to get its length is expensive (gas cost)
\t *
\t * @param _of delegate to query voting power history length for
\t * @return voting power history array length for the delegate of interest
\t */
\tfunction votingPowerHistoryLength(address _of) public view returns(uint256) {
\t\t// read array length and return
\t\treturn votingPowerHistory[_of].length;
\t}
\t/**
\t * @notice Gets past total token supply value at some block `_blockNum`
\t *
\t * @dev Throws if `_blockNum` is not in the past (not the finalized block)
\t *
\t * @param _blockNum block number to get the total token supply at
\t * @return past total token supply at block number `_blockNum`
\t */
\tfunction totalSupplyAt(uint256 _blockNum) public view returns(uint256) {
\t\t// make sure block number is not in the past (not the finalized block)
\t\trequire(_blockNum < block.number, "block not yet mined");
\t\t// `totalSupplyHistory` is an array ordered by `k`, ascending;
\t\t// apply binary search on `totalSupplyHistory` to find such an entry number `i`, that
\t\t// `totalSupplyHistory[i].k <= _blockNum`, but in the same time
\t\t// `totalSupplyHistory[i + 1].k > _blockNum`
\t\t// return the result - value `totalSupplyHistory[i].v` found at index `i`
\t\treturn __binaryLookup(totalSupplyHistory, _blockNum);
\t}
\t/**
\t * @dev Reads an entire total token supply history array
\t *
\t * @return total token supply history array, a key-value pair array,
\t *      where key is a block number and value is total token supply at that block
\t */
\tfunction entireSupplyHistory() public view returns(KV[] memory) {
\t\t// return an entire array as memory
\t\treturn totalSupplyHistory;
\t}
\t/**
\t * @dev Returns length of the total token supply history array;
\t *      useful since reading an entire array just to get its length is expensive (gas cost)
\t *
\t * @return total token supply history array
\t */
\tfunction totalSupplyHistoryLength() public view returns(uint256) {
\t\t// read array length and return
\t\treturn totalSupplyHistory.length;
\t}
\t/**
\t * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to`
\t *
\t * @dev Accepts zero value address to delegate voting power to, effectively
\t *      removing the delegate in that case
\t *
\t * @param _to address to delegate voting power to
\t */
\tfunction delegate(address _to) public {
\t\t// verify delegations are enabled
\t\trequire(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled");
\t\t// delegate call to `__delegate`
\t\t__delegate(msg.sender, _to);
\t}
\t/**
\t * @dev Powers the meta transaction for `delegate` - `delegateWithAuthorization`
\t *
\t * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`
\t * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings
\t *
\t * @param _from delegator who delegates his voting power
\t * @param _to delegate who receives the voting power
\t */
\tfunction __delegate(address _from, address _to) private {
\t\t// read current delegate to be replaced by a new one
\t\taddress _fromDelegate = votingDelegates[_from];
\t\t// read current voting power (it is equal to token balance)
\t\tuint256 _value = tokenBalances[_from];
\t\t// reassign voting delegate to `_to`
\t\tvotingDelegates[_from] = _to;
\t\t// update voting power for `_fromDelegate` and `_to`
\t\t__moveVotingPower(_from, _fromDelegate, _to, _value);
\t\t// emit an event
\t\temit DelegateChanged(_from, _fromDelegate, _to);
\t}
\t/**
\t * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to`
\t *
\t * @dev Accepts zero value address to delegate voting power to, effectively
\t *      removing the delegate in that case
\t *
\t * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing,
\t *      see https://eips.ethereum.org/EIPS/eip-712
\t *
\t * @param _to address to delegate voting power to
\t * @param _nonce nonce used to construct the signature, and used to validate it;
\t *      nonce is increased by one after successful signature validation and vote delegation
\t * @param _exp signature expiration time
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction delegateWithAuthorization(address _to, bytes32 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public {
\t\t// verify delegations on behalf are enabled
\t\trequire(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled");
\t\t// derive signer of the EIP712 Delegation message
\t\taddress signer = __deriveSigner(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp), v, r, s);
\t\t// perform message integrity and security validations
\t\trequire(block.timestamp < _exp, "signature expired"); // Compound msg
\t\t// use the nonce supplied (verify, mark as used, emit event)
\t\t__useNonce(signer, _nonce, false);
\t\t// delegate call to `__delegate` - execute the logic required
\t\t__delegate(signer, _to);
\t}
\t/**
\t * @dev Auxiliary function to move voting power `_value`
\t *      from delegate `_from` to the delegate `_to`
\t *
\t * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0`
\t *
\t * @param _by an address which executed delegate, mint, burn, or transfer operation
\t *      which had led to delegate voting power change
\t * @param _from delegate to move voting power from
\t * @param _to delegate to move voting power to
\t * @param _value voting power to move from `_from` to `_to`
\t */
\tfunction __moveVotingPower(address _by, address _from, address _to, uint256 _value) private {
\t\t// if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`)
\t\tif(_from == _to || _value == 0) {
\t\t\t// return silently with no action
\t\t\treturn;
\t\t}
\t\t// if source address is not zero - decrease its voting power
\t\tif(_from != address(0)) {
\t\t\t// get a link to an array of voting power history records for an address specified
\t\t\tKV[] storage _h = votingPowerHistory[_from];
\t\t\t// update source voting power: decrease by `_value`
\t\t\t(uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, sub, _value);
\t\t\t// emit an event
\t\t\temit VotingPowerChanged(_by, _from, _fromVal, _toVal);
\t\t}
\t\t// if destination address is not zero - increase its voting power
\t\tif(_to != address(0)) {
\t\t\t// get a link to an array of voting power history records for an address specified
\t\t\tKV[] storage _h = votingPowerHistory[_to];
\t\t\t// update destination voting power: increase by `_value`
\t\t\t(uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, add, _value);
\t\t\t// emit an event
\t\t\temit VotingPowerChanged(_by, _to, _fromVal, _toVal);
\t\t}
\t}
\t/**
\t * @dev Auxiliary function to append key-value pair to an array,
\t *      sets the key to the current block number and
\t *      value as derived
\t *
\t * @param _h array of key-value pairs to append to
\t * @param op a function (add/subtract) to apply
\t * @param _delta the value for a key-value pair to add/subtract
\t */
\tfunction __updateHistory(
\t\tKV[] storage _h,
\t\tfunction(uint256,uint256) pure returns(uint256) op,
\t\tuint256 _delta
\t) private returns(uint256 _fromVal, uint256 _toVal) {
\t\t// init the old value - value of the last pair of the array
\t\t_fromVal = _h.length == 0? 0: _h[_h.length - 1].v;
\t\t// init the new value - result of the operation on the old value
\t\t_toVal = op(_fromVal, _delta);
\t\t// if there is an existing voting power value stored for current block
\t\tif(_h.length != 0 && _h[_h.length - 1].k == block.number) {
\t\t\t// update voting power which is already stored in the current block
\t\t\t_h[_h.length - 1].v = uint192(_toVal);
\t\t}
\t\t// otherwise - if there is no value stored for current block
\t\telse {
\t\t\t// add new element into array representing the value for current block
\t\t\t_h.push(KV(uint64(block.number), uint192(_toVal)));
\t\t}
\t}
\t/**
\t * @dev Auxiliary function to lookup for a value in a sorted by key (ascending)
\t *      array of key-value pairs
\t *
\t * @dev This function finds a key-value pair element in an array with the closest key
\t *      to the key of interest (not exceeding that key) and returns the value
\t *      of the key-value pair element found
\t *
\t * @dev An array to search in is a KV[] key-value pair array ordered by key `k`,
\t *      it is sorted in ascending order (`k` increases as array index increases)
\t *
\t * @dev Returns zero for an empty array input regardless of the key input
\t *
\t * @param _h an array of key-value pair elements to search in
\t * @param _k key of interest to look the value for
\t * @return the value of the key-value pair of the key-value pair element with the closest
\t *      key to the key of interest (not exceeding that key)
\t */
\tfunction __binaryLookup(KV[] storage _h, uint256 _k) private view returns(uint256) {
\t\t// if an array is empty, there is nothing to lookup in
\t\tif(_h.length == 0) {
\t\t\t// by documented agreement, fall back to a zero result
\t\t\treturn 0;
\t\t}
\t\t// check last key-value pair key:
\t\t// if the key is smaller than the key of interest
\t\tif(_h[_h.length - 1].k <= _k) {
\t\t\t// we're done - return the value from the last element
\t\t\treturn _h[_h.length - 1].v;
\t\t}
\t\t// check first voting power history record block number:
\t\t// if history was never updated before the block of interest
\t\tif(_h[0].k > _k) {
\t\t\t// we're done - voting power at the block num of interest was zero
\t\t\treturn 0;
\t\t}
\t\t// left bound of the search interval, originally start of the array
\t\tuint256 i = 0;
\t\t// right bound of the search interval, originally end of the array
\t\tuint256 j = _h.length - 1;
\t\t// the iteration process narrows down the bounds by
\t\t// splitting the interval in a half oce per each iteration
\t\twhile(j > i) {
\t\t\t// get an index in the middle of the interval [i, j]
\t\t\tuint256 k = j - (j - i) / 2;
\t\t\t// read an element to compare it with the value of interest
\t\t\tKV memory kv = _h[k];
\t\t\t// if we've got a strict equal - we're lucky and done
\t\t\tif(kv.k == _k) {
\t\t\t\t// just return the result - pair value at index `k`
\t\t\t\treturn kv.v;
\t\t\t}
\t\t\t// if the value of interest is larger - move left bound to the middle
\t\t\telse if (kv.k < _k) {
\t\t\t\t// move left bound `i` to the middle position `k`
\t\t\t\ti = k;
\t\t\t}
\t\t\t// otherwise, when the value of interest is smaller - move right bound to the middle
\t\t\telse {
\t\t\t\t// move right bound `j` to the middle position `k - 1`:
\t\t\t\t// element at position `k` is greater and cannot be the result
\t\t\t\tj = k - 1;
\t\t\t}
\t\t}
\t\t// reaching that point means no exact match found
\t\t// since we're interested in the element which is not larger than the
\t\t// element of interest, we return the lower bound `i`
\t\treturn _h[i].v;
\t}
\t/**
\t * @dev Adds a + b
\t *      Function is used as a parameter for other functions
\t *
\t * @param a addition term 1
\t * @param b addition term 2
\t * @return a + b
\t */
\tfunction add(uint256 a, uint256 b) private pure returns(uint256) {
\t\t// add `a` to `b` and return
\t\treturn a + b;
\t}
\t/**
\t * @dev Subtracts a - b
\t *      Function is used as a parameter for other functions
\t *
\t * @dev Requires a ≥ b
\t *
\t * @param a subtraction term 1
\t * @param b subtraction term 2, b ≤ a
\t * @return a - b
\t */
\tfunction sub(uint256 a, uint256 b) private pure returns(uint256) {
\t\t// subtract `b` from `a` and return
\t\treturn a - b;
\t}
\t// ===== End: DAO Support (Compound-like voting delegation) =====
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ERC20Spec.sol";
import "./ERC165Spec.sol";
/**
 * @title ERC1363 Interface
 *
 * @dev Interface defining a ERC1363 Payable Token contract.
 *      Implementing contracts MUST implement the ERC1363 interface as well as the ERC20 and ERC165 interfaces.
 */
interface ERC1363 is ERC20, ERC165  {
\t/*
\t * Note: the ERC-165 identifier for this interface is 0xb0202a11.
\t * 0xb0202a11 ===
\t *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
\t *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
\t *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
\t *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
\t *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
\t *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
\t */
\t/**
\t * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
\t * @param to address The address which you want to transfer to
\t * @param value uint256 The amount of tokens to be transferred
\t * @return true unless throwing
\t */
\tfunction transferAndCall(address to, uint256 value) external returns (bool);
\t/**
\t * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
\t * @param to address The address which you want to transfer to
\t * @param value uint256 The amount of tokens to be transferred
\t * @param data bytes Additional data with no specified format, sent in call to `to`
\t * @return true unless throwing
\t */
\tfunction transferAndCall(address to, uint256 value, bytes memory data) external returns (bool);
\t/**
\t * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
\t * @param from address The address which you want to send tokens from
\t * @param to address The address which you want to transfer to
\t * @param value uint256 The amount of tokens to be transferred
\t * @return true unless throwing
\t */
\tfunction transferFromAndCall(address from, address to, uint256 value) external returns (bool);
\t/**
\t * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
\t * @param from address The address which you want to send tokens from
\t * @param to address The address which you want to transfer to
\t * @param value uint256 The amount of tokens to be transferred
\t * @param data bytes Additional data with no specified format, sent in call to `to`
\t * @return true unless throwing
\t */
\tfunction transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool);
\t/**
\t * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
\t * and then call `onApprovalReceived` on spender.
\t * @param spender address The address which will spend the funds
\t * @param value uint256 The amount of tokens to be spent
\t */
\tfunction approveAndCall(address spender, uint256 value) external returns (bool);
\t/**
\t * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
\t * and then call `onApprovalReceived` on spender.
\t * @param spender address The address which will spend the funds
\t * @param value uint256 The amount of tokens to be spent
\t * @param data bytes Additional data with no specified format, sent in call to `spender`
\t */
\tfunction approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool);
}
/**
 * @title ERC1363Receiver Interface
 *
 * @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall`
 *      from ERC1363 token contracts.
 */
interface ERC1363Receiver {
\t/*
\t * Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
\t * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
\t */
\t/**
\t * @notice Handle the receipt of ERC1363 tokens
\t *
\t * @dev Any ERC1363 smart contract calls this function on the recipient
\t *      after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
\t *      transfer. Return of other than the magic value MUST result in the
\t *      transaction being reverted.
\t *      Note: the token contract address is always the message sender.
\t *
\t * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
\t * @param from address The address which are token transferred from
\t * @param value uint256 The amount of tokens transferred
\t * @param data bytes Additional data with no specified format
\t * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
\t *      unless throwing
\t */
\tfunction onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4);
}
/**
 * @title ERC1363Spender Interface
 *
 * @dev Interface for any contract that wants to support `approveAndCall`
 *      from ERC1363 token contracts.
 */
interface ERC1363Spender {
\t/*
\t * Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
\t * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
\t */
\t/**
\t * @notice Handle the approval of ERC1363 tokens
\t *
\t * @dev Any ERC1363 smart contract calls this function on the recipient
\t *      after an `approve`. This function MAY throw to revert and reject the
\t *      approval. Return of other than the magic value MUST result in the
\t *      transaction being reverted.
\t *      Note: the token contract address is always the message sender.
\t *
\t * @param owner address The address which called `approveAndCall` function
\t * @param value uint256 The amount of tokens to be spent
\t * @param data bytes Additional data with no specified format
\t * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
\t *      unless throwing
\t */
\tfunction onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @title EIP-2612: permit - 712-signed approvals
 *
 * @notice A function permit extending ERC-20 which allows for approvals to be made via secp256k1 signatures.
 *      This kind of “account abstraction for ERC-20” brings about two main benefits:
 *        - transactions involving ERC-20 operations can be paid using the token itself rather than ETH,
 *        - approve and pull operations can happen in a single transaction instead of two consecutive transactions,
 *        - while adding as little as possible over the existing ERC-20 standard.
 *
 * @notice See https://eips.ethereum.org/EIPS/eip-2612#specification
 */
interface EIP2612 {
\t/**
\t * @notice EIP712 domain separator of the smart contract. It should be unique to the contract
\t *      and chain to prevent replay attacks from other domains, and satisfy the requirements of EIP-712,
\t *      but is otherwise unconstrained.
\t */
\tfunction DOMAIN_SEPARATOR() external view returns (bytes32);
\t/**
\t * @notice Counter of the nonces used for the given address; nonce are used sequentially
\t *
\t * @dev To prevent from replay attacks nonce is incremented for each address after a successful `permit` execution
\t *
\t * @param owner an address to query number of used nonces for
\t * @return number of used nonce, nonce number to be used next
\t */
\tfunction nonces(address owner) external view returns (uint);
\t/**
\t * @notice For all addresses owner, spender, uint256s value, deadline and nonce, uint8 v, bytes32 r and s,
\t *      a call to permit(owner, spender, value, deadline, v, r, s) will set approval[owner][spender] to value,
\t *      increment nonces[owner] by 1, and emit a corresponding Approval event,
\t *      if and only if the following conditions are met:
\t *        - The current blocktime is less than or equal to deadline.
\t *        - owner is not the zero address.
\t *        - nonces[owner] (before the state update) is equal to nonce.
\t *        - r, s and v is a valid secp256k1 signature from owner of the message:
\t *
\t * @param owner token owner address, granting an approval to spend its tokens
\t * @param spender an address approved by the owner (token owner)
\t *      to spend some tokens on its behalf
\t * @param value an amount of tokens spender `spender` is allowed to
\t *      transfer on behalf of the token owner
\t * @param v the recovery byte of the signature
\t * @param r half of the ECDSA signature pair
\t * @param s half of the ECDSA signature pair
\t */
\tfunction permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @title EIP-3009: Transfer With Authorization
 *
 * @notice A contract interface that enables transferring of fungible assets via a signed authorization.
 *      See https://eips.ethereum.org/EIPS/eip-3009
 *      See https://eips.ethereum.org/EIPS/eip-3009#specification
 */
interface EIP3009 {
\t/**
\t * @dev Fired whenever the nonce gets used (ex.: `transferWithAuthorization`, `receiveWithAuthorization`)
\t *
\t * @param authorizer an address which has used the nonce
\t * @param nonce the nonce used
\t */
\tevent AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
\t/**
\t * @dev Fired whenever the nonce gets cancelled (ex.: `cancelAuthorization`)
\t *
\t * @dev Both `AuthorizationUsed` and `AuthorizationCanceled` imply the nonce
\t *      cannot be longer used, the only difference is that `AuthorizationCanceled`
\t *      implies no smart contract state change made (except the nonce marked as cancelled)
\t *
\t * @param authorizer an address which has cancelled the nonce
\t * @param nonce the nonce cancelled
\t */
\tevent AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);
\t/**
\t * @notice Returns the state of an authorization, more specifically
\t *      if the specified nonce was already used by the address specified
\t *
\t * @dev Nonces are expected to be client-side randomly generated 32-byte data
\t *      unique to the authorizer's address
\t *
\t * @param authorizer    Authorizer's address
\t * @param nonce         Nonce of the authorization
\t * @return true if the nonce is used
\t */
\tfunction authorizationState(
\t\taddress authorizer,
\t\tbytes32 nonce
\t) external view returns (bool);
\t/**
\t * @notice Execute a transfer with a signed authorization
\t *
\t * @param from          Payer's address (Authorizer)
\t * @param to            Payee's address
\t * @param value         Amount to be transferred
\t * @param validAfter    The time after which this is valid (unix time)
\t * @param validBefore   The time before which this is valid (unix time)
\t * @param nonce         Unique nonce
\t * @param v             v of the signature
\t * @param r             r of the signature
\t * @param s             s of the signature
\t */
\tfunction transferWithAuthorization(
\t\taddress from,
\t\taddress to,
\t\tuint256 value,
\t\tuint256 validAfter,
\t\tuint256 validBefore,
\t\tbytes32 nonce,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) external;
\t/**
\t * @notice Receive a transfer with a signed authorization from the payer
\t *
\t * @dev This has an additional check to ensure that the payee's address matches
\t *      the caller of this function to prevent front-running attacks.
\t * @dev See https://eips.ethereum.org/EIPS/eip-3009#security-considerations
\t *
\t * @param from          Payer's address (Authorizer)
\t * @param to            Payee's address
\t * @param value         Amount to be transferred
\t * @param validAfter    The time after which this is valid (unix time)
\t * @param validBefore   The time before which this is valid (unix time)
\t * @param nonce         Unique nonce
\t * @param v             v of the signature
\t * @param r             r of the signature
\t * @param s             s of the signature
\t */
\tfunction receiveWithAuthorization(
\t\taddress from,
\t\taddress to,
\t\tuint256 value,
\t\tuint256 validAfter,
\t\tuint256 validBefore,
\t\tbytes32 nonce,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) external;
\t/**
\t * @notice Attempt to cancel an authorization
\t *
\t * @param authorizer    Authorizer's address
\t * @param nonce         Nonce of the authorization
\t * @param v             v of the signature
\t * @param r             r of the signature
\t * @param s             s of the signature
\t */
\tfunction cancelAuthorization(
\t\taddress authorizer,
\t\tbytes32 nonce,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @title Access Control List
 *
 * @notice Access control smart contract provides an API to check
 *      if specific operation is permitted globally and/or
 *      if particular user has a permission to execute it.
 *
 * @notice It deals with two main entities: features and roles.
 *
 * @notice Features are designed to be used to enable/disable specific
 *      functions (public functions) of the smart contract for everyone.
 * @notice User roles are designed to restrict access to specific
 *      functions (restricted functions) of the smart contract to some users.
 *
 * @notice Terms "role", "permissions" and "set of permissions" have equal meaning
 *      in the documentation text and may be used interchangeably.
 * @notice Terms "permission", "single permission" implies only one permission bit set.
 *
 * @notice Access manager is a special role which allows to grant/revoke other roles.
 *      Access managers can only grant/revoke permissions which they have themselves.
 *      As an example, access manager with no other roles set can only grant/revoke its own
 *      access manager permission and nothing else.
 *
 * @notice Access manager permission should be treated carefully, as a super admin permission:
 *      Access manager with even no other permission can interfere with another account by
 *      granting own access manager permission to it and effectively creating more powerful
 *      permission set than its own.
 *
 * @dev Both current and OpenZeppelin AccessControl implementations feature a similar API
 *      to check/know "who is allowed to do this thing".
 * @dev Zeppelin implementation is more flexible:
 *      - it allows setting unlimited number of roles, while current is limited to 256 different roles
 *      - it allows setting an admin for each role, while current allows having only one global admin
 * @dev Current implementation is more lightweight:
 *      - it uses only 1 bit per role, while Zeppelin uses 256 bits
 *      - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows
 *        setting only one role in a single transaction
 *
 * @dev This smart contract is designed to be inherited by other
 *      smart contracts which require access control management capabilities.
 *
 * @dev Access manager permission has a bit 255 set.
 *      This bit must not be used by inheriting contracts for any other permissions/features.
 */
contract AccessControl {
\t/**
\t * @notice Access manager is responsible for assigning the roles to users,
\t *      enabling/disabling global features of the smart contract
\t * @notice Access manager can add, remove and update user roles,
\t *      remove and update global features
\t *
\t * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features
\t * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled
\t */
\tuint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000;
\t/**
\t * @dev Bitmask representing all the possible permissions (super admin role)
\t * @dev Has all the bits are enabled (2^256 - 1 value)
\t */
\tuint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF...
\t/**
\t * @notice Privileged addresses with defined roles/permissions
\t * @notice In the context of ERC20/ERC721 tokens these can be permissions to
\t *      allow minting or burning tokens, transferring on behalf and so on
\t *
\t * @dev Maps user address to the permissions bitmask (role), where each bit
\t *      represents a permission
\t * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
\t *      represents all possible permissions
\t * @dev 'This' address mapping represents global features of the smart contract
\t */
\tmapping(address => uint256) public userRoles;
\t/**
\t * @dev Fired in updateRole() and updateFeatures()
\t *
\t * @param _by operator which called the function
\t * @param _to address which was granted/revoked permissions
\t * @param _requested permissions requested
\t * @param _actual permissions effectively set
\t */
\tevent RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual);
\t/**
\t * @notice Creates an access control instance,
\t *      setting contract creator to have full privileges
\t */
\tconstructor() {
\t\t// contract creator has full privileges
\t\tuserRoles[msg.sender] = FULL_PRIVILEGES_MASK;
\t}
\t/**
\t * @notice Retrieves globally set of features enabled
\t *
\t * @dev Effectively reads userRoles role for the contract itself
\t *
\t * @return 256-bit bitmask of the features enabled
\t */
\tfunction features() public view returns(uint256) {
\t\t// features are stored in 'this' address  mapping of `userRoles` structure
\t\treturn userRoles[address(this)];
\t}
\t/**
\t * @notice Updates set of the globally enabled features (`features`),
\t *      taking into account sender's permissions
\t *
\t * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
\t * @dev Function is left for backward compatibility with older versions
\t *
\t * @param _mask bitmask representing a set of features to enable/disable
\t */
\tfunction updateFeatures(uint256 _mask) public {
\t\t// delegate call to `updateRole`
\t\tupdateRole(address(this), _mask);
\t}
\t/**
\t * @notice Updates set of permissions (role) for a given user,
\t *      taking into account sender's permissions.
\t *
\t * @dev Setting role to zero is equivalent to removing an all permissions
\t * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
\t *      copying senders' permissions (role) to the user
\t * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
\t *
\t * @param operator address of a user to alter permissions for or zero
\t *      to alter global features of the smart contract
\t * @param role bitmask representing a set of permissions to
\t *      enable/disable for a user specified
\t */
\tfunction updateRole(address operator, uint256 role) public {
\t\t// caller must have a permission to update user roles
\t\trequire(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied");
\t\t// evaluate the role and reassign it
\t\tuserRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
\t\t// fire an event
\t\temit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
\t}
\t/**
\t * @notice Determines the permission bitmask an operator can set on the
\t *      target permission set
\t * @notice Used to calculate the permission bitmask to be set when requested
\t *     in `updateRole` and `updateFeatures` functions
\t *
\t * @dev Calculated based on:
\t *      1) operator's own permission set read from userRoles[operator]
\t *      2) target permission set - what is already set on the target
\t *      3) desired permission set - what do we want set target to
\t *
\t * @dev Corner cases:
\t *      1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:
\t *        `desired` bitset is returned regardless of the `target` permission set value
\t *        (what operator sets is what they get)
\t *      2) Operator with no permissions (zero bitset):
\t *        `target` bitset is returned regardless of the `desired` value
\t *        (operator has no authority and cannot modify anything)
\t *
\t * @dev Example:
\t *      Consider an operator with the permissions bitmask     00001111
\t *      is about to modify the target permission set          01010101
\t *      Operator wants to set that permission set to          00110011
\t *      Based on their role, an operator has the permissions
\t *      to update only lowest 4 bits on the target, meaning that
\t *      high 4 bits of the target set in this example is left
\t *      unchanged and low 4 bits get changed as desired:      01010011
\t *
\t * @param operator address of the contract operator which is about to set the permissions
\t * @param target input set of permissions to operator is going to modify
\t * @param desired desired set of permissions operator would like to set
\t * @return resulting set of permissions given operator will set
\t */
\tfunction evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) {
\t\t// read operator's permissions
\t\tuint256 p = userRoles[operator];
\t\t// taking into account operator's permissions,
\t\t// 1) enable the permissions desired on the `target`
\t\ttarget |= p & desired;
\t\t// 2) disable the permissions desired on the `target`
\t\ttarget &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));
\t\t// return calculated result
\t\treturn target;
\t}
\t/**
\t * @notice Checks if requested set of features is enabled globally on the contract
\t *
\t * @param required set of features to check against
\t * @return true if all the features requested are enabled, false otherwise
\t */
\tfunction isFeatureEnabled(uint256 required) public view returns(bool) {
\t\t// delegate call to `__hasRole`, passing `features` property
\t\treturn __hasRole(features(), required);
\t}
\t/**
\t * @notice Checks if transaction sender `msg.sender` has all the permissions required
\t *
\t * @param required set of permissions (role) to check against
\t * @return true if all the permissions requested are enabled, false otherwise
\t */
\tfunction isSenderInRole(uint256 required) public view returns(bool) {
\t\t// delegate call to `isOperatorInRole`, passing transaction sender
\t\treturn isOperatorInRole(msg.sender, required);
\t}
\t/**
\t * @notice Checks if operator has all the permissions (role) required
\t *
\t * @param operator address of the user to check role for
\t * @param required set of permissions (role) to check
\t * @return true if all the permissions requested are enabled, false otherwise
\t */
\tfunction isOperatorInRole(address operator, uint256 required) public view returns(bool) {
\t\t// delegate call to `__hasRole`, passing operator's permissions (role)
\t\treturn __hasRole(userRoles[operator], required);
\t}
\t/**
\t * @dev Checks if role `actual` contains all the permissions required `required`
\t *
\t * @param actual existent role
\t * @param required required role
\t * @return true if actual has required role (all permissions), false otherwise
\t */
\tfunction __hasRole(uint256 actual, uint256 required) internal pure returns(bool) {
\t\t// check the bitmask for the role required and return the result
\t\treturn actual & required == required;
\t}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @title Address Utils
 *
 * @dev Utility library of inline functions on addresses
 *
 * @dev Copy of the Zeppelin's library:
 *      https://github.com/gnosis/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol
 */
library AddressUtils {
\t/**
\t * @notice Checks if the target address is a contract
\t *
\t * @dev It is unsafe to assume that an address for which this function returns
\t *      false is an externally-owned account (EOA) and not a contract.
\t *
\t * @dev Among others, `isContract` will return false for the following
\t *      types of addresses:
\t *        - an externally-owned account
\t *        - a contract in construction
\t *        - an address where a contract will be created
\t *        - an address where a contract lived, but was destroyed
\t *
\t * @param addr address to check
\t * @return whether the target address is a contract
\t */
\tfunction isContract(address addr) internal view returns (bool) {
\t\t// a variable to load `extcodesize` to
\t\tuint256 size = 0;
\t\t// XXX Currently there is no better way to check if there is a contract in an address
\t\t// than to check the size of the code at that address.
\t\t// See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.
\t\t// TODO: Check this again before the Serenity release, because all addresses will be contracts.
\t\t// solium-disable-next-line security/no-inline-assembly
\t\tassembly {
\t\t\t// retrieve the size of the code at address `addr`
\t\t\tsize := extcodesize(addr)
\t\t}
\t\t// positive size indicates a smart contract address
\t\treturn size > 0;
\t}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @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.
 *
 * @dev Copy of the Zeppelin's library:
 *      https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e/contracts/utils/cryptography/ECDSA.sol
 */
library ECDSA {
\t/**
\t * @dev Returns the address that signed a hashed message (`hash`) with
\t * `signature`. This address can then be used for verification purposes.
\t *
\t * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
\t * this function rejects them by requiring the `s` value to be in the lower
\t * half order, and the `v` value to be either 27 or 28.
\t *
\t * IMPORTANT: `hash` _must_ be the result of a hash operation for the
\t * verification to be secure: it is possible to craft signatures that
\t * recover to arbitrary addresses for non-hashed data. A safe way to ensure
\t * this is by receiving a hash of the original message (which may otherwise
\t * be too long), and then calling {toEthSignedMessageHash} on it.
\t *
\t * Documentation for signature generation:
\t * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
\t * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
\t */
\tfunction recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
\t\t// Divide the signature in r, s and v variables
\t\tbytes32 r;
\t\tbytes32 s;
\t\tuint8 v;
\t\t// Check the signature length
\t\t// - case 65: r,s,v signature (standard)
\t\t// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
\t\tif (signature.length == 65) {
\t\t\t// ecrecover takes the signature parameters, and the only way to get them
\t\t\t// currently is to use assembly.
\t\t\tassembly {
\t\t\t\tr := mload(add(signature, 0x20))
\t\t\t\ts := mload(add(signature, 0x40))
\t\t\t\tv := byte(0, mload(add(signature, 0x60)))
\t\t\t}
\t\t}
\t\telse if (signature.length == 64) {
\t\t\t// ecrecover takes the signature parameters, and the only way to get them
\t\t\t// currently is to use assembly.
\t\t\tassembly {
\t\t\t\tlet vs := mload(add(signature, 0x40))
\t\t\t\tr := mload(add(signature, 0x20))
\t\t\t\ts := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
\t\t\t\tv := add(shr(255, vs), 27)
\t\t\t}
\t\t}
\t\telse {
\t\t\trevert("invalid signature length");
\t\t}
\t\treturn recover(hash, v, r, s);
\t}
\t/**
\t * @dev Overload of {ECDSA-recover} that receives the `v`,
\t * `r` and `s` signature fields separately.
\t */
\tfunction recover(
\t\tbytes32 hash,
\t\tuint8 v,
\t\tbytes32 r,
\t\tbytes32 s
\t) internal pure returns (address) {
\t\t// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
\t\t// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
\t\t// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
\t\t// signatures from current libraries generate a unique signature with an s-value in the lower half order.
\t\t//
\t\t// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
\t\t// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
\t\t// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
\t\t// these malleable signatures as well.
\t\trequire(
\t\t\tuint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
\t\t\t"invalid signature 's' value"
\t\t);
\t\trequire(v == 27 || v == 28, "invalid signature 'v' value");
\t\t// If the signature is valid (and not malleable), return the signer address
\t\taddress signer = ecrecover(hash, v, r, s);
\t\trequire(signer != address(0), "invalid signature");
\t\treturn signer;
\t}
\t/**
\t * @dev Returns an Ethereum Signed Message, created from a `hash`. This
\t * produces hash corresponding to the one signed with the
\t * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
\t * JSON-RPC method as part of EIP-191.
\t *
\t * See {recover}.
\t */
\tfunction toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
\t\t// 32 is the length in bytes of hash,
\t\t// enforced by the type signature above
\t\treturn keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
32", hash));
\t}
\t/**
\t * @dev Returns an Ethereum Signed Typed Data, created from a
\t * `domainSeparator` and a `structHash`. This produces hash corresponding
\t * to the one signed with the
\t * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
\t * JSON-RPC method as part of EIP-712.
\t *
\t * See {recover}.
\t */
\tfunction toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
\t\treturn keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
\t}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @title EIP-20: ERC-20 Token Standard
 *
 * @notice The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,
 *      is a Token Standard that implements an API for tokens within Smart Contracts.
 *
 * @notice It provides functionalities like to transfer tokens from one account to another,
 *      to get the current token balance of an account and also the total supply of the token available on the network.
 *      Besides these it also has some other functionalities like to approve that an amount of
 *      token from an account can be spent by a third party account.
 *
 * @notice If a Smart Contract implements the following methods and events it can be called an ERC-20 Token
 *      Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum.
 *
 * @notice See https://ethereum.org/en/developers/docs/standards/tokens/erc-20/
 * @notice See https://eips.ethereum.org/EIPS/eip-20
 */
interface ERC20 {
\t/**
\t * @dev Fired in transfer(), transferFrom() to indicate that token transfer happened
\t *
\t * @param from an address tokens were consumed from
\t * @param to an address tokens were sent to
\t * @param value number of tokens transferred
\t */
\tevent Transfer(address indexed from, address indexed to, uint256 value);
\t/**
\t * @dev Fired in approve() to indicate an approval event happened
\t *
\t * @param owner an address which granted a permission to transfer
\t *      tokens on its behalf
\t * @param spender an address which received a permission to transfer
\t *      tokens on behalf of the owner `_owner`
\t * @param value amount of tokens granted to transfer on behalf
\t */
\tevent Approval(address indexed owner, address indexed spender, uint256 value);
\t/**
\t * @return name of the token (ex.: USD Coin)
\t */
\t// OPTIONAL - This method can be used to improve usability,
\t// but interfaces and other contracts MUST NOT expect these values to be present.
\t// function name() external view returns (string memory);
\t/**
\t * @return symbol of the token (ex.: USDC)
\t */
\t// OPTIONAL - This method can be used to improve usability,
\t// but interfaces and other contracts MUST NOT expect these values to be present.
\t// function symbol() external view returns (string memory);
\t/**
\t * @dev Returns the number of decimals used to get its user representation.
\t *      For example, if `decimals` equals `2`, a balance of `505` tokens should
\t *      be displayed to a user as `5,05` (`505 / 10 ** 2`).
\t *
\t * @dev Tokens usually opt for a value of 18, imitating the relationship between
\t *      Ether and Wei. This is the value {ERC20} uses, unless this function is
\t *      overridden;
\t *
\t * @dev NOTE: This information is only used for _display_ purposes: it in
\t *      no way affects any of the arithmetic of the contract, including
\t *      {IERC20-balanceOf} and {IERC20-transfer}.
\t *
\t * @return token decimals
\t */
\t// OPTIONAL - This method can be used to improve usability,
\t// but interfaces and other contracts MUST NOT expect these values to be present.
\t// function decimals() external view returns (uint8);
\t/**
\t * @return the amount of tokens in existence
\t */
\tfunction totalSupply() external view returns (uint256);
\t/**
\t * @notice Gets the balance of a particular address
\t *
\t * @param _owner the address to query the the balance for
\t * @return balance an amount of tokens owned by the address specified
\t */
\tfunction balanceOf(address _owner) external view returns (uint256 balance);
\t/**
\t * @notice Transfers some tokens to an external address or a smart contract
\t *
\t * @dev Called by token owner (an address which has a
\t *      positive token balance tracked by this smart contract)
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * self address or
\t *          * smart contract which doesn't support ERC20
\t *
\t * @param _to an address to transfer tokens to,
\t *      must be either an external address or a smart contract,
\t *      compliant with the ERC20 standard
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @return success true on success, throws otherwise
\t */
\tfunction transfer(address _to, uint256 _value) external returns (bool success);
\t/**
\t * @notice Transfers some tokens on behalf of address `_from' (token owner)
\t *      to some other address `_to`
\t *
\t * @dev Called by token owner on his own or approved address,
\t *      an address approved earlier by token owner to
\t *      transfer some amount of tokens on its behalf
\t * @dev Throws on any error like
\t *      * insufficient token balance or
\t *      * incorrect `_to` address:
\t *          * zero address or
\t *          * same as `_from` address (self transfer)
\t *          * smart contract which doesn't support ERC20
\t *
\t * @param _from token owner which approved caller (transaction sender)
\t *      to transfer `_value` of tokens on its behalf
\t * @param _to an address to transfer tokens to,
\t *      must be either an external address or a smart contract,
\t *      compliant with the ERC20 standard
\t * @param _value amount of tokens to be transferred,, zero
\t *      value is allowed
\t * @return success true on success, throws otherwise
\t */
\tfunction transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
\t/**
\t * @notice Approves address called `_spender` to transfer some amount
\t *      of tokens on behalf of the owner (transaction sender)
\t *
\t * @dev Transaction sender must not necessarily own any tokens to grant the permission
\t *
\t * @param _spender an address approved by the caller (token owner)
\t *      to spend some tokens on its behalf
\t * @param _value an amount of tokens spender `_spender` is allowed to
\t *      transfer on behalf of the token owner
\t * @return success true on success, throws otherwise
\t */
\tfunction approve(address _spender, uint256 _value) external returns (bool success);
\t/**
\t * @notice Returns the amount which _spender is still allowed to withdraw from _owner.
\t *
\t * @dev A function to check an amount of tokens owner approved
\t *      to transfer on its behalf by some other address called "spender"
\t *
\t * @param _owner an address which approves transferring some tokens on its behalf
\t * @param _spender an address approved to transfer some tokens on behalf
\t * @return remaining an amount of tokens approved address `_spender` can transfer on behalf
\t *      of token owner `_owner`
\t */
\tfunction allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
 * @title ERC-165 Standard Interface Detection
 *
 * @dev Interface of the ERC165 standard, as defined in the
 *       https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * @dev Implementers can declare support of contract interfaces,
 *      which can then be queried by others.
 *
 * @author Christian Reitwießner, Nick Johnson, Fabian Vogelsteller, Jordi Baylina, Konrad Feldmeier, William Entriken
 */
interface ERC165 {
\t/**
\t * @notice Query if a contract implements an interface
\t *
\t * @dev Interface identification is specified in ERC-165.
\t *      This function uses less than 30,000 gas.
\t *
\t * @param interfaceID The interface identifier, as specified in ERC-165
\t * @return `true` if the contract implements `interfaceID` and
\t *      `interfaceID` is not 0xffffffff, `false` otherwise
\t */
\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);
}