// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)pragmasolidity ^0.8.20;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/errorAddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/errorAddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/errorFailedInnerCall();
/**
* @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
if (address(this).balance< amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
if (address(this).balance< value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata
) internalviewreturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty// otherwise we already know that it was a contractif (returndata.length==0&& target.code.length==0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/functionverifyCallResult(bool success, bytesmemory returndata) internalpurereturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/function_revert(bytesmemory returndata) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
Contract Source Code
File 2 of 7: BitMaps.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/BitMaps.sol)pragmasolidity ^0.8.20;/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, provided the keys are sequential.
* Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*
* BitMaps pack 256 booleans across each bit of a single 256-bit slot of `uint256` type.
* Hence booleans corresponding to 256 _sequential_ indices would only consume a single slot,
* unlike the regular `bool` which would consume an entire slot for a single value.
*
* This results in gas savings in two ways:
*
* - Setting a zero value to non-zero only once every 256 times
* - Accessing the same warm slot for every 256 _sequential_ indices
*/libraryBitMaps{
structBitMap {
mapping(uint256 bucket =>uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/functionget(BitMap storage bitmap, uint256 index) internalviewreturns (bool) {
uint256 bucket = index >>8;
uint256 mask =1<< (index &0xff);
return bitmap._data[bucket] & mask !=0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/functionsetTo(BitMap storage bitmap, uint256 index, bool value) internal{
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/functionset(BitMap storage bitmap, uint256 index) internal{
uint256 bucket = index >>8;
uint256 mask =1<< (index &0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/functionunset(BitMap storage bitmap, uint256 index) internal{
uint256 bucket = index >>8;
uint256 mask =1<< (index &0xff);
bitmap._data[bucket] &=~mask;
}
}
Contract Source Code
File 3 of 7: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 value) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 value) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 value) externalreturns (bool);
}
Contract Source Code
File 4 of 7: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
Contract Source Code
File 5 of 7: MerkleProof.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)pragmasolidity ^0.8.20;/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*/libraryMerkleProof{
/**
*@dev The multiproof provided is not valid.
*/errorMerkleProofInvalidMultiproof();
/**
* @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.
*/functionverify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internalpurereturns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*/functionverifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internalpurereturns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*/functionprocessProof(bytes32[] memory proof, bytes32 leaf) internalpurereturns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i =0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*/functionprocessProofCalldata(bytes32[] calldata proof, bytes32 leaf) internalpurereturns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i =0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/functionmultiProofVerify(bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internalpurereturns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/functionmultiProofVerifyCalldata(bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internalpurereturns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/functionprocessMultiProof(bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internalpurereturns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of// the Merkle tree.uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.if (leavesLen + proofLen != totalHashes +1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".bytes32[] memory hashes =newbytes32[](totalHashes);
uint256 leafPos =0;
uint256 hashPos =0;
uint256 proofPos =0;
// At each step, we compute the next hash using two values:// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we// get the next hash.// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the// `proof` array.for (uint256 i =0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes >0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes -1];
}
} elseif (leavesLen >0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/functionprocessMultiProofCalldata(bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internalpurereturns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of// the Merkle tree.uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.if (leavesLen + proofLen != totalHashes +1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".bytes32[] memory hashes =newbytes32[](totalHashes);
uint256 leafPos =0;
uint256 hashPos =0;
uint256 proofPos =0;
// At each step, we compute the next hash using two values:// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we// get the next hash.// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the// `proof` array.for (uint256 i =0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes >0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes -1];
}
} elseif (leavesLen >0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Sorts the pair (a, b) and hashes the result.
*/function_hashPair(bytes32 a, bytes32 b) privatepurereturns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/function_efficientHash(bytes32 a, bytes32 b) privatepurereturns (bytes32 value) {
/// @solidity memory-safe-assemblyassembly {
mstore(0x00, a)
mstore(0x20, b)
value :=keccak256(0x00, 0x40)
}
}
}
Contract Source Code
File 6 of 7: PresailDeck.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.22;import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import"@openzeppelin/contracts/utils/structs/BitMaps.sol";
import"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title PresailDeck
* @dev Contract for distributing tokens using a Merkle tree.
*/contractPresailDeck{
usingSafeERC20forIERC20;
structDistribution {
bytes32 merkleRoot;
uint256 lockedTokens;
uint256 claimedTokens;
address token;
bool invalidated;
address owner;
bool markedForReplacement;
bool replaced;
}
mapping(uint256=> Distribution) public distributions;
mapping(uint256=> BitMaps.BitMap) private claimedBitmaps;
uint256public distributionsCount;
eventTokensLocked(uint256indexed distributionId, addressindexed owner, bytes32indexed merkleRoot, uint256 lockedTokens, address token, bool forceExactAmountTransfer);
eventTokensClaimed(uint256indexed distributionId, addressindexed recipient, uint256 amount, address token, addressindexed transferRecipient);
eventTokensReclaimed(uint256indexed distributionId, uint256 reclaimedTokens, address token);
eventTokensDeposited(uint256indexed distributionId, uint256 lockedTokens, uint256 depositedTokens, address token, bool forceExactAmountTransfer);
eventDistributionSetInvalidated(uint256indexed distributionId, bool invalidated);
eventDistributionReplaced(uint256indexed distributionReplacedId, uint256indexed distributionId, addressindexed owner);
errorUnauthorizedAccess(address caller, address owner);
errorDistributionInvalidated(uint256 distributionId);
errorDistributionNotInvalidated(uint256 distributionId);
errorTokensAlreadyClaimed(address recipient);
errorClaimedTokensExceedLockedAmount(uint256 claimedTokens, uint256 lockedTokens);
errorInvalidMerkleProof();
errorArraysLengthMismatch();
errorTokenMismatch();
errorDistributionMarkedForReplacement(uint256 distributionId);
errorDistributionNotMarkedForReplacement(uint256 distributionId);
errorDistributionAlreadyReplaced(uint256 distributionId);
errorNonExactAmountTransfer();
modifieronlyOwner(uint256 _distributionId) {
if (distributions[_distributionId].owner !=msg.sender)
revert UnauthorizedAccess(msg.sender, distributions[_distributionId].owner);
_;
}
/**
* @dev Locks tokens in the contract for distribution.
* @param _token The address of the token contract.
* @param _totalTokens The total number of tokens to be distributed.
* @param _merkleRoot The Merkle root of the Merkle tree containing the token distribution.
* @param _replacesDistribution If this new distribution replaces an existing one
* @param _distributionToReplace If _replacesDistribution is true, this is the index of the distribution to replace
*/functionlockTokens(address _token,
uint256 _totalTokens,
bytes32 _merkleRoot,
bool _replacesDistribution,
uint256 _distributionToReplace,
bool _forceExactAmountTransfer
) external{
uint256 currentDistributionId = distributionsCount;
uint256 distributionExistingBalance =0;
if (_replacesDistribution) {
Distribution storage distributionToReplace = distributions[_distributionToReplace];
if (distributionToReplace.replaced)
revert DistributionAlreadyReplaced(_distributionToReplace);
if (!distributionToReplace.markedForReplacement)
revert DistributionNotMarkedForReplacement(_distributionToReplace);
if (distributionToReplace.owner !=msg.sender)
revert UnauthorizedAccess(msg.sender, distributionToReplace.owner);
if (distributionToReplace.token != _token)
revert TokenMismatch();
distributionToReplace.replaced =true;
distributionExistingBalance = distributionToReplace.lockedTokens - distributionToReplace.claimedTokens;
emit DistributionReplaced(_distributionToReplace, currentDistributionId, msg.sender);
}
distributionsCount++;
distributions[currentDistributionId].merkleRoot = _merkleRoot;
distributions[currentDistributionId].token = _token;
distributions[currentDistributionId].owner =msg.sender;
uint256 balanceBefore = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransferFrom(msg.sender, address(this), _totalTokens);
uint256 balanceAfter = IERC20(_token).balanceOf(address(this));
uint256 netTransferAmount = balanceAfter - balanceBefore;
// If we indicated it to force exact amounts, then the total entered and what was actually transferred should be the same.if (_forceExactAmountTransfer && _totalTokens != netTransferAmount)
revert NonExactAmountTransfer();
distributions[currentDistributionId].lockedTokens = distributionExistingBalance + netTransferAmount;
emit TokensLocked(currentDistributionId, msg.sender, _merkleRoot, netTransferAmount, _token, _forceExactAmountTransfer);
}
/**
* @dev Claims tokens for a recipient based on a Merkle proof.
* @param _distributionId The ID of the distribution.
* @param _index The index of the leaf in the Merkle tree.
* @param _amount The amount of tokens to claim.
* @param _proof The Merkle proof for the claimed tokens.
*/functionclaimTokens(uint256 _distributionId, uint256 _index, uint256 _amount, bytes32[] calldata _proof) external{
_claim(_distributionId, _index, msg.sender, _amount, _proof, msg.sender);
}
/**
* @notice Claims tokens from multiple distributions in a single call.
* @dev This function allows users to claim tokens from multiple distributions simultaneously, providing an array of distribution IDs, accounts, amounts, and proofs.
* @param _distributionIds An array of distribution IDs from which tokens will be claimed.
* @param _indexes An array of indexes for each distribution.
* @param _amounts An array of amounts of tokens to claim for each distribution.
* @param _proofs An array of Merkle proofs for each distribution claim.
*/functionclaimMultipleTokens(uint256[] calldata _distributionIds, uint256[] calldata _indexes, uint256[] calldata _amounts, bytes32[][] calldata _proofs) external{
if (_distributionIds.length!= _indexes.length||
_distributionIds.length!= _amounts.length||
_distributionIds.length!= _proofs.length) {
revert ArraysLengthMismatch();
}
for (uint256 i =0; i < _distributionIds.length; i++) {
_claim(_distributionIds[i], _indexes[i], msg.sender, _amounts[i], _proofs[i], msg.sender);
}
}
/**
* @dev Allows the owner to clawback tokens of a recipient based on a Merkle proof.
* @param _distributionId The ID of the distribution.
* @param _index The index of the leaf in the Merkle tree.
* @param _account The recipient's address to clawback from.
* @param _amount The amount of tokens to reclaim.
* @param _proof The Merkle proof for the reclaimed tokens.
*/functionclawbackTokens(uint256 _distributionId, uint256 _index, address _account, uint256 _amount, bytes32[] calldata _proof) externalonlyOwner(_distributionId) {
Distribution storage distribution = distributions[_distributionId];
_claim(_distributionId, _index, _account, _amount, _proof, distribution.owner);
}
/**
* @dev Internal function to handle token claims.
* @param _distributionId The ID of the distribution.
* @param _index The index of the leaf in the Merkle tree.
* @param _recipient The recipient's address.
* @param _amount The amount of tokens to claim.
* @param _proof The Merkle proof for the claimed tokens.
* @param _transferRecipient The address to transfer the claimed tokens to.
*/function_claim(uint256 _distributionId, uint256 _index, address _recipient, uint256 _amount, bytes32[] calldata _proof, address _transferRecipient) internal{
Distribution storage distribution = distributions[_distributionId];
if (distribution.invalidated)
revert DistributionInvalidated(_distributionId);
if (isClaimed(_distributionId, _index))
revert TokensAlreadyClaimed(_recipient);
if (!MerkleProof.verifyCalldata(_proof, distribution.merkleRoot, _leaf(_index, _recipient, _amount)))
revert InvalidMerkleProof();
BitMaps.BitMap storage claimedBitmap = claimedBitmaps[_distributionId];
BitMaps.set(claimedBitmap, _index);
distribution.claimedTokens = distribution.claimedTokens + _amount;
if (distribution.claimedTokens > distribution.lockedTokens)
revert ClaimedTokensExceedLockedAmount(distribution.claimedTokens, distribution.lockedTokens);
IERC20(distribution.token).safeTransfer(_transferRecipient, _amount);
emit TokensClaimed(_distributionId, _recipient, _amount, distribution.token, _transferRecipient);
}
/**
* @dev Allows the owner to reclaim tokens and invalidates a distribution.
* To be used in case of emergency or after some deadline if beneficiaries are not claiming anymore.
* @param _distributionId The ID of the distribution.
*/functionreclaimTokensAndInvalidateDistribution(uint256 _distributionId) externalonlyOwner(_distributionId) {
Distribution storage distribution = distributions[_distributionId];
if (distribution.invalidated)
revert DistributionInvalidated(_distributionId);
distribution.invalidated =true;
uint256 tokensLeft = distribution.lockedTokens - distribution.claimedTokens;
IERC20(distribution.token).safeTransfer(distribution.owner, tokensLeft);
emit TokensReclaimed(_distributionId, tokensLeft, distribution.token);
emit DistributionSetInvalidated(_distributionId, true);
}
/**
* @dev Allows the owner to invalidate a distribution and mark it for replacement.
* To be used for creating a distribution that replaces another distribution.
* Leaves the tokens still locked in the contract so they can be "transferred" to a new distribution that replaces this one.
* @param _distributionId The ID of the distribution.
*/functioninvalidateDistributionForReplacement(uint256 _distributionId) externalonlyOwner(_distributionId) {
Distribution storage distribution = distributions[_distributionId];
// Can only invalidate it for replacement if:// - it HAS NOT been invalidated AND// - it HAS NOT been already replaced AND// - it HAS NOT been marked for replacement (using invalidateDistributionForReplacement)if (distribution.invalidated)
revert DistributionInvalidated(_distributionId);
if (distribution.replaced)
revert DistributionAlreadyReplaced(_distributionId);
if (distribution.markedForReplacement)
revert DistributionMarkedForReplacement(_distributionId);
distribution.invalidated =true;
distribution.markedForReplacement =true;
emit DistributionSetInvalidated(_distributionId, true);
}
/**
* @dev Allows the owner to cancel the invalidation of a distribution that has been marked for replacement.
* @param _distributionId The ID of the distribution.
*/functioncancelInvalidateDistributionForReplacement(uint256 _distributionId) externalonlyOwner(_distributionId) {
Distribution storage distribution = distributions[_distributionId];
// Can only cancel it if:// - it HAS been invalidated AND// - it HAS NOT been already replaced AND// - it HAS been marked for replacement (using invalidateDistributionForReplacement)if (!distribution.invalidated)
revert DistributionNotInvalidated(_distributionId);
if (distribution.replaced)
revert DistributionAlreadyReplaced(_distributionId);
if (!distribution.markedForReplacement)
revert DistributionNotMarkedForReplacement(_distributionId);
distribution.invalidated =false;
distribution.markedForReplacement =false;
emit DistributionSetInvalidated(_distributionId, false);
}
/**
* @dev Allows owner to deposit tokens into their distribution.
* Only to be used if for some reason they initially locked less tokens than the sum of all amounts in tree.
* @param _distributionId The ID of the distribution.
* @param _tokenAmount The amount of tokens to deposit.
*/functiondepositTokens(uint256 _distributionId, uint256 _tokenAmount, bool _forceExactAmountTransfer) externalonlyOwner(_distributionId) {
Distribution storage distribution = distributions[_distributionId];
if (distribution.invalidated)
revert DistributionInvalidated(_distributionId);
uint256 balanceBefore = IERC20(distribution.token).balanceOf(address(this));
IERC20(distribution.token).safeTransferFrom(msg.sender, address(this), _tokenAmount);
uint256 balanceAfter = IERC20(distribution.token).balanceOf(address(this));
uint256 netTransferAmount = balanceAfter - balanceBefore;
// If we indicated it to force exact mounts, then the total entered and what was actually transferred should be the same.if (_forceExactAmountTransfer && _tokenAmount != netTransferAmount)
revert NonExactAmountTransfer();
distribution.lockedTokens = distribution.lockedTokens + netTransferAmount;
emit TokensDeposited(_distributionId, distribution.lockedTokens, netTransferAmount, distribution.token, _forceExactAmountTransfer);
}
/**
* @dev Internal function to compute the leaf hash for a given index, account, and amount.
* @param index The index of the leaf in the Merkle tree.
* @param account The account address.
* @param amount The token amount.
* @return The computed leaf hash.
*/function_leaf(uint256 index, address account, uint256 amount) internalpurereturns (bytes32) {
returnkeccak256(bytes.concat(keccak256(abi.encode(index, account, amount))));
}
/**
* @dev Checks if a recipient has already claimed tokens.
* @param _distributionId The ID of the distribution.
* @param _index The index of the leaf in the Merkle tree.
* @return A boolean indicating whether the tokens are already claimed.
*/functionisClaimed(uint256 _distributionId, uint256 _index) publicviewreturns (bool) {
return BitMaps.get(claimedBitmaps[_distributionId], _index);
}
/**
* @dev Checks if multiple recipients have already claimed tokens.
* @param _distributionId The ID of the distribution.
* @param _indexes The index of the leaf in the Merkle tree.
* @return An array of booleans indicating whether the tokens are already claimed.
*/functionareClaimed(uint256 _distributionId, uint256[] calldata _indexes) publicviewreturns (bool[] memory) {
bool[] memory results =newbool[](_indexes.length);
for (uint256 i =0; i < _indexes.length; i++) {
results[i] = BitMaps.get(claimedBitmaps[_distributionId], _indexes[i]);
}
return results;
}
}
Contract Source Code
File 7 of 7: SafeERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.20;import {IERC20} from"../IERC20.sol";
import {IERC20Permit} from"../extensions/IERC20Permit.sol";
import {Address} from"../../../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.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @dev An operation with an ERC20 token failed.
*/errorSafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/errorSafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal{
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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, bytesmemory 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.bytesmemory returndata =address(token).functionCall(data);
if (returndata.length!=0&&!abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// 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 cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return success && (returndata.length==0||abi.decode(returndata, (bool))) &&address(token).code.length>0;
}
}