Skip to content
Verified contractPartialMIT

SwarmLedger

Address0x88b3d26edfd7c7310fc9864bed8e26552a373385
Balance

0 ETH

 

Transactions

1

 

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,407,196
Creation transaction
0x8a1d19d0d7…1d92285f54

src/swarm/SwarmLedger.sol

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

import {wadLn} from "solmate/src/utils/SignedWadMath.sol";
import {SwarmCast} from "./SwarmCast.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IMainDuelBuyer, ISwarmVault} from "../IMainDuelBuyer.sol";

/// Swarm Duel's money, exactly as the spec defines it: a library of external functions
/// SwarmDuel calls on its own storage (delegatecall), so the game and the money keep their own bytecode. Besides
/// the bookkeeping it runs the two paths that only move tokens (a buy, a claim), so SwarmDuel stays in its size budget;
/// SwarmDuel sends the team's 1% each split returns.
///
/// A split's 60% is the turn's dividends, paid at the turn's close to every dividend share then (the jackpot's 10 seed
/// shares included: their part stays waiting for the jackpot); 3% to the stakers; 1% to the team; the rest waits as
/// IMD and is bought as $IMDUEL in capped steps, into one jackpot across games: the $IMDUEL held less the prizes owed.
/// Shares cost `1 + m/50 + IN/K` IMD each, K = 200 IMD. The winning bid pays max(2 IMD, 20%), keeps its refund, buys
/// dividend shares for its payment and takes 1% of the jackpot. A human win splits 80% of the jackpot equally over the
/// game's played White moves; any other ending pays nothing more.
library SwarmLedger {
    using SwarmCast for uint256;
    using SafeERC20 for IERC20;

    uint256 internal constant K = 200 ether;
    uint256 internal constant JACKPOT_SHARES = 10 ether;
    uint256 internal constant ACC = 1e27;
    uint256 internal constant MIN_PAYMENT = 2 ether;
    uint256 internal constant DISCOUNT_BPS = 8_000;
    uint256 internal constant DIVIDEND_BPS = 6_000;
    uint256 internal constant STAKERS_BPS = 300;
    uint256 internal constant TEAM_BPS = 100;
    uint256 internal constant REFERRAL_BPS = 300; // of a referred split, to its referrer, out of the jackpot's part
    uint256 internal constant DRIP_BPS = 100; // of the jackpot, to each turn's winning move
    uint256 internal constant WIN_PCT = 80; // of the jackpot on a human win, over the game's played White moves

    uint8 internal constant PLAIN = 1; // shares at once
    uint8 internal constant BID = 2; // the leading bid, escrowed
    uint8 internal constant WON = 3; // the winning bid, settled
    uint8 internal constant PAID = 1; // flags: a WON's refund and prize claimed
    uint8 internal constant WIN_PAID = 2; // its part of a human win claimed
    uint256 internal constant BUY_GAS = 6_500_000; // a swap with the main duel's queued move and its fallback (5.78M)
    uint256 internal constant BUY_RESERVE = 400_000;
    /// At most this much waiting IMD a buy (user, 2026-11-13): a sandwich that props the price up with liquidity placed in
    /// the same transaction gains in step with the amount bought and pays a fixed cost to set up, so above about 50 IMD
    /// at the pool's depth on 2026-11-13 it paid; at 20 it loses.
    uint256 internal constant BUY_CAP = 20 ether;
    uint256 internal constant SYNC_GAS = 150_000; // the vault's sync, after the buy's bookkeeping (a failure ignored)

    // a player's counts (section 9): bit offsets and widths
    uint256 internal constant MOVES = 0; // 24 bits
    uint256 internal constant PIECES = 24; // 16 bits per piece type 1-6
    uint256 internal constant QUEENS = 120; // 12
    uint256 internal constant GAMES = 132; // 16
    uint256 internal constant WINS = 148; // 12
    uint256 internal constant DRAWS = 160; // 12
    uint256 internal constant MATES = 172; // 12
    uint256 internal constant EVEN_WINS = 184; // 8
    uint256 internal constant LAST_GAME = 192; // 32
    uint256 internal constant FIRST = 224; // 1

    event Bought(address owner, uint256 spent, uint256 out, uint256 toVault);
    event BuyFailed(address owner, uint256 waiting);
    event Claimed(uint256 indexed id, address indexed owner, uint256 imd, uint256 imduel);

    error NotEnoughGas();
    error Busy(); // the pool manager is already unlocked: a call from inside someone's own unlock can't buy
    error NotYours();

    /// The live contracts a buy uses.
    struct Market {
        IERC20 imd;
        IERC20 imduel;
        IMainDuelBuyer buyer;
        address vault;
    }

    /// A game's money: the word every close updates, the accumulator, and a human win's part. IMD's supply (about 2^83
    /// wei) bounds IN and S far below their widths.
    struct Book {
        uint96 taken; // IN: the IMD that bought shares
        uint80 shares; // S: dividend shares, from JACKPOT_SHARES
        uint32 moves; // the game's played White moves
        uint8 result; // 0 running, 1 White won, 2 Black won, 3 drawn
        uint8 level; // its odds
        uint256 acc; // dividends per dividend share, x ACC
        uint96 perMove; // $IMDUEL each played White move gets on a human win
    }

    /// A deposit: shares at once, the leading bid, or the winning bid. Two words; IMD's supply (about 2^83 wei) bounds
    /// every amount far below its width.
    struct Position {
        address owner;
        uint96 amount; // the IMD put in
        uint80 shares; // n: dividend shares
        uint96 debt; // the dividends counted out: its accrual when bought (rounded up), then what it took
        uint32 gameNo;
        uint16 ply; // the humans' turn it was made in
        uint8 kind;
        uint8 flags;
        uint16 move; // the move it was made with, NO_MOVE if none (the record: no money reads it)
    }

    /// What SwarmDuel holds for others: IMD, and the $IMDUEL owed as prizes (the jackpot is the rest of its $IMDUEL,
    /// the waiting IMD the rest of its IMD); four words, each kept by the steps that write it together (referrals alone).
    struct Money {
        uint96 pending; // this turn's dividends, paid at its close (every split)
        uint96 stakersWaiting; // the stakers' part of the waiting IMD (every split and buy)
        uint48 lastBuyBlock; // the block of the last buy: one a block
        uint96 escrow; // the leading bid (every lead and close)
        uint96 refunds; // owed to winning bids
        uint96 dividends; // kept for holders (every close and claim)
        uint96 prizes; // $IMDUEL: prizes and human-win parts not yet claimed
        uint96 referrals; // IMD owed to referrers (every referred split and referral claim)
    }

    /// A turn's close, for its winner.
    struct Close {
        uint64 id; // the winning position
        uint32 gameNo;
        uint16 ply; // the turn
        uint8 piece; // the moved piece's type (1-6)
        bool queen; // it took the swarm's queen
        bool mate; // it mated
        uint256 bid;
        uint256 paid; // pay(bid)
        uint256 cost; // of the payment, taken by the swarm's ask
        bool referred; // the bid came through a referral link: its split pays its referrer
    }

    /// The winning payment for a bid of `bid`: max(2 IMD, the bid less its 80%, the refund rounding down).
    function pay(uint256 bid) internal pure returns (uint256 p) {
        p = bid - bid * DISCOUNT_BPS / 10_000;
        if (p < MIN_PAYMENT) p = MIN_PAYMENT;
    }

    /// Position `p` (its owner and amount `x` written) buys shares with `x` IMD in game `gameNo` at the humans' turn
    /// `ply` (a deposit, a move that doesn't lead, an outbid bid): the split, then the shares, its second word written
    /// whole; returns them and the team's IMD to send.
    function deposit(Book storage b, Money storage k, Position storage p, uint256 x, uint256 gameNo, uint256 ply, bool referred)
        external
        returns (uint256 n, uint256 toTeam, uint256 toRef)
    {
        (toTeam, toRef) = _split(k, x, referred);
        n = _shares(b, x, ply);
        (b.taken, b.shares) = (b.taken + x.toUint96(), b.shares + n.toUint80());
        (p.shares, p.debt, p.gameNo, p.ply, p.kind) = (n.toUint80(), _debt(b, n), uint32(gameNo), uint16(ply), PLAIN);
    }

    /// Settles the winning position `w` at its turn's close (`c`): its dividend shares for its payment, the payment
    /// less the ask's cost split, its prize (1% of the jackpot), the turn's dividends, and its owner's counts. Returns
    /// the team's IMD to send and the prize.
    function settle(
        mapping(uint256 => Book) storage books,
        Money storage k,
        Position storage w,
        mapping(address => uint256) storage players,
        IERC20 imduel,
        Close memory c
    ) external returns (uint256 toTeam, uint256 prize, uint256 toRef) {
        Book storage b = books[c.gameNo];
        uint256 n = _shares(b, c.paid, c.ply);
        (toTeam, toRef) = _split(k, c.paid - c.cost, c.referred);
        (b.taken, b.shares, b.moves) = (b.taken + c.paid.toUint96(), b.shares + n.toUint80(), b.moves + 1);
        (w.kind, w.shares, w.debt) = (WON, n.toUint80(), _debt(b, n));
        prize = jackpot(k, imduel) * DRIP_BPS / 10_000;
        k.prizes += prize.toUint96();
        // the turn's dividends, to every dividend share now (the winner's and this turn's deposits' included); the
        // seed shares' part and the rounding stay waiting for the jackpot
        uint256 all = b.shares;
        uint256 delta = uint256(k.pending) * ACC / all;
        b.acc += delta;
        (k.dividends, k.pending) = (k.dividends + _ceil((all - JACKPOT_SHARES) * delta).toUint96(), 0);
        _count(books, players, w.owner, c);
    }

    /// One capped buy of the waiting IMD for `msg.sender`, who owns its main-duel move:
    /// at most BUY_CAP of it, the stakers' part in proportion; at most one a block; too little gas, or the pool manager already unlocked (a call from inside someone's own
    /// unlock), reverts it when `required` (buy()), else skips it, recording nothing; a success sends the stakers'
    /// part to the vault and keeps the rest, which is the jackpot's. A failure only waits for the next buy.
    function buyStep(Money storage k, Market memory mk, bool required) external {
        uint256 all = waiting(k, mk.imd);
        if (all == 0 || k.lastBuyBlock == block.number) return;
        if (gasleft() < BUY_GAS + BUY_GAS / 63 + BUY_RESERVE) {
            if (required) revert NotEnoughGas();
            return;
        }
        if (!_ready(mk.buyer)) {
            if (required) revert Busy();
            return;
        }
        k.lastBuyBlock = uint48(block.number);
        uint256 w = all < BUY_CAP ? all : BUY_CAP;
        uint256 stakers = k.stakersWaiting; // their share of the buy is stakers / all
        if (stakers > all) stakers = all;
        uint256 imdBefore = mk.imd.balanceOf(address(this));
        uint256 duelBefore = mk.imduel.balanceOf(address(this));
        mk.imd.forceApprove(address(mk.buyer), w);
        bytes memory data = abi.encodeCall(IMainDuelBuyer.buy, (w, msg.sender));
        address to = address(mk.buyer);
        bool ok;
        assembly ("memory-safe") {
            ok := call(BUY_GAS, to, 0, add(data, 32), mload(data), 0, 0) // nothing copied back: balances tell
        }
        mk.imd.forceApprove(address(mk.buyer), 0);
        uint256 imdAfter = mk.imd.balanceOf(address(this));
        uint256 spent = imdBefore > imdAfter ? imdBefore - imdAfter : 0; // IMD sent back: nothing spent, a failure
        if (ok && spent != 0) {
            uint256 duelAfter = mk.imduel.balanceOf(address(this));
            uint256 out = duelAfter > duelBefore ? duelAfter - duelBefore : 0;
            uint256 toVault = out * stakers / all;
            k.stakersWaiting = (stakers - spent * stakers / all).toUint96();
            emit Bought(msg.sender, spent, out, toVault);
            if (toVault != 0) {
                mk.imduel.safeTransfer(mk.vault, toVault);
                try ISwarmVault(mk.vault).sync{gas: SYNC_GAS}() {} catch {}
            }
        } else {
            emit BuyFailed(msg.sender, w);
        }
    }

    /// The end of a game with `result`: on a human win, 80% of the jackpot split equally over the game's played White
    /// moves (owed as prizes); any other result pays nothing more. Returns each move's part and the jackpot left.
    function end(Book storage b, Money storage k, uint8 result, IERC20 imduel)
        external
        returns (uint256 perMove, uint256 left)
    {
        left = jackpot(k, imduel);
        uint256 moves = b.moves;
        if (result == 1 && moves != 0) {
            perMove = left * WIN_PCT / 100 / moves;
            (b.perMove, k.prizes) = (perMove.toUint96(), k.prizes + (perMove * moves).toUint96());
            left -= perMove * moves;
        }
        b.result = result;
    }

    /// Pays `msg.sender`'s positions `ids`: dividends and refunds in IMD, prizes and human-win parts in $IMDUEL;
    /// returns the totals.
    function claimAll(
        mapping(uint256 => Book) storage books,
        mapping(uint256 => Position) storage positions,
        mapping(uint256 => uint256) storage prizes,
        Money storage k,
        uint256[] calldata ids,
        IERC20 imd,
        IERC20 imduel
    ) external returns (uint256 imdTotal, uint256 imduelTotal) {
        for (uint256 i; i < ids.length; i++) {
            uint256 id = ids[i];
            Position storage p = positions[id];
            if (p.owner != msg.sender) revert NotYours();
            (uint256 a, uint256 e) = _take(books[p.gameNo], p, k, prizes[id]);
            if (a + e != 0) emit Claimed(id, msg.sender, a, e);
            (imdTotal, imduelTotal) = (imdTotal + a, imduelTotal + e);
        }
        if (imdTotal != 0) imd.safeTransfer(msg.sender, imdTotal);
        if (imduelTotal != 0) imduel.safeTransfer(msg.sender, imduelTotal);
    }

    /// The IMD waiting to be bought: all IMD held that nobody is owed.
    function waiting(Money storage k, IERC20 imd) public view returns (uint256) {
        uint256 held = imd.balanceOf(address(this));
        uint256 owedNow = uint256(k.escrow) + k.dividends + k.refunds + k.pending + k.referrals;
        return held > owedNow ? held - owedNow : 0;
    }

    /// The jackpot: all $IMDUEL held that isn't owed as prizes.
    function jackpot(Money storage k, IERC20 imduel) public view returns (uint256) {
        uint256 held = imduel.balanceOf(address(this));
        return held > k.prizes ? held - k.prizes : 0;
    }

    /// What position `p` (its prize `prize`) can claim now: dividends and, for a winning move, its refund (IMD), its
    /// prize and, once its game is a human win, its part ($IMDUEL).
    function owed(Book storage b, Position storage p, uint256 prize)
        public
        view
        returns (uint256 dividends, uint256 refund, uint256 won, uint256 part)
    {
        uint256 accrued = uint256(p.shares) * b.acc / ACC;
        if (accrued > p.debt) dividends = accrued - p.debt;
        if (p.kind != WON) return (dividends, 0, 0, 0);
        uint8 flags = p.flags;
        if (flags & PAID == 0) (refund, won) = (p.amount - pay(p.amount), prize);
        if (b.result == 1 && flags & WIN_PAID == 0) part = b.perMove;
    }

    /// The shares `x` IMD would buy now at turn `ply` (the page's quote).
    function quote(Book storage b, uint256 x, uint256 ply) external view returns (uint256) {
        return _shares(b, x, ply);
    }

    /// Takes what position `p` can claim now out of the buckets: returns the IMD and the $IMDUEL to pay.
    function _take(Book storage b, Position storage p, Money storage k, uint256 prize)
        private
        returns (uint256 imd, uint256 imduel)
    {
        (uint256 dividends, uint256 refund, uint256 won, uint256 part) = owed(b, p, prize);
        if (dividends != 0) (p.debt, k.dividends) = (p.debt + dividends.toUint96(), k.dividends - dividends.toUint96());
        if (p.kind == WON) {
            uint8 flags = p.flags | PAID;
            if (part != 0) flags |= WIN_PAID;
            if (flags != p.flags) {
                (p.flags, k.refunds, k.prizes) =
                    (flags, k.refunds - refund.toUint96(), k.prizes - (won + part).toUint96());
            }
        }
        return (dividends + refund, won + part);
    }

    /// The buyer can buy now; one whose check reverts is read as not ready, so it can't revert a deposit or a step.
    function _ready(IMainDuelBuyer buyer) private view returns (bool) {
        try buyer.ready() returns (bool r) {
            return r;
        } catch {
            return false;
        }
    }

    /// Splits `x` IMD: 60% to the turn's dividends (paid at its close), 3% to the stakers' waiting part, 1% returned
    /// for the team, 3% owed to the referrer when `referred` (out of the jackpot's part), the rest waits for the jackpot.
    function _split(Money storage k, uint256 x, bool referred) private returns (uint256 toTeam, uint256 toRef) {
        uint256 d = x * DIVIDEND_BPS / 10_000;
        uint256 s = x * STAKERS_BPS / 10_000;
        toTeam = x * TEAM_BPS / 10_000;
        (k.pending, k.stakersWaiting) = (k.pending + d.toUint96(), k.stakersWaiting + s.toUint96());
        if (referred) {
            toRef = x * REFERRAL_BPS / 10_000;
            k.referrals += toRef.toUint96();
        }
    }

    /// Section 9: the winning move's owner's counts, in the order the game plays them; a new game folds the last
    /// one's result first (it is over: one game at a time).
    function _count(
        mapping(uint256 => Book) storage books,
        mapping(address => uint256) storage players,
        address owner,
        Close memory c
    ) private {
        uint256 w = players[owner];
        uint256 last = uint32(w >> LAST_GAME);
        if (last != c.gameNo) {
            if (last != 0) {
                Book storage lb = books[last];
                uint8 r = lb.result;
                if (r == 1) w = _bump(_bump(w, WINS, 12), EVEN_WINS, lb.level == 0 ? 8 : 0);
                else if (r == 3) w = _bump(w, DRAWS, 12);
            }
            w = (_bump(w, GAMES, 16) & ~(uint256(type(uint32).max) << LAST_GAME)) | (uint256(c.gameNo) << LAST_GAME);
            if (c.gameNo == 1) w |= 1 << FIRST;
        }
        w = _bump(_bump(w, MOVES, 24), PIECES + 16 * (c.piece - 1), 16);
        if (c.queen) w = _bump(w, QUEENS, 12);
        if (c.mate) w = _bump(w, MATES, 12);
        players[owner] = w;
    }

    /// Adds one to the `width`-bit counter at `shift`, saturating; a zero width adds nothing.
    function _bump(uint256 w, uint256 shift, uint256 width) internal pure returns (uint256) {
        uint256 max = (1 << width) - 1;
        return (w >> shift) & max == max ? w : w + (1 << shift);
    }

    /// `K * ln(1 + x / (a*K + IN))` with `a = 1 + m/50`, m the humans' moves played at turn `ply`.
    function _shares(Book storage b, uint256 x, uint256 ply) private view returns (uint256) {
        uint256 base = K + K * (ply >> 1) / 50 + b.taken;
        return K * uint256(wadLn(int256(1e18 + x * 1e18 / base))) / 1e18;
    }

    /// A new holding's dividend debt: its shares' accrual so far, rounded up.
    function _debt(Book storage b, uint256 n) private view returns (uint96) {
        return _ceil(n * b.acc).toUint96();
    }

    function _ceil(uint256 x) private pure returns (uint256) {
        return (x + ACC - 1) / ACC;
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

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

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

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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.
     */
    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.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

lib/v4-core/lib/solmate/src/utils/SignedWadMath.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @notice Signed 18 decimal fixed point (wad) arithmetic library.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SignedWadMath.sol)
/// @author Modified from Remco Bloemen (https://xn--2-umb.com/22/exp-ln/index.html)

/// @dev Will not revert on overflow, only use where overflow is not possible.
function toWadUnsafe(uint256 x) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18.
        r := mul(x, 1000000000000000000)
    }
}

/// @dev Takes an integer amount of seconds and converts it to a wad amount of days.
/// @dev Will not revert on overflow, only use where overflow is not possible.
/// @dev Not meant for negative second amounts, it assumes x is positive.
function toDaysWadUnsafe(uint256 x) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18 and then divide it by 86400.
        r := div(mul(x, 1000000000000000000), 86400)
    }
}

/// @dev Takes a wad amount of days and converts it to an integer amount of seconds.
/// @dev Will not revert on overflow, only use where overflow is not possible.
/// @dev Not meant for negative day amounts, it assumes x is positive.
function fromDaysWadUnsafe(int256 x) pure returns (uint256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 86400 and then divide it by 1e18.
        r := div(mul(x, 86400), 1000000000000000000)
    }
}

/// @dev Will not revert on overflow, only use where overflow is not possible.
function unsafeWadMul(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by y and divide by 1e18.
        r := sdiv(mul(x, y), 1000000000000000000)
    }
}

/// @dev Will return 0 instead of reverting if y is zero and will
/// not revert on overflow, only use where overflow is not possible.
function unsafeWadDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18 and divide it by y.
        r := sdiv(mul(x, 1000000000000000000), y)
    }
}

function wadMul(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Store x * y in r for now.
        r := mul(x, y)

        // Combined overflow check (`x == 0 || (x * y) / x == y`) and edge case check
        // where x == -1 and y == type(int256).min, for y == -1 and x == min int256,
        // the second overflow check will catch this.
        // See: https://secure-contracts.com/learn_evm/arithmetic-checks.html#arithmetic-checks-for-int256-multiplication
        // Combining into 1 expression saves gas as resulting bytecode will only have 1 `JUMPI`
        // rather than 2.
        if iszero(
            and(
                or(iszero(x), eq(sdiv(r, x), y)),
                or(lt(x, not(0)), sgt(y, 0x8000000000000000000000000000000000000000000000000000000000000000))
            )
        ) {
            revert(0, 0)
        }

        // Scale the result down by 1e18.
        r := sdiv(r, 1000000000000000000)
    }
}

function wadDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Store x * 1e18 in r for now.
        r := mul(x, 1000000000000000000)

        // Equivalent to require(y != 0 && ((x * 1e18) / 1e18 == x))
        if iszero(and(iszero(iszero(y)), eq(sdiv(r, 1000000000000000000), x))) {
            revert(0, 0)
        }

        // Divide r by y.
        r := sdiv(r, y)
    }
}

/// @dev Will not work with negative bases, only use when x is positive.
function wadPow(int256 x, int256 y) pure returns (int256) {
    // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)
    return wadExp((wadLn(x) * y) / 1e18); // Using ln(x) means x must be greater than 0.
}

function wadExp(int256 x) pure returns (int256 r) {
    unchecked {
        // When the result is < 0.5 we return zero. This happens when
        // x <= floor(log(0.5e18) * 1e18) ~ -42e18
        if (x <= -42139678854452767551) return 0;

        // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
        // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
        if (x >= 135305999368893231589) revert("EXP_OVERFLOW");

        // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
        // for more intermediate precision and a binary basis. This base conversion
        // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
        x = (x << 78) / 5**18;

        // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
        // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
        // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
        int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;
        x = x - k * 54916777467707473351141471128;

        // k is in the range [-61, 195].

        // Evaluate using a (6, 7)-term rational approximation.
        // p is made monic, we'll multiply by a scale factor later.
        int256 y = x + 1346386616545796478920950773328;
        y = ((y * x) >> 96) + 57155421227552351082224309758442;
        int256 p = y + x - 94201549194550492254356042504812;
        p = ((p * y) >> 96) + 28719021644029726153956944680412240;
        p = p * x + (4385272521454847904659076985693276 << 96);

        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        int256 q = x - 2855989394907223263936484059900;
        q = ((q * x) >> 96) + 50020603652535783019961831881945;
        q = ((q * x) >> 96) - 533845033583426703283633433725380;
        q = ((q * x) >> 96) + 3604857256930695427073651918091429;
        q = ((q * x) >> 96) - 14423608567350463180887372962807573;
        q = ((q * x) >> 96) + 26449188498355588339934803723976023;

        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial won't have zeros in the domain as all its roots are complex.
            // No scaling is necessary because p is already 2**96 too large.
            r := sdiv(p, q)
        }

        // r should be in the range (0.09, 0.25) * 2**96.

        // We now need to multiply r by:
        // * the scale factor s = ~6.031367120.
        // * the 2**k factor from the range reduction.
        // * the 1e18 / 2**96 factor for base conversion.
        // We do this all at once, with an intermediate result in 2**213
        // basis, so the final right shift is always by a positive amount.
        r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
    }
}

function wadLn(int256 x) pure returns (int256 r) {
    unchecked {
        require(x > 0, "UNDEFINED");

        // We want to convert x from 10**18 fixed point to 2**96 fixed point.
        // We do this by multiplying by 2**96 / 10**18. But since
        // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
        // and add ln(2**96 / 10**18) at the end.

        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            r := or(r, shl(2, lt(0xf, shr(r, x))))
            r := or(r, shl(1, lt(0x3, shr(r, x))))
            r := or(r, lt(0x1, shr(r, x)))
        }

        // Reduce range of x to (1, 2) * 2**96
        // ln(2^k * x) = k * ln(2) + ln(x)
        int256 k = r - 96;
        x <<= uint256(159 - k);
        x = int256(uint256(x) >> 159);

        // Evaluate using a (8, 8)-term rational approximation.
        // p is made monic, we will multiply by a scale factor later.
        int256 p = x + 3273285459638523848632254066296;
        p = ((p * x) >> 96) + 24828157081833163892658089445524;
        p = ((p * x) >> 96) + 43456485725739037958740375743393;
        p = ((p * x) >> 96) - 11111509109440967052023855526967;
        p = ((p * x) >> 96) - 45023709667254063763336534515857;
        p = ((p * x) >> 96) - 14706773417378608786704636184526;
        p = p * x - (795164235651350426258249787498 << 96);

        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        // q is monic by convention.
        int256 q = x + 5573035233440673466300451813936;
        q = ((q * x) >> 96) + 71694874799317883764090561454958;
        q = ((q * x) >> 96) + 283447036172924575727196451306956;
        q = ((q * x) >> 96) + 401686690394027663651624208769553;
        q = ((q * x) >> 96) + 204048457590392012362485061816622;
        q = ((q * x) >> 96) + 31853899698501571402653359427138;
        q = ((q * x) >> 96) + 909429971244387300277376558375;
        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already 2**96 too large.
            r := sdiv(p, q)
        }

        // r is in the range (0, 0.125) * 2**96

        // Finalization, we need to:
        // * multiply by the scale factor s = 5.549…
        // * add ln(2**96 / 10**18)
        // * add k * ln(2)
        // * multiply by 10**18 / 2**96 = 5**18 >> 78

        // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
        r *= 1677202110996718588342820967067443963516166;
        // add ln(2) * k * 5e18 * 2**192
        r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
        // add ln(2**96 / 10**18) * 5e18 * 2**192
        r += 600920179829731861736702779321621459595472258049074101567377883020018308;
        // base conversion: mul 2**18 / 2**192
        r >>= 174;
    }
}

/// @dev Will return 0 instead of reverting if y is zero.
function unsafeDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Divide x by y.
        r := sdiv(x, y)
    }
}

src/IMainDuelBuyer.sol

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

/// Buys $IMDUEL with its caller's IMD in the main duel, at most one pool fee of price rise a call.
interface IMainDuelBuyer {
    /// Pulls at most `maxIn` IMD from the caller and swaps it for $IMDUEL, stopping where the price has risen by about
    /// one pool fee; `owner` owns the main-duel move the trade bids. Returns the IMD spent and the $IMDUEL sent back.
    function buy(uint256 maxIn, address owner) external returns (uint256 spent, uint256 out);

    /// Whether a buy can run now: false inside someone's own pool-manager unlock, where the buyer's unlock reverts.
    function ready() external view returns (bool);

    function imd() external view returns (address);

    function imduel() external view returns (address);
}

/// The staking vault's part SwarmDuel uses.
interface ISwarmVault {
    function asset() external view returns (address);

    function sync() external;
}

src/swarm/SwarmCast.sol

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

/// The two checked casts Swarm Duel uses, as OpenZeppelin's SafeCast writes them (same error). Its own name: the hook's
/// build already has v4-core's SafeCast, and IMD's launch check refuses two artifacts of one name in a build.
library SwarmCast {
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) revert SafeCastOverflowedUintDowncast(96, value);
        return uint96(value);
    }

    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) revert SafeCastOverflowedUintDowncast(80, value);
        return uint80(value);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "v4-core/=lib/v4-core/",
    "@uniswap/v4-core/=lib/v4-core/",
    "forge-std/=lib/v4-core/lib/forge-std/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.