Перейти к содержимому
Проверенный контрактТочноеGPL-3.0

VaultLite

Адрес0xdada4c5c5512155a40cdeba47cccbdebaccbdada
Баланс

0 ETH

 

Транзакций

4

 

Компилятор

solc 0.8.39

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.39+commit.ce47f2c8
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
paris
Лицензия
GPL-3.0
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 501 265
Транзакция создания
0x6ae4d33719…534410ce10

non-custodial-personal-trust/src/solidity_v3/VaultLite.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {SecureVaultBase} from "./SecureVaultBase.sol";
import {resolveFeeRecipient} from "./interfaces/IVaultFactory.sol";

//********
//      Project silentvault.app
//                            ********//

/// @title VaultLite (v3)
/// @notice 0.3%/year management fee realised only on withdraw / claim execution,
///         10% cut on every sweep.
/// @dev    The metadata price is read from the registry by the base on every write,
///         so registering this template with metaFeeUsd > 0 makes it behave exactly
///         like Pro; registering 0 quotes 0, and any value is just a tip.
contract VaultLite is SecureVaultBase {
    bytes32 public constant TEMPLATE_ID = keccak256("VaultLite/3");
    uint256 public constant MGMT_FEE_DIVISOR = 333; // 0.3% per YEAR
    uint256 public constant SWEEP_FEE_BPS = 1000; // 10%

    constructor(
        InitParams memory p,
        address feeRecipient_,
        address factory_
    )
        SecureVaultBase(
            p,
            resolveFeeRecipient(feeRecipient_, factory_),
            factory_
        )
    {}

    function templateName() external pure override returns (string memory) {
        return "VaultLite";
    }

    function templateId() public pure override returns (bytes32) {
        return TEMPLATE_ID;
    }

    /// @dev fee = balance * dt / YEAR / MGMT_FEE_DIVISOR (1/333, ~0.3003%/year).
    ///      Charged pro-rata since the last withdrawal; if the fee transfer fails,
    ///      no fee is taken (fail-open to user).
    function _collectManagementFee(
        uint256 balance
    ) internal override returns (uint256) {
        uint256 dt = block.timestamp - lastWithdrawalTime;
        uint256 fee = (balance * dt) / YEAR / MGMT_FEE_DIVISOR;
        if (fee == 0 || fee >= balance) return balance;

        if (_trySend(vaultToken, feeRecipient, fee)) {
            emit FeeCollected(vaultToken, fee);
            return balance - fee;
        }
        emit FeeSkipped(vaultToken, fee);
        return balance;
    }

    function _applySweepFee(
        address token,
        uint256 bal
    ) internal override returns (uint256 toRecipient) {
        uint256 fee = (bal * SWEEP_FEE_BPS) / 10_000;
        if (fee == 0) return bal;
        if (_trySend(token, feeRecipient, fee)) {
            emit FeeCollected(token, fee);
            return bal - fee;
        }
        emit FeeSkipped(token, fee);
        return bal;
    }
}

@openzeppelin/[email protected]/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

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

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

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

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

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

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

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/[email protected]/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@openzeppelin/[email protected]/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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);
}

@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/[email protected]/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/[email protected]/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

non-custodial-personal-trust/src/solidity_v3/SecureVaultBase.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {
    ReentrancyGuard
} from "@openzeppelin/[email protected]/utils/ReentrancyGuard.sol";
import {Ownable2Step} from "@openzeppelin/[email protected]/access/Ownable2Step.sol";
import {Ownable} from "@openzeppelin/[email protected]/access/Ownable.sol";
import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import {
    IERC20Metadata
} from "@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol";
import {IVaultFactory} from "./interfaces/IVaultFactory.sol";

/// @title SecureVaultBase (v3)
/// @notice Shared non-upgradeable trust vault.
///         - Revocable mode: settlor (owner) + whitelist can withdraw under a rate
///           limit per cooldown; the owner alone may cancel a running claim.
///         - Irrevocable mode: nobody can withdraw; corpus only leaves via the
///           beneficiary claim flow; claim can never be cancelled.
///         - Ownerless mode: irrevocable, and ownership is renounced inside the
///           constructor, so not a single parameter is mutable after deploy. The
///           deployer keeps exactly one ability — writing the write-once will —
///           and nothing else.
///         - Beneficiaries are hashed (keccak256(recipient, salt)), immutable,
///           OR / winner-takes-all.
///         - After the first successful claim the vault is Settled forever:
///           withdraw / rate / countdown are locked; stray deposits of the core
///           asset can be re-claimed instantly by any beneficiary; sweep still works.
///
/// @dev UI vocabulary: "Emergency" functions are presented as "Claim" in the
///      frontend (triggerEmergency = start claim countdown, cancelEmergency =
///      cancel claim, executeEmergency = execute claim). On-chain names are kept
///      stable on purpose.
abstract contract SecureVaultBase is ReentrancyGuard, Ownable2Step {
    // --- constants ---
    uint16 public constant VERSION = 3;
    uint256 public constant RATE_DENOMINATOR = 10_000_000;
    uint256 public constant MAX_WITHDRAWAL_RATE_CAP = 5_000_000; // 50%
    uint256 public constant MIN_RATE = 1;
    uint256 public constant MIN_WITHDRAWAL_INTERVAL = 23 hours;
    uint256 public constant MAX_WITHDRAWAL_INTERVAL = 365 days;
    uint256 public constant MIN_EMERGENCY_COUNTDOWN = 16 hours;
    /// @dev Ownerless vaults have no owner, so the countdown can never be raised
    ///      after deploy — the chosen value is final. 16h is too short to notice a
    ///      stray trigger while the will is still unwritten.
    uint256 public constant MIN_OWNERLESS_COUNTDOWN = 7 days;
    uint256 public constant MAX_EMERGENCY_COUNTDOWN = 180 days;
    uint256 public constant YEAR = 31_557_600; // 365.25 * 24 * 3600
    uint8 public constant MAX_WHITELIST = 10;
    uint8 public constant MAX_SWEEP_TOKENS = 20;
    uint256 public constant MAX_METADATA_BYTES = 24_576;
    uint8 public constant RATE_POLICY_DECREASE_ONLY = 0;
    uint8 public constant RATE_POLICY_FLEXIBLE = 1;
    uint8 public constant TRUST_REVOCABLE = 0;
    uint8 public constant TRUST_IRREVOCABLE = 1;
    uint8 public constant TRUST_OWNERLESS = 2; // irrevocable + renounced in constructor

    enum VaultState {
        Active, // normal operation
        Claiming, // claim countdown running (or elapsed, not yet executed)
        Settled // first claim executed; permanent
    }

    struct InitParams {
        address owner;
        address token; // address(0) = ETH
        bytes32[] recipientHashes;
        uint256 maxWithdrawalRate; // 0 required in irrevocable mode
        uint256 initialWithdrawalRate; // 0 required in irrevocable mode
        uint256 initialEmergencyCountdown;
        address[] extraWhitelist; // must be empty in irrevocable mode
        uint8 ratePolicy; // 0 = decrease-only, 1 = flexible within max
        bool publicEmergencyEnabled;
        uint256 publicEmergencyFee; // paid into the vault, not the team
        bool cancelEmergencyAllowed; // must be false in irrevocable mode
        uint8 trustMode; // 0 = revocable, 1 = irrevocable, 2 = ownerless
        uint256 withdrawalInterval; // cooldown, 23h .. 365d
    }

    // --- immutables ---
    address public immutable vaultToken;
    /// @dev Ownerless mode only: the sole address that may still write the will
    ///      (and nothing else). Elsewhere it equals the initial owner and is never
    ///      consulted.
    address public immutable deployer;
    address public immutable feeRecipient;
    /// @dev Where the metadata *price* comes from. The address is locked at deploy
    ///      and the constructor proves it has code and knows this template id; the
    ///      price itself is fetched from the registry on every read. The factory
    ///      owner (team) therefore keeps pricing authority over existing vaults.
    address public immutable factory;
    uint8 public immutable ratePolicy;
    bool public immutable publicEmergencyEnabled;
    uint256 public immutable publicEmergencyFee;
    bool public immutable cancelEmergencyAllowed;
    uint8 public immutable trustMode;
    uint256 public immutable withdrawalInterval;

    // --- state ---
    uint256 public withdrawalRate;
    uint256 public maxWithdrawalRate;
    uint256 public emergencyCountdown;
    uint256 public lastWithdrawalTime;
    /// @dev Set once and never cleared. After the first claim settles, `notInEmergency`
    ///      therefore stays true forever — that is what permanently closes withdraw,
    ///      rate, countdown and whitelist administration. A cancel DOES clear it.
    uint256 public emergencyTriggerTime;
    uint64 public settledAt; // 0 until the first successful claim execution
    uint8 public whitelistCount;
    address[] private _wlList; // enumerable mirror, <= MAX_WHITELIST
    bytes public protocolMetadata;

    mapping(address => bool) public isWhitelisted;
    mapping(bytes32 => bool) public isLegalRecipientHash;

    // --- events ---
    event Withdrawn(address indexed user, uint256 amount);
    event RateUpdated(uint256 newRate);
    event MaxRateDecreased(uint256 newMaxRate);
    event EmergencyCountdownStarted(uint256 countdown, address indexed caller);
    event EmergencyCancelled(address indexed caller);
    event EmergencyCountdownUpdated(uint256 newCountdown);
    event EmergencyExecuted(address indexed recipient, uint256 amount);
    event Settled(address indexed recipient, uint256 amount);
    event WhitelistUpdated(address indexed user, bool isAdded);
    event InitialDeposit(address indexed sender, uint256 amount);
    event TokenSwept(
        address indexed token,
        address indexed recipient,
        uint256 amount
    );
    error SweepAllFailed(uint256 attempted, string everyFailReason);
    event SweepItemResult(address indexed token, bool success, string reason);
    event SweepSummary(uint256 attempted, uint256 succeeded);
    event MetadataStored(bytes32 contentHash);
    event FeeCollected(address indexed token, uint256 amount);
    event FeeSkipped(address indexed token, uint256 amount);

    modifier onlyWhitelisted() {
        require(isWhitelisted[msg.sender], "Security: not whitelisted");
        _;
    }

    /// @dev Also permanently true once Settled, because `emergencyTriggerTime` is
    ///      never reset at that point. Administration closing with settlement is
    ///      intended, not an oversight — see the variable's note.
    modifier notInEmergency() {
        require(emergencyTriggerTime == 0, "Security: claim in progress");
        _;
    }

    modifier notIrrevocable() {
        require(trustMode == TRUST_REVOCABLE, "Security: irrevocable");
        _;
    }

    /// @dev Settled is permanent. Administration (metadata, whitelist edits)
    ///      closes with it, exactly as the UI states.
    modifier notSettled() {
        require(settledAt == 0, "Security: settled");
        _;
    }

    /// @dev Ownerless vaults end up with `owner() == address(0)`, so a plain
    ///      `onlyOwner` would put the write-once will permanently out of reach.
    ///      The deployer keeps that single ability. It is deliberately NOT added
    ///      to `isPrivileged`: the deployer cannot withdraw or trigger for free.
    /// @dev Reverts with `OwnableUnauthorizedAccount` so the existing frontend
    ///      hint keeps matching.
    /// @dev The `o == address(0)` term is implied by TRUST_OWNERLESS (the
    ///      constructor renounces) but is kept as a tripwire: if that ever stops,
    ///      the deployer and a live owner would both be able to write.
    modifier onlyOwnerOrDeployer() {
        address o = owner();
        if (
            msg.sender != o &&
            !(trustMode == TRUST_OWNERLESS &&
                msg.sender == deployer &&
                o == address(0))
        ) revert OwnableUnauthorizedAccount(msg.sender);
        _;
    }

    constructor(
        InitParams memory p,
        address feeRecipient_,
        address factory_
    ) Ownable(p.owner) {
        require(p.owner != address(0), "Init: owner");
        require(feeRecipient_ != address(0), "Init: feeRecipient");
        require(factory_ != address(0), "Init: factory");

        // A vault is only meaningful with a registry behind it. Prove at deploy time
        // that the address has code AND that it knows this template id, so a
        // self-deployer cannot point at a bare EOA or an unrelated contract. A
        // genuine 0 quote is still a free template; only an unanswerable registry
        // is rejected here.
        require(factory_.code.length > 0, "Init: factory code");
        try IVaultFactory(factory_).quoteMetaWei(templateId()) returns (
            uint256,
            uint256,
            bool
        ) {} catch {
            revert("Init: factory template");
        }
        require(
            p.ratePolicy == RATE_POLICY_DECREASE_ONLY ||
                p.ratePolicy == RATE_POLICY_FLEXIBLE,
            "Init: ratePolicy"
        );
        require(
            p.trustMode == TRUST_REVOCABLE ||
                p.trustMode == TRUST_IRREVOCABLE ||
                p.trustMode == TRUST_OWNERLESS,
            "Init: trustMode"
        );
        require(p.recipientHashes.length > 0, "Init: recipient hashes");
        require(
            p.withdrawalInterval >= MIN_WITHDRAWAL_INTERVAL &&
                p.withdrawalInterval <= MAX_WITHDRAWAL_INTERVAL,
            "Init: interval"
        );
        require(
            p.initialEmergencyCountdown >= MIN_EMERGENCY_COUNTDOWN &&
                p.initialEmergencyCountdown <= MAX_EMERGENCY_COUNTDOWN,
            "Init: countdown"
        );
        if (p.trustMode == TRUST_OWNERLESS) {
            require(
                p.initialEmergencyCountdown >= MIN_OWNERLESS_COUNTDOWN,
                "Init: ownerless countdown"
            );
        }

        if (p.trustMode != TRUST_REVOCABLE) {
            require(!p.cancelEmergencyAllowed, "Init: irrevocable cancel");
            require(
                p.extraWhitelist.length == 0,
                "Init: irrevocable whitelist"
            );
            require(
                p.maxWithdrawalRate == 0 && p.initialWithdrawalRate == 0,
                "Init: irrevocable rate"
            );
        } else {
            require(
                p.maxWithdrawalRate >= MIN_RATE &&
                    p.maxWithdrawalRate <= MAX_WITHDRAWAL_RATE_CAP,
                "Init: max rate"
            );
            require(
                p.initialWithdrawalRate >= MIN_RATE &&
                    p.initialWithdrawalRate <= p.maxWithdrawalRate,
                "Init: initial rate"
            );
        }

        vaultToken = p.token;
        feeRecipient = feeRecipient_;
        factory = factory_;
        deployer = p.owner;
        ratePolicy = p.ratePolicy;
        publicEmergencyEnabled = p.publicEmergencyEnabled;
        publicEmergencyFee = p.publicEmergencyFee;
        cancelEmergencyAllowed = p.cancelEmergencyAllowed;
        trustMode = p.trustMode;
        withdrawalInterval = p.withdrawalInterval;

        maxWithdrawalRate = p.maxWithdrawalRate;
        withdrawalRate = p.initialWithdrawalRate;
        emergencyCountdown = p.initialEmergencyCountdown;
        lastWithdrawalTime = block.timestamp - p.withdrawalInterval;

        for (uint256 i = 0; i < p.recipientHashes.length; i++) {
            isLegalRecipientHash[p.recipientHashes[i]] = true;
        }

        if (p.trustMode == TRUST_REVOCABLE) {
            _addToWhitelist(p.owner);
            for (uint256 i = 0; i < p.extraWhitelist.length; i++) {
                _addToWhitelist(p.extraWhitelist[i]);
            }
            require(whitelistCount <= MAX_WHITELIST, "Init: whitelist cap");
        }
        // Irrevocable: whitelist stays empty forever; withdraw() is unreachable.

        if (p.trustMode == TRUST_OWNERLESS) {
            // Renounce here. `msg.sender` is the factory, so `onlyOwner` on
            // renounceOwnership() would not match the settlor — call the internal
            // transfer instead and inline the reachability check the public
            // override would have run. `_transferOwnership` already clears
            // `_pendingOwner` in Ownable2Step, so this is renounce minus the
            // modifier. Without public start nobody could ever claim, so refuse
            // to deploy such a vault at all.
            require(
                publicEmergencyEnabled,
                "Renounce: vault would be unreachable"
            );
            _transferOwnership(address(0));
        }
    }

    // --- template identity (pure, so it is part of the bytecode hash) ---

    /// @dev Tier label only ("VaultPro" / "VaultLite"). The trust type is a
    ///      separate axis carried by `trustMode`, and deliberately not by the
    ///      name or the id — one registry entry per tier.
    function templateName() external pure virtual returns (string memory);

    /// @dev Registry key: the fee tier only. `trustMode` is an InitParams arg and
    ///      deliberately not part of the id, so each tier keeps exactly one
    ///      registry entry. The constructor validates the mode and the
    ///      mode-specific rules; the frontend additionally asserts
    ///      `owner() == address(0)` after an ownerless deploy.
    /// @dev Declared (public) rather than (external) so the base contract itself
    ///      can use it as the registry key for metadata pricing. It is also called
    ///      from the base constructor, so an implementation must return a
    ///      compile-time constant — reading state or an immutable assigned later
    ///      would resolve to zero there. It is also called
    ///      from the base constructor, so an implementation must return a
    ///      compile-time constant — reading state or an immutable assigned later
    ///      would resolve to zero there.
    function templateId() public pure virtual returns (bytes32);

    // --- views ---

    function vaultState() public view returns (VaultState) {
        if (settledAt != 0) return VaultState.Settled;
        if (emergencyTriggerTime != 0) return VaultState.Claiming;
        return VaultState.Active;
    }

    /// @dev True for both irrevocable flavours — ownerless is irrevocable too, so
    ///      the frontend keeps hiding the withdraw and rate surfaces.
    function isIrrevocable() public view returns (bool) {
        return trustMode != TRUST_REVOCABLE;
    }

    function vaultTokenBalance_raw() public view returns (uint256) {
        return _vaultBalance();
    }

    function vaultTokenBalance()
        public
        view
        returns (uint256 rawBalance, uint256 readableAmount_fixed0)
    {
        rawBalance = _vaultBalance();
        uint8 decimals = 18;
        if (vaultToken != address(0)) {
            try IERC20Metadata(vaultToken).decimals() returns (uint8 d) {
                if (d <= 77) decimals = d; // 10**78 overflows; fall back to 18 on a bad value
            } catch {}
        }
        readableAmount_fixed0 = rawBalance / (10 ** uint256(decimals));
    }

    function isPrivileged(address account) public view returns (bool) {
        return account == owner() || isWhitelisted[account];
    }

    /// @notice Enumerable whitelist. Index 0..whitelistCount-1 are members.
    function whitelist(uint256 index) external view returns (address) {
        return _wlList[index];
    }

    function emergencyDeadline() public view returns (uint256) {
        if (emergencyTriggerTime == 0) return 0;
        return emergencyTriggerTime + emergencyCountdown;
    }

    // --- withdraw (revocable only; unreachable in irrevocable and ownerless) ---

    function withdraw() external onlyWhitelisted notInEmergency nonReentrant {
        require(
            block.timestamp >= lastWithdrawalTime + withdrawalInterval,
            "Security: cooldown"
        );

        uint256 balance = _vaultBalance();
        require(balance > 0, "Vault: empty");

        balance = _collectManagementFee(balance);

        uint256 amount = (balance * withdrawalRate) / RATE_DENOMINATOR;
        require(amount > 0, "Vault: amount zero");

        lastWithdrawalTime = block.timestamp;
        _sendVaultToken(msg.sender, amount);
        emit Withdrawn(msg.sender, amount);
    }

    /// @dev VaultLite overrides to take 0.3% * dt; default is no fee.
    function _collectManagementFee(
        uint256 balance
    ) internal virtual returns (uint256) {
        return balance;
    }

    // --- claim flow (on-chain name: emergency) ---

    function triggerEmergency() external payable notInEmergency {
        bool privileged = isPrivileged(msg.sender);
        if (!privileged) {
            require(publicEmergencyEnabled, "Claim: public disabled");
            require(msg.value >= publicEmergencyFee, "Claim: start deposit");
        }

        emergencyTriggerTime = block.timestamp;
        emit EmergencyCountdownStarted(emergencyCountdown, msg.sender);
        if (msg.value > 0) {
            emit InitialDeposit(msg.sender, msg.value);
        }
    }

    /// @notice Owner only. A claim is the owner's own brake; the whitelist may
    ///         start one for free, but not stop one.
    /// @dev    Kept as an explicit require rather than `onlyOwner` so the
    ///         "cancel disabled" message still wins. The string is deliberately
    ///         owner-specific (not "not privileged"): the whitelist IS privileged
    ///         elsewhere, so the generic wording would mislead here.
    function cancelEmergency() external {
        require(cancelEmergencyAllowed, "Claim: cancel disabled");
        require(msg.sender == owner(), "Claim: only the owner may cancel");
        require(emergencyTriggerTime != 0, "Claim: not started");
        require(
            block.timestamp < emergencyTriggerTime + emergencyCountdown,
            "Claim: too late to cancel"
        );
        emergencyTriggerTime = 0;
        emit EmergencyCancelled(msg.sender);
    }

    /// @notice Pays the entire core balance to a proven beneficiary.
    /// @dev First successful execution marks the vault Settled permanently.
    ///      Later calls (stray deposits) still work and are instant because
    ///      the countdown has already elapsed.
    function executeEmergency(
        address recipient,
        bytes32 salt
    ) external nonReentrant {
        require(emergencyTriggerTime != 0, "Claim: not started");
        require(
            block.timestamp >= emergencyTriggerTime + emergencyCountdown,
            "Claim: countdown"
        );
        _assertValidProof(recipient, salt);

        uint256 balance = _vaultBalance();
        require(balance > 0, "Claim: no funds");

        balance = _collectManagementFee(balance);
        lastWithdrawalTime = block.timestamp;

        // Settle before the external call (CEI): a reentrant hook on the recipient
        // already sees Settled, which also shuts out the entry points that carry no
        // notSettled. A failed send reverts the whole call, so settledAt never
        // lands half-applied.
        bool first = settledAt == 0;
        if (first) settledAt = uint64(block.timestamp);

        _sendVaultToken(recipient, balance);
        emit EmergencyExecuted(recipient, balance);
        if (first) emit Settled(recipient, balance);
    }

    function sweepTokenToRecipient(
        address[] calldata tokens,
        address recipient,
        bytes32 salt
    ) external nonReentrant {
        require(
            tokens.length > 0 && tokens.length <= MAX_SWEEP_TOKENS,
            "Sweep: length"
        );
        _assertValidProof(recipient, salt);

        uint256 succeeded;
        string memory failLog;

        for (uint256 i = 0; i < tokens.length; i++) {
            bool ok = true;
            string memory s;

            try this.sweepOne(tokens[i], recipient) returns (bool r) {
                ok = r;
            } catch (bytes memory reason) {
                ok = false;
                try this._decodeRevertExt(reason) returns (
                    string memory decoded
                ) {
                    s = decoded;
                } catch {
                    s = "failed";
                }
            }
            if (ok) {
                succeeded++;
                emit SweepItemResult(tokens[i], true, "");
            } else {
                // sweepOne returned false without a reason: fill one in rather than
                // dropping the row silently
                if (bytes(s).length == 0) s = "failed";
                emit SweepItemResult(tokens[i], false, s);
                failLog = string(abi.encodePacked(failLog, s, "||"));
            }
        }

        emit SweepSummary(tokens.length, succeeded);
        if (succeeded == 0) {
            revert SweepAllFailed(tokens.length, failLog);
        }
    }

    /// @notice Isolated per-token sweep. Only callable by this contract.
    /// @dev `token == address(0)` sweeps stray native ETH even when the core asset is an
    ///      ERC-20: `_tokenBalance` reads `address(this).balance` for it, and VaultLite
    ///      takes its 10% on that ETH as well. When the core asset IS ETH the guard
    ///      below rejects address(0), so the corpus itself can never be swept.
    function sweepOne(
        address token,
        address recipient
    ) external returns (bool) {
        require(msg.sender == address(this), "Security: internal only");
        require(
            token != vaultToken,
            "Security: use executeEmergency for main asset"
        );

        uint256 bal = _tokenBalance(token);
        require(bal > 0, "Sweep: empty");

        uint256 toRecipient = _applySweepFee(token, bal);
        require(
            _trySend(token, recipient, toRecipient),
            "Sweep: recipient transfer"
        );
        emit TokenSwept(token, recipient, toRecipient);
        return true;
    }

    /// @dev VaultLite takes 10% when the fee transfer succeeds; otherwise 100% to recipient.
    function _applySweepFee(
        address token,
        uint256 bal
    ) internal virtual returns (uint256 toRecipient) {
        token; // unused in the base
        return bal;
    }

    // --- metadata (write-once) ---

    /// @notice Registry quote for this template's metadata fee, full price only.
    /// @dev Only the quote's first return is used; minWei and oracleOk are dropped.
    ///      Read on every call, so an existing vault keeps following the registry
    ///      and an owner price change applies immediately.
    /// @dev Strict, no fail-open: if the registry cannot answer this reverts, so a
    ///      write cannot silently become free. A genuine 0 quote (free template)
    ///      still passes. The constructor already proved the factory has code and
    ///      knows this id, so this only trips on a registry that broke later.
    function quoteMetaWei() public view returns (uint256 fullWei) {
        (fullWei, , ) = IVaultFactory(factory).quoteMetaWei(templateId());
    }

    /// @notice Raw metadata fee for this template, in USD (8 dec). 0 = free.
    /// @dev Display only, and exact where a rate-based conversion would round.
    /// @dev Strict like quoteMetaWei(): the constructor guarantees the factory
    ///      answers, so this needs no catch.
    function META_FEE_USD() external view returns (uint64) {
        return IVaultFactory(factory).metaFeeUsdFor(templateId());
    }

    /// @notice Write the one-shot encrypted metadata. msg.value must be at least
    ///         the quoted full price; anything above it also goes to feeRecipient
    ///         as a voluntary contribution.
    /// @dev A free template quotes 0, so any value passes and the call behaves
    ///      like a plain tip. An unanswerable registry reverts the whole write.
    /// @dev A failed transfer is fail-open: the ETH stays in the vault and ends up
    ///      with the beneficiary. It never blocks the write.
    function initializeSecurityProtocol(
        bytes calldata data
    ) external payable virtual onlyOwnerOrDeployer nonReentrant {
        // Strict quote: a broken registry reverts here with the factory's own reason
        // ("Factory: template") before this line can fire. Rare enough to leave
        // unwrapped rather than hide the real cause.
        require(msg.value >= quoteMetaWei(), "Metadata: fee");
        _storeMetadata(data);

        if (msg.value > 0 && !_trySend(address(0), feeRecipient, msg.value)) {
            emit FeeSkipped(address(0), msg.value);
        }
    }

    function _storeMetadata(bytes calldata data) internal notSettled {
        require(protocolMetadata.length == 0, "Metadata: already stored");
        require(
            data.length > 0 && data.length <= MAX_METADATA_BYTES,
            "Metadata: size"
        );
        protocolMetadata = data;
        emit MetadataStored(keccak256(data));
    }

    // --- admin ---

    function decreaseMaxWithdrawalRate(
        uint256 newMaxRate
    ) external onlyOwner notIrrevocable notInEmergency {
        require(newMaxRate >= MIN_RATE, "Rate: min");
        require(newMaxRate < maxWithdrawalRate, "Rate: only decrease max");
        if (withdrawalRate > newMaxRate) {
            withdrawalRate = newMaxRate;
            emit RateUpdated(withdrawalRate);
        }
        maxWithdrawalRate = newMaxRate;
        emit MaxRateDecreased(newMaxRate);
    }

    function updateWithdrawalRate(
        uint256 newRate
    ) external onlyOwner notIrrevocable notInEmergency {
        require(newRate >= MIN_RATE, "Rate: min");
        require(newRate <= maxWithdrawalRate, "Rate: exceeds max");
        if (ratePolicy == RATE_POLICY_DECREASE_ONLY) {
            require(newRate <= withdrawalRate, "Rate: only decrease");
        }
        withdrawalRate = newRate;
        emit RateUpdated(newRate);
    }

    function increaseEmergencyCountdown(
        uint256 newCountdown
    ) external onlyOwner notInEmergency {
        require(newCountdown > emergencyCountdown, "Claim: only increase");
        require(newCountdown <= MAX_EMERGENCY_COUNTDOWN, "Claim: cap");
        emergencyCountdown = newCountdown;
        emit EmergencyCountdownUpdated(newCountdown);
    }

    function addToWhitelist(
        address user
    ) external onlyOwner notIrrevocable notSettled notInEmergency {
        _addToWhitelist(user);
        require(whitelistCount <= MAX_WHITELIST, "Whitelist: cap");
    }

    function removeFromWhitelist(
        address user
    ) external onlyOwner notSettled notInEmergency {
        _removeFromWhitelist(user);
    }

    /// @notice A whitelisted member can only remove themselves.
    /// @dev Parameterless by design: peer removal (and the old owner-protection
    ///      check) is impossible by construction. The owner keeps
    ///      removeFromWhitelist(user) for arbitrary removal — including the
    ///      owner's own address. Emergency brake is preserved: a member can step
    ///      off whenever someone else could still start a claim.
    /// @dev    Unlike the two admin paths this one deliberately has no
    ///         `notInEmergency`: stepping off must stay possible during a countdown,
    ///         that is exactly what makes it the brake.
    /// @dev    Someone who can still start a claim must be left behind: public
    ///         start, another member, or a still-existing owner. The old third
    ///         term was always true once renounced (owner() == 0), so the last
    ///         member leaving turned a renounced vault with private start into a
    ///         permanently dead one — beneficiaries hold their salt and cannot
    ///         even start. The only cost: after a renounce the last member must
    ///         stay.
    function removeFromWhitelistSelf() external onlyWhitelisted {
        require(
            publicEmergencyEnabled ||
                whitelistCount > 1 ||
                owner() != address(0),
            "Whitelist: last member"
        );
        _removeFromWhitelist(msg.sender);
    }

    /// @dev A running countdown is precisely the moment the owner holds the cancel
    ///      right, so a fresh proposal is blocked here: the pending owner should
    ///      always inherit a vault that is not mid-countdown. Accepting an
    ///      already-proposed transfer stays open — that handover was agreed
    ///      before the countdown and completing it mid-countdown is harmless.
    function transferOwnership(
        address newOwner
    ) public override onlyOwner notInEmergency {
        super.transferOwnership(newOwner);
    }

    /// @notice Renouncing is permanent. Refuse it while nobody else could still
    ///         start a claim, otherwise the corpus becomes unreachable forever.
    /// @dev The owner can always start a claim today; after renouncing that is
    ///      gone. A claim must therefore stay startable by someone else: either
    ///      public start is enabled, or a whitelisted withdrawer exists
    ///      (irrevocable mode has no whitelist by construction, so there it
    ///      reduces to requiring publicEmergencyEnabled).
    function renounceOwnership() public override onlyOwner {
        // Only these two terms mean anything: onlyOwner guarantees a nonzero
        // owner(), so `owner() != 0` is always true here, and `count > 1` is
        // already covered by `> 0`. Adding either short-circuits the check.
        require(
            publicEmergencyEnabled || whitelistCount > 0,
            "Renounce: vault would be unreachable"
        );
        super.renounceOwnership();
    }

    // --- internals ---
    function _assertValidProof(address recipient, bytes32 salt) internal view {
        require(recipient != address(0), "Security: zero recipient");
        bytes32 proof = keccak256(abi.encode(recipient, salt));
        require(isLegalRecipientHash[proof], "Security: invalid proof");
    }

    function _addToWhitelist(address user) internal {
        require(user != address(0), "Whitelist: zero");
        if (!isWhitelisted[user]) {
            isWhitelisted[user] = true;
            _wlList.push(user);
            whitelistCount += 1;
            emit WhitelistUpdated(user, true);
        }
    }

    function _removeFromWhitelist(address user) internal {
        if (!isWhitelisted[user]) return;
        uint256 len = _wlList.length;
        for (uint256 i = 0; i < len; i++) {
            if (_wlList[i] == user) {
                _wlList[i] = _wlList[len - 1];
                _wlList.pop();
                break;
            }
        }
        isWhitelisted[user] = false;
        whitelistCount -= 1;
        emit WhitelistUpdated(user, false);
    }

    function _vaultBalance() internal view returns (uint256) {
        return _tokenBalance(vaultToken);
    }

    function _tokenBalance(address token) internal view returns (uint256) {
        if (token == address(0)) return address(this).balance;
        return IERC20(token).balanceOf(address(this));
    }

    function _sendVaultToken(address to, uint256 amount) internal {
        require(_trySend(vaultToken, to, amount), "Vault: transfer failed");
    }

    function _trySend(
        address token,
        address to,
        uint256 amount
    ) internal returns (bool success) {
        if (amount == 0) return true;
        if (token == address(0)) {
            (success, ) = payable(to).call{value: amount}("");
            return success;
        }
        bytes memory data;
        (success, data) = token.call(
            abi.encodeWithSelector(IERC20.transfer.selector, to, amount)
        );
        if (!success) return false;
        // No return data, or short data: go by success (same trade-off as
        // SafeERC20). With data, read the first word directly and never touch
        // abi.decode — decode validates bools as 0/1 and still reverts on a token
        // that returns 2, and the withdraw path has no outer try.
        if (data.length < 32) return true;
        uint256 word;
        assembly {
            word := mload(add(data, 0x20))
        }
        return word != 0;
    }

    /// @dev Last line of defence: a hostile token can return a fake Error(string)
    ///      that makes the decode here fail; the caller's try/catch catches it and
    ///      reports "failed".
    function _decodeRevertExt(
        bytes memory reason
    ) external view returns (string memory) {
        require(msg.sender == address(this), "Security: internal only");
        return _decodeRevert(reason);
    }

    /// @dev Pull the Error(string) payload out. `reason` points at the length slot
    ///      and the body starts at +32; handing it to abi.decode needs both the
    ///      pointer fixed (-> +0x24) and the length fixed, since moving only the
    ///      pointer makes the length read as the offset and runs out of bounds.
    ///      Copying once avoids fighting the layout; reason strings are short, so
    ///      the cost is negligible.
    function _decodeRevert(
        bytes memory reason
    ) internal pure returns (string memory) {
        if (reason.length < 68) return "failed";
        bytes4 sel;
        assembly {
            sel := mload(add(reason, 0x20))
        }
        if (sel != 0x08c379a0) return "failed"; // not an Error(string)

        bytes memory payload = new bytes(reason.length - 4);
        for (uint256 i = 0; i < payload.length; i++) {
            payload[i] = reason[i + 4];
        }
        return abi.decode(payload, (string));
    }

    receive() external payable {
        emit InitialDeposit(msg.sender, msg.value);
    }
}

non-custodial-personal-trust/src/solidity_v3/interfaces/IVaultFactory.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/// @notice Factory v3 surface used by vault templates. Deploy-time and
///         metadata-time only. Never on withdraw / claim / sweep.
/// @dev    Metadata pricing is read live on every write (SecureVaultBase), so the
///         registry keeps full control over what an existing vault charges.

interface IVaultFactory {
    function feeRecipient() external view returns (address);

    function quoteDeployWei(
        bytes32 templateId
    ) external view returns (uint256 fullWei, uint256 minWei, bool oracleOk);

    function quoteDeployMinWei(
        bytes32 templateId
    ) external view returns (uint256);

    function quoteMetaWei(
        bytes32 templateId
    ) external view returns (uint256 fullWei, uint256 minWei, bool oracleOk);

    /// @dev Returns 0 when the template's metadata is free.
    function quoteMetaMinWei(
        bytes32 templateId
    ) external view returns (uint256);

    /// @dev Quote an arbitrary USD amount (8 dec) into wei, with the same oracle,
    ///      clamps and haircut as deploy quotes. Not used by the vaults themselves
    ///      (they call quoteMetaWei); kept for the frontend's $/ETH rate and gas
    ///      estimates.
    function quoteUsdWei(
        uint64 usd8
    ) external view returns (uint256 fullWei, uint256 minWei);

    /// @dev Raw metadata fee for a template, in USD (8 dec). 0 = free.
    ///      Never reverts, so a vault can read it for display.
    function metaFeeUsdFor(bytes32 templateId) external view returns (uint64);
}

/// @notice Deploy-time only. Prefer factory.feeRecipient(); fallback if factory is
///         missing, reverts, or returns zero. Each vault pins the result as immutable.
function resolveFeeRecipient(
    address fallbackFee,
    address factory_
) view returns (address) {
    if (factory_ != address(0)) {
        try IVaultFactory(factory_).feeRecipient() returns (address r) {
            if (r != address(0)) return r;
        } catch {}
    }
    return fallbackFee;
}
Настройки компилятораПоказать
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": []
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.