Skip to content
Verified contractExactMIT

SpawnToken

Address0x137ce4ae2ce15dfe86b7999f5ecb293ea70066e1
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,423,778
Creation transaction
0xb649da9261…02ce003641

contracts/SpawnToken.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IFeeDistributor} from "./FeeDistributor.sol";

/// @title SpawnToken — one creature, every chain.
/// @notice The hub instance pre-mints the entire global supply to the SpawnPad
/// (which runs the genesis curve). Spoke replicas start at zero and are minted
/// / burned by their chain's gateway as tokens cross chains, so the SUM of
/// supplies across all chains is always exactly the global supply.
contract SpawnToken is ERC20 {
    /// The protocol contract allowed to bridge-mint/burn: the pad on the hub,
    /// the gateway on a spoke.
    address public immutable controller;
    bool public immutable isHub;
    /// This chain's FeeDistributor, told about every transfer so holder
    /// dividends follow balances. Storage, not immutable: the premint in the
    /// constructor already runs the `_update` hook.
    address public distributor;

    constructor(
        string memory name_,
        string memory symbol_,
        address controller_,
        bool isHub_,
        uint256 premint,
        address premintTo,
        address distributor_
    ) ERC20(name_, symbol_) {
        controller = controller_;
        isHub = isHub_;
        distributor = distributor_;
        if (premint > 0) _mint(premintTo, premint);
    }

    function _update(address from, address to, uint256 value) internal override {
        super._update(from, to, value);
        if (distributor != address(0)) IFeeDistributor(distributor).handleTransfer(from, to, value);
    }

    function bridgeMint(address to, uint256 amount) external {
        require(msg.sender == controller, "ST: not controller");
        _mint(to, amount);
    }

    function bridgeBurn(address from, uint256 amount) external {
        require(msg.sender == controller, "ST: not controller");
        _burn(from, amount);
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

// 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

// 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

// 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/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 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/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 _safeTransfer(token, to, value, false);
    }

    /**
     * @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 _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

@openzeppelin/contracts/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/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

/**
 * @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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // 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;

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// 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);
}

contracts/FeeDistributor.sol

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

import {OmniUSD} from "./OmniUSD.sol";
import {Roles} from "./Roles.sol";

interface IFeeDistributor {
    function handleTransfer(address from, address to, uint256 amount) external;
}

/// @title FeeDistributor — the holders' share of trading fees, paid out HERE.
/// @notice One instance per user-facing chain. The hub splits each token's
/// holders pot pro-rata to where the supply lives; this chain's slice lands
/// in this contract (in this chain's OmniUSD) when someone pulls it. Holders
/// then claim with a pure local transaction on their own chain — no
/// cross-chain hop, no snapshot ceremony.
///
/// Accounting is the classic magnified-dividends-per-share pattern: every
/// token transfer reports in through its hook, so a holder's claimable
/// amount follows their balance automatically — buy more, earn more of the
/// next drop; sell, and the earned part stays claimable. Protocol accounts
/// (the gateway, this contract) hold inventory, not bags: they are excluded
/// and earn nothing.
contract FeeDistributor is IFeeDistributor, Roles {
    uint256 internal constant MAG = 2 ** 128;
    /// A drop only folds into the stream once at least this many shares
    /// (1,000 tokens) exist on this chain; until then it waits in
    /// `pendingOf`. Without a floor, a drop landing on a few wei of shares
    /// sends `magDPS` so high that `magDPS × balance` overflows on the next
    /// real mint — which reverts the token's transfer hook and bricks every
    /// delivery of that token on this chain. With the floor, that product
    /// stays below 2^255 until more than $1.7e14 has been dropped on one
    /// token here.
    uint256 public constant MIN_SHARES = 1_000e18;

    OmniUSD public immutable usd;
    /// This chain's protocol agent — the gateway. Only it can drop fees in.
    address public agent;

    mapping(address => bool) public excluded;
    /// Once sealed, the excluded set is final.
    bool public exclusionsSealed;
    /// Shares alive across every token of this chain. Exclusions are only
    /// legal while this is zero: excluding an account that already holds
    /// shares would leave them counted forever.
    uint256 public liveShares;

    // Everything below is keyed by the LOCAL token contract (this chain's
    // replica). The token itself is the caller of `handleTransfer`, so a
    // rogue contract can only corrupt its own key.
    mapping(address => uint256) public magDPS;
    mapping(address => uint256) public totalShares;
    /// Drops that arrive while too few shares exist wait here and fold into
    /// the stream as soon as holders reach MIN_SHARES.
    mapping(address => uint256) public pendingOf;
    mapping(address => mapping(address => uint256)) public sharesOf;
    mapping(address => mapping(address => int256)) internal corrections;
    mapping(address => mapping(address => uint256)) public withdrawnOf;

    event FeeDropped(address indexed token, uint256 amount);
    event HolderClaimed(address indexed token, address indexed holder, uint256 amount);
    event AgentSet(address agent);
    event Excluded(address indexed account);
    event ExclusionsSealed();

    constructor(OmniUSD _usd) {
        usd = _usd;
        excluded[address(this)] = true;
    }

    function setAgent(address a) external onlyAdmin {
        require(agent == address(0), "DIST: agent set");
        agent = a;
        excluded[a] = true;
        emit AgentSet(a);
        emit Excluded(a);
    }

    /// Wire-up only: legal until the set is sealed, and only while no share
    /// exists yet — so no live share ever needs resyncing.
    function exclude(address a) external onlyAdmin {
        require(!exclusionsSealed, "DIST: exclusions sealed");
        require(liveShares == 0, "DIST: shares live");
        excluded[a] = true;
        emit Excluded(a);
    }

    function sealExclusions() external onlyAdmin {
        exclusionsSealed = true;
        emit ExclusionsSealed();
    }

    /* ---------------------------- token hook ---------------------------- */

    /// Every replica reports its transfers here (mints come from the zero
    /// address, burns go to it). Shares mirror the balances of non-excluded
    /// accounts, with the standard per-account corrections so already-earned
    /// dividends never move when tokens do.
    function handleTransfer(address from, address to, uint256 amount) external {
        address token = msg.sender;
        if (amount > 0) {
            uint256 dec;
            uint256 inc;
            if (from != address(0) && !excluded[from]) {
                uint256 cur = sharesOf[token][from];
                dec = amount > cur ? cur : amount;
                if (dec > 0) _decrease(token, from, dec);
            }
            if (to != address(0) && !excluded[to]) {
                inc = amount;
                _increase(token, to, amount);
            }
            if (inc != dec) liveShares = liveShares + inc - dec;
        }
        _flush(token);
    }

    /* ------------------------------ drops ------------------------------ */

    /// Fold `amount` oUSD into the dividend stream for `token`'s current
    /// holders. The agent funds this contract with the same amount in the
    /// same transaction.
    function drop(address token, uint256 amount) external {
        require(msg.sender == agent, "DIST: not agent");
        pendingOf[token] += amount;
        _flush(token);
        emit FeeDropped(token, amount);
    }

    /* ------------------------------ claims ------------------------------ */

    /// Total ever earned by `account` on `token` drops.
    function accumulated(address token, address account) public view returns (uint256) {
        return
            uint256(int256(magDPS[token] * sharesOf[token][account]) + corrections[token][account]) /
            MAG;
    }

    function withdrawable(address token, address account) public view returns (uint256) {
        return accumulated(token, account) - withdrawnOf[token][account];
    }

    function claim(address token) external returns (uint256 amount) {
        amount = withdrawable(token, msg.sender);
        require(amount > 0, "DIST: nothing to claim");
        withdrawnOf[token][msg.sender] += amount;
        usd.transfer(msg.sender, amount);
        emit HolderClaimed(token, msg.sender, amount);
    }

    /* ----------------------------- internal ----------------------------- */

    function _increase(address token, address account, uint256 x) internal {
        sharesOf[token][account] += x;
        totalShares[token] += x;
        corrections[token][account] -= int256(magDPS[token] * x);
    }

    function _decrease(address token, address account, uint256 x) internal {
        sharesOf[token][account] -= x;
        totalShares[token] -= x;
        corrections[token][account] += int256(magDPS[token] * x);
    }

    function _flush(address token) internal {
        uint256 p = pendingOf[token];
        uint256 s = totalShares[token];
        if (p == 0 || s < MIN_SHARES) return;
        pendingOf[token] = 0;
        magDPS[token] += (p * MAG) / s;
    }
}

contracts/OmniUSD.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ITokenMessengerV2} from "./cctp/ITokenMessengerV2.sol";
import {Roles} from "./Roles.sol";

/// @title OmniUSD — the omnichain settlement dollar, 1:1 backed by USDC.
/// @notice One instance lives on each logical chain. Value moves across chains
/// by burn-on-source / mint-on-destination, driven by the protocol agent of
/// each chain (the SpawnPad on the hub, the SpawnGateway on a spoke).
///
/// Two modes, fixed at construction:
///  - BACKED (`usdc != 0`, every user-facing chain): this contract is also the
///    chain's USDC vault. oUSD only comes into existence against USDC paid in
///    here, or against value that arrived by protocol message.
///  - LEDGER (`usdc == 0`, the hub): a pure accounting unit. The hub holds no
///    dollars — it holds the books (curve reserves, fee pots) for dollars
///    that sit in the spokes' vaults.
///
/// GLOBAL BACKING INVARIANT (modulo value in flight between chains):
///   Σ over backed instances of USDC held × SCALE
///     == Σ over ALL instances (hub ledger included) of oUSD totalSupply.
/// Every function below preserves it: USDC in ⇄ oUSD minted (or carried by
/// message), USDC out ⇄ oUSD burned (or consumed from a message).
///
/// A vault can be locally short (dollars entered on chain A, a seller cashes
/// out on chain B). A payout then mints oUSD instead — a claim redeemable as
/// soon as liquidity returns — and the operator rebalances vault-to-vault
/// with Circle CCTP. There is NO function that sends USDC anywhere but to a
/// user redeeming their own oUSD, a protocol payout, or a configured peer
/// vault.
///
/// WHO CAN DO WHAT (see Roles):
///  - ADMIN names the agent (once) and the peer vaults (once per label). A
///    peer can never be re-aimed, but a NEW label can always be named — and
///    a label whose "peer vault" is an attacker's address is a way out of
///    the vault. That is why the admin must be a timelock: naming a peer is
///    then public for days before `rebalance` can use it.
///  - OPERATOR sets the deposit cap, reopens deposits and rebalances — to
///    existing peers only. It can move liquidity between protocol vaults
///    (a liveness power), never out of them.
///  - GUARDIAN can close deposits. Nobody can close exits: `unwrap` and
///    `payout` have no switch.
///
/// Every function that moves USDC is `nonReentrant`. USDC has no transfer
/// hooks today; the guard is there so an upgrade of the token could never
/// turn the vault's balance-delta accounting against it.
contract OmniUSD is ERC20, ReentrancyGuard, Roles {
    using SafeERC20 for IERC20;

    /// USDC has 6 decimals, oUSD 18.
    uint256 public constant SCALE = 1e12;
    /// The smallest deposit that may ride a protocol message, in oUSD wei —
    /// one USDC unit. A real USDC transfer can never credit less; the floor
    /// is here so a deposit that credited NOTHING (a token that moved no
    /// balance) is refused instead of sending the hub a zero-dollar message,
    /// and so both vaults (`OmniUSDLocal` too) refuse exactly the same thing.
    uint256 public constant MIN_DEPOSIT = 1e12;
    /// CCTP V2 Standard Transfer: attested at source-chain finality.
    uint32 public constant CCTP_FINALITY_STANDARD = 2000;

    uint32 public immutable chainLabel;
    /// The backing asset; address(0) puts this instance in ledger mode.
    IERC20 public immutable usdc;
    /// Circle's TokenMessengerV2 on this chain; address(0) = no rebalancing.
    ITokenMessengerV2 public immutable tokenMessenger;

    address public agent;
    /// Ceiling on the vault's USDC balance, enforced on every deposit. Starts
    /// at 0: deposits are closed until the operator opens them (guarded launch).
    uint256 public depositCap;
    /// The guardian's stop for NEW money (`wrap`, `depositFor`). Exits
    /// (`unwrap`, `payout`) ignore it.
    bool public depositsPaused;

    struct Peer {
        uint32 domain; // CCTP domain of the peer's chain
        bytes32 vault; // the peer OmniUSD instance over there
    }
    /// chain label -> the only place `rebalance` can send USDC for that chain.
    mapping(uint32 => Peer) public peers;

    event Wrapped(address indexed account, uint256 usdcIn, uint256 minted);
    event Unwrapped(address indexed account, uint256 usdcOut);
    event Deposited(address indexed from, uint256 usdcIn, uint256 amount);
    /// `minted` is the part of a payout that could not leave as USDC: the
    /// sub-SCALE dust when paid, or the whole amount when the vault was short
    /// or the transfer was refused.
    event PaidOut(address indexed to, uint256 usdcOut, uint256 minted);
    event DepositCapSet(uint256 cap);
    event AgentSet(address agent);
    event DepositsPaused(address by);
    event DepositsUnpaused(address by);
    event PeerSet(uint32 indexed label, uint32 domain, bytes32 vault);
    event Rebalanced(uint32 indexed label, uint32 domain, bytes32 vault, uint256 usdcOut);

    modifier onlyAgent() {
        require(msg.sender == agent, "oUSD: not agent");
        _;
    }

    modifier backed() {
        require(address(usdc) != address(0), "oUSD: ledger only");
        _;
    }

    constructor(uint32 _chainLabel, address _usdc, address _tokenMessenger) ERC20("OmniUSD", "oUSD") {
        if (_usdc == address(0)) {
            require(_tokenMessenger == address(0), "oUSD: ledger has no CCTP");
        } else {
            require(IERC20Metadata(_usdc).decimals() == 6, "oUSD: usdc decimals");
        }
        chainLabel = _chainLabel;
        usdc = IERC20(_usdc);
        tokenMessenger = ITokenMessengerV2(_tokenMessenger);
    }

    /* ------------------------ admin & operator ------------------------ */

    function setAgent(address a) external onlyAdmin {
        require(agent == address(0), "oUSD: agent set");
        agent = a;
        emit AgentSet(a);
    }

    function setDepositCap(uint256 cap) external onlyOperator backed {
        depositCap = cap;
        emit DepositCapSet(cap);
    }

    function pauseDeposits() external onlyGuardian backed {
        depositsPaused = true;
        emit DepositsPaused(msg.sender);
    }

    function unpauseDeposits() external onlyOperator backed {
        depositsPaused = false;
        emit DepositsUnpaused(msg.sender);
    }

    /// Names the peer vault for a chain — once. A peer can never be changed,
    /// so a rebalance route, once published, is fixed for good. (New labels
    /// can still be added — by the admin only; see the contract header.)
    function setPeer(uint32 label, uint32 cctpDomain, bytes32 peerVault) external onlyAdmin backed {
        require(label != chainLabel && peerVault != bytes32(0), "oUSD: bad peer");
        require(peers[label].vault == bytes32(0), "oUSD: peer set");
        peers[label] = Peer(cctpDomain, peerVault);
        emit PeerSet(label, cctpDomain, peerVault);
    }

    /// Moves vault liquidity to the peer vault of `dstLabel` with CCTP V2
    /// (Standard Transfer, zero fee, anyone may relay the attestation). The
    /// USDC is in flight until minted to the peer; it can land nowhere else.
    function rebalance(uint32 dstLabel, uint256 usdc6) external onlyOperator backed nonReentrant {
        require(address(tokenMessenger) != address(0), "oUSD: no CCTP");
        Peer memory p = peers[dstLabel];
        require(p.vault != bytes32(0), "oUSD: no peer");
        usdc.forceApprove(address(tokenMessenger), usdc6);
        tokenMessenger.depositForBurn(
            usdc6,
            p.domain,
            p.vault,
            address(usdc),
            bytes32(0),
            0,
            CCTP_FINALITY_STANDARD
        );
        emit Rebalanced(dstLabel, p.domain, p.vault, usdc6);
    }

    /* ------------------------------ users ------------------------------ */

    /// USDC in, oUSD out, 1:1.
    function wrap(uint256 usdc6) external backed nonReentrant returns (uint256 amount18) {
        amount18 = _pull(msg.sender, usdc6);
        _mint(msg.sender, amount18);
        emit Wrapped(msg.sender, amount18 / SCALE, amount18);
    }

    /// oUSD in, USDC out, 1:1. Only whole USDC units burn — sub-SCALE dust
    /// stays with the caller. Reverts when this chain's vault is short; the
    /// oUSD stays a valid claim until liquidity is rebalanced in.
    function unwrap(uint256 amount18) external backed nonReentrant returns (uint256 usdc6) {
        usdc6 = amount18 / SCALE;
        require(usdc6 > 0, "oUSD: dust");
        require(usdc.balanceOf(address(this)) >= usdc6, "oUSD: vault short");
        _burn(msg.sender, usdc6 * SCALE);
        usdc.safeTransfer(msg.sender, usdc6);
        emit Unwrapped(msg.sender, usdc6);
    }

    /// USDC this vault can pay out right now.
    function liquidity() external view returns (uint256) {
        return address(usdc) == address(0) ? 0 : usdc.balanceOf(address(this));
    }

    /* ------------------------------ agent ------------------------------ */

    /// Takes `usdc6` from `from` WITHOUT minting oUSD: the value is about to
    /// ride a protocol message (≡ wrap + bridgeBurn in one step). Returns the
    /// 18-decimal amount the message must carry.
    function depositFor(address from, uint256 usdc6)
        external
        onlyAgent
        backed
        nonReentrant
        returns (uint256 amount18)
    {
        amount18 = _pull(from, usdc6);
        require(amount18 >= MIN_DEPOSIT, "oUSD: dust");
        emit Deposited(from, amount18 / SCALE, amount18);
    }

    /// Settles value that arrived by protocol message. NEVER reverts for a
    /// real recipient: it runs on the message path, where a revert would
    /// strand the payout. Pays USDC when the vault has it and USDC accepts the
    /// transfer (Circle can blacklist a recipient); otherwise mints the whole
    /// amount as oUSD, redeemable later. Sub-SCALE dust is always minted so
    /// conservation is exact to the wei.
    function payout(address to, uint256 amount18) external onlyAgent backed nonReentrant {
        uint256 usdc6 = amount18 / SCALE;
        uint256 minted = amount18;
        if (usdc6 > 0 && _trySendUsdc(to, usdc6)) {
            minted = amount18 - usdc6 * SCALE;
        } else {
            usdc6 = 0;
        }
        if (minted > 0) _mint(to, minted);
        emit PaidOut(to, usdc6, minted);
    }

    function bridgeMint(address to, uint256 amount) external onlyAgent {
        _mint(to, amount);
    }

    function bridgeBurn(address from, uint256 amount) external onlyAgent {
        _burn(from, amount);
    }

    /* ---------------------------- internals ---------------------------- */

    /// Pulls USDC into the vault under the deposit cap and returns the oUSD
    /// value of what ACTUALLY arrived (balance delta, not the request).
    function _pull(address from, uint256 usdc6) private returns (uint256 amount18) {
        require(usdc6 > 0, "oUSD: zero");
        require(!depositsPaused, "oUSD: deposits paused");
        uint256 before = usdc.balanceOf(address(this));
        require(before + usdc6 <= depositCap, "oUSD: deposit cap");
        usdc.safeTransferFrom(from, address(this), usdc6);
        amount18 = (usdc.balanceOf(address(this)) - before) * SCALE;
    }

    /// A USDC transfer that reports failure instead of reverting.
    function _trySendUsdc(address to, uint256 usdc6) private returns (bool) {
        if (usdc.balanceOf(address(this)) < usdc6) return false;
        (bool ok, bytes memory ret) = address(usdc).call(abi.encodeCall(IERC20.transfer, (to, usdc6)));
        if (!ok) return false;
        return ret.length == 0 || (ret.length == 32 && uint256(bytes32(ret)) == 1);
    }
}

contracts/Roles.sol

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

/// @title Roles — the three keys every SPAWN! contract answers to.
/// @notice Powers are split by what they can do to user funds:
///
///  - ADMIN decides topology and custody (who is a gateway, a peer vault, a
///    route, an agent). Every such power, in hostile hands, can forge value
///    or drain a vault — so the admin is meant to be a TimelockController:
///    slow and public. Two-step transfer: a typo cannot orphan a contract.
///  - OPERATOR tunes prices and limits and can unpause. Nothing it can do
///    moves funds out of the protocol; the admin may always act in its place.
///  - GUARDIAN can only pause — a hot key for a fast stop. The operator and
///    the admin can pause too.
///
/// A fresh contract has the deployer as admin and no operator or guardian.
abstract contract Roles {
    address public admin;
    address public pendingAdmin;
    address public operator;
    address public guardian;

    event AdminTransferStarted(address indexed admin, address indexed nominee);
    event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
    event OperatorSet(address indexed operator);
    event GuardianSet(address indexed guardian);

    constructor() {
        admin = msg.sender;
        emit AdminTransferred(address(0), msg.sender);
    }

    modifier onlyAdmin() {
        _onlyAdmin();
        _;
    }

    modifier onlyOperator() {
        _onlyOperator();
        _;
    }

    modifier onlyGuardian() {
        _onlyGuardian();
        _;
    }

    function _onlyAdmin() internal view {
        require(msg.sender == admin, "ROLES: not admin");
    }

    function _onlyOperator() internal view {
        require(msg.sender == operator || msg.sender == admin, "ROLES: not operator");
    }

    function _onlyGuardian() internal view {
        require(
            msg.sender == guardian || msg.sender == operator || msg.sender == admin,
            "ROLES: not guardian"
        );
    }

    /// Names the next admin; nothing changes until the nominee accepts.
    /// Naming address(0) cancels a pending transfer.
    function transferAdmin(address nominee) external onlyAdmin {
        pendingAdmin = nominee;
        emit AdminTransferStarted(admin, nominee);
    }

    function acceptAdmin() external {
        require(msg.sender == pendingAdmin, "ROLES: not nominee");
        emit AdminTransferred(admin, msg.sender);
        admin = msg.sender;
        pendingAdmin = address(0);
        _onAdminChanged(msg.sender);
    }

    function setOperator(address operator_) external onlyAdmin {
        operator = operator_;
        emit OperatorSet(operator_);
    }

    function setGuardian(address guardian_) external onlyAdmin {
        guardian = guardian_;
        emit GuardianSet(guardian_);
    }

    /// Hook for contracts that mirror the admin somewhere else (the LayerZero
    /// adapter re-points its endpoint delegate).
    function _onAdminChanged(address newAdmin) internal virtual {}
}

contracts/cctp/ITokenMessengerV2.sol

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

/// @title Minimal interface to Circle's CCTP V2 TokenMessengerV2.
/// @notice Signature copied from circlefin/evm-cctp-contracts
/// `src/v2/TokenMessengerV2.sol` (master). The real contract also reverts
/// when the caller is denylisted by Circle, when `maxFee >= amount`, and —
/// if Circle ever switches its `minFee` on — when `maxFee` is below
/// `getMinFeeAmount(amount)`.
interface ITokenMessengerV2 {
    /// @param amount amount of `burnToken` to burn (pulled from msg.sender)
    /// @param destinationDomain CCTP domain of the destination chain
    /// @param mintRecipient address minted to on the destination, as bytes32
    /// @param burnToken the local USDC
    /// @param destinationCaller who may relay on the destination; bytes32(0)
    /// lets anyone relay
    /// @param maxFee max fee paid on the destination, in burnToken units
    /// @param minFinalityThreshold 2000 = finalized (Standard Transfer),
    /// 1000 = confirmed (Fast Transfer)
    function depositForBurn(
        uint256 amount,
        uint32 destinationDomain,
        bytes32 mintRecipient,
        address burnToken,
        bytes32 destinationCaller,
        uint256 maxFee,
        uint32 minFinalityThreshold
    ) external;
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.