// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import "./utils/Ownable.sol";
import "./MerkleDistributor.sol";
contract DistributorRegistry is Ownable {
mapping(uint256 => address) public distributorsBySeason;
mapping(address => bool) public distributors;
/**
* @dev Struct to represent claim data for batch processing.
* @param rootNumber The Merkle root number associated with the claim.
* @param index The index within the Merkle tree for this particular claim.
* @param amount The amount of tokens to be claimed.
* @param merkleProof The Merkle proof associated with the claim to validate it against the root.
*/
struct MultiClaimData {
uint256 seasonNumber;
uint256 index;
uint256 amount;
bytes32[] merkleProof;
}
event DistributorAdded(uint256 indexed _seasonNumber, address _distributor);
event DistributorRemoved(uint256 indexed _seasonNumber, address _distributor);
constructor(address _admin) Ownable(_admin) {
// solhint-disable-previous-line no-empty-blocks
}
function addDistributor(uint256 _seasonNumber, address _distributor) external onlyOwner {
require(distributorsBySeason[_seasonNumber] == address(0), "Season number already set");
distributorsBySeason[_seasonNumber] = _distributor;
distributors[_distributor] = true;
emit DistributorAdded(_seasonNumber, _distributor);
}
function removeDistributor(uint256 _seasonNumber) external onlyOwner {
address distributor = distributorsBySeason[_seasonNumber];
delete distributorsBySeason[_seasonNumber];
delete distributors[distributor];
emit DistributorRemoved(_seasonNumber, distributor);
}
function isDistributor(address _distributor) external view returns (bool) {
return distributors[_distributor];
}
/**
* @dev Supports batch claiming, instead of transferring to the recipient directly,
* tokens are locked in the TokenLock contract.
* @param _claimData An array containing details for each claim the caller wishes to make.
*/
function multiClaim(MultiClaimData[] memory _claimData) external {
for (uint256 i = 0; i < _claimData.length; ++i) {
uint256 seasonNumber = _claimData[i].seasonNumber;
uint256 index = _claimData[i].index;
uint256 amount = _claimData[i].amount;
bytes32[] memory merkleProof = _claimData[i].merkleProof;
MerkleDistributor(distributorsBySeason[seasonNumber]).claimFromRegistry(
index,
amount,
merkleProof,
msg.sender
);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import "./NFI.sol";
import "./TokenLock.sol";
import "./utils/Ownable.sol";
/**
* @title MerkleDistributor
* @author NFTfi
* @dev Modified version of Uniswap's MerkleDistributor
* https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol
* Main difference: in claim instead of transferring the tokens to the user,
* we transfer it to the tokenLock contract
*/
contract MerkleDistributor is Ownable, Pausable {
NFI public immutable nfi;
TokenLock public immutable tokenLock;
address public immutable distributorRegistry;
uint256 public immutable claimCutoffDate;
bytes32 public merkleRoot;
mapping(uint256 => uint256) private claimedBitMap;
event Claimed(uint256 _index, uint256 _amount, bytes32[] _merkleProof, address indexed _account);
/**
* @dev Constructor initializes references for NFTfi token and TokenLock contract.
* It also sets the owner of the contract.
* @param _admin The initial owner of the contract, usually able to set Merkle roots.
* @param _nfi Address of the NFTfi token contract.
* @param _tokenLock Address of the TokenLock contract where tokens are transferred upon claims.
*/
constructor(
bytes32 _merkleRoot,
address _admin,
address _nfi,
address _tokenLock,
address _distributorRegistry,
uint256 _claimCutoffDate
) Ownable(_admin) {
merkleRoot = _merkleRoot;
nfi = NFI(_nfi);
tokenLock = TokenLock(_tokenLock);
distributorRegistry = _distributorRegistry;
claimCutoffDate = _claimCutoffDate;
}
function isClaimed(uint256 _index) public view returns (bool) {
uint256 claimedWordIndex = _index / 256;
uint256 claimedBitIndex = _index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 _index) private {
uint256 claimedWordIndex = _index / 256;
uint256 claimedBitIndex = _index % 256;
claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex);
}
function claim(
uint256 _index,
uint256 _amount,
bytes32[] memory _merkleProof
) external {
_claim(_index, _amount, _merkleProof, msg.sender);
}
function claimFromRegistry(
uint256 _index,
uint256 _amount,
bytes32[] memory _merkleProof,
address _claimer
) external {
require(msg.sender == distributorRegistry, "Only registry");
_claim(_index, _amount, _merkleProof, _claimer);
}
function _claim(
uint256 _index,
uint256 _amount,
bytes32[] memory _merkleProof,
address _claimer
) internal whenNotPaused {
require(block.timestamp < claimCutoffDate, "cutoff date elapsed");
require(!isClaimed(_index), "distributor: already claimed");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(_index, _claimer, _amount));
require(MerkleProof.verify(_merkleProof, merkleRoot, node), "distributor: invalid proof");
// Mark it claimed and send the token.
_setClaimed(_index);
nfi.approve(address(tokenLock), _amount);
tokenLock.lockTokensFromDistributor(_amount, _claimer);
emit Claimed(_index, _amount, _merkleProof, _claimer);
}
/**
* @dev Drain to admin address in an emergency
* @param _amount of tokens to drain
*/
function drain(uint256 _amount) public onlyOwner {
nfi.transfer(owner(), _amount);
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must not be paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must be paused.
*/
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title NFI
* @author NFTfi
* @dev standard ERC20 token
*/
contract NFI is ERC20 {
constructor(uint256 _initialSupply, address _owner) ERC20("NFTfi Token", "NFI") {
_mint(_owner, _initialSupply);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*
* Modified version from openzeppelin/contracts/access/Ownable.sol that allows to
* initialize the owner using a parameter in the constructor
*/
abstract contract Ownable is Context {
address private _owner;
address private _ownerCandidate;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor(address _initialOwner) {
_setOwner(_initialOwner);
}
/**
* @dev Requests transferring ownership of the contract to a new account (`_newOwnerCandidate`).
* Can only be called by the current owner.
*/
function requestTransferOwnership(address _newOwnerCandidate) public virtual onlyOwner {
require(_newOwnerCandidate != address(0), "Ownable: new owner is the zero address");
_ownerCandidate = _newOwnerCandidate;
}
function acceptTransferOwnership() public virtual {
require(_ownerCandidate == _msgSender(), "Ownable: not owner candidate");
_setOwner(_ownerCandidate);
delete _ownerCandidate;
}
function cancelTransferOwnership() public virtual onlyOwner {
delete _ownerCandidate;
}
function rejectTransferOwnership() public virtual {
require(_ownerCandidate == _msgSender(), "Ownable: not owner candidate");
delete _ownerCandidate;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Sets the owner.
*/
function _setOwner(address _newOwner) internal {
address oldOwner = _owner;
_owner = _newOwner;
emit OwnershipTransferred(oldOwner, _newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
/**
* @title ProtocolSigningUtils
* @author NFTfi
* @notice Helper library for NFTfi. This contract manages verifying signatures
* from an NFTfi protocol address to enforce KYC requirements on-chain
*/
library ProtocolSigningUtils {
/**
* @dev Signature struct
*
* @param expiry The timestamp after which the signature is considered expired and invalid.
* @param signer Signing protocol address
* @param signature The actual ECDSA signature bytes of the signed data
*/
struct ProtocolSignature {
uint256 expiry;
address signer;
bytes signature;
}
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @notice Verifies the validity of a protocol signature.
* @dev This function checks whether the protocol signature is valid and hasn't expired.
* It constructs a message from the input parameters and verifies its signature against
* the expected signer.
*
* @param _user The address of the user initiating the withdrawal.
* @param _amount The amount the user is withdrawing.
* @param _requestTimestamp The timestamp when the withdrawal request was made.
* @param _protocolSignature - The signature structure containing:
* - signer: The address of the signer, in this case and address controlled by the protocol
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the protocol, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - user withdrawing from TokenLock
* - amount withdrawn
* - requestTimestamp time of the request for the withdrawal to check signature for each individual call
* - protocolSignature.signer
* - protocolSignature.expiry
* @return bool True if the protocol signature is valid; otherwise, false.
*/
function isValidProtocolSignature(
address _user,
uint256 _amount,
uint256 _requestTimestamp,
ProtocolSignature memory _protocolSignature
) internal view returns (bool) {
require(block.timestamp <= _protocolSignature.expiry, "Protocol Signature expired");
bytes32 message = keccak256(
abi.encodePacked(_user, _amount, _requestTimestamp, _protocolSignature.signer, _protocolSignature.expiry)
);
return
SignatureChecker.isValidSignatureNow(
_protocolSignature.signer,
ECDSA.toEthSignedMessageHash(message),
_protocolSignature.signature
);
}
}
/**
* @title ProtocolSigningUtils
* @author NFTfi
* @notice Deployable contract for of the above library
*/
contract ProtocolSigningUtilsContract {
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @notice Verifies the validity of a protocol signature.
* @dev This function checks whether the protocol signature is valid and hasn't expired.
* It constructs a message from the input parameters and verifies its signature against
* the expected signer.
*
* @param _user The address of the user initiating the withdrawal.
* @param _amount The amount the user is withdrawing.
* @param _requestTimestamp The timestamp when the withdrawal request was made.
* @param _protocolSignature - The signature structure containing:
* - signer: The address of the signer, in this case and address controlled by the protocol
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the protocol, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - user withdrawing from TokenLock
* - amount withdrawn
* - requestTimestamp time of the request for the withdrawal to check signature for each individual call
* - protocolSignature.signer
* - protocolSignature.expiry
* @return bool True if the protocol signature is valid; otherwise, false.
*/
function isValidProtocolSignature(
address _user,
uint256 _amount,
uint256 _requestTimestamp,
ProtocolSigningUtils.ProtocolSignature memory _protocolSignature
) external view returns (bool) {
return ProtocolSigningUtils.isValidProtocolSignature(_user, _amount, _requestTimestamp, _protocolSignature);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import "./NFI.sol";
import "./DistributorRegistry.sol";
import "./TokenUtilityAccounting.sol";
import "./utils/Ownable.sol";
import "./utils/ProtocolSigningUtils.sol";
/**
* @title TokenLock
* @author NFTfi
* @dev This contract allows users to lock tokens with a request-based withdrawal mechanism. Withdrawals
* have cooldown periods and need a protocol signature if the tokens withdrawn come from the distributor
* and not from an external source. It integrates with a `TokenUtilityAccounting` contract.
*/
contract TokenLock is Ownable, Pausable {
using SafeERC20 for NFI;
// Contract that calculates a token utility score with a (locked) time based multiplier.
// Optional, can be left zero-address and added in the future.
TokenUtilityAccounting public tokenUtilityAccounting;
NFI public immutable nfiToken;
DistributorRegistry public immutable distributorRegistry;
address public protocolSignerAddress;
// Cooldown time before a withdrawal can be executed after request in seconds
uint256 public cooldown;
mapping(address => uint256) public totalLockedTokens;
mapping(address => uint256) public distributorLockedTokens;
mapping(address => uint256) public withdrawalRequestAmounts;
mapping(bytes32 => bool) private withdrawRequests;
/**
* @dev Emitted when tokens are locked in the contract.
* @param _amount The amount of tokens locked.
* @param _user Address of the user who locked the tokens.
*/
event Locked(uint256 _amount, address indexed _user);
/**
* @dev Emitted when a user requests to withdraw their tokens.
* @param _amount The amount of tokens the user wants to withdraw.
* @param _user Address of the user requesting the withdrawal.
* @param _timestamp When the withdrawal request was made. Unix timstamp in seconds.
* Needs to be saved for withdrawal!
* @param _needsProtocolSignature If the withdrawal requires a protocol signature.
*/
event WithdrawalRequested(uint256 _amount, address indexed _user, uint256 _timestamp, bool _needsProtocolSignature);
/**
* @dev Emitted when a user's withdrawal request is deleted.
* @param _amount The amount of tokens the user initially wanted to withdraw.
* @param _user Address of the user whose request was deleted.
* @param _timestamp When request was made (unix timstamp in seconds)
*/
event WithdrawalRequestDeleted(uint256 _amount, address indexed _user, uint256 _timestamp);
/**
* @dev Emitted when a user withdraws their tokens.
* @param _amount The amount of tokens withdrawn.
* @param _user Address of the user making the withdrawal.
*/
event Withdrawn(uint256 _amount, address indexed _user);
/**
* @dev Initializes the contract, setting initial admin, token, distributor, and cooldown values.
* @param _admin Admin's address.
* @param _nfi Address of the NFI token.
* @param _distributorRegistry MerkleDistributor contract address.
* @param _protocolSignerAddress protocol signature checking feature can be turned off by setting it to 0 address
* @param _cooldown Cooldown time in seconds.
*/
constructor(
address _admin,
address _nfi,
address _distributorRegistry,
address _tokenUtilityAccounting,
address _protocolSignerAddress,
uint256 _cooldown
) Ownable(_admin) {
nfiToken = NFI(_nfi);
distributorRegistry = DistributorRegistry(_distributorRegistry);
tokenUtilityAccounting = TokenUtilityAccounting(_tokenUtilityAccounting);
protocolSignerAddress = _protocolSignerAddress;
cooldown = _cooldown;
}
/**
* @dev Allows the distributor to lock tokens on behalf of a beneficiary (claimer).
* @param _amount Amount of tokens to lock.
* @param _beneficiary Address of the beneficiary.
*/
function lockTokensFromDistributor(uint256 _amount, address _beneficiary) external {
require(distributorRegistry.isDistributor(msg.sender), "Only registered distributor");
_lockTokens(_amount, _beneficiary);
distributorLockedTokens[_beneficiary] += _amount;
}
/**
* @dev Allows a user to lock their externally owned tokens
* @param _amount Amount of tokens to lock.
*/
function lockTokens(uint256 _amount) external {
_lockTokens(_amount, msg.sender);
}
/**
* @dev Internal function to handle locking of tokens.
* @param _amount Amount of tokens to lock.
* @param _beneficiary Address for whom the tokens are being locked.
*/
function _lockTokens(uint256 _amount, address _beneficiary) internal whenNotPaused {
nfiToken.safeTransferFrom(msg.sender, address(this), _amount);
totalLockedTokens[_beneficiary] += _amount;
if (address(tokenUtilityAccounting) != address(0)) {
tokenUtilityAccounting.lock(_beneficiary, _amount);
}
emit Locked(_amount, _beneficiary);
}
/**
* @dev Allows a user to request a withdrawal of their tokens.
* @param _amount Amount of tokens to request for withdrawal.
*/
function requestWithdrawal(uint256 _amount) external whenNotPaused {
require(
_amount + withdrawalRequestAmounts[msg.sender] <= totalLockedTokens[msg.sender],
"request amounts > total"
);
bytes32 requestHash = _calculateRequestHash(_amount, msg.sender, block.timestamp);
require(!withdrawRequests[requestHash], "duplicate request");
withdrawalRequestAmounts[msg.sender] += _amount;
withdrawRequests[requestHash] = true;
bool needsProtocolSignature = isProtocolSignatureNeeded(_amount, msg.sender);
emit WithdrawalRequested(_amount, msg.sender, block.timestamp, needsProtocolSignature);
if (address(tokenUtilityAccounting) != address(0)) {
tokenUtilityAccounting.unlock(msg.sender, _amount);
}
}
/**
* @dev Allows a user to delete their withdrawal request.
* @param _amount Amount of tokens that were requested for withdrawal.
* @param _requestTimestamp Timestamp of the original withdrawal request.
*/
function deleteWithdrawRequest(uint256 _amount, uint256 _requestTimestamp) external whenNotPaused {
bytes32 requestHash = _calculateRequestHash(_amount, msg.sender, _requestTimestamp);
require(withdrawRequests[requestHash], "no request");
delete withdrawRequests[requestHash];
withdrawalRequestAmounts[msg.sender] -= _amount;
emit WithdrawalRequestDeleted(_amount, msg.sender, _requestTimestamp);
if (address(tokenUtilityAccounting) != address(0)) {
tokenUtilityAccounting.lock(msg.sender, _amount);
}
}
/**
* @dev Allows a user to withdraw their tokens after a cooldown,
* with a protocol signature if we withdraw from the ditributor locked pot.
* @param _amount Amount of tokens to withdraw.
* @param _requestTimestamp Timestamp of the original withdrawal request.
* @param _protocolSignatureExpiry The timestamp after which the signature is considered expired and invalid.
* Not checked if we withdraw from the non-ditributor locked pot.
* Can be left with 0 values in that case.
* @param _protocolSignature The actual ECDSA signature bytes of the signed data
* Not checked if we withdraw from the non-ditributor locked pot.
* Can be left with 0 values in that case.
*/
function withdraw(
uint256 _amount,
uint256 _requestTimestamp,
uint256 _protocolSignatureExpiry,
bytes calldata _protocolSignature
) external whenNotPaused {
require(_amount <= totalLockedTokens[msg.sender], "withdraw amount > total");
// cooldown checking feature can be turned off by setting it to 0
if (cooldown > 0) {
bytes32 requestHash = _calculateRequestHash(_amount, msg.sender, _requestTimestamp);
require(withdrawRequests[requestHash], "no request");
require(block.timestamp >= _requestTimestamp + cooldown, "cooldown not up");
delete withdrawRequests[requestHash];
withdrawalRequestAmounts[msg.sender] -= _amount;
} else {
if (address(tokenUtilityAccounting) != address(0)) {
tokenUtilityAccounting.unlock(msg.sender, _amount);
}
}
bool needsProtocolSignature = isProtocolSignatureNeeded(_amount, msg.sender);
// protocol signature checking feature can be turned off by setting signer address to 0 address
if (needsProtocolSignature && protocolSignerAddress != address(0)) {
require(
ProtocolSigningUtils.isValidProtocolSignature(
msg.sender,
_amount,
_requestTimestamp,
ProtocolSigningUtils.ProtocolSignature({
expiry: _protocolSignatureExpiry,
signer: protocolSignerAddress,
signature: _protocolSignature
})
),
"Protocol signature invalid"
);
// if we needed Protocol Signature anyway, we deduct it primarily from the distributor locked pot
if (distributorLockedTokens[msg.sender] > _amount) {
distributorLockedTokens[msg.sender] -= _amount;
} else {
distributorLockedTokens[msg.sender] = 0;
}
}
totalLockedTokens[msg.sender] -= _amount;
nfiToken.safeTransfer(msg.sender, _amount);
emit Withdrawn(_amount, msg.sender);
}
/**
* @dev Allows the owner to set a new TokenUtilityAccounting contract.
* @param _newTokenUtilityAccounting Address of the new TokenUtilityAccounting contract.
*/
function setTokenUtilityAccounting(address _newTokenUtilityAccounting) external onlyOwner {
tokenUtilityAccounting = TokenUtilityAccounting(_newTokenUtilityAccounting);
}
/**
* @dev Sets up new cooldown period
* cooldown checking feature can be turned off by setting it to 0
* @param _cooldown - Cooldown time before a withdrawal can be executed after request in seconds
*/
function setCooldown(uint256 _cooldown) external onlyOwner {
cooldown = _cooldown;
}
/**
* @dev Sets up new protocol signer address,
* protocol signature checking feature can be turned off by setting it to 0 address
* @param _protocolSignerAddress -
*/
function setProtocolSignerAddress(address _protocolSignerAddress) external onlyOwner {
protocolSignerAddress = _protocolSignerAddress;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must not be paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must be paused.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @dev Calculates the hash of a withdrawal request.
* @param _amount Amount of tokens to withdraw.
* @param _user Address of the user.
* @param _timestamp Timestamp of the request.
* @return Hash of the withdrawal request.
*/
function _calculateRequestHash(
uint256 _amount,
address _user,
uint256 _timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_amount, _user, _timestamp));
}
/**
* @dev Determines if a protocol signature is needed for a withdrawal.
* @param _amount Amount of tokens to withdraw.
* @param _user Address of the user.
* @return True if protocol signature is needed, false otherwise.
*/
function isProtocolSignatureNeeded(uint256 _amount, address _user) public view returns (bool) {
uint256 externalLockedTokens = totalLockedTokens[_user] - distributorLockedTokens[_user];
return (externalLockedTokens < _amount);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;
/**
* @title TokenUtilityAccounting
* @author NFTfi
* @dev
*/
contract TokenUtilityAccounting {
address public tokenLock;
mapping(address => uint256) public weightedAvgLockTimes;
mapping(address => uint256) public amounts;
// these two only needed if we wanted to distribute a finite,
// given amount of rewards proportionally for locking times and amounts acrued
uint256 public totalWeightedAvgLockTime;
uint256 public totalAmount;
event Update(
address indexed _user,
uint256 _weightedAvgLockTime,
uint256 _acruedUserAmount,
uint256 _totalWeightedAvgLockTime,
uint256 _totalAmount
);
constructor(address _tokenLock) {
tokenLock = _tokenLock;
}
modifier onlyTokenLock() {
require(msg.sender == tokenLock, "Only token lock");
_;
}
function lock(address _user, uint256 _amount) external onlyTokenLock {
_updateUserWeightedAvgLockTime(_user, _amount);
_updateTotalWeightedAvgLockTime(_amount);
amounts[_user] += _amount;
totalAmount += _amount;
emit Update(_user, weightedAvgLockTimes[_user], amounts[_user], totalWeightedAvgLockTime, totalAmount);
}
function unlock(address _user, uint256 _amount) external onlyTokenLock {
amounts[_user] -= _amount;
totalAmount -= _amount;
emit Update(_user, weightedAvgLockTimes[_user], amounts[_user], totalWeightedAvgLockTime, totalAmount);
}
/**
* @dev updates weighted avg lock time for a given user based on the added amount
* @param _user -
* @param _amount - amount added
*/
function _updateUserWeightedAvgLockTime(address _user, uint256 _amount) internal {
weightedAvgLockTimes[_user] = _calculateWeightedAvgLockTime(
_amount,
amounts[_user],
weightedAvgLockTimes[_user]
);
}
/**
* @dev updates weighted avg lock time for the whole system based on the added amount
* @param _amount - amount added
*/
function _updateTotalWeightedAvgLockTime(uint256 _amount) internal {
totalWeightedAvgLockTime = _calculateWeightedAvgLockTime(_amount, totalAmount, totalWeightedAvgLockTime);
}
/**
* @dev calculates weightedAvgMultiplier virtual timestamp value with
* a new data point of token _amount weight and the current time
* This function is either called by _updateAvgMultiplierStart or has to be called after
* an explicit stake() or a deleteWithdrawRequest(), or any other possible instances,
* The function takes the existing average and it's weight (existing balance) then calculates
* it with the new value and weight with a weighted avg calculation between the 2 datapoints.
* @param _amount - amount added
* @param _oldAmount - cumulative amount before
* @param _oldWeightedAvgLockTime -
*/
function _calculateWeightedAvgLockTime(
uint256 _amount,
uint256 _oldAmount,
uint256 _oldWeightedAvgLockTime
) internal view returns (uint256) {
if (_oldAmount == 0 || _oldWeightedAvgLockTime == 0) {
// if we are at initial state with just 1 datapoint
return block.timestamp;
} else {
uint256 totalWeight = _oldAmount + _amount;
// weighted avg calculation between the old value and the new lock timestamp
return (_oldAmount * _oldWeightedAvgLockTime + _amount * block.timestamp) / totalWeight;
}
}
}
{
"compilationTarget": {
"contracts/DistributorRegistry.sol": "DistributorRegistry"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_admin","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"_seasonNumber","type":"uint256"},{"indexed":false,"internalType":"address","name":"_distributor","type":"address"}],"name":"DistributorAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"_seasonNumber","type":"uint256"},{"indexed":false,"internalType":"address","name":"_distributor","type":"address"}],"name":"DistributorRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"acceptTransferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_seasonNumber","type":"uint256"},{"internalType":"address","name":"_distributor","type":"address"}],"name":"addDistributor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"cancelTransferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"distributors","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"distributorsBySeason","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_distributor","type":"address"}],"name":"isDistributor","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"seasonNumber","type":"uint256"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32[]","name":"merkleProof","type":"bytes32[]"}],"internalType":"struct DistributorRegistry.MultiClaimData[]","name":"_claimData","type":"tuple[]"}],"name":"multiClaim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rejectTransferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_seasonNumber","type":"uint256"}],"name":"removeDistributor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newOwnerCandidate","type":"address"}],"name":"requestTransferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]