PlanetDispenser

Description:

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

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
"
    },
    "@openzeppelin/contracts/interfaces/IERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";
"
    },
    "@openzeppelin/contracts/interfaces/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";
"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC721/IERC721.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)

pragma solidity >=0.6.2;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    },
    "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
"
    },
    "@openzeppelin/contracts/utils/Pausable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

interface IAzimuth {
    function hasBeenLinked(uint32 _point) external view returns (bool result);
    function getKeys(
        uint32 _point
    )
        external
        view
        returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision);
    function points(
        uint32 _point
    )
        external
        view
        returns (
            bytes32 encryptionKey,
            bytes32 authenticationKey,
            bool hasSponsor,
            bool active,
            bool escapeRequested,
            uint32 sponsor,
            uint32 escapeRequestedTo,
            uint32 cryptoSuiteVersion,
            uint32 keyRevisionNumber,
            uint32 continuityNumber
        );
    function getPointSize(uint32 _point) external pure returns (uint8 _size);
    function getOwner(uint32 _point) external view returns (address owner);
    function owner() external view returns (address);
    function getSpawnProxy(
        uint32 _point
    ) external view returns (address spawnProxy);
    function getPrefix(uint32 _point) external pure returns (uint16 prefix);
    function getSpawnCount(uint32 _point) external view returns (uint32 spawnCount);
}
enum Size {
    Galaxy, // = 0
    Star, // = 1
    Planet // = 2
}
"
    },
    "contracts/interfaces/IEcliptic.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

interface IEcliptic is IERC721 {
    // Core Ecliptic functions
    function spawn(uint32 _point, address _target) external;
    function transferPoint(
        uint32 _point,
        address _target,
        bool _reset
    ) external;
    function configureKeys(
        uint32 _point,
        bytes32 _encryptionKey,
        bytes32 _authenticationKey,
        uint32 _cryptoSuiteVersion,
        bool _discontinuous
    ) external;
    function escape(uint32 _point, uint32 _sponsor) external;
    function cancelEscape(uint32 _point) external;
    function adopt(uint32 _point) external;
    function reject(uint32 _point) external;
    function detach(uint32 _point) external;

    // Proxy management
    function setSpawnProxy(uint32 _point, address _spawner) external;
    function setTransferProxy(uint32 _point, address _transferrer) external;
    function setManagementProxy(uint32 _point, address _manager) external;
    function setVotingProxy(uint32 _point, address _voter) external;

    // View functions
    function canSpawn(
        uint32 _point,
        address _who
    ) external view returns (bool result);
    function getTransferProxy(
        uint32 _point
    ) external view returns (address transferProxy);
    function getManagementProxy(
        uint32 _point
    ) external view returns (address managementProxy);
    function getVotingProxy(
        uint32 _point
    ) external view returns (address votingProxy);
    function getOwner(uint32 _point) external view returns (address owner);
    function isOwner(
        uint32 _point,
        address _who
    ) external view returns (bool result);
    function getPointSize(uint32 _point) external pure returns (uint8 _size);
    function getSpawnCount(
        uint32 _point
    ) external view returns (uint32 spawnCount);
    function getSpawned(
        uint32 _point
    ) external view returns (uint32[] memory spawned);
    function hasSponsor(uint32 _point) external view returns (bool has);
    function getSponsor(uint32 _point) external view returns (uint32 sponsor);
    function isSponsor(
        uint32 _point,
        uint32 _sponsor
    ) external view returns (bool result);
    function isEscaping(uint32 _point) external view returns (bool escaping);
    function getEscapeRequest(
        uint32 _point
    ) external view returns (uint32 escape);
    function isRequestingEscapeTo(
        uint32 _point,
        uint32 _sponsor
    ) external view returns (bool result);
    function isActive(uint32 _point) external view returns (bool equals);
    function hasBeenLinked(uint32 _point) external view returns (bool result);
    function getKeys(
        uint32 _point
    )
        external
        view
        returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision);
    function getKeyRevisionNumber(
        uint32 _point
    ) external view returns (uint32 revision);
    function getContinuityNumber(
        uint32 _point
    ) external view returns (uint32 continuityNumber);

    // Contract references
    function azimuth() external view returns (address);
    function polls() external view returns (address);
    function claims() external view returns (address);
    function treasuryProxy() external view returns (address);

    // Owner functions
    function owner() external view returns (address);
}
"
    },
    "contracts/PlanetDispenser.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import "./interfaces/IEcliptic.sol";
import "./interfaces/IAzimuth.sol";

/**
 * @title PlanetDispenser
 * @notice Urbit Planet Dispenser with pseudo-random selection + redemption fixed at 1 URBIT token.
 *         Star owners may participate by setting this contract as their spawn proxy.
 *         Whitelist mode may be used to ensure only approved stars can participate.
 *         In order to discourage cherry-picking of vanity planets, the contract selects
 *         a fixed number of planets per star which may be spawned during a given epoch.
 *
 * @author Urbit Foundation
 */
contract PlanetDispenser is Ownable, ReentrancyGuard, Pausable {
    using SafeERC20 for IERC20;

    // ─────────────────────────────────────────────────────────────────────
    // State
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Seconds per epoch for planet menu rotation
    uint64 public epochSeconds = 30 minutes;
    /// @notice Number of planet choices offered per epoch
    uint8 public planetChoicesCount = 16;

    /// @dev Pool struct encapsulates swap-and-pop state for each star
    struct Pool {
        mapping(uint32 => uint32) map; // swap-and-pop remapping: index => remapped value
    }
    mapping(uint32 => Pool) private pools; // starId => pool

    /// @dev Track remaining planet count at the start of each epoch for stable menu generation
    mapping(uint32 => mapping(uint64 => uint32)) private epochRemainingCount;

    /// @notice Whitelist of allowed stars
    mapping(uint32 => bool) public whitelist;
    /// @notice Array of whitelisted star IDs for enumeration
    uint32[] public whitelistedStars;

    IAzimuth public immutable azimuth;
    IERC20 public immutable urbitToken;

    /// @notice Fixed price per planet in URBIT tokens (1 URBIT = 1e18 wei)
    uint256 public constant ONE_URBIT_TOKEN = 1e18;
    /// @notice Maximum number of planets spawnable from a single star (2^16 - 1)
    uint32 private constant MAX_PLANETS = 65_535;

    // ─────────────────────────────────────────────────────────────────────
    // Events / Errors
    // ─────────────────────────────────────────────────────────────────────

    error StarNotAllowed();
    error InvalidPlanetChoice();
    error InvalidStarOwner();
    error InvalidEpochDuration();
    error InvalidPlanetCount();
    error InsufficientPermitValue();
    error InvalidAddress();
    error InvalidStarId();
    error StaleIndex();

    event PlanetRedeemed(
        uint32 indexed starId,
        uint32 indexed planetId,
        address indexed buyer,
        uint256 price
    );

    event WhitelistUpdated(uint32 indexed starId, bool isWhitelisted);
    event EpochDurationUpdated(uint256 oldDuration, uint256 newDuration);
    event PlanetCountUpdated(uint8 oldCount, uint8 newCount);

    // ─────────────────────────────────────────────────────────────────────
    // Constructor
    // ─────────────────────────────────────────────────────────────────────

    constructor(address _azimuth, address _urbitToken) Ownable(msg.sender) {
        if (_azimuth == address(0)) revert InvalidAddress();
        if (_urbitToken == address(0)) revert InvalidAddress();
        azimuth = IAzimuth(_azimuth);
        urbitToken = IERC20(_urbitToken);
    }

    // ─────────────────────────────────────────────────────────────────────
    // Pool Management
    // ─────────────────────────────────────────────────────────────────────

    function _getRemainingCount(uint32 starId) internal view returns (uint32) {
        uint32 spawnedCount = azimuth.getSpawnCount(starId);
        return MAX_PLANETS - spawnedCount;
    }

    /// @dev Get stable remaining count for the current epoch
    function _getEpochRemainingCount(uint32 starId, uint64 epoch) internal returns (uint32) {
        uint32 stored = epochRemainingCount[starId][epoch];
        if (stored == 0) {
            // First access in this epoch - initialize with current remaining count
            stored = _getRemainingCount(starId);
            epochRemainingCount[starId][epoch] = stored;
        }
        return stored;
    }

    /// @dev View-only version: get epoch remaining count without modifying storage
    function _getEpochRemainingCountView(uint32 starId, uint64 epoch) internal view returns (uint32) {
        uint32 stored = epochRemainingCount[starId][epoch];
        // If not yet initialized for this epoch, use current remaining count
        return stored == 0 ? _getRemainingCount(starId) : stored;
    }

    /// @dev Returns pool index and 0-based suffix
    function _draw(
        uint32 starId,
        uint256 seed,
        uint32 remaining
    ) internal view returns (uint32 idx, uint32 suffix) {
        Pool storage p = pools[starId];

        idx = uint32(seed % remaining);
        suffix = p.map[idx] == 0 ? idx : p.map[idx];
    }

    /// @dev Burns 'idx' from the star's pool (swap-and-pop)
    function _pop(uint32 starId, uint32 idx) internal {
        Pool storage p = pools[starId];
        uint32 remaining = _getRemainingCount(starId);

        // Prevent race condition: ensure idx is still valid
        if (idx >= remaining) revert StaleIndex();

        uint32 last = remaining - 1;

        if (idx != last) {
            uint32 valAtLast = p.map[last] == 0 ? last : p.map[last];
            p.map[idx] = valAtLast;
        }
        if (p.map[last] != 0) delete p.map[last];
    }

    // ─────────────────────────────────────────────────────────────────────
    // Public View Functions
    // ─────────────────────────────────────────────────────────────────────

    function currentEpoch() public view returns (uint64) {
        return uint64(block.timestamp / epochSeconds);
    }

    /// @notice Get seconds remaining in the current epoch
    /// @return secondsRemaining Number of seconds until the next epoch starts
    function epochTimeRemaining()
        public
        view
        returns (uint64 secondsRemaining)
    {
        uint64 currentTime = uint64(block.timestamp);
        uint64 epochStart = currentEpoch() * epochSeconds;
        uint64 epochEnd = epochStart + epochSeconds;
        return epochEnd - currentTime;
    }

    /// @notice Check if a star is actively participating in the planet dispenser
    /// @param starId The ID of the star to check
    /// @return bool True if the star can fulfill planet redemptions
    function isParticipating(uint32 starId) public view returns (bool) {
        // Check whitelist
        if (!whitelist[starId]) return false;

        // Ensure this contract is set as spawn proxy
        if (azimuth.getSpawnProxy(starId) != address(this)) return false;

        // Ensure star has enough planets remaining
        if (_getRemainingCount(starId) < planetChoicesCount) return false;

        return true;
    }

    /// @notice Get the available planets for a star in the current epoch
    /// @param starId The ID of the star
    /// @return out Array of planet IDs available for purchase
    function planetChoices(
        uint32 starId
    ) public view returns (uint32[] memory out) {
        if (!isParticipating(starId)) revert StarNotAllowed();

        uint64 epoch = currentEpoch();
        uint32 epochRemaining = _getEpochRemainingCountView(starId, epoch);

        // Always return exactly planetChoicesCount planets
        out = new uint32[](planetChoicesCount);
        for (uint8 i = 0; i < planetChoicesCount; ) {
            uint256 seed = uint256(
                keccak256(abi.encodePacked(starId, epoch, i))
            );
            (, uint32 suffix) = _draw(starId, seed, epochRemaining);
            uint32 pid = calcPlanetId(starId, uint16(suffix + 1));

            // Check for duplicates
            bool dup = false;
            for (uint8 j = 0; j < i; ++j) {
                if (out[j] == pid) {
                    dup = true;
                    break;
                }
            }
            if (!dup) {
                out[i] = pid;
                unchecked {
                    ++i;
                }
            }
            // If duplicate, re-roll deterministically by continuing loop without incrementing i
        }
    }

    /// @notice Check if a planet is a valid choice for the current epoch
    /// @param planetId The ID of the planet to check
    /// @return bool True if the planet is a valid choice
    function isValidChoice(uint32 planetId) public view returns (bool) {
        uint32 starId = uint32(azimuth.getPrefix(planetId));
        if (planetId <= starId) return false;
        if (!whitelist[starId]) return false;

        try this.planetChoices(starId) returns (uint32[] memory choices) {
            for (uint256 i = 0; i < choices.length; ) {
                if (choices[i] == planetId) return true;
                unchecked {
                    ++i;
                }
            }
        } catch {
            return false;
        }
        return false;
    }

    /// @notice Get count of remaining planets available for a star
    /// @param starId The ID of the star to check
    /// @return remaining Number of planets still available to spawn
    function getRemainingPlanetCount(
        uint32 starId
    ) external view returns (uint32 remaining) {
        return _getRemainingCount(starId);
    }

    /// @notice Get all whitelisted star IDs
    /// @return Array of all whitelisted star IDs
    function getWhitelistedStars() external view returns (uint32[] memory) {
        return whitelistedStars;
    }

    /// @notice Get the count of whitelisted stars
    /// @return Number of stars currently whitelisted
    function whitelistedCount() external view returns (uint256) {
        return whitelistedStars.length;
    }

    // ─────────────────────────────────────────────────────────────────────
    // Redemption Functions
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Purchase and redeem a planet (requires prior token approval)
    /// @param planetId The ID of the planet to purchase
    /// @param recipient The address that will receive the spawned planet
    function redeemPlanet(
        uint32 planetId,
        address recipient
    ) external nonReentrant whenNotPaused {
        if (recipient == address(0)) revert InvalidAddress();
        uint32 starId = uint32(azimuth.getPrefix(planetId));

        if (!whitelist[starId]) revert StarNotAllowed();

        // Find which epoch choice this planet corresponds to
        uint64 epoch = currentEpoch();
        uint32 epochRemaining = _getEpochRemainingCount(starId, epoch);

        bool found = false;
        uint32 targetIdx = 0;

        // Fixed iteration count - always exactly planetChoicesCount
        for (uint8 i = 0; i < planetChoicesCount && !found; ) {
            uint256 seed = uint256(
                keccak256(abi.encodePacked(starId, epoch, i))
            );
            (uint32 idx, uint32 suffix) = _draw(starId, seed, epochRemaining);

            if (calcPlanetId(starId, uint16(suffix + 1)) == planetId) {
                targetIdx = idx;
                found = true;
            }
            unchecked {
                ++i;
            }
        }

        if (!found) revert InvalidPlanetChoice();

        _pop(starId, targetIdx); // uniqueness guarantee
        _finishRedeem(planetId, starId, recipient);
    }

    /// @notice Purchase and redeem a planet using EIP-2612 permit (single transaction)
    /// @param planetId The ID of the planet to purchase
    /// @param recipient The address that will receive the spawned planet
    /// @param value The permit value (must be >= ONE_URBIT_TOKEN, supports type(uint256).max)
    /// @param deadline Permit expiration timestamp
    /// @param v Permit signature component
    /// @param r Permit signature component
    /// @param s Permit signature component
    function redeemPlanetWithPermit(
        uint32 planetId,
        address recipient,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external nonReentrant whenNotPaused {
        if (recipient == address(0)) revert InvalidAddress();
        // Require permit value to be at least ONE_URBIT_TOKEN
        if (value < ONE_URBIT_TOKEN) revert InsufficientPermitValue();

        uint32 starId = uint32(azimuth.getPrefix(planetId));

        if (!whitelist[starId]) revert StarNotAllowed();

        // Find which epoch choice this planet corresponds to
        uint64 epoch = currentEpoch();
        uint32 epochRemaining = _getEpochRemainingCount(starId, epoch);

        bool found = false;
        uint32 targetIdx = 0;

        // Fixed iteration count - always exactly planetChoicesCount
        for (uint8 i = 0; i < planetChoicesCount && !found; ) {
            uint256 seed = uint256(
                keccak256(abi.encodePacked(starId, epoch, i))
            );
            (uint32 idx, uint32 suffix) = _draw(starId, seed, epochRemaining);

            if (calcPlanetId(starId, uint16(suffix + 1)) == planetId) {
                targetIdx = idx;
                found = true;
            }
            unchecked {
                ++i;
            }
        }

        if (!found) revert InvalidPlanetChoice();

        // Execute permit to authorize token transfer
        IERC20Permit(address(urbitToken)).permit(
            msg.sender,
            address(this),
            value,
            deadline,
            v,
            r,
            s
        );

        _pop(starId, targetIdx); // uniqueness guarantee
        _finishRedeem(planetId, starId, recipient);
    }

    /// @notice Internal function to handle planet redemption logic
    /// @param planetId The ID of the planet to redeem
    /// @param starId The ID of the star (passed to avoid re-computation)
    /// @param recipient The address that will receive the spawned planet
    function _finishRedeem(
        uint32 planetId,
        uint32 starId,
        address recipient
    ) internal {
        // Transfer 1 URBIT token directly to star owner
        address starOwner = azimuth.getOwner(starId);
        if (starOwner == address(0)) revert InvalidStarOwner();

        urbitToken.safeTransferFrom(msg.sender, starOwner, ONE_URBIT_TOKEN);

        // Spawn and transfer the planet to recipient
        IEcliptic ecliptic = IEcliptic(azimuth.owner());
        ecliptic.spawn(planetId, recipient);
        ecliptic.transferPoint(planetId, recipient, false);

        emit PlanetRedeemed(starId, planetId, recipient, ONE_URBIT_TOKEN);
    }

    // ─────────────────────────────────────────────────────────────────────
    // Admin Functions
    // ─────────────────────────────────────────────────────────────────────

    function updateWhitelist(
        uint32 starId,
        bool isWhitelisted
    ) external onlyOwner {
        if (isWhitelisted && !whitelist[starId]) {
            // Adding to whitelist
            whitelistedStars.push(starId);
        } else if (!isWhitelisted && whitelist[starId]) {
            // Removing from whitelist - find and remove from array
            for (uint256 i = 0; i < whitelistedStars.length; i++) {
                if (whitelistedStars[i] == starId) {
                    whitelistedStars[i] = whitelistedStars[
                        whitelistedStars.length - 1
                    ];
                    whitelistedStars.pop();
                    break;
                }
            }
        }

        whitelist[starId] = isWhitelisted;
        emit WhitelistUpdated(starId, isWhitelisted);
    }

    /// @notice Set the epoch duration for planet menu rotation
    /// @param _epochSeconds New epoch duration in seconds (minimum 1 minute, maximum 24 hours)
    function setEpochDuration(uint256 _epochSeconds) external onlyOwner {
        if (_epochSeconds < 1 minutes || _epochSeconds > 24 hours) {
            revert InvalidEpochDuration();
        }

        uint256 oldDuration = epochSeconds;
        epochSeconds = uint64(_epochSeconds);

        emit EpochDurationUpdated(oldDuration, _epochSeconds);
    }

    /// @notice Set the number of planet choices offered per epoch
    /// @param _count New planet count (minimum 1, maximum 32)
    function setPlanetChoicesCount(uint8 _count) external onlyOwner {
        if (_count == 0 || _count > 32) {
            revert InvalidPlanetCount();
        }

        uint8 oldCount = planetChoicesCount;
        planetChoicesCount = _count;

        emit PlanetCountUpdated(oldCount, _count);
    }

    /// @notice Pause all planet redemption operations
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Resume all planet redemption operations
    function unpause() external onlyOwner {
        _unpause();
    }

    // ─────────────────────────────────────────────────────────────────────
    // Helper Functions
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Calculate planet ID from star ID and planet index using efficient bit-shifting
    /// @param starId The ID of the star (256-65535)
    /// @param planetIndex The planet index within the star (1-65535)
    /// @return planetId The calculated planet ID
    function calcPlanetId(
        uint32 starId,
        uint16 planetIndex
    ) public pure returns (uint32 planetId) {
        if (starId >= 65536) revert InvalidStarId();
        if (planetIndex == 0) revert InvalidPlanetChoice();
        return (uint32(planetIndex) << 16) | starId;
    }

    /// @notice Get price, allowance, and balance info for a buyer
    /// @param buyer Address to check payment readiness for
    /// @return price Cost per planet (always 1 URBIT token)
    /// @return allowance Curre

Tags:
ERC20, ERC721, ERC165, Multisig, Pausable, Non-Fungible, Swap, Upgradeable, Multi-Signature, Factory|addr:0x9894fe218fb2f8986e7aa7dd342ae093736d9c31|verified:true|block:23623566|tx:0x0ef4c9147c5f0af90c2889290229becca35f8d5488b57744bb8b3bbc1cd59e7b|first_check:1761041898

Submitted on: 2025-10-21 12:18:20

Comments

Log in to comment.

No comments yet.