Skip to content
Verified contractPartialMIT

AllocationVault

Address0x481e7717fe7bf9c99f7e5d7315f8eac2725a19ff
Balance

0 ETH

 

Transactions

392

 

Compiler

solc 0.8.34

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
No
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,597,663
Creation transaction
0x4c896768ac…44f209a443

contracts/AllocationVault.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.34;

import {IERC20} from "./vendor/openzeppelin/token/ERC20/IERC20.sol";
import {Adminable} from "./utils/Adminable.sol";
import {SafeERC20} from "./utils/SafeERC20.sol";

/// @notice Admin-managed token vault with category-level allocation accounting.
/// @dev KAFT must leave this vault through transferFromCategory so category caps remain auditable.
contract AllocationVault is Adminable {
    using SafeERC20 for IERC20;

    uint16 public constant BPS_DENOMINATOR = 10_000;

    struct Category {
        bytes32 id;
        string name;
        uint16 bps;
        uint8 policy;
        uint256 cap;
        uint256 spent;
        bool exists;
    }

    struct CategoryInput {
        bytes32 id;
        string name;
        uint16 bps;
        uint8 policy;
        uint256 cap;
    }

    error AllocationVaultETHTransferFailed();
    error AllocationVaultZeroAddress();
    error AllocationVaultInvalidAmount();
    error AllocationVaultTokenAlreadySet();
    error AllocationVaultTokenNotSet();
    error AllocationVaultPlanAlreadySet();
    error AllocationVaultEmptyPlan();
    error AllocationVaultInvalidCategoryId();
    error AllocationVaultCategoryExists(bytes32 categoryId);
    error AllocationVaultCategoryNotFound(bytes32 categoryId);
    error AllocationVaultInvalidBps(bytes32 categoryId, uint16 bps);
    error AllocationVaultInvalidBpsSum(uint256 sumBps);
    error AllocationVaultInvalidCap(bytes32 categoryId, uint256 cap);
    error AllocationVaultCapSumExceedsBalance(uint256 capSum, uint256 balance);
    error AllocationVaultInsufficientCategoryRemaining(bytes32 categoryId, uint256 requested, uint256 remaining);
    error AllocationVaultCannotBypassAllocationToken();
    error AllocationVaultRecoverWouldTouchReserved(uint256 requested, uint256 availableExcess);

    event AllocationTokenSet(address indexed token);
    event AllocationCategorySet(bytes32 indexed categoryId, string name, uint16 bps, uint8 policy, uint256 cap);
    event AllocationPlanSet(uint256 categoryCount, uint256 totalBps, uint256 totalCap);
    event CategoryTransfer(
        bytes32 indexed categoryId, address indexed token, address indexed to, uint256 amount, uint256 categorySpent
    );
    event VaultTransfer(address indexed token, address indexed to, uint256 amount);
    event VaultTransferETH(address indexed to, uint256 amount);
    event ExcessAllocationTokenRecovered(address indexed to, uint256 amount);

    IERC20 public allocationToken;
    bool public planSet;
    uint256 public totalCap;
    uint256 public totalSpent;

    bytes32[] private _categoryIds;
    mapping(bytes32 => Category) private _categories;

    constructor(address admin_) Adminable(admin_) {}

    receive() external payable {}

    function setAllocationToken(IERC20 token_) external onlyAdmin {
        if (address(token_) == address(0)) revert AllocationVaultZeroAddress();
        if (address(allocationToken) != address(0)) revert AllocationVaultTokenAlreadySet();
        allocationToken = token_;
        emit AllocationTokenSet(address(token_));
    }

    function setPlan(CategoryInput[] calldata inputs) external onlyAdmin {
        IERC20 token = allocationToken;
        if (address(token) == address(0)) revert AllocationVaultTokenNotSet();
        if (planSet) revert AllocationVaultPlanAlreadySet();

        uint256 len = inputs.length;
        if (len == 0) revert AllocationVaultEmptyPlan();

        uint256 sumBps;
        uint256 capSum;
        for (uint256 i; i < len; ++i) {
            CategoryInput calldata item = inputs[i];
            if (item.id == bytes32(0)) revert AllocationVaultInvalidCategoryId();
            if (_categories[item.id].exists) revert AllocationVaultCategoryExists(item.id);
            if (item.bps == 0) revert AllocationVaultInvalidBps(item.id, item.bps);
            if (item.cap == 0) revert AllocationVaultInvalidCap(item.id, item.cap);

            _categories[item.id] = Category({
                id: item.id,
                name: item.name,
                bps: item.bps,
                policy: item.policy,
                cap: item.cap,
                spent: 0,
                exists: true
            });
            _categoryIds.push(item.id);
            sumBps += item.bps;
            capSum += item.cap;

            emit AllocationCategorySet(item.id, item.name, item.bps, item.policy, item.cap);
        }

        if (sumBps != BPS_DENOMINATOR) revert AllocationVaultInvalidBpsSum(sumBps);

        uint256 balance = token.balanceOf(address(this));
        if (capSum > balance) revert AllocationVaultCapSumExceedsBalance(capSum, balance);

        totalCap = capSum;
        planSet = true;
        emit AllocationPlanSet(len, sumBps, capSum);
    }

    function transferFromCategory(bytes32 categoryId, address to, uint256 amount) external onlyAdmin {
        if (to == address(0)) revert AllocationVaultZeroAddress();
        if (amount == 0) revert AllocationVaultInvalidAmount();

        IERC20 token = allocationToken;
        if (address(token) == address(0)) revert AllocationVaultTokenNotSet();

        Category storage category = _categories[categoryId];
        if (!category.exists) revert AllocationVaultCategoryNotFound(categoryId);

        uint256 remaining = category.cap - category.spent;
        if (amount > remaining) revert AllocationVaultInsufficientCategoryRemaining(categoryId, amount, remaining);

        category.spent += amount;
        totalSpent += amount;
        token.safeTransfer(to, amount);

        emit CategoryTransfer(categoryId, address(token), to, amount, category.spent);
    }

    function transferERC20(address token, address to, uint256 amount) external onlyAdmin {
        if (token == address(0) || to == address(0)) revert AllocationVaultZeroAddress();
        if (address(allocationToken) == address(0)) revert AllocationVaultTokenNotSet();
        if (token == address(allocationToken)) revert AllocationVaultCannotBypassAllocationToken();
        IERC20(token).safeTransfer(to, amount);
        emit VaultTransfer(token, to, amount);
    }

    function transferETH(address to, uint256 amount) external onlyAdmin {
        if (to == address(0)) revert AllocationVaultZeroAddress();
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert AllocationVaultETHTransferFailed();
        emit VaultTransferETH(to, amount);
    }

    function recoverExcessAllocationToken(address to, uint256 amount) external onlyAdmin {
        if (to == address(0)) revert AllocationVaultZeroAddress();
        if (amount == 0) revert AllocationVaultInvalidAmount();
        if (address(allocationToken) == address(0)) revert AllocationVaultTokenNotSet();

        uint256 available = availableExcessAllocationToken();
        if (amount > available) revert AllocationVaultRecoverWouldTouchReserved(amount, available);

        allocationToken.safeTransfer(to, amount);
        emit ExcessAllocationTokenRecovered(to, amount);
    }

    function categoryExists(bytes32 categoryId) external view returns (bool) {
        return _categories[categoryId].exists;
    }

    function categoryCount() external view returns (uint256) {
        return _categoryIds.length;
    }

    function getCategoryIds() external view returns (bytes32[] memory) {
        return _categoryIds;
    }

    function getCategory(bytes32 categoryId) external view returns (Category memory) {
        Category memory category = _categories[categoryId];
        if (!category.exists) revert AllocationVaultCategoryNotFound(categoryId);
        return category;
    }

    function getCategories() external view returns (Category[] memory out) {
        uint256 len = _categoryIds.length;
        out = new Category[](len);
        for (uint256 i; i < len; ++i) {
            out[i] = _categories[_categoryIds[i]];
        }
    }

    function remainingCategory(bytes32 categoryId) public view returns (uint256) {
        Category memory category = _categories[categoryId];
        if (!category.exists) revert AllocationVaultCategoryNotFound(categoryId);
        return category.cap - category.spent;
    }

    function reservedOutstanding() public view returns (uint256) {
        return totalCap - totalSpent;
    }

    function availableExcessAllocationToken() public view returns (uint256) {
        IERC20 token = allocationToken;
        if (address(token) == address(0)) return 0;

        uint256 balance = token.balanceOf(address(this));
        uint256 reserved = reservedOutstanding();
        if (balance <= reserved) return 0;
        return balance - reserved;
    }
}

contracts/utils/Adminable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.34;

abstract contract Adminable {
    error AdminableUnauthorized(address caller);
    error AdminablePendingAdminUnauthorized(address caller);
    error AdminableZeroAddress();
    error AdminableInvalidAdmin(address candidate);
    error AdminableNoPendingAdmin();

    event AdminTransferStarted(address indexed currentAdmin, address indexed pendingAdmin);
    event AdminTransferCancelled(address indexed currentAdmin, address indexed pendingAdmin);

    event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);

    address public admin;
    address public pendingAdmin;

    constructor(address admin_) {
        if (admin_ == address(0)) revert AdminableZeroAddress();
        if (admin_ == address(this)) revert AdminableInvalidAdmin(admin_);
        admin = admin_;
        emit AdminTransferred(address(0), admin_);
    }

    modifier onlyAdmin() {
        if (msg.sender != admin) revert AdminableUnauthorized(msg.sender);
        _;
    }

    function proposeAdmin(address newAdmin) public onlyAdmin {
        if (newAdmin == address(0)) revert AdminableZeroAddress();
        if (newAdmin == address(this) || newAdmin == admin) revert AdminableInvalidAdmin(newAdmin);
        pendingAdmin = newAdmin;
        emit AdminTransferStarted(admin, newAdmin);
    }

    function cancelAdminTransfer() external onlyAdmin {
        address currentPendingAdmin = pendingAdmin;
        if (currentPendingAdmin == address(0)) revert AdminableNoPendingAdmin();
        pendingAdmin = address(0);
        emit AdminTransferCancelled(admin, currentPendingAdmin);
    }

    function acceptAdmin() external {
        if (msg.sender != pendingAdmin) revert AdminablePendingAdminUnauthorized(msg.sender);
        address old = admin;
        admin = msg.sender;
        pendingAdmin = address(0);
        emit AdminTransferred(old, msg.sender);
    }

    function transferAdmin(address newAdmin) external onlyAdmin {
        proposeAdmin(newAdmin);
    }
}

contracts/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.34;

import {IERC20} from "../vendor/openzeppelin/token/ERC20/IERC20.sol";

library SafeERC20 {
    error SafeERC20FailedOperation(address token);

    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, value)));
    }

    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory callData = abi.encodeCall(token.approve, (spender, value));
        if (!_callOptionalReturnBool(token, callData)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, callData);
        }
    }

    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        forceApprove(token, spender, newAllowance);
    }

    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        if (oldAllowance < value) revert SafeERC20FailedOperation(address(token));
        uint256 newAllowance = oldAllowance - value;
        forceApprove(token, spender, newAllowance);
    }

    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        (bool success, bytes memory returndata) = address(token).call(data);
        if (!success) revert SafeERC20FailedOperation(address(token));
        if (returndata.length > 0 && !abi.decode(returndata, (bool))) revert SafeERC20FailedOperation(address(token));
    }

    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        (bool success, bytes memory returndata) = address(token).call(data);
        if (!success) return false;
        if (returndata.length == 0) return true;
        return abi.decode(returndata, (bool));
    }
}

contracts/vendor/openzeppelin/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": false
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.