ETH Price: $3,493.34 (+1.16%)

Contract

0xA62dA56e9a330646386365dC6B2945b5C4d120ed
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
BarnFacet

Compiler Version
v0.7.6+commit.7338295f

Optimization Enabled:
Yes with 9999 runs

Other Settings:
default evmVersion
File 1 of 26 : BarnFacet.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../interfaces/IBarn.sol";
import "../libraries/LibBarnStorage.sol";
import "../libraries/LibOwnership.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract BarnFacet {
    using SafeMath for uint256;

    uint256 constant public MAX_LOCK = 365 days;
    uint256 constant BASE_MULTIPLIER = 1e18;

    event Deposit(address indexed user, uint256 amount, uint256 newBalance);
    event Withdraw(address indexed user, uint256 amountWithdrew, uint256 amountLeft);
    event Lock(address indexed user, uint256 timestamp);
    event Delegate(address indexed from, address indexed to);
    event DelegatedPowerIncreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower);
    event DelegatedPowerDecreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower);

    function initBarn(address _bond, address _rewards) public {
        require(_bond != address(0), "BOND address must not be 0x0");

        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();

        require(!ds.initialized, "Barn: already initialized");
        LibOwnership.enforceIsContractOwner();

        ds.initialized = true;

        ds.bond = IERC20(_bond);
        ds.rewards = IRewards(_rewards);
    }

    // deposit allows a user to add more bond to his staked balance
    function deposit(uint256 amount) public {
        require(amount > 0, "Amount must be greater than 0");

        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();
        uint256 allowance = ds.bond.allowance(msg.sender, address(this));
        require(allowance >= amount, "Token allowance too small");

        // this must be called before the user's balance is updated so the rewards contract can calculate
        // the amount owed correctly
        if (address(ds.rewards) != address(0)) {
            ds.rewards.registerUserAction(msg.sender);
        }

        uint256 newBalance = balanceOf(msg.sender).add(amount);
        _updateUserBalance(ds.userStakeHistory[msg.sender], newBalance);
        _updateLockedBond(bondStakedAtTs(block.timestamp).add(amount));

        address delegatedTo = userDelegatedTo(msg.sender);
        if (delegatedTo != address(0)) {
            uint256 newDelegatedPower = delegatedPower(delegatedTo).add(amount);
            _updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);

            emit DelegatedPowerIncreased(msg.sender, delegatedTo, amount, newDelegatedPower);
        }

        ds.bond.transferFrom(msg.sender, address(this), amount);

        emit Deposit(msg.sender, amount, newBalance);
    }

    // withdraw allows a user to withdraw funds if the balance is not locked
    function withdraw(uint256 amount) public {
        require(amount > 0, "Amount must be greater than 0");
        require(userLockedUntil(msg.sender) <= block.timestamp, "User balance is locked");

        uint256 balance = balanceOf(msg.sender);
        require(balance >= amount, "Insufficient balance");

        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();

        // this must be called before the user's balance is updated so the rewards contract can calculate
        // the amount owed correctly
        if (address(ds.rewards) != address(0)) {
            ds.rewards.registerUserAction(msg.sender);
        }

        _updateUserBalance(ds.userStakeHistory[msg.sender], balance.sub(amount));
        _updateLockedBond(bondStakedAtTs(block.timestamp).sub(amount));

        address delegatedTo = userDelegatedTo(msg.sender);
        if (delegatedTo != address(0)) {
            uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(amount);
            _updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);

            emit DelegatedPowerDecreased(msg.sender, delegatedTo, amount, newDelegatedPower);
        }

        ds.bond.transfer(msg.sender, amount);

        emit Withdraw(msg.sender, amount, balance.sub(amount));
    }

    // lock a user's currently staked balance until timestamp & add the bonus to his voting power
    function lock(uint256 timestamp) public {
        require(timestamp > block.timestamp, "Timestamp must be in the future");
        require(timestamp <= block.timestamp + MAX_LOCK, "Timestamp too big");
        require(balanceOf(msg.sender) > 0, "Sender has no balance");

        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();
        LibBarnStorage.Stake[] storage checkpoints = ds.userStakeHistory[msg.sender];
        LibBarnStorage.Stake storage currentStake = checkpoints[checkpoints.length - 1];

        require(timestamp > currentStake.expiryTimestamp, "New timestamp lower than current lock timestamp");

        _updateUserLock(checkpoints, timestamp);

        emit Lock(msg.sender, timestamp);
    }

    function depositAndLock(uint256 amount, uint256 timestamp) public {
        deposit(amount);
        lock(timestamp);
    }

    // delegate allows a user to delegate his voting power to another user
    function delegate(address to) public {
        require(msg.sender != to, "Can't delegate to self");

        uint256 senderBalance = balanceOf(msg.sender);
        require(senderBalance > 0, "No balance to delegate");

        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();

        emit Delegate(msg.sender, to);

        address delegatedTo = userDelegatedTo(msg.sender);
        if (delegatedTo != address(0)) {
            uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(senderBalance);
            _updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);

            emit DelegatedPowerDecreased(msg.sender, delegatedTo, senderBalance, newDelegatedPower);
        }

        if (to != address(0)) {
            uint256 newDelegatedPower = delegatedPower(to).add(senderBalance);
            _updateDelegatedPower(ds.delegatedPowerHistory[to], newDelegatedPower);

            emit DelegatedPowerIncreased(msg.sender, to, senderBalance, newDelegatedPower);
        }

        _updateUserDelegatedTo(ds.userStakeHistory[msg.sender], to);
    }

    // stopDelegate allows a user to take back the delegated voting power
    function stopDelegate() public {
        return delegate(address(0));
    }

    // balanceOf returns the current BOND balance of a user (bonus not included)
    function balanceOf(address user) public view returns (uint256) {
        return balanceAtTs(user, block.timestamp);
    }

    // balanceAtTs returns the amount of BOND that the user currently staked (bonus NOT included)
    function balanceAtTs(address user, uint256 timestamp) public view returns (uint256) {
        LibBarnStorage.Stake memory stake = stakeAtTs(user, timestamp);

        return stake.amount;
    }

    // stakeAtTs returns the Stake object of the user that was valid at `timestamp`
    function stakeAtTs(address user, uint256 timestamp) public view returns (LibBarnStorage.Stake memory) {
        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();
        LibBarnStorage.Stake[] storage stakeHistory = ds.userStakeHistory[user];

        if (stakeHistory.length == 0 || timestamp < stakeHistory[0].timestamp) {
            return LibBarnStorage.Stake(block.timestamp, 0, block.timestamp, address(0));
        }

        uint256 min = 0;
        uint256 max = stakeHistory.length - 1;

        if (timestamp >= stakeHistory[max].timestamp) {
            return stakeHistory[max];
        }

        // binary search of the value in the array
        while (max > min) {
            uint256 mid = (max + min + 1) / 2;
            if (stakeHistory[mid].timestamp <= timestamp) {
                min = mid;
            } else {
                max = mid - 1;
            }
        }

        return stakeHistory[min];
    }

    // votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block
    function votingPower(address user) public view returns (uint256) {
        return votingPowerAtTs(user, block.timestamp);
    }

    // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time
    function votingPowerAtTs(address user, uint256 timestamp) public view returns (uint256) {
        LibBarnStorage.Stake memory stake = stakeAtTs(user, timestamp);

        uint256 ownVotingPower;

        // if the user delegated his voting power to another user, then he doesn't have any voting power left
        if (stake.delegatedTo != address(0)) {
            ownVotingPower = 0;
        } else {
            uint256 balance = stake.amount;
            uint256 multiplier = _stakeMultiplier(stake, timestamp);
            ownVotingPower = balance.mul(multiplier).div(BASE_MULTIPLIER);
        }

        uint256 delegatedVotingPower = delegatedPowerAtTs(user, timestamp);

        return ownVotingPower.add(delegatedVotingPower);
    }

    // bondStaked returns the total raw amount of BOND staked at the current block
    function bondStaked() public view returns (uint256) {
        return bondStakedAtTs(block.timestamp);
    }

    // bondStakedAtTs returns the total raw amount of BOND users have deposited into the contract
    // it does not include any bonus
    function bondStakedAtTs(uint256 timestamp) public view returns (uint256) {
        return _checkpointsBinarySearch(LibBarnStorage.barnStorage().bondStakedHistory, timestamp);
    }

    // delegatedPower returns the total voting power that a user received from other users
    function delegatedPower(address user) public view returns (uint256) {
        return delegatedPowerAtTs(user, block.timestamp);
    }

    // delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time
    function delegatedPowerAtTs(address user, uint256 timestamp) public view returns (uint256) {
        return _checkpointsBinarySearch(LibBarnStorage.barnStorage().delegatedPowerHistory[user], timestamp);
    }

    // same as multiplierAtTs but for the current block timestamp
    function multiplierOf(address user) public view returns (uint256) {
        return multiplierAtTs(user, block.timestamp);
    }

    // multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp
    // it includes the decay mechanism
    function multiplierAtTs(address user, uint256 timestamp) public view returns (uint256) {
        LibBarnStorage.Stake memory stake = stakeAtTs(user, timestamp);

        return _stakeMultiplier(stake, timestamp);
    }

    // userLockedUntil returns the timestamp until the user's balance is locked
    function userLockedUntil(address user) public view returns (uint256) {
        LibBarnStorage.Stake memory c = stakeAtTs(user, block.timestamp);

        return c.expiryTimestamp;
    }

    // userDelegatedTo returns the address to which a user delegated their voting power; address(0) if not delegated
    function userDelegatedTo(address user) public view returns (address) {
        LibBarnStorage.Stake memory c = stakeAtTs(user, block.timestamp);

        return c.delegatedTo;
    }

    // _checkpointsBinarySearch executes a binary search on a list of checkpoints that's sorted chronologically
    // looking for the closest checkpoint that matches the specified timestamp
    function _checkpointsBinarySearch(LibBarnStorage.Checkpoint[] storage checkpoints, uint256 timestamp) internal view returns (uint256) {
        if (checkpoints.length == 0 || timestamp < checkpoints[0].timestamp) {
            return 0;
        }

        uint256 min = 0;
        uint256 max = checkpoints.length - 1;

        if (timestamp >= checkpoints[max].timestamp) {
            return checkpoints[max].amount;
        }

        // binary search of the value in the array
        while (max > min) {
            uint256 mid = (max + min + 1) / 2;
            if (checkpoints[mid].timestamp <= timestamp) {
                min = mid;
            } else {
                max = mid - 1;
            }
        }

        return checkpoints[min].amount;
    }

    // _stakeMultiplier calculates the multiplier for the given stake at the given timestamp
    function _stakeMultiplier(LibBarnStorage.Stake memory stake, uint256 timestamp) internal view returns (uint256) {
        if (timestamp >= stake.expiryTimestamp) {
            return BASE_MULTIPLIER;
        }

        uint256 diff = stake.expiryTimestamp - timestamp;
        if (diff >= MAX_LOCK) {
            return BASE_MULTIPLIER.mul(2);
        }

        return BASE_MULTIPLIER.add(diff.mul(BASE_MULTIPLIER).div(MAX_LOCK));
    }

    // _updateUserBalance manages an array of checkpoints
    // if there's already a checkpoint for the same timestamp, the amount is updated
    // otherwise, a new checkpoint is inserted
    function _updateUserBalance(LibBarnStorage.Stake[] storage checkpoints, uint256 amount) internal {
        if (checkpoints.length == 0) {
            checkpoints.push(LibBarnStorage.Stake(block.timestamp, amount, block.timestamp, address(0)));
        } else {
            LibBarnStorage.Stake storage old = checkpoints[checkpoints.length - 1];

            if (old.timestamp == block.timestamp) {
                old.amount = amount;
            } else {
                checkpoints.push(LibBarnStorage.Stake(block.timestamp, amount, old.expiryTimestamp, old.delegatedTo));
            }
        }
    }

    // _updateUserLock updates the expiry timestamp on the user's stake
    // it assumes that if the user already has a balance, which is checked for in the lock function
    // then there must be at least 1 checkpoint
    function _updateUserLock(LibBarnStorage.Stake[] storage checkpoints, uint256 expiryTimestamp) internal {
        LibBarnStorage.Stake storage old = checkpoints[checkpoints.length - 1];

        if (old.timestamp < block.timestamp) {
            checkpoints.push(LibBarnStorage.Stake(block.timestamp, old.amount, expiryTimestamp, old.delegatedTo));
        } else {
            old.expiryTimestamp = expiryTimestamp;
        }
    }

    // _updateUserDelegatedTo updates the delegateTo property on the user's stake
    // it assumes that if the user already has a balance, which is checked for in the delegate function
    // then there must be at least 1 checkpoint
    function _updateUserDelegatedTo(LibBarnStorage.Stake[] storage checkpoints, address to) internal {
        LibBarnStorage.Stake storage old = checkpoints[checkpoints.length - 1];

        if (old.timestamp < block.timestamp) {
            checkpoints.push(LibBarnStorage.Stake(block.timestamp, old.amount, old.expiryTimestamp, to));
        } else {
            old.delegatedTo = to;
        }
    }

    // _updateDelegatedPower updates the power delegated TO the user in the checkpoints history
    function _updateDelegatedPower(LibBarnStorage.Checkpoint[] storage checkpoints, uint256 amount) internal {
        if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].timestamp < block.timestamp) {
            checkpoints.push(LibBarnStorage.Checkpoint(block.timestamp, amount));
        } else {
            LibBarnStorage.Checkpoint storage old = checkpoints[checkpoints.length - 1];
            old.amount = amount;
        }
    }

    // _updateLockedBond stores the new `amount` into the BOND locked history
    function _updateLockedBond(uint256 amount) internal {
        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();

        if (ds.bondStakedHistory.length == 0 || ds.bondStakedHistory[ds.bondStakedHistory.length - 1].timestamp < block.timestamp) {
            ds.bondStakedHistory.push(LibBarnStorage.Checkpoint(block.timestamp, amount));
        } else {
            LibBarnStorage.Checkpoint storage old = ds.bondStakedHistory[ds.bondStakedHistory.length - 1];
            old.amount = amount;
        }
    }
}

File 2 of 26 : Barn.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "./interfaces/IDiamondCut.sol";
import "./interfaces/IDiamondLoupe.sol";
import "./libraries/LibDiamond.sol";
import "./libraries/LibOwnership.sol";
import "./libraries/LibDiamondStorage.sol";
import "./interfaces/IERC165.sol";
import "./interfaces/IERC173.sol";

contract Barn {
    constructor(IDiamondCut.FacetCut[] memory _diamondCut, address _owner) payable {
        require(_owner != address(0), "owner must not be 0x0");

        LibDiamond.diamondCut(_diamondCut, address(0), new bytes(0));
        LibOwnership.setContractOwner(_owner);

        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        // adding ERC165 data
        ds.supportedInterfaces[type(IERC165).interfaceId] = true;
        ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true;
        ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true;
        ds.supportedInterfaces[type(IERC173).interfaceId] = true;
    }

    // Find facet for function that is called and execute the
    // function if a facet is found and return any value.
    fallback() external payable {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        address facet = address(bytes20(ds.facets[msg.sig].facetAddress));
        require(facet != address(0), "Diamond: Function does not exist");

        assembly {
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch result
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return (0, returndatasize())
            }
        }
    }

    receive() external payable {}
}

File 3 of 26 : IDiamondCut.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

interface IDiamondCut {
    enum FacetCutAction {Add, Replace, Remove}
    // Add=0, Replace=1, Remove=2

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external;

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}

File 4 of 26 : IDiamondLoupe.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
    /// These functions are expected to be called frequently
    /// by tools.

    struct Facet {
        address facetAddress;
        bytes4[] functionSelectors;
    }

    /// @notice Gets all facet addresses and their four byte function selectors.
    /// @return facets_ Facet
    function facets() external view returns (Facet[] memory facets_);

    /// @notice Gets all the function selectors supported by a specific facet.
    /// @param _facet The facet address.
    /// @return facetFunctionSelectors_
    function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);

    /// @notice Get all the facet addresses used by a diamond.
    /// @return facetAddresses_
    function facetAddresses() external view returns (address[] memory facetAddresses_);

    /// @notice Gets the facet that supports the given selector.
    /// @dev If facet is not found return address(0).
    /// @param _functionSelector The function selector.
    /// @return facetAddress_ The facet address.
    function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}

File 5 of 26 : LibDiamond.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../interfaces/IDiamondCut.sol";
import "./LibDiamondStorage.sol";

library LibDiamond {
    event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);

    // Internal function version of diamondCut
    // This code is almost the same as the external diamondCut,
    // except it is using 'Facet[] memory _diamondCut' instead of
    // 'Facet[] calldata _diamondCut'.
    // The code is duplicated to prevent copying calldata to memory which
    // causes an error for a two dimensional array.
    function diamondCut(
        IDiamondCut.FacetCut[] memory _diamondCut,
        address _init,
        bytes memory _calldata
    ) internal {
        uint256 selectorCount = LibDiamondStorage.diamondStorage().selectors.length;

        for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
            selectorCount = executeDiamondCut(selectorCount, _diamondCut[facetIndex]);
        }

        emit DiamondCut(_diamondCut, _init, _calldata);

        initializeDiamondCut(_init, _calldata);
    }

    // executeDiamondCut takes one single FacetCut action and executes it
    // if FacetCutAction can't be identified, it reverts
    function executeDiamondCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) {
        require(cut.functionSelectors.length > 0, "LibDiamond: No selectors in facet to cut");

        if (cut.action == IDiamondCut.FacetCutAction.Add) {
            require(cut.facetAddress != address(0), "LibDiamond: add facet address can't be address(0)");
            enforceHasContractCode(cut.facetAddress, "LibDiamond: add facet must have code");

            return _handleAddCut(selectorCount, cut);
        }

        if (cut.action == IDiamondCut.FacetCutAction.Replace) {
            require(cut.facetAddress != address(0), "LibDiamond: remove facet address can't be address(0)");
            enforceHasContractCode(cut.facetAddress, "LibDiamond: remove facet must have code");

            return _handleReplaceCut(selectorCount, cut);
        }

        if (cut.action == IDiamondCut.FacetCutAction.Remove) {
            require(cut.facetAddress == address(0), "LibDiamond: remove facet address must be address(0)");

            return _handleRemoveCut(selectorCount, cut);
        }

        revert("LibDiamondCut: Incorrect FacetCutAction");
    }

    // _handleAddCut executes a cut with the type Add
    // it reverts if the selector already exists
    function _handleAddCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        for (uint256 selectorIndex; selectorIndex < cut.functionSelectors.length; selectorIndex++) {
            bytes4 selector = cut.functionSelectors[selectorIndex];

            address oldFacetAddress = ds.facets[selector].facetAddress;
            require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");

            ds.facets[selector] = LibDiamondStorage.Facet(
                cut.facetAddress,
                uint16(selectorCount)
            );
            ds.selectors.push(selector);

            selectorCount++;
        }

        return selectorCount;
    }

    // _handleReplaceCut executes a cut with the type Replace
    // it does not allow replacing immutable functions
    // it does not allow replacing with the same function
    // it does not allow replacing a function that does not exist
    function _handleReplaceCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        for (uint256 selectorIndex; selectorIndex < cut.functionSelectors.length; selectorIndex++) {
            bytes4 selector = cut.functionSelectors[selectorIndex];

            address oldFacetAddress = ds.facets[selector].facetAddress;

            // only useful if immutable functions exist
            require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
            require(oldFacetAddress != cut.facetAddress, "LibDiamondCut: Can't replace function with same function");
            require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");

            // replace old facet address
            ds.facets[selector].facetAddress = cut.facetAddress;
        }

        return selectorCount;
    }

    // _handleRemoveCut executes a cut with the type Remove
    // for efficiency, the selector to be deleted is replaced with the last one and then the last one is popped
    // it reverts if the function doesn't exist or it's immutable
    function _handleRemoveCut(uint256 selectorCount, IDiamondCut.FacetCut memory cut) internal returns (uint256) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        for (uint256 selectorIndex; selectorIndex < cut.functionSelectors.length; selectorIndex++) {
            bytes4 selector = cut.functionSelectors[selectorIndex];

            LibDiamondStorage.Facet memory oldFacet = ds.facets[selector];

            require(oldFacet.facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
            require(oldFacet.facetAddress != address(this), "LibDiamondCut: Can't remove immutable function.");

            // replace selector with last selector
            if (oldFacet.selectorPosition != selectorCount - 1) {
                bytes4 lastSelector = ds.selectors[selectorCount - 1];
                ds.selectors[oldFacet.selectorPosition] = lastSelector;
                ds.facets[lastSelector].selectorPosition = oldFacet.selectorPosition;
            }

            // delete last selector
            ds.selectors.pop();
            delete ds.facets[selector];

            selectorCount--;
        }

        return selectorCount;
    }

    function initializeDiamondCut(address _init, bytes memory _calldata) internal {
        if (_init == address(0)) {
            require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but _calldata is not empty");
            return;
        }

        require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
        if (_init != address(this)) {
            enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
        }

        (bool success, bytes memory error) = _init.delegatecall(_calldata);
        if (!success) {
            if (error.length > 0) {
                // bubble up the error
                revert(string(error));
            } else {
                revert("LibDiamondCut: _init function reverted");
            }
        }
    }

    function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
        uint256 contractSize;
        assembly {
            contractSize := extcodesize(_contract)
        }
        require(contractSize > 0, _errorMessage);
    }
}

File 6 of 26 : LibOwnership.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "./LibDiamondStorage.sol";

library LibOwnership {
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    function setContractOwner(address _newOwner) internal {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        address previousOwner = ds.contractOwner;
        require(previousOwner != _newOwner, "Previous owner and new owner must be different");

        ds.contractOwner = _newOwner;

        emit OwnershipTransferred(previousOwner, _newOwner);
    }

    function contractOwner() internal view returns (address contractOwner_) {
        contractOwner_ = LibDiamondStorage.diamondStorage().contractOwner;
    }

    function enforceIsContractOwner() view internal {
        require(msg.sender == LibDiamondStorage.diamondStorage().contractOwner, "Must be contract owner");
    }

    modifier onlyOwner {
        require(msg.sender == LibDiamondStorage.diamondStorage().contractOwner, "Must be contract owner");
        _;
    }
}

File 7 of 26 : LibDiamondStorage.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

library LibDiamondStorage {
    bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");

    struct Facet {
        address facetAddress;
        uint16 selectorPosition;
    }

    struct DiamondStorage {
        // function selector => facet address and selector position in selectors array
        mapping(bytes4 => Facet) facets;
        bytes4[] selectors;

        // ERC165
        mapping(bytes4 => bool) supportedInterfaces;

        // owner of the contract
        address contractOwner;
    }

    function diamondStorage() internal pure returns (DiamondStorage storage ds) {
        bytes32 position = DIAMOND_STORAGE_POSITION;
        assembly {
            ds.slot := position
        }
    }
}

File 8 of 26 : IERC165.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

interface IERC165 {
    /// @notice Query if a contract implements an interface
    /// @param interfaceId The interface identifier, as specified in ERC-165
    /// @dev Interface identification is specified in ERC-165. This function
    ///  uses less than 30,000 gas.
    /// @return `true` if the contract implements `interfaceID` and
    ///  `interfaceID` is not 0xffffffff, `false` otherwise
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 9 of 26 : IERC173.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;

/// @title ERC-173 Contract Ownership Standard
///  Note: the ERC-165 identifier for this interface is 0x7f5828d0
/* is ERC165 */
interface IERC173 {
    /// @dev This emits when ownership of a contract changes.
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /// @notice Get the address of the owner
    /// @return owner_ The address of the owner.
    function owner() external view returns (address owner_);

    /// @notice Set the address of the new owner of the contract
    /// @dev Set _newOwner to address(0) to renounce any ownership.
    /// @param _newOwner The address of the new owner of the contract
    function transferOwnership(address _newOwner) external;
}

File 10 of 26 : OwnershipFacet.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;

import "../libraries/LibOwnership.sol";
import "../interfaces/IERC173.sol";

contract OwnershipFacet is IERC173 {
    function transferOwnership(address _newOwner) external override {
        LibOwnership.enforceIsContractOwner();
        LibOwnership.setContractOwner(_newOwner);
    }

    function owner() external override view returns (address owner_) {
        owner_ = LibOwnership.contractOwner();
    }
}

File 11 of 26 : DiamondCutFacet.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../interfaces/IDiamondCut.sol";
import "../libraries/LibDiamond.sol";
import "../libraries/LibOwnership.sol";

contract DiamondCutFacet is IDiamondCut {
    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external override {
        LibOwnership.enforceIsContractOwner();

        uint256 selectorCount = LibDiamondStorage.diamondStorage().selectors.length;
        for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
            FacetCut memory cut;
            cut.action = _diamondCut[facetIndex].action;
            cut.facetAddress = _diamondCut[facetIndex].facetAddress;
            cut.functionSelectors = _diamondCut[facetIndex].functionSelectors;

            selectorCount = LibDiamond.executeDiamondCut(selectorCount, cut);
        }

        emit DiamondCut(_diamondCut, _init, _calldata);

        LibDiamond.initializeDiamondCut(_init, _calldata);
    }
}

File 12 of 26 : DiamondLoupeFacet.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../libraries/LibDiamondStorage.sol";
import "../interfaces/IDiamondLoupe.sol";
import "../interfaces/IERC165.sol";

contract DiamondLoupeFacet is IDiamondLoupe, IERC165 {
    // Diamond Loupe Functions
    ////////////////////////////////////////////////////////////////////
    /// These functions are expected to be called frequently by tools.
    //
    // struct Facet {
    //     address facetAddress;
    //     bytes4[] functionSelectors;
    // }
    /// @notice Gets all facets and their selectors.
    /// @return facets_ Facet
    function facets() external override view returns (Facet[] memory facets_) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
        uint256 selectorCount = ds.selectors.length;

        // create an array set to the maximum size possible
        facets_ = new Facet[](selectorCount);

        // create an array for counting the number of selectors for each facet
        uint8[] memory numFacetSelectors = new uint8[](selectorCount);

        // total number of facets
        uint256 numFacets;

        // loop through function selectors
        for (uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++) {
            bytes4 selector = ds.selectors[selectorIndex];
            address facetAddress_ = ds.facets[selector].facetAddress;
            bool continueLoop = false;

            // find the functionSelectors array for selector and add selector to it
            for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
                if (facets_[facetIndex].facetAddress == facetAddress_) {
                    facets_[facetIndex].functionSelectors[numFacetSelectors[facetIndex]] = selector;
                    // probably will never have more than 256 functions from one facet contract
                    require(numFacetSelectors[facetIndex] < 255);
                    numFacetSelectors[facetIndex]++;
                    continueLoop = true;
                    break;
                }
            }

            // if functionSelectors array exists for selector then continue loop
            if (continueLoop) {
                continueLoop = false;
                continue;
            }

            // create a new functionSelectors array for selector
            facets_[numFacets].facetAddress = facetAddress_;
            facets_[numFacets].functionSelectors = new bytes4[](selectorCount);
            facets_[numFacets].functionSelectors[0] = selector;

            numFacetSelectors[numFacets] = 1;
            numFacets++;
        }

        for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
            uint256 numSelectors = numFacetSelectors[facetIndex];
            bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
            // setting the number of selectors
            assembly {
                mstore(selectors, numSelectors)
            }
        }

        // setting the number of facets
        assembly {
            mstore(facets_, numFacets)
        }
    }

    /// @notice Gets all the function selectors supported by a specific facet.
    /// @param _facet The facet address.
    /// @return _facetFunctionSelectors The selectors associated with a facet address.
    function facetFunctionSelectors(address _facet) external override view returns (bytes4[] memory _facetFunctionSelectors) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        uint256 selectorCount = ds.selectors.length;
        uint256 numSelectors;
        _facetFunctionSelectors = new bytes4[](selectorCount);

        // loop through function selectors
        for (uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++) {
            bytes4 selector = ds.selectors[selectorIndex];
            address facetAddress_ = ds.facets[selector].facetAddress;
            if (_facet == facetAddress_) {
                _facetFunctionSelectors[numSelectors] = selector;
                numSelectors++;
            }
        }

        // Set the number of selectors in the array
        assembly {
            mstore(_facetFunctionSelectors, numSelectors)
        }
    }

    /// @notice Get all the facet addresses used by a diamond.
    /// @return facetAddresses_
    function facetAddresses() external override view returns (address[] memory facetAddresses_) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();

        uint256 selectorCount = ds.selectors.length;
        // create an array set to the maximum size possible
        facetAddresses_ = new address[](selectorCount);
        uint256 numFacets;

        // loop through function selectors
        for (uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++) {
            bytes4 selector = ds.selectors[selectorIndex];
            address facetAddress_ = ds.facets[selector].facetAddress;
            bool continueLoop = false;

            // see if we have collected the address already and break out of loop if we have
            for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
                if (facetAddress_ == facetAddresses_[facetIndex]) {
                    continueLoop = true;
                    break;
                }
            }

            // continue loop if we already have the address
            if (continueLoop) {
                continueLoop = false;
                continue;
            }

            // include address
            facetAddresses_[numFacets] = facetAddress_;
            numFacets++;
        }

        // Set the number of facet addresses in the array
        assembly {
            mstore(facetAddresses_, numFacets)
        }
    }

    /// @notice Gets the facet address that supports the given selector.
    /// @dev If facet is not found return address(0).
    /// @param _functionSelector The function selector.
    /// @return facetAddress_ The facet address.
    function facetAddress(bytes4 _functionSelector) external override view returns (address facetAddress_) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
        facetAddress_ = ds.facets[_functionSelector].facetAddress;
    }

    // This implements ERC-165.
    function supportsInterface(bytes4 _interfaceId) external override view returns (bool) {
        LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
        return ds.supportedInterfaces[_interfaceId];
    }
}

File 13 of 26 : ChangeRewardsFacet.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../libraries/LibBarnStorage.sol";
import "../libraries/LibOwnership.sol";

contract ChangeRewardsFacet {
    function changeRewardsAddress(address _rewards) public {
        LibOwnership.enforceIsContractOwner();

        LibBarnStorage.Storage storage ds = LibBarnStorage.barnStorage();
        ds.rewards = IRewards(_rewards);
    }
}

File 14 of 26 : LibBarnStorage.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IRewards.sol";

library LibBarnStorage {
    bytes32 constant STORAGE_POSITION = keccak256("com.barnbridge.barn.storage");

    struct Checkpoint {
        uint256 timestamp;
        uint256 amount;
    }

    struct Stake {
        uint256 timestamp;
        uint256 amount;
        uint256 expiryTimestamp;
        address delegatedTo;
    }

    struct Storage {
        bool initialized;

        // mapping of user address to history of Stake objects
        // every user action creates a new object in the history
        mapping(address => Stake[]) userStakeHistory;

        // array of bond staked Checkpoint
        // deposits/withdrawals create a new object in the history (max one per block)
        Checkpoint[] bondStakedHistory;

        // mapping of user address to history of delegated power
        // every delegate/stopDelegate call create a new checkpoint (max one per block)
        mapping(address => Checkpoint[]) delegatedPowerHistory;

        IERC20 bond;
        IRewards rewards;
    }

    function barnStorage() internal pure returns (Storage storage ds) {
        bytes32 position = STORAGE_POSITION;
        assembly {
            ds.slot := position
        }
    }
}

File 15 of 26 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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);
}

File 16 of 26 : IRewards.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

interface IRewards {
    function registerUserAction(address user) external;
}

File 17 of 26 : BarnMock.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;

import "../interfaces/IRewards.sol";

contract BarnMock {
    IRewards public r;
    uint256 public bondStaked;
    mapping(address => uint256) private balances;

    function setRewards(address rewards) public {
        r = IRewards(rewards);
    }

    function callRegisterUserAction(address user) public {
        return r.registerUserAction(user);
    }

    function deposit(address user, uint256 amount) public {
        callRegisterUserAction(user);

        balances[user] = balances[user] + amount;
        bondStaked = bondStaked + amount;
    }

    function withdraw(address user, uint256 amount) public {
        require(balances[user] >= amount, "insufficient balance");

        callRegisterUserAction(user);

        balances[user] = balances[user] - amount;
        bondStaked = bondStaked - amount;
    }

    function balanceOf(address user) public view returns (uint256) {
        return balances[user];
    }
}

File 18 of 26 : Rewards.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IBarn.sol";

contract Rewards is Ownable {
    using SafeMath for uint256;

    uint256 constant decimals = 10 ** 18;

    struct Pull {
        address source;
        uint256 startTs;
        uint256 endTs;
        uint256 totalDuration;
        uint256 totalAmount;
    }

    Pull public pullFeature;
    bool public disabled;
    uint256 public lastPullTs;

    uint256 public balanceBefore;
    uint256 public currentMultiplier;

    mapping(address => uint256) public userMultiplier;
    mapping(address => uint256) public owed;

    IBarn public barn;
    IERC20 public rewardToken;

    event Claim(address indexed user, uint256 amount);

    constructor(address _owner, address _token, address _barn) {
        require(_token != address(0), "reward token must not be 0x0");
        require(_barn != address(0), "barn address must not be 0x0");

        transferOwnership(_owner);

        rewardToken = IERC20(_token);
        barn = IBarn(_barn);
    }

    // registerUserAction is called by the Barn every time the user does a deposit or withdrawal in order to
    // account for the changes in reward that the user should get
    // it updates the amount owed to the user without transferring the funds
    function registerUserAction(address user) public {
        require(msg.sender == address(barn), 'only callable by barn');

        _calculateOwed(user);
    }

    // claim calculates the currently owed reward and transfers the funds to the user
    function claim() public returns (uint256){
        _calculateOwed(msg.sender);

        uint256 amount = owed[msg.sender];
        require(amount > 0, "nothing to claim");

        owed[msg.sender] = 0;

        rewardToken.transfer(msg.sender, amount);

        // acknowledge the amount that was transferred to the user
        ackFunds();

        emit Claim(msg.sender, amount);

        return amount;
    }

    // ackFunds checks the difference between the last known balance of `token` and the current one
    // if it goes up, the multiplier is re-calculated
    // if it goes down, it only updates the known balance
    function ackFunds() public {
        uint256 balanceNow = rewardToken.balanceOf(address(this));

        if (balanceNow == 0 || balanceNow <= balanceBefore) {
            balanceBefore = balanceNow;
            return;
        }

        uint256 totalStakedBond = barn.bondStaked();
        // if there's no bond staked, it doesn't make sense to ackFunds because there's nobody to distribute them to
        // and the calculation would fail anyways due to division by 0
        if (totalStakedBond == 0) {
            return;
        }

        uint256 diff = balanceNow.sub(balanceBefore);
        uint256 multiplier = currentMultiplier.add(diff.mul(decimals).div(totalStakedBond));

        balanceBefore = balanceNow;
        currentMultiplier = multiplier;
    }

    // setupPullToken is used to setup the rewards system; only callable by contract owner
    // set source to address(0) to disable the functionality
    function setupPullToken(address source, uint256 startTs, uint256 endTs, uint256 amount) public {
        require(msg.sender == owner(), "!owner");
        require(!disabled, "contract is disabled");

        if (pullFeature.source != address(0)) {
            require(source == address(0), "contract is already set up, source must be 0x0");
            disabled = true;
        } else {
            require(source != address(0), "contract is not setup, source must be != 0x0");
        }

        if (source == address(0)) {
            require(startTs == 0, "disable contract: startTs must be 0");
            require(endTs == 0, "disable contract: endTs must be 0");
            require(amount == 0, "disable contract: amount must be 0");
        } else {
            require(endTs > startTs, "setup contract: endTs must be greater than startTs");
            require(amount > 0, "setup contract: amount must be greater than 0");
        }

        pullFeature.source = source;
        pullFeature.startTs = startTs;
        pullFeature.endTs = endTs;
        pullFeature.totalDuration = endTs.sub(startTs);
        pullFeature.totalAmount = amount;

        if (lastPullTs < startTs) {
            lastPullTs = startTs;
        }
    }

    // setBarn sets the address of the BarnBridge Barn into the state variable
    function setBarn(address _barn) public {
        require(_barn != address(0), 'barn address must not be 0x0');
        require(msg.sender == owner(), '!owner');

        barn = IBarn(_barn);
    }

    // _pullToken calculates the amount based on the time passed since the last pull relative
    // to the total amount of time that the pull functionality is active and executes a transferFrom from the
    // address supplied as `pullTokenFrom`, if enabled
    function _pullToken() internal {
        if (
            pullFeature.source == address(0) ||
            block.timestamp < pullFeature.startTs
        ) {
            return;
        }

        uint256 timestampCap = pullFeature.endTs;
        if (block.timestamp < pullFeature.endTs) {
            timestampCap = block.timestamp;
        }

        if (lastPullTs >= timestampCap) {
            return;
        }

        uint256 timeSinceLastPull = timestampCap.sub(lastPullTs);
        uint256 shareToPull = timeSinceLastPull.mul(decimals).div(pullFeature.totalDuration);
        uint256 amountToPull = pullFeature.totalAmount.mul(shareToPull).div(decimals);

        lastPullTs = block.timestamp;
        rewardToken.transferFrom(pullFeature.source, address(this), amountToPull);
    }

    // _calculateOwed calculates and updates the total amount that is owed to an user and updates the user's multiplier
    // to the current value
    // it automatically attempts to pull the token from the source and acknowledge the funds
    function _calculateOwed(address user) internal {
        _pullToken();
        ackFunds();

        uint256 reward = _userPendingReward(user);

        owed[user] = owed[user].add(reward);
        userMultiplier[user] = currentMultiplier;
    }

    // _userPendingReward calculates the reward that should be based on the current multiplier / anything that's not included in the `owed[user]` value
    // it does not represent the entire reward that's due to the user unless added on top of `owed[user]`
    function _userPendingReward(address user) internal view returns (uint256) {
        uint256 multiplier = currentMultiplier.sub(userMultiplier[user]);

        return barn.balanceOf(user).mul(multiplier).div(decimals);
    }
}

File 19 of 26 : Ownable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../GSN/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.
 */
abstract contract Ownable is Context {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(_owner == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = 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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

File 20 of 26 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

File 21 of 26 : IBarn.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../libraries/LibBarnStorage.sol";

interface IBarn {
    // deposit allows a user to add more bond to his staked balance
    function deposit(uint256 amount) external;

    // withdraw allows a user to withdraw funds if the balance is not locked
    function withdraw(uint256 amount) external;

    // lock a user's currently staked balance until timestamp & add the bonus to his voting power
    function lock(uint256 timestamp) external;

    // delegate allows a user to delegate his voting power to another user
    function delegate(address to) external;

    // stopDelegate allows a user to take back the delegated voting power
    function stopDelegate() external;

    // lock the balance of a proposal creator until the voting ends; only callable by DAO
    function lockCreatorBalance(address user, uint256 timestamp) external;

    // balanceOf returns the current BOND balance of a user (bonus not included)
    function balanceOf(address user) external view returns (uint256);

    // balanceAtTs returns the amount of BOND that the user currently staked (bonus NOT included)
    function balanceAtTs(address user, uint256 timestamp) external view returns (uint256);

    // stakeAtTs returns the Stake object of the user that was valid at `timestamp`
    function stakeAtTs(address user, uint256 timestamp) external view returns (LibBarnStorage.Stake memory);

    // votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block
    function votingPower(address user) external view returns (uint256);

    // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time
    function votingPowerAtTs(address user, uint256 timestamp) external view returns (uint256);

    // bondStaked returns the total raw amount of BOND staked at the current block
    function bondStaked() external view returns (uint256);

    // bondStakedAtTs returns the total raw amount of BOND users have deposited into the contract
    // it does not include any bonus
    function bondStakedAtTs(uint256 timestamp) external view returns (uint256);

    // delegatedPower returns the total voting power that a user received from other users
    function delegatedPower(address user) external view returns (uint256);

    // delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time
    function delegatedPowerAtTs(address user, uint256 timestamp) external view returns (uint256);

    // multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp
    // it includes the decay mechanism
    function multiplierAtTs(address user, uint256 timestamp) external view returns (uint256);

    // userLockedUntil returns the timestamp until the user's balance is locked
    function userLockedUntil(address user) external view returns (uint256);

    // userDidDelegate returns the address to which a user delegated their voting power; address(0) if not delegated
    function userDelegatedTo(address user) external view returns (address);

    // bondCirculatingSupply returns the current circulating supply of BOND
    function bondCirculatingSupply() external view returns (uint256);
}

File 22 of 26 : Context.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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 GSN 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 payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

File 23 of 26 : MulticallMock.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;

import "../interfaces/IBarn.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";

contract MulticallMock {
    using SafeMath for uint256;

    IBarn barn;
    IERC20 bond;

    constructor(address _barn, address _bond) {
        barn = IBarn(_barn);
        bond = IERC20(_bond);
    }

    function multiDelegate(uint256 amount, address user1, address user2) public {
        bond.approve(address(barn), amount);

        barn.deposit(amount);
        barn.delegate(user1);
        barn.delegate(user2);
        barn.delegate(user1);
    }

    function multiDeposit(uint256 amount) public {
        bond.approve(address(barn), amount.mul(3));

        barn.deposit(amount);
        barn.deposit(amount);
        barn.deposit(amount);
    }
}

File 24 of 26 : ERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 guidelines: functions revert instead
 * of 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 {
    using SafeMath for uint256;
    using Address for address;

    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _decimals = 18;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view 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 {_setupDecimals} is
     * called.
     *
     * 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 returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view 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);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        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].add(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) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is 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);

        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(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
     *
     * - `to` 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 = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(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);

        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(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 Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

    /**
     * @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 to 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 { }
}

File 25 of 26 : Address.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

    /**
     * @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");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (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");
        return _functionCallWithValue(target, data, value, errorMessage);
    }

    function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
        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

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 26 of 26 : ERC20Mock.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract ERC20Mock is ERC20("ERC20Mock", "MCK") {
    bool public transferFromCalled = false;

    bool public transferCalled = false;
    address public transferRecipient = address(0);
    uint256 public transferAmount = 0;

    function mint(address user, uint256 amount) public {
        _mint(user, amount);
    }

    function burnFrom(address user, uint256 amount) public {
        _burn(user, amount);
    }

    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        transferFromCalled = true;

        return super.transferFrom(sender, recipient, amount);
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        transferCalled = true;
        transferRecipient = recipient;
        transferAmount = amount;

        return super.transfer(recipient, amount);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 9999
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Delegate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"to_newDelegatedPower","type":"uint256"}],"name":"DelegatedPowerDecreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"to_newDelegatedPower","type":"uint256"}],"name":"DelegatedPowerIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"Lock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountWithdrew","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountLeft","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"MAX_LOCK","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"balanceAtTs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bondStaked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"bondStakedAtTs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"delegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"delegatedPower","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"delegatedPowerAtTs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"depositAndLock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_bond","type":"address"},{"internalType":"address","name":"_rewards","type":"address"}],"name":"initBarn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"lock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"multiplierAtTs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"multiplierOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"stakeAtTs","outputs":[{"components":[{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"expiryTimestamp","type":"uint256"},{"internalType":"address","name":"delegatedTo","type":"address"}],"internalType":"struct LibBarnStorage.Stake","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stopDelegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"userDelegatedTo","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"userLockedUntil","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"votingPower","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"votingPowerAtTs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]

608060405234801561001057600080fd5b50611eab806100206000396000f3fe608060405234801561001057600080fd5b50600436106101775760003560e01c80638e4a5248116100d8578063c07473f61161008c578063d265a11511610066578063d265a115146102e3578063dd467064146102f6578063f77f962f1461030957610177565b8063c07473f6146102b5578063c2077e81146102c8578063cbf8eda9146102d057610177565b8063bef624d8116100bd578063bef624d81461026f578063bf0ae48c1461028f578063bfc10279146102a257610177565b80638e4a524814610249578063b6b55f251461025c57610177565b80635c19a95c1161012f5780636f121578116101145780636f1215781461021b57806370a08231146102235780637a1410961461023657610177565b80635c19a95c1461020057806365a5d5f01461021357610177565b80632e1a7d4d116101605780632e1a7d4d146101c5578063417edd4d146101da5780635107a3ae146101ed57610177565b8063169df0641461017c57806318ab6a3c146101a5575b600080fd5b61018f61018a3660046119c7565b61031c565b60405161019c9190611e3d565b60405180910390f35b6101b86101b3366004611a13565b610330565b60405161019c9190611e09565b6101d86101d3366004611a5c565b610507565b005b61018f6101e8366004611a13565b6107eb565b6101d86101fb3660046119e1565b610804565b6101d861020e3660046119c7565b6108d5565b61018f610aca565b6101d8610ad2565b61018f6102313660046119c7565b610ade565b61018f610244366004611a13565b610aea565b61018f6102573660046119c7565b610b0b565b6101d861026a366004611a5c565b610b17565b61028261027d3660046119c7565b610e5f565b60405161019c9190611aad565b61018f61029d3660046119c7565b610e77565b6101d86102b0366004611a8c565b610e8f565b61018f6102c33660046119c7565b610ea5565b61018f610eb1565b61018f6102de366004611a13565b610ec1565b61018f6102f1366004611a13565b610f45565b6101d8610304366004611a5c565b610f7b565b61018f610317366004611a5c565b61108f565b60006103288242610f45565b90505b919050565b61033861197f565b60006103426110a5565b6001600160a01b03851660009081526001820160205260409020805491925090158061038b57508060008154811061037657fe5b90600052602060002090600402016000015484105b156103c55760405180608001604052804281526020016000815260200142815260200160006001600160a01b031681525092505050610501565b80546000906000198101908390829081106103dc57fe5b90600052602060002090600402016000015486106104565782818154811061040057fe5b6000918252602091829020604080516080810182526004909302909101805483526001810154938301939093526002830154908201526003909101546001600160a01b0316606082015294506105019350505050565b818111156104a457600060026001838501010490508684828154811061047857fe5b906000526020600020906004020160000154116104975780925061049e565b6001810391505b50610456565b8282815481106104b057fe5b6000918252602091829020604080516080810182526004909302909101805483526001810154938301939093526002830154908201526003909101546001600160a01b031660608201529450505050505b92915050565b600081116105305760405162461bcd60e51b815260040161052790611bbd565b60405180910390fd5b4261053a33610e77565b11156105585760405162461bcd60e51b815260040161052790611c99565b600061056333610ade565b9050818110156105855760405162461bcd60e51b815260040161052790611bf4565b600061058f6110a5565b60058101549091506001600160a01b0316156106235760058101546040517f66a7d8210000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906366a7d821906105f0903390600401611aad565b600060405180830381600087803b15801561060a57600080fd5b505af115801561061e573d6000803e3d6000fd5b505050505b33600090815260018201602052604090206106479061064284866110c9565b61110b565b61066261065d846106574261108f565b906110c9565b611279565b600061066d33610e5f565b90506001600160a01b0381161561070357600061068d856106578461031c565b6001600160a01b038316600090815260038501602052604090209091506106b49082611334565b816001600160a01b0316336001600160a01b03167ffb73cd22fb01f433ef312f758a708c1c7d1442ec871b9dd2546b3ec85a8b4e7687846040516106f9929190611e46565b60405180910390a3505b6004808301546040517fa9059cbb0000000000000000000000000000000000000000000000000000000081526001600160a01b039091169163a9059cbb9161074f913391899101611aff565b602060405180830381600087803b15801561076957600080fd5b505af115801561077d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a19190611a3c565b50337ff279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b568856107cf86826110c9565b6040516107dd929190611e46565b60405180910390a250505050565b6000806107f88484610330565b60200151949350505050565b6001600160a01b03821661082a5760405162461bcd60e51b815260040161052790611b4f565b60006108346110a5565b805490915060ff16156108595760405162461bcd60e51b815260040161052790611b18565b6108616113d7565b80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011781556004810180546001600160a01b039485167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560059091018054929093169116179055565b336001600160a01b03821614156108fe5760405162461bcd60e51b815260040161052790611c2b565b600061090933610ade565b90506000811161092b5760405162461bcd60e51b815260040161052790611d2d565b60006109356110a5565b6040519091506001600160a01b0384169033907fab7d75eccd27c9989942a3a6e4137e415df0ad90ec428751b16361f16fe8780f90600090a3600061097933610e5f565b90506001600160a01b03811615610a0f576000610999846106578461031c565b6001600160a01b038316600090815260038501602052604090209091506109c09082611334565b816001600160a01b0316336001600160a01b03167ffb73cd22fb01f433ef312f758a708c1c7d1442ec871b9dd2546b3ec85a8b4e768684604051610a05929190611e46565b60405180910390a3505b6001600160a01b03841615610aa9576000610a3384610a2d8761031c565b9061140a565b6001600160a01b03861660009081526003850160205260409020909150610a5a9082611334565b846001600160a01b0316336001600160a01b03167f9306546ca617a204223f7da51d942104c887cf8e53f8fd454af55a529aaa689a8684604051610a9f929190611e46565b60405180910390a3505b3360009081526001830160205260409020610ac49085611464565b50505050565b6301e1338081565b610adc60006108d5565b565b600061032882426107eb565b600080610af78484610330565b9050610b038184611573565b949350505050565b60006103288242610aea565b60008111610b375760405162461bcd60e51b815260040161052790611bbd565b6000610b416110a5565b6004808201546040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081529293506000926001600160a01b039091169163dd62ed3e91610b93913391309101611ac1565b60206040518083038186803b158015610bab57600080fd5b505afa158015610bbf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be39190611a74565b905082811015610c055760405162461bcd60e51b815260040161052790611b86565b60058201546001600160a01b031615610c965760058201546040517f66a7d8210000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906366a7d82190610c63903390600401611aad565b600060405180830381600087803b158015610c7d57600080fd5b505af1158015610c91573d6000803e3d6000fd5b505050505b6000610ca584610a2d33610ade565b3360009081526001850160205260409020909150610cc3908261110b565b610cd361065d85610a2d4261108f565b6000610cde33610e5f565b90506001600160a01b03811615610d74576000610cfe86610a2d8461031c565b6001600160a01b03831660009081526003870160205260409020909150610d259082611334565b816001600160a01b0316336001600160a01b03167f9306546ca617a204223f7da51d942104c887cf8e53f8fd454af55a529aaa689a8884604051610d6a929190611e46565b60405180910390a3505b6004808501546040517f23b872dd0000000000000000000000000000000000000000000000000000000081526001600160a01b03909116916323b872dd91610dc291339130918b9101611adb565b602060405180830381600087803b158015610ddc57600080fd5b505af1158015610df0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e149190611a3c565b50336001600160a01b03167f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a158684604051610e50929190611e46565b60405180910390a25050505050565b600080610e6c8342610330565b606001519392505050565b600080610e848342610330565b604001519392505050565b610e9882610b17565b610ea181610f7b565b5050565b60006103288242610ec1565b6000610ebc4261108f565b905090565b600080610ece8484610330565b60608101519091506000906001600160a01b031615610eef57506000610f23565b60208201516000610f008487611573565b9050610f1e670de0b6b3a7640000610f1884846115e9565b90611642565b925050505b6000610f2f8686610f45565b9050610f3b828261140a565b9695505050505050565b6000610f74610f526110a5565b6001600160a01b03851660009081526003919091016020526040902083611684565b9392505050565b428111610f9a5760405162461bcd60e51b815260040161052790611dd2565b6301e133804201811115610fc05760405162461bcd60e51b815260040161052790611c62565b6000610fcb33610ade565b11610fe85760405162461bcd60e51b815260040161052790611d64565b6000610ff26110a5565b33600090815260018201602052604081208054929350918290600019810190811061101957fe5b906000526020600020906004020190508060020154841161104c5760405162461bcd60e51b815260040161052790611cd0565b611056828561178b565b336001600160a01b03167f625fed9875dada8643f2418b838ae0bc78d9a148a18eee4ee1979ff0f3f5d427856040516107dd9190611e3d565b600061032861109c6110a5565b60020183611684565b7fe96c66e59227df98cba2247b26f0b557ed0f64708a0822054b1f9fc99942071590565b6000610f7483836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061185f565b815461119f5760408051608081018252428082526020808301858152938301918252600060608401818152875460018082018a55898452939092209451600490920290940190815593519084015551600283015551600390910180547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b03909216919091179055610ea1565b8154600090839060001981019081106111b457fe5b9060005260206000209060040201905042816000015414156111dc5760018101829055611274565b6040805160808101825242815260208082018581526002858101549484019485526003808701546001600160a01b03908116606087019081528a5460018082018d5560008d81529790972097516004909102909701968755935194860194909455945190840155519190920180547fffffffffffffffffffffffff000000000000000000000000000000000000000016919092161790555b505050565b60006112836110a5565b600281015490915015806112bd575060028101805442919060001981019081106112a957fe5b906000526020600020906002020160000154105b156113015760408051808201909152428152602080820184815260028085018054600181810183556000928352949091209451910290930192835551910155610ea1565b60028101805460009190600019810190811061131957fe5b60009182526020909120600160029092020101839055505050565b815415806113655750815442908390600019810190811061135157fe5b906000526020600020906002020160000154105b156113a7576040805180820190915242815260208082018381528454600181810187556000878152939093209351600290910290930192835551910155610ea1565b8154600090839060001981019081106113bc57fe5b60009182526020909120600160029092020101829055505050565b6113df6118f6565b600301546001600160a01b03163314610adc5760405162461bcd60e51b815260040161052790611d9b565b600082820183811015610f74576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b81546000908390600019810190811061147957fe5b906000526020600020906004020190504281600001541015611537576040805160808101825242815260018381015460208084019182526002808701549585019586526001600160a01b03888116606087019081528a548087018c5560008c815294909420965160049094029096019283559251938201939093559351918401919091559051600390920180547fffffffffffffffffffffffff00000000000000000000000000000000000000001692909116919091179055611274565b6003810180546001600160a01b0384167fffffffffffffffffffffffff0000000000000000000000000000000000000000909116179055505050565b60008260400151821061158f5750670de0b6b3a7640000610501565b60408301518290036301e1338081106115bd576115b5670de0b6b3a764000060026115e9565b915050610501565b610b036115da6301e13380610f1884670de0b6b3a76400006115e9565b670de0b6b3a76400009061140a565b6000826115f857506000610501565b8282028284828161160557fe5b0414610f745760405162461bcd60e51b8152600401808060200182810382526021815260200180611e556021913960400191505060405180910390fd5b6000610f7483836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061191a565b815460009015806116b257508260008154811061169d57fe5b90600052602060002090600202016000015482105b156116bf57506000610501565b82546000906000198101908590829081106116d657fe5b9060005260206000209060020201600001548410611715578481815481106116fa57fe5b90600052602060002090600202016001015492505050610501565b8181111561176357600060026001838501010490508486828154811061173757fe5b906000526020600020906002020160000154116117565780925061175d565b6001810391505b50611715565b84828154811061176f57fe5b9060005260206000209060020201600101549250505092915050565b8154600090839060001981019081106117a057fe5b906000526020600020906004020190504281600001541015611858576040805160808101825242815260018381015460208084019182529383018681526003808701546001600160a01b03908116606087019081528a548087018c5560008c815298909820965160049098029096019687559251938601939093555160028501559151920180547fffffffffffffffffffffffff00000000000000000000000000000000000000001692909116919091179055611274565b6002015550565b600081848411156118ee5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156118b357818101518382015260200161189b565b50505050905090810190601f1680156118e05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b7fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c90565b600081836119695760405162461bcd60e51b81526020600482018181528351602484015283519092839260449091019190850190808383600083156118b357818101518382015260200161189b565b50600083858161197557fe5b0495945050505050565b604051806080016040528060008152602001600081526020016000815260200160006001600160a01b031681525090565b80356001600160a01b038116811461032b57600080fd5b6000602082840312156119d8578081fd5b610f74826119b0565b600080604083850312156119f3578081fd5b6119fc836119b0565b9150611a0a602084016119b0565b90509250929050565b60008060408385031215611a25578182fd5b611a2e836119b0565b946020939093013593505050565b600060208284031215611a4d578081fd5b81518015158114610f74578182fd5b600060208284031215611a6d578081fd5b5035919050565b600060208284031215611a85578081fd5b5051919050565b60008060408385031215611a9e578182fd5b50508035926020909101359150565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b60208082526019908201527f4261726e3a20616c726561647920696e697469616c697a656400000000000000604082015260600190565b6020808252601c908201527f424f4e442061646472657373206d757374206e6f742062652030783000000000604082015260600190565b60208082526019908201527f546f6b656e20616c6c6f77616e636520746f6f20736d616c6c00000000000000604082015260600190565b6020808252601d908201527f416d6f756e74206d7573742062652067726561746572207468616e2030000000604082015260600190565b60208082526014908201527f496e73756666696369656e742062616c616e6365000000000000000000000000604082015260600190565b60208082526016908201527f43616e27742064656c656761746520746f2073656c6600000000000000000000604082015260600190565b60208082526011908201527f54696d657374616d7020746f6f20626967000000000000000000000000000000604082015260600190565b60208082526016908201527f557365722062616c616e6365206973206c6f636b656400000000000000000000604082015260600190565b6020808252602f908201527f4e65772074696d657374616d70206c6f776572207468616e2063757272656e7460408201527f206c6f636b2074696d657374616d700000000000000000000000000000000000606082015260800190565b60208082526016908201527f4e6f2062616c616e636520746f2064656c656761746500000000000000000000604082015260600190565b60208082526015908201527f53656e64657220686173206e6f2062616c616e63650000000000000000000000604082015260600190565b60208082526016908201527f4d75737420626520636f6e7472616374206f776e657200000000000000000000604082015260600190565b6020808252601f908201527f54696d657374616d70206d75737420626520696e207468652066757475726500604082015260600190565b8151815260208083015190820152604080830151908201526060918201516001600160a01b03169181019190915260800190565b90815260200190565b91825260208201526040019056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a26469706673582212208f64fa20edab76b607b6c193355a43d3bfd9d8bfe1f7bc4ea5a07a32959088eb64736f6c63430007060033

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101775760003560e01c80638e4a5248116100d8578063c07473f61161008c578063d265a11511610066578063d265a115146102e3578063dd467064146102f6578063f77f962f1461030957610177565b8063c07473f6146102b5578063c2077e81146102c8578063cbf8eda9146102d057610177565b8063bef624d8116100bd578063bef624d81461026f578063bf0ae48c1461028f578063bfc10279146102a257610177565b80638e4a524814610249578063b6b55f251461025c57610177565b80635c19a95c1161012f5780636f121578116101145780636f1215781461021b57806370a08231146102235780637a1410961461023657610177565b80635c19a95c1461020057806365a5d5f01461021357610177565b80632e1a7d4d116101605780632e1a7d4d146101c5578063417edd4d146101da5780635107a3ae146101ed57610177565b8063169df0641461017c57806318ab6a3c146101a5575b600080fd5b61018f61018a3660046119c7565b61031c565b60405161019c9190611e3d565b60405180910390f35b6101b86101b3366004611a13565b610330565b60405161019c9190611e09565b6101d86101d3366004611a5c565b610507565b005b61018f6101e8366004611a13565b6107eb565b6101d86101fb3660046119e1565b610804565b6101d861020e3660046119c7565b6108d5565b61018f610aca565b6101d8610ad2565b61018f6102313660046119c7565b610ade565b61018f610244366004611a13565b610aea565b61018f6102573660046119c7565b610b0b565b6101d861026a366004611a5c565b610b17565b61028261027d3660046119c7565b610e5f565b60405161019c9190611aad565b61018f61029d3660046119c7565b610e77565b6101d86102b0366004611a8c565b610e8f565b61018f6102c33660046119c7565b610ea5565b61018f610eb1565b61018f6102de366004611a13565b610ec1565b61018f6102f1366004611a13565b610f45565b6101d8610304366004611a5c565b610f7b565b61018f610317366004611a5c565b61108f565b60006103288242610f45565b90505b919050565b61033861197f565b60006103426110a5565b6001600160a01b03851660009081526001820160205260409020805491925090158061038b57508060008154811061037657fe5b90600052602060002090600402016000015484105b156103c55760405180608001604052804281526020016000815260200142815260200160006001600160a01b031681525092505050610501565b80546000906000198101908390829081106103dc57fe5b90600052602060002090600402016000015486106104565782818154811061040057fe5b6000918252602091829020604080516080810182526004909302909101805483526001810154938301939093526002830154908201526003909101546001600160a01b0316606082015294506105019350505050565b818111156104a457600060026001838501010490508684828154811061047857fe5b906000526020600020906004020160000154116104975780925061049e565b6001810391505b50610456565b8282815481106104b057fe5b6000918252602091829020604080516080810182526004909302909101805483526001810154938301939093526002830154908201526003909101546001600160a01b031660608201529450505050505b92915050565b600081116105305760405162461bcd60e51b815260040161052790611bbd565b60405180910390fd5b4261053a33610e77565b11156105585760405162461bcd60e51b815260040161052790611c99565b600061056333610ade565b9050818110156105855760405162461bcd60e51b815260040161052790611bf4565b600061058f6110a5565b60058101549091506001600160a01b0316156106235760058101546040517f66a7d8210000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906366a7d821906105f0903390600401611aad565b600060405180830381600087803b15801561060a57600080fd5b505af115801561061e573d6000803e3d6000fd5b505050505b33600090815260018201602052604090206106479061064284866110c9565b61110b565b61066261065d846106574261108f565b906110c9565b611279565b600061066d33610e5f565b90506001600160a01b0381161561070357600061068d856106578461031c565b6001600160a01b038316600090815260038501602052604090209091506106b49082611334565b816001600160a01b0316336001600160a01b03167ffb73cd22fb01f433ef312f758a708c1c7d1442ec871b9dd2546b3ec85a8b4e7687846040516106f9929190611e46565b60405180910390a3505b6004808301546040517fa9059cbb0000000000000000000000000000000000000000000000000000000081526001600160a01b039091169163a9059cbb9161074f913391899101611aff565b602060405180830381600087803b15801561076957600080fd5b505af115801561077d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a19190611a3c565b50337ff279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b568856107cf86826110c9565b6040516107dd929190611e46565b60405180910390a250505050565b6000806107f88484610330565b60200151949350505050565b6001600160a01b03821661082a5760405162461bcd60e51b815260040161052790611b4f565b60006108346110a5565b805490915060ff16156108595760405162461bcd60e51b815260040161052790611b18565b6108616113d7565b80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011781556004810180546001600160a01b039485167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560059091018054929093169116179055565b336001600160a01b03821614156108fe5760405162461bcd60e51b815260040161052790611c2b565b600061090933610ade565b90506000811161092b5760405162461bcd60e51b815260040161052790611d2d565b60006109356110a5565b6040519091506001600160a01b0384169033907fab7d75eccd27c9989942a3a6e4137e415df0ad90ec428751b16361f16fe8780f90600090a3600061097933610e5f565b90506001600160a01b03811615610a0f576000610999846106578461031c565b6001600160a01b038316600090815260038501602052604090209091506109c09082611334565b816001600160a01b0316336001600160a01b03167ffb73cd22fb01f433ef312f758a708c1c7d1442ec871b9dd2546b3ec85a8b4e768684604051610a05929190611e46565b60405180910390a3505b6001600160a01b03841615610aa9576000610a3384610a2d8761031c565b9061140a565b6001600160a01b03861660009081526003850160205260409020909150610a5a9082611334565b846001600160a01b0316336001600160a01b03167f9306546ca617a204223f7da51d942104c887cf8e53f8fd454af55a529aaa689a8684604051610a9f929190611e46565b60405180910390a3505b3360009081526001830160205260409020610ac49085611464565b50505050565b6301e1338081565b610adc60006108d5565b565b600061032882426107eb565b600080610af78484610330565b9050610b038184611573565b949350505050565b60006103288242610aea565b60008111610b375760405162461bcd60e51b815260040161052790611bbd565b6000610b416110a5565b6004808201546040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081529293506000926001600160a01b039091169163dd62ed3e91610b93913391309101611ac1565b60206040518083038186803b158015610bab57600080fd5b505afa158015610bbf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be39190611a74565b905082811015610c055760405162461bcd60e51b815260040161052790611b86565b60058201546001600160a01b031615610c965760058201546040517f66a7d8210000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906366a7d82190610c63903390600401611aad565b600060405180830381600087803b158015610c7d57600080fd5b505af1158015610c91573d6000803e3d6000fd5b505050505b6000610ca584610a2d33610ade565b3360009081526001850160205260409020909150610cc3908261110b565b610cd361065d85610a2d4261108f565b6000610cde33610e5f565b90506001600160a01b03811615610d74576000610cfe86610a2d8461031c565b6001600160a01b03831660009081526003870160205260409020909150610d259082611334565b816001600160a01b0316336001600160a01b03167f9306546ca617a204223f7da51d942104c887cf8e53f8fd454af55a529aaa689a8884604051610d6a929190611e46565b60405180910390a3505b6004808501546040517f23b872dd0000000000000000000000000000000000000000000000000000000081526001600160a01b03909116916323b872dd91610dc291339130918b9101611adb565b602060405180830381600087803b158015610ddc57600080fd5b505af1158015610df0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e149190611a3c565b50336001600160a01b03167f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a158684604051610e50929190611e46565b60405180910390a25050505050565b600080610e6c8342610330565b606001519392505050565b600080610e848342610330565b604001519392505050565b610e9882610b17565b610ea181610f7b565b5050565b60006103288242610ec1565b6000610ebc4261108f565b905090565b600080610ece8484610330565b60608101519091506000906001600160a01b031615610eef57506000610f23565b60208201516000610f008487611573565b9050610f1e670de0b6b3a7640000610f1884846115e9565b90611642565b925050505b6000610f2f8686610f45565b9050610f3b828261140a565b9695505050505050565b6000610f74610f526110a5565b6001600160a01b03851660009081526003919091016020526040902083611684565b9392505050565b428111610f9a5760405162461bcd60e51b815260040161052790611dd2565b6301e133804201811115610fc05760405162461bcd60e51b815260040161052790611c62565b6000610fcb33610ade565b11610fe85760405162461bcd60e51b815260040161052790611d64565b6000610ff26110a5565b33600090815260018201602052604081208054929350918290600019810190811061101957fe5b906000526020600020906004020190508060020154841161104c5760405162461bcd60e51b815260040161052790611cd0565b611056828561178b565b336001600160a01b03167f625fed9875dada8643f2418b838ae0bc78d9a148a18eee4ee1979ff0f3f5d427856040516107dd9190611e3d565b600061032861109c6110a5565b60020183611684565b7fe96c66e59227df98cba2247b26f0b557ed0f64708a0822054b1f9fc99942071590565b6000610f7483836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061185f565b815461119f5760408051608081018252428082526020808301858152938301918252600060608401818152875460018082018a55898452939092209451600490920290940190815593519084015551600283015551600390910180547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b03909216919091179055610ea1565b8154600090839060001981019081106111b457fe5b9060005260206000209060040201905042816000015414156111dc5760018101829055611274565b6040805160808101825242815260208082018581526002858101549484019485526003808701546001600160a01b03908116606087019081528a5460018082018d5560008d81529790972097516004909102909701968755935194860194909455945190840155519190920180547fffffffffffffffffffffffff000000000000000000000000000000000000000016919092161790555b505050565b60006112836110a5565b600281015490915015806112bd575060028101805442919060001981019081106112a957fe5b906000526020600020906002020160000154105b156113015760408051808201909152428152602080820184815260028085018054600181810183556000928352949091209451910290930192835551910155610ea1565b60028101805460009190600019810190811061131957fe5b60009182526020909120600160029092020101839055505050565b815415806113655750815442908390600019810190811061135157fe5b906000526020600020906002020160000154105b156113a7576040805180820190915242815260208082018381528454600181810187556000878152939093209351600290910290930192835551910155610ea1565b8154600090839060001981019081106113bc57fe5b60009182526020909120600160029092020101829055505050565b6113df6118f6565b600301546001600160a01b03163314610adc5760405162461bcd60e51b815260040161052790611d9b565b600082820183811015610f74576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b81546000908390600019810190811061147957fe5b906000526020600020906004020190504281600001541015611537576040805160808101825242815260018381015460208084019182526002808701549585019586526001600160a01b03888116606087019081528a548087018c5560008c815294909420965160049094029096019283559251938201939093559351918401919091559051600390920180547fffffffffffffffffffffffff00000000000000000000000000000000000000001692909116919091179055611274565b6003810180546001600160a01b0384167fffffffffffffffffffffffff0000000000000000000000000000000000000000909116179055505050565b60008260400151821061158f5750670de0b6b3a7640000610501565b60408301518290036301e1338081106115bd576115b5670de0b6b3a764000060026115e9565b915050610501565b610b036115da6301e13380610f1884670de0b6b3a76400006115e9565b670de0b6b3a76400009061140a565b6000826115f857506000610501565b8282028284828161160557fe5b0414610f745760405162461bcd60e51b8152600401808060200182810382526021815260200180611e556021913960400191505060405180910390fd5b6000610f7483836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061191a565b815460009015806116b257508260008154811061169d57fe5b90600052602060002090600202016000015482105b156116bf57506000610501565b82546000906000198101908590829081106116d657fe5b9060005260206000209060020201600001548410611715578481815481106116fa57fe5b90600052602060002090600202016001015492505050610501565b8181111561176357600060026001838501010490508486828154811061173757fe5b906000526020600020906002020160000154116117565780925061175d565b6001810391505b50611715565b84828154811061176f57fe5b9060005260206000209060020201600101549250505092915050565b8154600090839060001981019081106117a057fe5b906000526020600020906004020190504281600001541015611858576040805160808101825242815260018381015460208084019182529383018681526003808701546001600160a01b03908116606087019081528a548087018c5560008c815298909820965160049098029096019687559251938601939093555160028501559151920180547fffffffffffffffffffffffff00000000000000000000000000000000000000001692909116919091179055611274565b6002015550565b600081848411156118ee5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156118b357818101518382015260200161189b565b50505050905090810190601f1680156118e05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b7fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c90565b600081836119695760405162461bcd60e51b81526020600482018181528351602484015283519092839260449091019190850190808383600083156118b357818101518382015260200161189b565b50600083858161197557fe5b0495945050505050565b604051806080016040528060008152602001600081526020016000815260200160006001600160a01b031681525090565b80356001600160a01b038116811461032b57600080fd5b6000602082840312156119d8578081fd5b610f74826119b0565b600080604083850312156119f3578081fd5b6119fc836119b0565b9150611a0a602084016119b0565b90509250929050565b60008060408385031215611a25578182fd5b611a2e836119b0565b946020939093013593505050565b600060208284031215611a4d578081fd5b81518015158114610f74578182fd5b600060208284031215611a6d578081fd5b5035919050565b600060208284031215611a85578081fd5b5051919050565b60008060408385031215611a9e578182fd5b50508035926020909101359150565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b60208082526019908201527f4261726e3a20616c726561647920696e697469616c697a656400000000000000604082015260600190565b6020808252601c908201527f424f4e442061646472657373206d757374206e6f742062652030783000000000604082015260600190565b60208082526019908201527f546f6b656e20616c6c6f77616e636520746f6f20736d616c6c00000000000000604082015260600190565b6020808252601d908201527f416d6f756e74206d7573742062652067726561746572207468616e2030000000604082015260600190565b60208082526014908201527f496e73756666696369656e742062616c616e6365000000000000000000000000604082015260600190565b60208082526016908201527f43616e27742064656c656761746520746f2073656c6600000000000000000000604082015260600190565b60208082526011908201527f54696d657374616d7020746f6f20626967000000000000000000000000000000604082015260600190565b60208082526016908201527f557365722062616c616e6365206973206c6f636b656400000000000000000000604082015260600190565b6020808252602f908201527f4e65772074696d657374616d70206c6f776572207468616e2063757272656e7460408201527f206c6f636b2074696d657374616d700000000000000000000000000000000000606082015260800190565b60208082526016908201527f4e6f2062616c616e636520746f2064656c656761746500000000000000000000604082015260600190565b60208082526015908201527f53656e64657220686173206e6f2062616c616e63650000000000000000000000604082015260600190565b60208082526016908201527f4d75737420626520636f6e7472616374206f776e657200000000000000000000604082015260600190565b6020808252601f908201527f54696d657374616d70206d75737420626520696e207468652066757475726500604082015260600190565b8151815260208083015190820152604080830151908201526060918201516001600160a01b03169181019190915260800190565b90815260200190565b91825260208201526040019056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a26469706673582212208f64fa20edab76b607b6c193355a43d3bfd9d8bfe1f7bc4ea5a07a32959088eb64736f6c63430007060033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.