Skip to content
Verified contractPartialMIT

RedToken

Address0xef7e1aa8613ce5af690b04d1d5d9207daccbd58e
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,334,178
Creation transaction
0x2f49e3fa7c…3c62bb3acd

src/v2/RedToken.sol

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

import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {IERC6909Claims} from "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol";

/// @title Red Is Good (RED) - token (inverse chart on a Uniswap v4 hook)
/// @author @AnonTraderQ (https://x.com/AnonTraderQ)
/// @custom:x https://x.com/AnonTraderQ
/// @notice Experimental project. Every buy pushes the displayed price DOWN and rebases holder balances UP;
///         every sell pushes it UP and rebases balances DOWN. Red candles are good here.
///         Liquidity is locked in the hook by code (no LP token, no admin withdrawal, no upgrade).
///         1% of the ETH side of every trade goes to the FeeCollector.
/// @notice Inverse-chart token, v2. Design: docs/v2-design.md section 4.
///  - Users hold "shares" internally. Displayed balance = shares × index. Only the hook updates the index.
///  - The PoolManager's balance is kept separately as fixed "units" (`poolManagerUnits`); it is unaffected by
///    the rebase.
///  - Difference from v1: the token can enter and leave the PoolManager, so standard routers work. Safety is
///    provided by two rules:
///      1) At the start of the transaction the hook freezes the index (`snapshot`). Every unit↔share conversion
///         within that transaction uses this frozen index; so "sell all" works even if the balance shrinks
///         during the transaction.
///      2) Exits from the PoolManager use the frozen index only up to the amount the hook authorized for that
///         swap; the rest is converted at the highest index ever seen (`hwm`). So parking in the PoolManager
///         (ERC6909 claim, another pool) cannot profit from index movements.
contract RedToken {
    uint256 public constant INDEX_ONE = 1e36;

    string public name;
    string public symbol;
    uint8 public constant decimals = 18;

    address public immutable poolManager;
    address public immutable deployer;
    address public hook;

    /// @notice Displayed units per share (INDEX_ONE scale). Never drops below INDEX_ONE (the model cannot go back
    ///         past launch).
    uint256 public index = INDEX_ONE;
    /// @notice Highest index seen so far. Unauthorized PoolManager exits are converted with this.
    uint256 public hwm = INDEX_ONE;
    uint256 public totalShares;
    /// @notice Fixed units held by the PoolManager. The hook mints them; every unit leaving the PoolManager is
    ///         deducted here.
    uint256 public poolManagerUnits;

    mapping(address => uint256) public sharesOf;
    mapping(address => mapping(address => uint256)) public allowance;

    // Transient storage (EIP-1153): cleared when the transaction ends.
    bytes32 private constant SNAP_SLOT = keccak256("RedToken.snapIndex");
    bytes32 private constant AUTH_SLOT = keccak256("RedToken.authorizedOut");

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event IndexUpdated(uint256 index);

    error OnlyHook();
    error HookAlreadySet();
    error ZeroIndex();
    error ZeroAddress();
    error InvalidRecipient();
    error InvalidSender();

    modifier onlyHook() {
        if (msg.sender != hook) revert OnlyHook();
        _;
    }

    constructor(string memory name_, string memory symbol_, address poolManager_) {
        name = name_;
        symbol = symbol_;
        poolManager = poolManager_;
        deployer = msg.sender;
    }

    /// @notice The hook address is set once and cannot be changed afterwards.
    function setHook(address hook_) external {
        if (msg.sender != deployer || hook != address(0)) revert HookAlreadySet();
        if (hook_ == address(0)) revert ZeroAddress();
        hook = hook_;
    }

    // ---------------------------------------------------------------------
    // Transient state
    // ---------------------------------------------------------------------

    /// @notice The index frozen for this transaction; 0 means not frozen.
    function snapIndex() public view returns (uint256 v) {
        bytes32 slot = SNAP_SLOT;
        assembly ("memory-safe") {
            v := tload(slot)
        }
    }

    /// @notice Remaining units that may leave the PoolManager at the frozen index in this transaction.
    function authorizedOut() public view returns (uint256 v) {
        bytes32 slot = AUTH_SLOT;
        assembly ("memory-safe") {
            v := tload(slot)
        }
    }

    /// @notice Index used for unit↔share conversions: the frozen one inside a transaction, the current one outside.
    function effectiveIndex() public view returns (uint256) {
        uint256 s = snapIndex();
        return s == 0 ? index : s;
    }

    // ---------------------------------------------------------------------
    // ERC20 view (in displayed units)
    // ---------------------------------------------------------------------

    function balanceOf(address account) public view returns (uint256) {
        if (account == poolManager) return poolManagerUnits;
        return FullMath.mulDiv(sharesOf[account], effectiveIndex(), INDEX_ONE);
    }

    /// @notice Circulating units + units in the pool. Claim units the hook has not yet burned (burned on the next
    ///         swap) are deducted from the supply; otherwise supply and market cap look inflated between two
    ///         transactions.
    function totalSupply() external view returns (uint256) {
        uint256 pending = IERC6909Claims(poolManager).balanceOf(hook, uint256(uint160(address(this))));
        return FullMath.mulDiv(totalShares, effectiveIndex(), INDEX_ONE) + poolManagerUnits - pending;
    }

    function sharesToUnits(uint256 shares) public view returns (uint256) {
        return FullMath.mulDiv(shares, effectiveIndex(), INDEX_ONE);
    }

    function unitsToShares(uint256 units) public view returns (uint256) {
        return FullMath.mulDiv(units, INDEX_ONE, effectiveIndex());
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transfer(address to, uint256 amount) external returns (bool) {
        _transfer(msg.sender, to, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        // The PoolManager approves nobody; not even a zero-amount "transfer from PoolManager" event may be emitted.
        if (from == poolManager) revert InvalidSender();
        uint256 allowed = allowance[from][msg.sender];
        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
        _transfer(from, to, amount);
        return true;
    }

    function _transfer(address from, address to, uint256 amount) internal {
        if (to == address(0)) revert ZeroAddress();

        if (from == poolManager) {
            // PoolManager.take(...) call. A take to the PoolManager itself would mint dead shares: forbidden.
            if (to == poolManager) revert InvalidRecipient();
            poolManagerUnits -= amount;
            if (to == hook) {
                // The hook's own take: the units are burned (the hook uses them for pool rescaling).
                emit Transfer(poolManager, address(0), amount);
                return;
            }
            // Exit to a user: the part the hook authorized for this swap at the frozen index, the rest at the
            // highest index seen. The recipient pays the rounding difference (in the protocol's favor).
            uint256 minted;
            uint256 rest = amount;
            uint256 auth = authorizedOut();
            uint256 snap = snapIndex();
            if (auth != 0 && snap != 0) {
                uint256 part = auth < amount ? auth : amount;
                _setAuthorizedOut(auth - part);
                minted = FullMath.mulDiv(part, INDEX_ONE, snap);
                rest = amount - part;
            }
            if (rest != 0) minted += FullMath.mulDiv(rest, INDEX_ONE, hwm);
            sharesOf[to] += minted;
            totalShares += minted;
            emit Transfer(poolManager, to, amount);
            return;
        }

        // The sender pays the rounding difference (in the protocol's favor).
        uint256 shares = FullMath.mulDivRoundingUp(amount, INDEX_ONE, effectiveIndex());
        sharesOf[from] -= shares;
        if (to == poolManager) {
            // Transfer before PoolManager.settle(...): the shares are burned, the PoolManager receives fixed units.
            totalShares -= shares;
            poolManagerUnits += amount;
        } else {
            sharesOf[to] += shares;
        }
        emit Transfer(from, to, amount);
    }

    // ---------------------------------------------------------------------
    // Hook only
    // ---------------------------------------------------------------------

    function setIndex(uint256 newIndex) external onlyHook {
        if (newIndex == 0) revert ZeroIndex();
        index = newIndex;
        if (newIndex > hwm) hwm = newIndex;
        emit IndexUpdated(newIndex);
    }

    /// @notice For the hook to pay its debt to the PoolManager (sync → mint → settle).
    function mintPoolManagerUnits(uint256 units) external onlyHook {
        poolManagerUnits += units;
        emit Transfer(address(0), poolManager, units);
    }

    /// @notice Freezes the index on the first swap of the transaction. Calling it again in the same transaction
    ///         changes nothing.
    function snapshot() external onlyHook {
        if (snapIndex() != 0) return;
        uint256 v = index;
        bytes32 slot = SNAP_SLOT;
        assembly ("memory-safe") {
            tstore(slot, v)
        }
    }

    /// @notice Adds the units this swap's recipient may take out of the PoolManager at the frozen index.
    function authorizeOut(uint256 units) external onlyHook {
        _setAuthorizedOut(authorizedOut() + units);
    }

    function _setAuthorizedOut(uint256 v) internal {
        bytes32 slot = AUTH_SLOT;
        assembly ("memory-safe") {
            tstore(slot, v)
        }
    }
}

lib/v4-core/src/interfaces/external/IERC6909Claims.sol

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

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

lib/v4-core/src/libraries/FullMath.sol

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-core/",
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/solmate/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "v4-core/=lib/v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.