{
    "Function": "slitherConstructorVariables",
    "File": "contracts/MerkleResistor.sol",
    "Parent Contracts": [],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract MerkleResistor {\n    using MerkleLib for bytes32;\n\n    // tree (vesting schedule) counter\n    uint public numTrees = 0;\n\n    // this represents a user chosen vesting schedule, post initiation\n    struct Tranche {\n        uint totalCoins; // total coins released after vesting complete\n        uint currentCoins; // unclaimed coins remaining in the contract, waiting to be vested\n        uint startTime; // start time of the vesting schedule\n        uint endTime;   // end time of the vesting schedule\n        uint coinsPerSecond;  // how many coins are emitted per second, this value is cached to avoid recomputing it\n        uint lastWithdrawalTime; // keep track of last time user claimed coins to compute coins owed for this withdrawal\n    }\n\n    // this represents an arbitrarily large set of token recipients with partially-initialized vesting schedules\n    struct MerkleTree {\n        bytes32 merkleRoot; // merkle root of tree whose leaves are ranges of vesting schedules for each recipient\n        bytes32 ipfsHash; // ipfs hash of the entire data set represented by the merkle root, in case our servers go down\n        uint minEndTime; // minimum length (offset, not absolute) of vesting schedule in seconds\n        uint maxEndTime; // maximum length (offset, not absolute) of vesting schedule in seconds\n        uint pctUpFront; // percent of vested coins that will be available and withdrawn upon initialization\n        address tokenAddress; // address of token to be distributed\n        uint tokenBalance; // amount of tokens allocated to this tree (this prevents trees from sharing tokens)\n    }\n\n    // initialized[recipient][treeIndex] = hasUserChosenVestingSchedule\n    // could have reused tranches (see below) for this but loading a bool is cheaper than loading an entire struct\n    // NOTE: if a user appears in the same tree multiple times, the first leaf initialized will prevent the others from initializing\n    mapping (address => mapping (uint => bool)) public initialized;\n\n    // basically an array of vesting schedules, but without annoying solidity array syntax\n    mapping (uint => MerkleTree) public merkleTrees;\n\n    // tranches[recipient][treeIndex] = chosenVestingSchedule\n    mapping (address => mapping (uint => Tranche)) public tranches;\n\n    // precision factory used to handle floating point arithmetic\n    uint constant public PRECISION = 1000000;\n\n    // every time a withdrawal occurs\n    event WithdrawalOccurred(uint indexed treeIndex, address indexed destination, uint numTokens, uint tokensLeft);\n\n    // every time a tree is added\n    event MerkleTreeAdded(uint indexed treeIndex, address indexed tokenAddress, bytes32 newRoot, bytes32 ipfsHash);\n\n    // every time a tree is topped up\n    event TokensDeposited(uint indexed treeIndex, address indexed tokenAddress, uint amount);\n\n    /// @notice Add a new merkle tree to the contract, creating a new merkle-vesting-schedule-range\n    /// @dev Anyone may call this function, therefore we must make sure trees cannot affect each other\n    /// @dev Root hash should be built from (destination, minTotalPayments, maxTotalPayments)\n    /// @param newRoot root hash of merkle tree representing vesting schedule ranges\n    /// @param ipfsHash the ipfs hash of the entire dataset, used for redundance so that creator can ensure merkleproof are always computable\n    /// @param minEndTime a continuous range of possible end times are specified, this is the minimum\n    /// @param maxEndTime a continuous range of possible end times are specified, this is the maximum\n    /// @param pctUpFront the percent of tokens user will get at initialization time (note this implies no lock time)\n    /// @param tokenAddress the address of the token contract that is being distributed\n    /// @param tokenBalance the amount of tokens user wishes to use to fund the airdrop, note trees can be under/overfunded\n    function addMerkleTree(bytes32 newRoot, bytes32 ipfsHash, uint minEndTime, uint maxEndTime, uint pctUpFront, address tokenAddress, uint tokenBalance) public {\n        // check basic coherence of request\n        require(pctUpFront < 100, 'pctUpFront >= 100');\n        require(minEndTime < maxEndTime, 'minEndTime must be less than maxEndTime');\n\n        // prefix operator ++ increments then evaluates\n        merkleTrees[++numTrees] = MerkleTree(\n            newRoot,\n            ipfsHash,\n            minEndTime,\n            maxEndTime,\n            pctUpFront,\n            tokenAddress,\n            0    // tokenBalance is 0 at first because no tokens have been deposited\n        );\n\n        // pull tokens from user to fund the tree\n        // if tree is insufficiently funded, then some users may not be able to be paid out, this is the responsibility\n        // of the tree creator, if trees are not funded, then the UI will not display the tree\n        depositTokens(numTrees, tokenBalance);\n        emit MerkleTreeAdded(numTrees, tokenAddress, newRoot, ipfsHash);\n    }\n\n    /// @notice Add funds to an existing merkle-tree\n    /// @dev Anyone may call this function, the only risk here is that the token contract is malicious, rendering the tree malicious\n    /// @param treeIndex index into array-like map of merkleTrees\n    /// @param value the amount of tokens user wishes to use to fund the airdrop, note trees can be under/overfunded\n    function depositTokens(uint treeIndex, uint value) public {\n        // storage because we edit\n        MerkleTree storage merkleTree = merkleTrees[treeIndex];\n\n        // bookkeeping to make sure trees do not share tokens\n        merkleTree.tokenBalance += value;\n\n        // do the transfer from the caller\n        // NOTE: it is possible for user to overfund the tree and there is no mechanism to reclaim excess tokens\n        // this is because there is no way for the contract to know when a tree has had all leaves claimed.\n        // There is also no way for the contract to know the minimum or maximum liabilities represented by the leaves\n        // in short, there is no on-chain inspection of any of the leaf data except at initialization time\n        // NOTE: a malicious token contract could cause merkleTree.tokenBalance to be out of sync with the token contract\n        // this is an unavoidable possibility, and it could render the tree unusable, while leaving other trees unharmed\n        require(IERC20(merkleTree.tokenAddress).transferFrom(msg.sender, address(this), value), \"ERC20 transfer failed\");\n        emit TokensDeposited(treeIndex, merkleTree.tokenAddress, value);\n    }\n\n    /// @notice Called once per recipient of a vesting schedule to initialize the vesting schedule and fix the parameters\n    /// @dev Only the recipient can initialize their own schedule here, because a meaningful choice is made\n    /// @dev If the tree is over-funded, excess funds are lost. No clear way to get around this without zk-proofs of global tree stats\n    /// @param treeIndex index into array-like map of merkleTrees\n    /// @param destination address that will receive tokens\n    /// @param vestingTime the actual length of the vesting schedule, chosen by the user\n    /// @param minTotalPayments the minimum amount of tokens they will receive, if they choose minEndTime as vestingTime\n    /// @param maxTotalPayments the maximum amount of tokens they will receive, if they choose maxEndTime as vestingTime\n    /// @param proof array of hashes linking leaf hash of (destination, minTotalPayments, maxTotalPayments) to root\n    function initialize(uint treeIndex, address destination, uint vestingTime, uint minTotalPayments, uint maxTotalPayments, bytes32[] memory proof) external {\n        // user selects own vesting schedule, not others\n        require(msg.sender == destination, 'Can only initialize your own tranche');\n        // can only initialize once\n        require(!initialized[destination][treeIndex], \"Already initialized\");\n        // compute merkle leaf, this is first element of proof\n        bytes32 leaf = keccak256(abi.encode(destination, minTotalPayments, maxTotalPayments));\n        // memory because we do not edit\n        MerkleTree memory tree = merkleTrees[treeIndex];\n        // this calls into MerkleLib, super cheap ~1000 gas per proof element\n        require(tree.merkleRoot.verifyProof(leaf, proof), \"The proof could not be verified.\");\n        // mark tree as initialized, preventing re-entrance or multiple initializations\n        initialized[destination][treeIndex] = true;\n\n        (bool valid, uint totalCoins, uint coinsPerSecond, uint startTime) = verifyVestingSchedule(treeIndex, vestingTime, minTotalPayments, maxTotalPayments);\n        require(valid, 'Invalid vesting schedule');\n\n        // fill out the struct for the address' vesting schedule\n        // don't have to mark as storage here, it's implied (why isn't it always implied when written to? solc-devs?)\n        tranches[destination][treeIndex] = Tranche(\n            totalCoins,    // this is just a cached number for UI, not used\n            totalCoins,    // starts out full\n            startTime,     // start time will usually be in the past, if pctUpFront > 0\n            block.timestamp + vestingTime,  // vesting starts from initialization time\n            coinsPerSecond,  // cached value to avoid recomputation\n            startTime      // this is lastWithdrawalTime, set to startTime to indicate no withdrawals have occurred yet\n        );\n        withdraw(treeIndex, destination);\n    }\n\n    /// @notice Move unlocked funds to the destination\n    /// @dev Anyone may call this function for anyone else, funds go to destination regardless, it's just a question of\n    /// @dev who provides the proof and pays the gas, msg.sender is not used in this function\n    /// @param treeIndex index into array-like map of merkleTrees, which tree should we apply the proof to?\n    /// @param destination recipient of tokens\n    function withdraw(uint treeIndex, address destination) public {\n        // initialize first, no operations on empty structs, I don't care if the values are \"probably zero\"\n        require(initialized[destination][treeIndex], \"You must initialize your account first.\");\n        // storage, since we are editing\n        Tranche storage tranche = tranches[destination][treeIndex];\n        // if it's empty, don't bother\n        require(tranche.currentCoins >  0, 'No coins left to withdraw');\n        uint currentWithdrawal = 0;\n\n        // if after vesting period ends, give them the remaining coins, also avoids dust from rounding errors\n        if (block.timestamp >= tranche.endTime) {\n            currentWithdrawal = tranche.currentCoins;\n        } else {\n            // compute allowed withdrawal\n            // secondsElapsedSinceLastWithdrawal * coinsPerSecond == coinsAccumulatedSinceLastWithdrawal\n            currentWithdrawal = (block.timestamp - tranche.lastWithdrawalTime) * tranche.coinsPerSecond;\n        }\n        // muto? servo\n        MerkleTree storage tree = merkleTrees[treeIndex];\n\n        // update struct, modern solidity will catch underflow and prevent currentWithdrawal from exceeding currentCoins\n        // but it's computed internally anyway, not user generated\n        tranche.currentCoins -= currentWithdrawal;\n        // move the time counter up so users can't double-withdraw allocated coins\n        // this also works as a re-entrance gate, so currentWithdrawal would be 0 upon re-entrance\n        tranche.lastWithdrawalTime = block.timestamp;\n        // handle the bookkeeping so trees don't share tokens, do it before transferring to create one more re-entrance gate\n        tree.tokenBalance -= currentWithdrawal;\n\n        // transfer the tokens, brah\n        // NOTE: if this is a malicious token, what could happen?\n        // 1/ token doesn't transfer given amount to recipient, this is bad for user, but does not effect other trees\n        // 2/ token fails for some reason, again bad for user, but this does not effect other trees\n        // 3/ token re-enters this function (or other, but this is the only one that transfers tokens out)\n        // in which case, lastWithdrawalTime == block.timestamp, so currentWithdrawal == 0\n        require(IERC20(tree.tokenAddress).transfer(destination, currentWithdrawal), 'Token transfer failed');\n        emit WithdrawalOccurred(treeIndex, destination, currentWithdrawal, tranche.currentCoins);\n    }\n\n    /// @notice Determine if the proposed vesting schedule is legit\n    /// @dev Anyone may call this to check, but it also returns values used in the initialization of vesting schedules\n    /// @param treeIndex index into array-like map of merkleTrees, which tree are we talking about?\n    /// @param vestingTime user chosen length of vesting schedule\n    /// @param minTotalPayments pre-committed (in the root hash) minimum of possible totalCoins\n    /// @param maxTotalPayments pre-committed (in the root hash) maximum of possible totalCoins\n    /// @return valid is the proposed vesting-schedule valid\n    /// @return totalCoins amount of coins allocated in the vesting schedule\n    /// @return coinsPerSecond amount of coins released every second, in the proposed vesting schedule\n    /// @return startTime start time of vesting schedule implied by supplied parameters, will always be <= block.timestamp\n    function verifyVestingSchedule(uint treeIndex, uint vestingTime, uint minTotalPayments, uint maxTotalPayments) public view returns (bool, uint, uint, uint) {\n        // vesting schedules for non-existing trees are invalid, I don't care how much you like uninitialized structs\n        if (treeIndex > numTrees) {\n            return (false, 0, 0, 0);\n        }\n\n        // memory not storage, since we do not edit the tree, and it's a view function anyways\n        MerkleTree memory tree = merkleTrees[treeIndex];\n\n        // vesting time must sit within the closed interval of [minEndTime, maxEndTime]\n        if (vestingTime > tree.maxEndTime || vestingTime < tree.minEndTime) {\n            return (false, 0, 0, 0);\n        }\n\n        uint totalCoins;\n        if (vestingTime == tree.maxEndTime) {\n            // this is to prevent dust accumulation from rounding errors\n            // maxEndTime results in max payments, no further computation necessary\n            totalCoins = maxTotalPayments;\n        } else {\n            // remember grade school algebra? slope = \u0394y / \u0394x\n            // this is the slope of eligible vesting schedules. In general, 0 < m < 1,\n            // (longer vesting schedules should result in less coins per second, hence \"resistor\")\n            // so we multiply by a precision factor to reduce rounding errors\n            // y axis = total coins released after vesting completed\n            // x axis = length of vesting schedule\n            // this is the line of valid end-points for the chosen vesting schedule line, see below\n            // NOTE: this reverts if minTotalPayments > maxTotalPayments, which is a good thing\n            uint paymentSlope = (maxTotalPayments - minTotalPayments) * PRECISION / (tree.maxEndTime - tree.minEndTime);\n\n            // y = mx + b = paymentSlope * (x - x0) + y0\n            // divide by precision factor here since we have completed the rounding error sensitive operations\n            totalCoins = (paymentSlope * (vestingTime - tree.minEndTime) / PRECISION) + minTotalPayments;\n        }\n\n        // this is a different slope, the slope of their chosen vesting schedule\n        // y axis = cumulative coins emitted\n        // x axis = time elapsed\n        // NOTE: vestingTime starts from block.timestamp, so doesn't include coins already available from pctUpFront\n        // totalCoins / vestingTime is wrong, we have to multiple by the proportion of the coins that are indexed\n        // by vestingTime, which is (100 - pctUpFront) / 100\n        uint coinsPerSecond = (totalCoins * (uint(100) - tree.pctUpFront)) / (vestingTime * 100);\n\n        // vestingTime is relative to initialization point\n        // endTime = block.timestamp + vestingTime\n        // vestingLength = totalCoins / coinsPerSecond\n        uint startTime = block.timestamp + vestingTime - (totalCoins / coinsPerSecond);\n\n        return (true, totalCoins, coinsPerSecond, startTime);\n    }\n\n}"
}