Airdrop

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/Airdrop.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

import "@openzeppelin/token/ERC20/IERC20.sol";
import "@openzeppelin/access/Ownable.sol";
import "@openzeppelin/utils/ReentrancyGuard.sol";
import {IVerifier} from "./interface/IVerifier.sol";
import {IDepositManager} from "./interface/IDepositManager.sol";

contract Airdrop is Ownable, ReentrancyGuard {
    struct UserInfo {
        bytes32 snsId;
        bytes32 proofHash;
        uint256 amountGranted;
        bool isProofValid;
        bool hasBeenRewarded;
        bool stake;
    }

    struct Proof {
        uint128[] proof_part1;
        uint256[] proof_part2;
    }

    struct Preprocessed {
        uint128[] preprocessedPart1;
        uint256[] preprocessedPart2;
    }

    struct PublicInputs {
        uint256[] publicInputs;
    }

    // wton token
    IERC20 public immutable wton;
    // The proof verification contract
    IVerifier public verifier;
    // deposit manager for user willing to stake their rewards
    IDepositManager public depositManagerProxy;
    address public layer2;

    mapping(address => UserInfo) public eligibleUser;
    address[] public eligibleUsers;
    uint256 public totalUserRewarded;
    uint256 public totalAmountDistributed;

    uint256 public smax;

    uint256 public constant MAXIMUM_PARTICIPANTS = 30;

    bool public airdropCompleted;

    // Events
    event UserRewarded(address indexed user, bytes32 snsId, bytes32 proofHash, uint256 amount);
    event WrongProofProvided(address indexed user, bytes32 snsId, bytes32 proofHash, uint256 amount);
    event VerifierUpdated(address indexed newVerifier);
    event WinnerListUpdated(uint256 numberOfWinners);
    event BatchRewardCompleted(uint256 successfulRewards, uint256 totalRewardAmount);
    event SmaxUpdated(uint256 newSmax);

    constructor(address _wton, address _verifier, address _depositManagerProxy, address _layer2) Ownable(msg.sender) {
        require(_wton != address(0), "Invalid token address");
        require(_verifier != address(0), "Invalid proof verifier address");
        require(_depositManagerProxy != address(0), "Invalid Deposit Manager address");
        require(_layer2 != address(0), "Invalid layer2 address");

        wton = IERC20(_wton);
        verifier = IVerifier(_verifier);
        depositManagerProxy = IDepositManager(_depositManagerProxy);
        wton.approve(_depositManagerProxy, 4500 * 10 ** 27);
        layer2 = _layer2;
        airdropCompleted = false;
        smax = 512;
    }

    function inputWinnerList(
        address[] calldata users,
        bytes32[] calldata snsIds,
        Proof[] calldata proofs,
        Preprocessed[] calldata preprocessed,
        PublicInputs[] calldata publicInputs,
        uint256[] calldata amountsGranted,
        bytes32[] calldata proofHashes,
        bool[] calldata stakes
    ) external onlyOwner {
        require(users.length == snsIds.length, "Users and SNS IDs length mismatch");
        require(users.length == proofs.length, "Users and proofs length mismatch");
        require(users.length == preprocessed.length, "Users and preprocessed length mismatch");
        require(users.length == amountsGranted.length, "Users and amounts length mismatch");
        require(users.length == proofHashes.length, "Users and proof hashes lengh mismatch");
        require(users.length == stakes.length, "Users and stakes lengh mismatch");
        require(users.length > 0, "Empty arrays not allowed");
        require(!airdropCompleted, "Airdrop event completed");

        uint256 totalAmountGranted;

        for (uint256 i = 0; i < users.length; i++) {
            require(eligibleUsers.length <= MAXIMUM_PARTICIPANTS, "Maximum participants reached");
            require(users[i] != address(0), "Invalid user address");
            require(snsIds[i] != bytes32(0), "Invalid SNS ID");
            require(amountsGranted[i] <= 150 * 10 ** 27, "max granted amount per user exceeded");

            // Check if user is already in the list
            require(eligibleUser[users[i]].snsId == bytes32(0), "User already exists");

            // Use safeVerify instead of direct call
            bool isValid = safeVerify(
                proofs[i].proof_part1,
                proofs[i].proof_part2,
                preprocessed[i].preprocessedPart1,
                preprocessed[i].preprocessedPart2,
                publicInputs[i].publicInputs,
                smax
            );

            eligibleUser[users[i]] = UserInfo({
                snsId: snsIds[i],
                proofHash: proofHashes[i],
                hasBeenRewarded: false,
                amountGranted: amountsGranted[i],
                isProofValid: isValid,
                stake: stakes[i]
            });

            // array for iteration
            eligibleUsers.push(users[i]);
            totalAmountGranted += amountsGranted[i];
            require(eligibleUsers.length <= MAXIMUM_PARTICIPANTS, "maximum number of participants exceeded");
        }
        require(wton.balanceOf(address(this)) >= totalAmountGranted, "Not enough wton available");
        emit WinnerListUpdated(users.length);
    } 


    /**
     * @dev Safe verification that returns false if the external call reverts
     */
    function safeVerify(
        uint128[] memory proof_part1,
        uint256[] memory proof_part2,
        uint128[] memory preprocessedPart1,
        uint256[] memory preprocessedPart2,
        uint256[] memory publicInputs,
        uint256 _smax
    ) private view returns (bool) {
        // Encode the function call
        bytes memory data = abi.encodeWithSelector(
            IVerifier.verify.selector,
            proof_part1,
            proof_part2,
            preprocessedPart1,
            preprocessedPart2,
            publicInputs,
            _smax
        );
        
        // Make the low-level call
        (bool success, bytes memory returnData) = address(verifier).staticcall(data);
        
        // If call failed, return false
        if (!success) {
            return false;
        }
        
        // If call succeeded but returned empty data, return false
        if (returnData.length == 0) {
            return false;
        }
        
        // Decode the boolean result
        return abi.decode(returnData, (bool));
    }

    /**
     * @dev Verify proofs and transfer tokens to all eligible users who haven't been rewarded
     */
    function rewardAll() external nonReentrant onlyOwner {
        require(eligibleUsers.length > 0, "No eligible users");
        require(!airdropCompleted, "Airdrop event completed");

        for (uint256 i = 0; i < eligibleUsers.length; i++) {
            address user = eligibleUsers[i];

            // Skip if already rewarded
            if (eligibleUser[user].hasBeenRewarded) {
                continue;
            }

            // Skip users associated with a wrong proof
            if (!eligibleUser[user].isProofValid) {
                emit WrongProofProvided(user, eligibleUser[user].snsId, eligibleUser[user].proofHash, eligibleUser[user].amountGranted);
            }

            // Mark as rewarded
            eligibleUser[user].hasBeenRewarded = true;

            totalUserRewarded++;
            uint256 rewardAmount;

            // Transfer tokens
            if (!eligibleUser[user].stake) {
                // Users who don't stake get half the amount
                rewardAmount = eligibleUser[user].amountGranted / 2;
                require(wton.transfer(user, rewardAmount), "Token transfer failed");
            } else {
                // Users who stake get the full amount
                rewardAmount = eligibleUser[user].amountGranted;
                require(
                    depositManagerProxy.deposit(layer2, user, rewardAmount),
                    "Failed to stake tokens"
                );
            }

            totalAmountDistributed += rewardAmount;

            emit UserRewarded(user, eligibleUser[user].snsId, eligibleUser[user].proofHash, rewardAmount);
        }

        airdropCompleted = true;
        emit BatchRewardCompleted(totalUserRewarded, totalAmountDistributed);
    }

    /**
     * @dev update granted amount for specific users
     */
    function updateGrantedAmount(address[] calldata users, uint256[] calldata amountsGranted) external onlyOwner {
        require(users.length == amountsGranted.length, "Users and amounts length mismatch");
        require(users.length > 0, "Empty arrays not allowed");
        require(!airdropCompleted, "Airdrop already completed");

        for (uint256 i = 0; i < users.length; ++i) {
            // Check if user exists
            require(eligibleUser[users[i]].snsId != bytes32(0), "User not found");

            // Check if user hasn't been rewarded yet
            require(!eligibleUser[users[i]].hasBeenRewarded, "User already rewarded");

            // Check new amount doesn't exceed maximum
            require(amountsGranted[i] <= 150 * 10 ** 27, "max granted amount per user reached");

            // Update the granted amount
            eligibleUser[users[i]].amountGranted = amountsGranted[i];
        }

        // Calculate total pending rewards after updates
        uint256 totalPendingRewards = 0;
        for (uint256 i = 0; i < eligibleUsers.length; i++) {
            if (!eligibleUser[eligibleUsers[i]].hasBeenRewarded) {
                totalPendingRewards += eligibleUser[eligibleUsers[i]].amountGranted;
            }
        }

        // Ensure contract has enough balance
        require(wton.balanceOf(address(this)) >= totalPendingRewards, "Insufficient WTON balance for updated amounts");

        emit WinnerListUpdated(users.length);
    }

    // emergency functions
    function removeUser(address user) external onlyOwner {
        require(!airdropCompleted, "Airdrop already completed");
        require(eligibleUser[user].snsId != bytes32(0), "User not found");
        require(!eligibleUser[user].hasBeenRewarded, "User already rewarded");

        // Remove from mapping
        delete eligibleUser[user];

        // Remove from array - find and replace with last element
        for (uint256 i = 0; i < eligibleUsers.length; ++i) {
            if (eligibleUsers[i] == user) {
                eligibleUsers[i] = eligibleUsers[eligibleUsers.length - 1];
                eligibleUsers.pop();
                break;
            }
        }
        emit WinnerListUpdated(eligibleUsers.length);
    }

    /**
     * @dev mark the event as completed
     */
    function completeAirdrop() external onlyOwner {
        airdropCompleted = true;
    }

    function setSmax(uint256 _smax) external onlyOwner {
        smax = _smax;
        emit SmaxUpdated(_smax);
    }

    /**
     * @dev withdraw remaining reward
     */
    function withdrawRemainingTokens() external onlyOwner {
        require(airdropCompleted, "Airdrop not completed yet");
        uint256 balance = wton.balanceOf(address(this));
        require(balance > 0, "No tokens to withdraw");
        require(wton.transfer(owner(), balance), "Token transfer failed");
    }

    /**
     * @dev Get the number of eligible users
     */
    function getEligibleUsersCount() external view returns (uint256) {
        return eligibleUsers.length;
    }

    /**
     * @dev Get eligible user address by index
     */
    function getEligibleUserByIndex(uint256 index) external view returns (address) {
        require(index < eligibleUsers.length, "Index out of bounds");
        return eligibleUsers[index];
    }

    /**
     * @dev Get the contract's token balance
     * @return uint256 current token balance
     */
    function getContractBalance() external view returns (uint256) {
        return wton.balanceOf(address(this));
    }

    /**
     * @dev Update the proof verifier contract (only owner)
     * @param _newVerifier New proof verifier contract address
     */
    function updateVerifier(address _newVerifier) external onlyOwner {
        require(_newVerifier != address(0), "Invalid verifier address");
        verifier = IVerifier(_newVerifier);
        emit VerifierUpdated(_newVerifier);
    }




}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
    },
    "lib/openzeppelin-contracts/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
"
    },
    "src/interface/IVerifier.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

/// @title The interface of the Verifier contract, responsible for the zero knowledge proof verification.
/// @author TOKAMAK project Ooo
interface IVerifier {
    /// @dev Verifies a zk-SNARK proof.
    /// Note: The function may revert execution instead of returning false in some cases.
    function verify(
        uint128[] calldata _proof_part1,
        uint256[] calldata _proof_part2,
        uint128[] calldata preprocessedPart1,
        uint256[] calldata preprocessedPart2,
        uint256[] calldata publicInputs,
        uint256 smax
    ) external view returns (bool);
}
"
    },
    "src/interface/IDepositManager.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

interface IDepositManager {
    /// @dev Deposit WTON for a specific user.
    function deposit(address layer2, address account, uint256 amount) external returns (bool);
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    }
  },
  "settings": {
    "remappings": [
      "@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
      "@openzeppelin/=lib/openzeppelin-contracts/contracts/",
      "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
      "forge-std/=lib/forge-std/src/",
      "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
      "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
      "openzeppelin-contracts/=lib/openzeppelin-contracts/"
    ],
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "metadata": {
      "useLiteralContent": false,
      "bytecodeHash": "ipfs",
      "appendCBOR": true
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "evmVersion": "shanghai",
    "viaIR": true
  }
}}

Tags:
ERC20, Multisig, Multi-Signature, Factory|addr:0xca0e8e30a8f9d83aa1035a7d0bca56216a5368f5|verified:true|block:23517916|tx:0x52a6bcfab517dea832c94d623f30ada030721a7c2ebc6a6cef89c78187fbeb1f|first_check:1759748004

Submitted on: 2025-10-06 12:53:26

Comments

Log in to comment.

No comments yet.